在c#的组合框中添加两个数组的值

本文关键字:两个 数组 添加 组合 | 更新日期: 2023-09-27 17:50:40

我的WFA中有一个组合框。我希望它在组合框中显示项目名称和价格。商品名称和价格存储在数据库表的两个不同列中。

string qw = "select wine from cms.menulist";
        MySqlDataAdapter da = new MySqlDataAdapter(qw, mycon);
        DataTable dt1 = new DataTable();
        da.Fill(dt1);
        foreach (DataRow row in dt1.Rows)
        {
            string wine = string.Format("{0}", row.ItemArray[0]);
            comboBox1.Items.Add(wine); 
        }

我使用上面的代码来检索组合框中的项目名称。因此,每当我在数据库中添加项时,组合框中的项就会相应更新。

现在连同项目名称(即葡萄酒在这种情况下),我还希望它的价格显示在项目名称旁边。价格存储在同一个表中,但存储在名为wine_price的不同列中。

例如,我希望组合框的选项如下

redwine 20美元白葡萄酒$40

在c#的组合框中添加两个数组的值

假设您有一个表示名称和价格的类,您可以简单地重写ToString,然后添加该类的实例:

public class NameAndPrice
{
    public string Name { get; set; }
    public double Price { get; set; }
    public override string ToString()
    {
        return String.Format("{0}: {1:c}", Name, Price);
    }
    public override int GetHashCode()
    {
        return ToString().GetHashCode();
    }
}
NameAndPrice a = new NameAndPrice() { Name = "Hello", Price = 1.25d };
comboBox1.Items.Add(a);

因此,对于数据库表中的每一行,创建一个NameAndPrice实例并将其添加到ComboBox中。