I am trying to show data from my SQL table on grid view, however, it is not showing the first row of data but the following rows of data a showing: Here is my code
public partial class DisplayGrid : System.Web.UI.Page
{
string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["PostbankConnectionString"].ConnectionString;
string query = "SELECT * FROM tbl_user";
protected void Page_Load(object sender, EventArgs e)
{
//query
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;
SqlDataReader reader;
con.Open();
reader = cmd.ExecuteReader();
if (reader.Read())
{
GridView1.DataSource = reader;
//Bind the data
GridView1.DataBind();
}
reader.Close();
con.Close();
}
}
Better to use DataTable
and load contents of SqlDataReader
with DataTable.Load()
instead of assigning the reader contents directly to GridView
instance:
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.CommandType = CommandType.Text;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows) // check if the reader contains rows
{
dt.Load(reader); // load to Datatable
GridView1.DataSource = dt; // assign data source from DataTable
GridView1.DataBind();
}
}
}
Note that SqlDataReader
is forward-only stream , you need to use DataTable
or other collections which able to perform both backward and forward lookups.
remove the line- if (reader.Read())
because DataReader.Read method advances the SqlDataReader to the next record.
Here is the code-
public partial class DisplayGrid : System.Web.UI.Page
{
string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["PostbankConnectionString"].ConnectionString;
string query = "SELECT * FROM tbl_user";
protected void Page_Load(object sender, EventArgs e)
{
//query
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;
SqlDataReader reader;
con.Open();
reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
//Bind the data
GridView1.DataBind();
reader.Close();
con.Close();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.