【问题标题】:Displaying 2 columns in one combobox在一个组合框中显示 2 列
【发布时间】:2013-08-07 14:56:54
【问题描述】:

我有一张员工表。我希望组合框显示员工编号和城市。

SqlCommand cmd = new SqlCommand();
Connection c = new Connection();
cmd.CommandText = "SELECT employeeNumber, city FROM tblEmployee";

SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds, "Employee");

comboBox1.DataSource = ds;

这就是我目前所得到的,有人可以帮我吗?

【问题讨论】:

标签: c# winforms


【解决方案1】:

您可以将 Format 事件添加到您的 ComboBox,并在其中组合您想要显示的任何内容:

private void _Combobox1_Format(object sender, ListControlConvertEventArgs e)
{
    var x = (DateFilterType)e.ListItem;
    e.Value = /* insert string concatenation stuff here... */;
}

【讨论】:

    【解决方案2】:

    您可以在您绑定到组合框的类上覆盖.ToString()

    class MyClass
    {
        public override string ToString()
        {
            return thing1.PadRight(10) + thing2.PadRight(10);
        }
        public string thing1 { get; set; }
        public string thing2 { get; set; }
    }
    

    如果你做类似的事情

    List<MyClass> mc = new List<MyClass>();
    mc.Add(new MyClass() { thing1 = "blah1", thing2 = "blah2});
    
    comboBox1.DataSource = mc;
    

    comboBox1 中显示的文本是blah1 blah2(我们将这里的格式去掉我所有的空格,但这些字符串应该被填充)

    然后你可以使用你想要的任何值

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
       label1.Text = ((MyClass)comboBox1.SelectedItem).ToString();
    }
    

    无需设置值成员

    【讨论】:

      【解决方案3】:

      在您的数据表中,使用表达式添加第三列。在最后一列中连接另外两列。

      查看this 以获取表达式参考。

      在此之后使用第三列绑定您的组合框。

      【讨论】:

      • @user2023203 我觉得这个link here on SO和你很像
      • @Brad 我从来没有谈过修改数据库...我谈到了数据表
      猜你喜欢
      • 1970-01-01
      • 2021-08-16
      • 2012-01-22
      • 1970-01-01
      • 2014-07-03
      • 2014-12-20
      • 1970-01-01
      • 1970-01-01
      • 2012-07-30
      相关资源
      最近更新 更多