我遇到了将我的一个表绑定到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#代码有问题,但我无法识别它。 感谢任何评论。
答案 0 :(得分:2)
试试这个: - 您缺少DataBind
方法,除此之外,我不知道您再次呼叫DataReader
的原因,也删除了该代码。另外,请使用参数化查询来阻止SQL Injection。类似于: - 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();
答案 1 :(得分:1)
这应该是更正后的代码
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();
答案 2 :(得分:0)
while (dr.Read()==true)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
答案 3 :(得分:0)
GridView1.DataBind();