Reputation: 39
I've got a problem binding one of my table to GridView. I tried everything but nothing helped. I have a Search button and I want it to show me the result of my search and I've got a DropDownList which binds to another table.
Here's the code:
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();
Nothing happens when I click the button I know that there is something wrong with my C# code but I am unable to Identify it. Appreciate any comment.
Upvotes: 0
Views: 51
Reputation: 930
This should be the corrected code
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();
Upvotes: 1
Reputation: 21795
Try this:- You are missing DataBind
method, apart from this I don't know why you are calling DataReader
again, have removed that code too. Also, Please use paramaterized query to prevent SQL Injection. Something like:- 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();
Upvotes: 2
Reputation: 2328
while (dr.Read()==true)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
Upvotes: 0