我正在尝试从wpf datagrid单击的单元格中获取正确的字符串,该单元格将在sql select语句中用于第二个wpf datagrid。 当输入静态字符串值时,它将起作用,但不能从动态字符串中起作用。我的代码有什么问题?
private void dataGrid1_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
DataRowView row = (DataRowView)dataGrid1.SelectedItems[0];
string barcode_string = row["BarCode"].ToString();
//string barcode_detail = "SELECT BarCode, PCBGUID FROM TB_AOIResult WHERE BarCode = '" + barcode_string + "'";
string barcode_detail = "SELECT BarCode, PCBGUID FROM TB_AOIResult WHERE BarCode = 'L002BO4'";
}
在sql语句中输入字符串时,它的工作原理就像一个超级按钮,但是我当然也希望大型数据库返回的动态字符串也能正常工作。
答案 0 :(得分:0)
您在查询的最后一个错过了一个"
。试试这个
string barcode_detail = "SELECT BarCode, PCBGUID
FROM TB_AOIResult WHERE
BarCode = "+"\'" +barcode_string + "\'";
答案 1 :(得分:0)
请不要在SQL语句中连接字符串。使用参数。检查数据库中“条形码”列的正确数据类型。
private void DataGrid1_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
DataTable dt = new DataTable();
DataRowView row = (DataRowView)dataGrid1.SelectedItems[0];
string barcode_string = row["BarCode"].ToString();
//string barcode_detail = "SELECT BarCode, PCBGUID FROM TB_AOIResult WHERE BarCode = '" + barcode_string + "'";
string barcode_detail = "SELECT BarCode, PCBGUID FROM TB_AOIResult WHERE BarCode = @BarCode;";
using (SqlConnection cn = new SqlConnection("Your connection string"))
{
SqlCommand cmd = new SqlCommand(barcode_detail, cn);
cmd.Parameters.Add("@BarCode", System.Data.SqlDbType.VarChar).Value = barcode_string;
cn.Open();
dt.Load(cmd.ExecuteReader());
//use the data in the data table
}
}
编辑
测试字符串。添加using System.Diagnostics
以使用Debug.Print
String literal = "L002BO4";
String variable = row["BarCode"].ToString();
if (literal.Length == variable.Length)
Debug.Print("The length of the strings match");
else
Debug.Print("The lengths do not match");
Char[] variableArray = variable.ToCharArray();
Char[] literalArray = literal.ToCharArray();
for (int index =0; index<literalArray.Length; index++)
{
if (variableArray[index] == literalArray[index])
Debug.Print($"index {index} matches");
else
Debug.Print($"index {index} does not match");
}
答案 2 :(得分:-1)
您能尝试以下吗
string barcode_detail = "SELECT BarCode, PCBGUID FROM TB_AOIResult WHERE BarCode = "+ barcode_string;