Trying to use a txtbox to input a number for a sql query in VS 2012 C#

Hello, I am creating a Windows Form App that the user will input info into a form and then generate a letter based on the information. I also need for them to be able to lookup these at a later date by a few options (Name, tracking number, amount).

The input form works well the info is going into the DB, but with the windows form and the datagridview. I cant lookup the way I want to it seems to just return all the data.

For example I want to use a text Box to input a tracking number and then return the data for that one row.
riley00Asked:
Who is Participating?
 
Kyle AbrahamsSenior .Net DeveloperCommented:
So that would look something like:
SqlConnection conn = new SqlConnection(myConnString);
SqlCommand cmd = new SqlCommand("select * from tracking_table where tracking_number = @tracking_number", conn);

cmd.Parameters.Add(new SqlParameter("@tracking_number", txtTrackingNumber.text));

try
{
   conn.Open();
   DataReader dr = conn.ExecuteReader();
   if (dr.Read())
   {
     // process dr
   }
}
catch (Exception ex)
{
  // handle errors.
}
finally
{
 conn.Close();
}

Open in new window

0
 
riley00Author Commented:
Sorry, I think I get what this code but not sure how to get the gridview to show results of this. I think I have tried to many things and I am just confused right now. Sorry.
0
 
Kyle AbrahamsSenior .Net DeveloperCommented:
Your grid view needs a datasource.

So in your process DR you would put that into a datatable, and from there set the gridview's datasource to a table.

eg:

 // process dr

while (dr.Read())
{
    DataRow row = dataTable.NewRow();
   row["Column1"] = dr["Column1"];
   // add additional columns
   dataTable.Rows.Add(row);
}
GridView.DataSource = dataTable;
GridView.DataBind();

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.