C# 使用特定参数从SQL数据库填充组合框

C# 使用特定参数从SQL数据库填充组合框,c#,wpf,C#,Wpf,我无法使用参数从sql server获取特定值。有人能解释一下为什么它在winfom上工作,而在wpf上不工作,以及我如何修复它吗 我的代码: private void UpdateItems() { COMBOBOX1.Items.Clear(); SqlConnection conn = new SqlConnection(Properties.Settings.Default.constring.ToString()); SqlDataAdapte

我无法使用参数从sql server获取特定值。有人能解释一下为什么它在winfom上工作,而在wpf上不工作,以及我如何修复它吗 我的代码:

private void UpdateItems()
{
       COMBOBOX1.Items.Clear();
       SqlConnection conn = new SqlConnection(Properties.Settings.Default.constring.ToString());
       SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM CLIENT where cod_cli='some_specific_string'", conn);
       DataSet ds = new DataSet();
       da.Fill(ds, "CLIENT");
       COMBOBOX1.ItemsSource = ds.Tables[0].DefaultView;
       COMBOBOX1.DisplayMemberPath = ds.Tables[0].Columns["FR"].ToString();
       COMBOBOX1.SelectedValuePath = ds.Tables[0].Columns["FC"].ToString(); 
}
执行此函数时,程序会因错误而崩溃:

System.Data.SqlClient.SqlException:'列名无效 “某些特定字符串。”

解决办法是

SqlConnection sqlConnection = new SqlConnection(Properties.Settings.Default.constring.ToString());
{
    SqlCommand sqlCmd = new SqlCommand("SELECT * FROM CLIENTS where cod_cli=@cod", sqlConnection);
    sqlCmd.Parameters.AddWithValue("@cod", cod_cli.Text);
    sqlConnection.Open();
    SqlDataReader sqlReader = sqlCmd.ExecuteReader();

    while (sqlReader.Read())
    {
        COMBOBOX1.Items.Add(sqlReader["FR"].ToString());
    }

    sqlReader.Close();
}
该查询不将字符串识别为参数,而是将其添加为SQL参数

SqlConnection conn = new SqlConnection(Properties.Settings.Default.constring.ToString());
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM CLIENT where cod_cli="some_specific_string", conn);
DataSet ds = new DataSet();
da.Fill(ds, "CLIENT");

//Populate the combobox
COMBOBOX1.ItemsSource = ds.Tables[0].DefaultView;
COMBOBOX1.DisplayMemberPath = "FR";`enter code here`
COMBOBOX1.SelectedValuePath = "FC";

where
“FR”和“FC”是您的
SELECT
Query

SELECT*FROM CLIENT,其中此行“cod\u cli”中的cod\u cli=“some\u specific\u string”在您的表中找不到该列。检查查询是否在sql中正确执行。查询是正确的,因为在winform中它工作正常,并采用正确的值。我在sql server manager上执行,它工作正常问题是在wpf上。我无法理解为什么它在winform上工作,而在wpf上不工作。代码是相同的,相同的查询是SqlException它与wpf无关。大多数情况下,您是在尝试错误的数据库。确保它在wpf和WinForm中连接到相同的位置。我找到解决方案
SqlConnection SqlConnection=new SqlConnection(Properties.Settings.Default.constring.ToString()){SqlCommand sqlCmd=new SqlCommand(“SELECT*FROM CLIENT where cod_CLIENT='cod_of_CLIENT'',SqlConnection);SqlConnection.Open();SqlDataReader sqlReader=sqlCmd.ExecuteReader();while(sqlReader.Read()){COMBOBOX!.Items.Add(sqlReader[“FN”].ToString();}sqlReader.Close();}
欢迎使用堆栈溢出;请说明您建议的解决方案,特别是为什么您认为它比已经提供的解决方案更好;这将帮助人们从你的答案中获得最大的好处