Search code examples
c#sqlwpfdatagridstring-comparison

How do i make a sql select dynamic string comparison to work?


I´m trying to get the correct string from a wpf datagrid clicked cell that i will use in a sql select statement to a second wpf datagrid. When entering a static string value it will work, but not from a dynamic string. What is wrong with my code?

    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'";
    }

When entering the string in the sql statement it works like a charm, but ofcourse i want the dynamic string returned from the large database work as well.


Solution

  • Please do not concatenate strings in SQL statements. Use parameters. Check your database for the correct data type of the BarCode column.

        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
            }
        }
    

    EDIT Test the strings. Add using System.Diagnostics to use 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");
            }