My problem is that i dont know enought about linking sql databases with c# code but what im trying to do is send a search query to my sql database and display the results back onto a data grid view. My problem lay within the returning and displaying the data. Below is my search method i created in the search button click event method:
我的问题是我不知道将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();
}
}
ive run the debugger and it works fine and executes i just cant for the life of me figure out how to put the results in the data grid view table. Any help and as much explanation as possible would be great, thanks a bunch!
香港专业教育学院运行调试器,它工作正常并执行我只是不能为我的生活弄清楚如何将结果放在数据网格视图表中。任何帮助和尽可能多的解释都会很棒,多亏一帮!
1 个解决方案
#1
0
You should read into SQL Injection. For code to work Replace this
您应该阅读SQL注入。要使用的代码替换它
sqlDataReader reader = command.ExecuteReader();
with
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"];
if using webforms add this line, in winforms ignore it
如果使用webforms添加此行,则在winforms中忽略它
dataGridView1.DataBind();
#1
0
You should read into SQL Injection. For code to work Replace this
您应该阅读SQL注入。要使用的代码替换它
sqlDataReader reader = command.ExecuteReader();
with
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"];
if using webforms add this line, in winforms ignore it
如果使用webforms添加此行,则在winforms中忽略它
dataGridView1.DataBind();