【问题标题】:Populate a combobox with array information使用数组信息填充组合框
【发布时间】:2014-11-21 03:59:24
【问题描述】:

我正在尝试使用另一个类中的数组的 PART 填充 ComboBox。我必须制作一个创建客户、库存和订单的应用程序。在订单表单上,我试图分别从客户和库存类中的数组中提取客户 ID 和库存 ID 信息。数组中包含多种类型的信息:客户 ID、姓名、地址、状态、邮编等;库存 ID、名称、折扣值和价格。

我的数组是这样设置的:

public static Customer[] myCustArray = new Customer[100];

public string customerID;
public string customerName;
public string customerAddress;
public string customerState;
public int customerZip;
public int customerAge;
public int totalOrdered;

这就是我的组合框的设置方式:

public void custIDComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    custIDComboBox.Items.AddRange(Customer.myCustArray);

    custIDComboBox.DataSource = Customer.getAllCustomers();
}

【问题讨论】:

  • 你能给我们看看代码吗?
  • 您希望来自两个不同数组的值进入同一个 ComboBox 还是不同的 ComboBox?另外,这适用于 ASP.Net、WPF 还是 WinForms?
  • @mahditahsildari 我不知道哪些部分是完全相关的。我已经像上面那样设置了我的数组。输入客户时,我正在尝试获取数组中的 customerID 字符串元素。
  • @MauriceReeves 两个单独的组合框。我相信 WinForms。我正在使用 Visual Studio 上课。
  • 非常好,然后按照下面@Mortalus 的示例进行操作。他为您提供保障。

标签: c# arrays combobox


【解决方案1】:

使用数据绑定。

提供一个现有的对象数组(在您的情况下为“客户”),定义如下:

public static Customer[] myCustArray = new Customer[100];

将数组定义为数据源,如下所示:

BindingSource theBindingSource = new BindingSource();
theBindingSource.DataSource = myCustArray;
myComboBox.DataSource = bindingSource.DataSource;

然后您可以像这样设置每个项目的标签和值:

//That should be a string represeting the name of the customer object property.
myComboBox.DisplayMember = "customerName";
myComboBox.ValueMember = "customerID";

就是这样。

【讨论】:

  • 您必须调用什么系统才能使用 DataLabel 和 DataValue 方法?
  • 我搞错了,组合框的属性是DataValueFieldDataTextField,你应该使用System.Web.UI.WebControls.DropDownList
  • @Mortalus 这不是网络应用程序
  • 你可以使用相同的'System.Windows.Forms.ComboBox' 我将在几秒钟内更改示例以适应..
  • 查看为 Win 表单编辑
【解决方案2】:
Customer.myCustArray[0] = new Customer { customerID = "1", customerName = "Jane" };  
Customer.myCustArray[1] = new Customer { customerID = "2", customerName = "Jack" };

你不需要上面两行,我添加它们来查看输出,以下代码生成 ComboBox 项:

foreach (Customer cus in Customer.myCustArray)
{
    comboBox1.Items.Add("[" + cus.customerID + "] " + cus.customerName);
}

您可以将此代码复制到相应的事件中,例如它可以是FormLoad,如果您希望每次激活表单时刷新组合框的项目,您可以这样做:

private void Form3_Activated(object sender, EventArgs e)
{
    comboBox1.Items.Clear();
    foreach (Customer cus in Customer.myCustArray)
    {
        comboBox1.Items.Add("[" + cus.customerID + "] " + cus.customerName);
    }
}

【讨论】:

  • 不,我有一个单独的表单来通过文本框添加客户。名称和其他所有内容都存储在上面的数组中。
  • 我已经有了数组,我只需要访问所有客户的索引 [0](我已设置为客户 ID)并将其显示到单独表单上的组合框中。
  • 然后只需将此代码用于 (int i = 0; i
  • @kovilpattiCsharper 我已经像在最初的问题中那样设置了数组。如何使用这样创建的数组专门调用 ID?
  • @mahditahsildari 我会用什么方法?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-25
  • 1970-01-01
  • 2013-06-22
  • 2011-11-20
  • 1970-01-01
  • 1970-01-01
  • 2019-07-28
相关资源
最近更新 更多