【问题标题】:Fill combobox from SQL database with specific parameter使用特定参数从 SQL 数据库填充组合框
【发布时间】:2019-06-27 12:28:33
【问题描述】:

我在使用参数从 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: '无效的列名 'some_specific_string'。'

【问题讨论】:

  • SELECT * FROM CLIENT where cod_cli="some_specific_string" in this line "cod_cli" 此列在您的表中未找到。检查查询是否在 sql 中正确执行。
  • 查询是正确的,因为在 winform 中它可以正常工作并采用正确的值。
  • 我在 sql server manager 上执行,它可以工作,问题出在 wpf 我无法理解为什么它在 Winform 上工作,而不是在 wpf 上,代码是相同和相同的查询
  • 它是一个 SqlException 它与 wpf 无关。大多数情况下,您正在尝试针对错误的数据库。确保它在 wpf 和 winforms 中都连接到相同
  • 我找到了解决方案SqlConnection sqlConnection = new SqlConnection(Properties.Settings.Default.constring.ToString())) { SqlCommand sqlCmd = new SqlCommand("SELECT * FROM CLIENT where cod_cli='cod_of_client''", sqlConnection); sqlConnection.Open(); SqlDataReader sqlReader = sqlCmd.ExecuteReader(); while (sqlReader.Read()) { COMBOBOX!.Items.Add(sqlReader["FN"].ToString()); } sqlReader.Close(); }

标签: c# wpf


【解决方案1】:

解决办法是

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 参数它可以工作。

【讨论】:

    【解决方案2】:
    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 查询中的现有列

    【讨论】:

    • 欢迎来到 Stack Overflow;请添加关于您建议的解决方案的解释,特别是为什么您认为它比已经提供的解决方案更好;这将帮助人们从您的回答中获得最大收益
    猜你喜欢
    • 2012-09-11
    • 1970-01-01
    • 2014-07-29
    • 1970-01-01
    • 1970-01-01
    • 2015-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多