Bind (Populate) GridView using SqlDataReader in ASP.Net

Last Reply 2 months ago By dharmendr

Posted 2 months ago

 I didn't get all the rows in gridview using this query(All the rows is appear in grdview except first row). if i execute only same query in sqlquery.sql its working...

  private void BindGrid()
        {
            SqlCommand cmd3 = new SqlCommand();
            cmd3.Connection = con;
            con.Open();
            cmd3.CommandType = CommandType.Text;
            cmd3.CommandText = "select bill.id, customer.customer_name as 'Customer Name', bill.grand_total, SUBSTRING(convert(varchar,bill.date,103),0,12) Date from bill,customer where bill.cid=customer.id and bill.bid=@bid";
            cmd3.Parameters.AddWithValue("@bid", Session["bid"].ToString());
            SqlDataReader dr1 = cmd3.ExecuteReader();
            if (dr1.HasRows)
            {
                while (dr1.Read())
                {
                    GridView1.DataSource = dr1;
                    GridView1.DataBind();
                    Response.Write(Session["bid"].ToString());
                }
            }
        
          
            dr1.Close();
            con.Close();
        }

 

   <asp:GridView ID="GridView1" runat="server" CssClass="table table-striped table-bordered table-hover" ></asp:GridView>

 

Posted 2 months ago

Hi JanviDarji,

Change your code with below code.

private void BindGrid()
{
    SqlCommand cmd3 = new SqlCommand();
    cmd3.Connection = con;
    con.Open();
    cmd3.CommandType = CommandType.Text;
    cmd3.CommandText = "select bill.id, customer.customer_name as 'Customer Name', bill.grand_total, SUBSTRING(convert(varchar,bill.date,103),0,12) Date from bill,customer where bill.cid=customer.id and bill.bid=@bid";
    cmd3.Parameters.AddWithValue("@bid", Session["bid"].ToString());
    GridView1.DataSource = cmd3.ExecuteReader(); ;
    GridView1.DataBind();
    Response.Write(Session["bid"].ToString());
    con.Close();
}