Nima Sharify
Nima Sharify

Reputation: 39

how to bind the gridview?

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

Answers (4)

Rama Kathare
Rama Kathare

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

Dhaval
Dhaval

Reputation: 2379

you missed this

GridView1.DataBind();

Upvotes: 0

Rahul Singh
Rahul Singh

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

shrekDeep
shrekDeep

Reputation: 2328

while (dr.Read()==true)
    {
        GridView1.DataSource = dt;
        GridView1.DataBind();

    }

Upvotes: 0

Related Questions