2
Answers

Connection must be valid and open

Mark Fenech

Mark Fenech

12y
4.5k
1
Hi, I am using a method which get me a list of items from database. I already used the connection to insert data to database and works fine, but when displaying data in gridview an exception pops up. Below you can find the method used, the code for binding data to gridview and the asp for the gridview. Hope you can help. Thanks

Method to retreive data

ublic List<Bet> getBets()
        {
            MySqlCommand cmd = Connection.CreateCommand();
            cmd = new MySqlCommand("SELECT * FROM bets ORDER BY date");

            try
            {
                if (this.Connection.State == ConnectionState.Closed)
                    this.Connection.Open();

                MySqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                List<Bet> bets = new List<Bet>();

                while (dr.Read())
                {
                    Bet myBet = new Bet();
                    myBet = FillBetfromRow(dr);
                    bets.Add(myBet);
                }
                return bets;
            }
            catch (MySqlException ex)
            {
                throw ex;
            }
            finally
            {
                if (Connection.State == ConnectionState.Open)
                    Connection.Close();
            }
        }

Binding data to gridview

gvBets.DataSource = new BetManagement().getBets();
            gvBets.DataBind();

asp code for gridview

<asp:GridView ID="gvBets" runat="server">
                    <Columns>
                        <asp:BoundField DataField="date" HeaderText="Date" />
                        <asp:BoundField DataField="details" HeaderText="Details" />
                        <asp:BoundField DataField="odds" HeaderText="Odds" />
                        <asp:BoundField DataField="stake" HeaderText="Stake" />
                        <asp:BoundField DataField="result" HeaderText="Result" />
                    </Columns>
                    </asp:GridView>

Hope you can help me tnx :D
Answers (2)