0

My overall goal is to be able to type in information into my textbox and click a button to search and get results from the database using gridview. So far I have my SqlDataSource SQL statement set up. I need to figure out how to link my button on click event with my SqlDataSource and Textbox.

Here is what I have so far:

 protected void Button1_Click(object sender, EventArgs e)
 {
     SqlConnection connection = new SqlConnection("Data Source=********;Initial Catalog=*******;User ID=*******;Password=*******");
     connection.Open();
 }

I am not sure how to use my SqlDataSource that I have already set up.

Updated Code:

SqlConnection sqlCon = new SqlConnection("*******");
        SqlDataAdapter dt = new SqlDataAdapter();
        DataSet ds = new DataSet();
        try
        {
            sqlCon.Open();
            dt.SelectCommand = new SqlCommand("SELECT* FROM  Core.Form_Section_SubSection_Item_Rel WHERE ([DataCollectionPeriodID] = @DataCollectionPeriodID)", sqlCon);
            dt.Fill(ds);
            sqlCon.Close();
            GridView1.DataBind();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
2
  • Are you getting data with a stored procedure? Commented Jun 17, 2014 at 13:16
  • @paabobo No Just a simple SQL select from where statement Commented Jun 17, 2014 at 13:22

1 Answer 1

1

I will advice you use are stored proc with a parameter and do something like below but you can change this to use your select query, just change commandtype

  using (SqlConnection sqlCon = new SqlConnection("connection string")) 
{ 

 using (SqlCommand cmd = new SqlCommand()) 
{ 
 sqlCon.Open(); 
 cmd.Connection = sqlCon; 
  cmd.CommandType = CommandType.Text; 
 cmd.CommandText = "SELECT* FROM Core.Form_Section_SubSection_Item_Rel WHERE         DataCollectionPeriodID = @DataCollectionPeriodID"; 
 cmd.CommandTimeout = 30; 
cmd.Parameters.Add("@DataCollectionPeriodID", SqlDbType.VarChar).Value = TextBox1.Text 
SqlDataAdapter dt = new SqlDataAdapter(cmd); 
DataSet ds = new DataSet(); 
 dt.Fill(ds); 

if (ds.Tables.Count > 0) 
{ 
 if (ds.Tables[0].Rows.Count > 0) 
 { 
 GridView1.DataSource = ds; 
  GridView1.DataBind(); 
 } 
} 
 } 
 }
Sign up to request clarification or add additional context in comments.

6 Comments

Ok so I changed it to use my selectquery but the gridview does not change.
you didnt set gridview.DataSource = ds before doing gridview.DataBind
in my GridView property DataSourceID is already set and when I ran it it said DataSource and DataSourceID cannot be used at the same time.
take the datasouceid out and just do the datasource
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.