【问题标题】:comboBox.SelectedItem problemcomboBox.SelectedItem 问题
【发布时间】:2011-09-06 17:15:08
【问题描述】:

ComboBox 正在绑定数据库

string str= comboBox1.SelectedItem.ToString();

该行为str 提供了System.Data.DataRowView 的值,但没有给出所选项目的名称。

【问题讨论】:

    标签: c# winforms visual-studio-2010 combobox


    【解决方案1】:

    在分配DataSource 之前,使用组合框的DisplayMemberValueMember 属性,并使用SelectedValue 而不是SelectedItem

    例如,如果您有一个 List<MyClass> - 其中 MyClass 有一个属性 int ID 和另一个 string Title - 并且您想将其分配为 comboBox1DataSource,您应该写:

    List<MyClass> myList; 
    ...
    
    comboBox1.DisplayMember = "Title";
    comboBox1.ValueMember = "ID";
    comboBox1.DataSource = myList;
    

    现在comboBox1.SelectedValueobject{int},可以转换为int 并使用。

    【讨论】:

    • 这给出了索引但没有写入内容
    • 那个是SelectedIndex,我说的是选择值
    • private void comboBox3_SelectedIndexChanged(object sender, EventArgs e) { label2.Text = comboBox3.SelectedItem.ToString(); }
    • 标签给 {System.Data.DataView}
    • @Maziar sharon 似乎想使用组合框的选定项目来填充带有文本的标签......问题不在于组合框本身的数据绑定......它也是该标签的数据绑定,或从所选项目中获取所需的文本
    【解决方案2】:

    ToString() 继承自 Object-Class。默认实现说明对应对象的类名。

    您可能希望将 SelectedItem 转换为 DataRowView 以访问该行的列值

    例如:

    String str = ((DataRowView)comboBox1.SelectedItem)["ColumnNameHere"];
    

    【讨论】:

      【解决方案3】:

      如果您想要所选项目的文本,只需使用comboBox1.Text

      【讨论】:

        【解决方案4】:

        试试这个

        if (comboBox1.SelectedItem is DataRowView) {
          string sval = ((DataRowView)comboBox1.SelectedItem).Row["ColumnName"].ToString();
        }
        

        【讨论】:

          猜你喜欢
          • 2012-12-19
          • 2011-10-14
          • 1970-01-01
          • 1970-01-01
          • 2017-02-10
          • 2021-08-21
          • 2010-10-25
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多