【问题标题】:Getting the ID of selected item in Combobox windows form在组合框窗口窗体中获取所选项目的 ID
【发布时间】:2012-07-29 15:26:30
【问题描述】:

我正在开发一个 C# Windows 窗体应用程序。我想在组合框中获取所选项目的 ID。下面是我的代码。

  private void ProductForm_Shown(object sender, EventArgs e)
    {
        SqlCeConnection Connection = new SqlCeConnection(ConString);
        Connection.Open();
        SqlCeDataAdapter da = new SqlCeDataAdapter("Select * from CastingMaterial", Connection);
        DataTable dt = new DataTable();
        da.Fill(dt);
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            ProductsComboBox.Items.Add(dt.Rows[i]["PartName"]);

        }
        ProductsComboBox.DisplayMember = "PartName";
        ProductsComboBox.ValueMember = "PartId";
        Connection.Close();
    }

    private void ProductsComboBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        int ProductIndex = ProductsComboBox.SelectedIndex;
        string productName = ProductsComboBox.Text.ToString();
        int ProductId =Convert.ToInt32(ProductsComboBox.SelectedValue);
        SqlCeConnection Connection = new SqlCeConnection(ConString);
        Connection.Open();
        String Query = "SELECT * From CastingMaterial where PartId=@PartId";
        SqlCeDataAdapter da = new SqlCeDataAdapter(Query, Connection);
        da.SelectCommand.Parameters.AddWithValue("PartId", ProductId);
        DataSet ds = new DataSet();
        SqlCeCommandBuilder commandBuilder = new SqlCeCommandBuilder(da);

        BindingSource bsource = new BindingSource();

        da.Fill(ds, "CastingMaterial");
        bsource.DataSource = ds.Tables["CastingMaterial"];
        Productgv.DataSource = bsource;
        Connection.Close();
    }

任何帮助将不胜感激。

【问题讨论】:

    标签: visual-studio-2010 c#-4.0


    【解决方案1】:

    您应该将项目添加为 DataRows。相反,您是从其中一列中提取值:

     ProductCombo.Items.Add( dt.Rows[i] );
    

    然后您正确设置了 DisplayMember 和 ValueMember,但是由于您错误地添加了项目,这没有任何效果。

    【讨论】:

      【解决方案2】:

      坦率地说,您需要更清楚地发布问题。

      您希望如何获取组合框的选定 ID?
      您打算将该 ID 用于什么目的?

      我认为您应该在这里更清楚地描述您的实际问题。 因为,代码对我来说似乎工作正常。

      而且,顺便说一句,您实际上不需要循环来设置组合框的数据项。您只需将组合的 DataSource 属性分配给您刚刚提取数据的 DataTable。

      ProductsComboBox.DataSource = dt ...工作得很好,你知道!
      然后,您可以将DisplayMemberValueMember 设置为各自的列。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-13
        • 2014-01-13
        • 1970-01-01
        相关资源
        最近更新 更多