我的问题是我不知道如何将sql数据库与c#代码链接,但我想要做的是将搜索查询发送到我的sql数据库并将结果显示回数据网格视图。我的问题在于返回并显示数据。下面是我在搜索按钮点击事件方法中创建的搜索方法:
// takes one of the parameters and searches the data base for all rows that match the parameter and argument
private void SearchBTN_Click(object sender, EventArgs e)
{
switch(searchCB.SelectedIndex)
{
case 0:
selectedItem = "HaulerName";
break;
case 1:
selectedItem = "TicketNumber";
break;
case 2:
selectedItem = "LeaseName";
break;
case 3:
selectedItem = "TicketDate";
break;
case 4:
selectedItem = "CustomerName";
break;
case 5:
selectedItem = "LeaseOperator";
break;
case 6:
selectedItem = "ProductName";
break;
}
if (selectedItem.Equals("TicketDate") == false)
{
query = "SELECT * FROM DisposalData.dbo.ThirdPartyDisposal WHERE " + selectedItem + " LIKE '" + searchTB.Text.ToString() + "%';";
var connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader reader = command.ExecuteReader();
}
}
我运行调试器,它工作正常并执行我只是不能为我的生活弄清楚如何将结果放在数据网格视图表中。任何帮助和尽可能多的解释都会很棒,非常感谢!
答案 0 :(得分:0)
您应该阅读SQL Injection。要使用的代码替换此
sqlDataReader reader = command.ExecuteReader();
带
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "ss");
dataGridView1.DataSource = ds.Tables["ss"];
如果使用webforms添加此行,则在winforms中忽略它
dataGridView1.DataBind();