![](/img/trans.png)
[英]How to Display Text Boxes on to the first row of Grid View in Asp.Net C#
[英]Grid view not showing the first row ASP.NET , C# Sql server
我試圖在網格視圖上顯示SQL表中的數據,但是,它不顯示數據的第一行,而是顯示隨后的數據行:這是我的代碼
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();
}
}
最好使用DataTable
並通過DataTable.Load()
加載SqlDataReader
內容,而不是將閱讀器的內容直接分配給GridView
實例:
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();
}
}
}
請注意, SqlDataReader
是僅向前流 ,您需要使用DataTable
或其他能夠執行反向和正向查找的集合。
刪除行if (reader.Read())
因為DataReader.Read方法將SqlDataReader推進到下if (reader.Read())
記錄。
這是代碼-
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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.