【问题标题】:Winforms comboboxes and parameterized stored procedureWinforms 组合框和参数化存储过程
【发布时间】:2015-05-22 16:07:53
【问题描述】:

在我的 tblSates 表中,我有一个名为 Monat 的列,其中包含这三个值 [01.2016、02.2016 和 03.2016] 我想在组合框中获取这些值。

我得到了这些值,但只是其中两个而不是全部三个。

这是我的代码:

private void FillCombobox2()
{
    string S = ConfigurationManager

    // TSQL-Statement
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;
    cmd.CommandText = ("SELECT DISTINCT Monat from tblSales");            
    SqlDataReader myReader;
    try
    {
        con.Open();
        myReader = cmd.ExecuteReader();
        if (myReader.Read())
        {
            DataTable dt = new DataTable();
            dt.Load(myReader);
            combobox1.DisplayMember = "Monat";
            combobox1.ValueMember = "Monat";
            combobox1.DataSource = dt;
            combobox1.SelectedIndex = -1;
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        con.Close();
    }
}

将不胜感激任何帮助或替代解决方案。

【问题讨论】:

  • cbPeriode1.SelectedValue 为空,显示如何用值填充combobox
  • private void FillCombobox() { string S = ConfigurationManager.ConnectionStrings; SqlConnection con = new SqlConnection(S); SqlCommand cmd = new SqlCommand(); cmd.Connection = con; cmd.CommandText = select distinct Monat from tblSales"); SqlDataReader myReader; try { con.Open(); myReader = cmd.ExecuteReader(); while (myReader.Read()) { cbPeriode1.Items.Add(myReader["Monat"]); }
  • Stackoverflow answer 对您的情况有帮助吗?
  • @Fabio。不幸的是没有
  • 我很伤心,你的cbPeriode1.SelectedValue 是空的。 SelectedValue 在您的情况下将始终为空,因为组合框是通过手动添加项目填充的,而不使用 ValueMember。为什么不能将SelectedItem 用于sql 参数cbPeriode1.SelectedItem.ToString()

标签: c# winforms stored-procedures combobox


【解决方案1】:

我删除了 reader.Read,然后调用 which 提升了位置(并跳过了我的三个记录之一)。或者我可以使用if (myReader.HasRows)

private void FillCombobox2()
{
    string S = ConfigurationManager

    // TSQL-Statement
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;
    cmd.CommandText = ("SELECT DISTINCT Monat from tblSales");            
    //SqlDataReader myReader;
    try
    {
        con.Open();
     SqlDataAdapter ad = new SqlDataAdapter(cmd);
     DataTable dt = new DataTable();
            ad.Fill(dt)             
            combobox1.DisplayMember = "Monat";
            combobox1.ValueMember = "Monat";
            combobox1.DataSource = dt;
            combobox1.SelectedIndex = -1;

        }

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        con.Close();
    }
}

【讨论】:

  • 是您问题中代码的答案还是更新?如果是前者 - 请添加一些解释,如果是后者 - 将更新移至问题。谢谢。
  • 很酷,值得添加一些解释,说明发生了什么变化,以及为什么这些变化解决了原来的问题。可能对后代有用。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-01
  • 2013-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多