【问题标题】:Binding a ListBox with ValueMember将 ListBox 与 ValueMember 绑定
【发布时间】:2013-12-14 14:58:06
【问题描述】:

我扩展了 ListBox 以构建我的 CustomListbox。

它将接受类对象数组作为数据源,我重写 OnDrawItem() 以通过读取类对象数组来显示它们。

到目前为止,一切正常。问题是我无法读取列表框的 ValueMember,因为我没有分配它。我想将我的 classObject 的属性之一添加为值成员

伪代码:

public class myModel
{
  int id;
  string name;
  XXXXXXXXX
  XXXXXXXXX
}

myModel[] ds = getData();
//myCustomListbox.ValueMember = "id";   //this doesnt seem to work
myCustomListbox.DataSource =ds;

我再说一遍,OnDrawItem() 将绘制所需的显示值。有什么方法我可以像这样重写来添加值项吗?

【问题讨论】:

    标签: c# .net winforms


    【解决方案1】:

    绑定仅适用于属性。将您的字段更改为属性(并确保它是公共的 - 默认情况下,类成员是私有的)

    public class myModel
    {
       public int id { get; set; }
       public string name { get; set; }
       // ...
    }
    

    现在一切都应该好了:

    myModel[] ds = getData();
    myCustomListbox.ValueMember = "id";
    myCustomListbox.DataSource = ds;
    

    BTW C# naming guidelines 建议对属性、方法和类型名称使用 Pascal 名称。

    【讨论】:

    • @Rams 您的财产是否标记为公开?您还可以展示您是如何阅读价值成员的吗?
    • 是的,它们都是公开的,并且 a 的值始终为空(也单击项目后)string a = myCustomListBox.ValueMember 在 SelectedIndexChanged 事件中
    • @Rams 确保已将 ValueMember 分配给适当的列表框。此代码应该可以正常工作 - 在选定的索引更改时,您应该看到 ValueMember 等于 "id"SelectedValue 应该是选定模型的 id
    • 不知道为什么这不起作用。我现在正在处理这个。 MyModel mod= (MyModel)myCustomListbox.SelectedItem; string a= mod.id;
    • @Rams 不清楚你在做什么。 mod.id 是整数,您正在尝试将其分配给字符串
    【解决方案2】:

    ListBox 与 C# 中的数据表(在 Windows 应用程序中)绑定是添加值成员所必需的。

    如果我们把没有值成员的代码写成如下,

     private void button1_Click(object sender, EventArgs e)
        {
            SqlDataAdapter da = new SqlDataAdapter("select * from Table1",con);
            da.Fill(dt);
    
            listBox1.DataSource = dt;
            // listBox1.ValueMember = "data";  //data is one of the coloumn of the table...
    
        }
    

    上述代码的输出如下所示

    System.Data.DataRowView

    System.Data.DataRowView

    System.Data.DataRowView

    如果我们在如下代码中提供值成员

    private void button1_Click(object sender, EventArgs e)
      {
        SqlDataAdapter da = new SqlDataAdapter("select * from Table1",con);
        da.Fill(dt);
        listBox1.DataSource = dt;
        listBox1.ValueMember = "data";  //data is one of the coloumn of the table...
      }
    

    输出将是...

    表中特定列的列表。这里是“数据”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多