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

p5fdfcr1  于 2022-11-18  发布在  其他
关注(0)|答案(2)|浏览(112)

我有问题,以获得特定的值从sql服务器与参数谁能解释我为什么它的工作在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:'列名'some_specific_string '无效'

yebdmbv4

yebdmbv41#

其解决方案是

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参数时,该查询可以正常工作。

nzk0hqpo

nzk0hqpo2#

SqlConnection conn = new SqlConnection(Properties.Settings.Default.constring.ToString());
conn.Open();
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";
COMBOBOX1.SelectedValuePath = "FC";

where“FR”和“FC”是SELECT查询中的现有列。

相关问题