[英]ASP.NET local SQL Server database C# gridview data binding Visual Studio 2013
[英]Binding database data to the GridView in ASP.Net
我嘗試將數據庫數據綁定到c#和asp.net中的gridview。 但我無法在gridview中看到數據。行被添加到gridview但它們是空的。 當我在SQLServer中運行該查詢時,它給出了正確的結果。我沒有添加或更改任何代碼到asp部分。我應該嗎? 我找不到問題所在:(請幫忙..
myConnection = WebConfigurationManager.ConnectionStrings["KutuphaneConnectionString"].ConnectionString;
connect = new SqlConnection(myConnection);
command = new SqlCommand();
connect.Open();
command.Connection = connect;
string komut = "SELECT K.ad,K.yazar,K.baskiNo,O.sonTeslimTarihi FROM OduncIslemleri O,Kitap K WHERE O.kullaniciId=" + Session["id"] + " AND O.kitapId = K.id;";
try
{
SqlCommand sqlCommand = new SqlCommand();
sqlCommand = connect.CreateCommand();
sqlCommand.CommandText = komut;
SqlDataAdapter sda = new SqlDataAdapter(sqlCommand.CommandText, connect);
SqlCommandBuilder scb = new SqlCommandBuilder(sda);
//Create a DataTable to hold the query results.
DataTable dTable = new DataTable();
//Fill the DataTable.
sda.Fill(dTable);
GridView1.DataSource = dTable;
GridView1.DataBind();
}
catch (SqlException)
{
//Console.WriteLine(e.StackTrace);
}
reader.Close();
connect.Close();
這是正確的答案:
myConnection = WebConfigurationManager.ConnectionStrings["KutuphaneConnectionString"].ConnectionString;
connect = new SqlConnection(myConnection);
string sorgu = "select K.ad,K.yazar,K.baskiNo,O.sonTeslimTarihi from Kitap K, OduncIslemleri O where O.kitapId = K.id and O.kullaniciId = "+ Session["id"];
SqlDataAdapter sadp = new SqlDataAdapter(sorgu, connect);
DataSet ds = new DataSet();
sadp.Fill(ds);
this.GridView1.DataSource = ds.Tables[0];
this.GridView1.DataBind();
connect.Close();
我還在Gridview中使用了模板字段。 autogeneratedFields也應該是真的。 我希望這對有同樣問題的人有所幫助
注意在綁定之后觸發的另一個事件,可以清除行
嘗試創建一個DataSet,然后使用Fill填充它。 我從未見過在DataTable上使用Fill - 並且在MSDN上找不到特定的重載。 但我懷疑這樣的重載不會修改DataTable的現有模式(因為它只是在您的示例中使用之前才創建,意味着它沒有列)。
我認為你必須使用BindingSource控件,將它的DataSource設置為DataTable,然后將GridView的DataSource設置為BindingSource。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.