繁体   English   中英

如何绑定GridView?

[英]how to bind the gridview?

将表格之一绑定到GridView时出现问题。 我尝试了一切,但没有任何帮助。 我有一个搜索按钮,我希望它向我显示搜索结果,并且有一个DropDownList绑定到另一个表。

这是代码:

SqlConnection my_cn = new SqlConnection("Data Source=NIMA-PC;Initial Catalog=PDFha;Integrated Security=True");
my_cn.Open();
SqlCommand cmd = new SqlCommand("SELECT Books.Name,Books.Subject,Books.PublisherName,Books.Summery FROM Books WHERE (Books.Subject= '" + subList.SelectedValue.ToString() + "') AND (Books.Name= '" + searchName.Text + "')", my_cn);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
adapter.Fill(ds);
DataTable dt = ds.Tables[0];
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read()==true)
{
   GridView1.DataSource = dt;
}
my_cn.Close();

当我单击按钮时什么也没有发生,我知道我的C#代码有问题,但是我无法识别它。 感谢任何评论。

试试这个:-您缺少DataBind方法,除此之外,我不知道您为什么再次调用DataReader ,也删除了该代码。 另外,请使用参数化查询来防止SQL注入 像这样的东西: cmd.Parameters.AddWithValue()

SqlConnection my_cn = new SqlConnection("Data Source=NIMA-PC;Initial Catalog=PDFha;Integrated Security=True");
my_cn.Open();
SqlCommand cmd = new SqlCommand("SELECT Books.Name,Books.Subject,Books.PublisherName,Books.Summery FROM Books WHERE (Books.Subject= '" + subList.SelectedValue.ToString() + "') AND (Books.Name= '" + searchName.Text + "')", my_cn);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
adapter.Fill(ds);
DataTable dt = ds.Tables[0];
GridView1.DataSource = dt;
GridView1.DataBind();
my_cn.Close();

这应该是正确的代码

SqlConnection my_cn = new SqlConnection("Data Source=NIMA-PC;Initial Catalog=PDFha;Integrated Security=True");
my_cn.Open();
SqlCommand cmd = new SqlCommand("SELECT Books.Name,Books.Subject,Books.PublisherName,Books.Summery FROM Books WHERE (Books.Subject= '" + subList.SelectedValue.ToString() + "') AND (Books.Name= '" + searchName.Text + "')", my_cn);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
adapter.Fill(ds);
DataTable dt = ds.Tables[0];
//Modified start
//You don't need SQLReader, While loop
GridView1.DataSource = dt;
GridView1.DataBind();
//Modified End
my_cn.Close();
while (dr.Read()==true)
    {
        GridView1.DataSource = dt;
        GridView1.DataBind();

    }

你错过了

GridView1.DataBind();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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