Visual Studio 2008 - SQL statement to update datagridview
I've got a datagridview object that shows that shows the data from an SQL database. When a user searches by Customer ID I want the datagridview to show the correct record. So far I have the code below but it doesn't work, i'm not exactly sure if i'm on the right path, any ideas?
private void btnCustomerID_Click(object sender, EventArgs e)
{
if (txtCustomerID.TextLength == 0)
{
MessageBox.Show("Please enter a Customer ID to search by Customer ID");
txtCustomerID.Focus();
}
else
{
String ID = txtCustomerID.Text;
开发者_开发知识库 String sqlQuery = (sqlCommandCustomer.CommandText = ("SELECT * FROM Customers WHERE [CustomerID] LIKE ID"));
dgCustomers.DataSource = sqlQuery;
}
}
Ignoring SQL injection and even passing parameters to the query.
Your basic issue is you know what you WANT to do, but aren't sure how to express it in code.
Pseudo Code:
1. Get the ID you want to filter for.
2. Pass the ID to a SQL statement.
3. Open a connection to the database.
4. Execute the SQL via a SQL command.
5. Store the result.
5. Close the open connection.
6. Databind the results to your datagrid.
I don`t think you can do that. What I would do is put the intial query in to a datatable and filter that using the select method. For you reference: http://msdn.microsoft.com/en-us/library/system.data.datatable.select.aspx
For one thing, you'd need to change
WHERE [CustomerID] LIKE ID
to either
WHERE [CustomerID] = ID
or
WHERE [CustomerID] LIKE %ID%
精彩评论