简体   繁体   中英

Binding database data to the GridView in ASP.Net

I try to bind database data to the gridview in c# and asp.net. But I couldn't see the datas in the gridview.Rows are added to the gridview but they are empty. When I run that query in SQLServer, it gives the correct result.I didn't add or change any code to the asp part.Should I? I couldn't find where is the problem :( please help..

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();

Here is the correct answer :

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();

I also used template fields in Gridview. Also autogeneratedFields should be true. I hope this helps to the people who have the same problem

注意在绑定之后触发的另一个事件,可以清除行

Try creating a DataSet and populate that using Fill instead. I've never seen Fill used on a DataTable - and can't find that particular overload on MSDN. My suspicion is, though, that such an overload would not modify the existing schema of the DataTable (which, since it's only just been created prior to use in your example, would mean that it has no columns).

我认为你必须使用BindingSource控件,将它的DataSource设置为DataTable,然后将GridView的DataSource设置为BindingSource。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM