C#在另一个表单的comboBox中添加新值



我试图通过另一种形式在组合框中添加用户选择的新值,用户必须在其中将所需值写入文本框。我还想检查一下,如果该值已经存在,是否会显示一条错误消息,并且没有添加任何值。

在表格中用combobox更新我写了这个方法:

public ArrayList getProducts() //to get all the products into an ArrayList and check if product to add already exists, but i get a cast error
{
return (ArrayList)cbbProducts.Items.Cast<ArrayList>();
}

//this is made in order to add the product to the combobox
public void addProductInCbb(string newProduct)
{
cbbProducts.Items.Add(newProduct);
}

这里我得到了第一个错误:我无法正确地将所有值强制转换到ArrayList中。在addProduct形式中;确认";按钮,我有:

private void btnConfirmNewProduct_Click(object sender, EventArgs e)
{   
Order o = new Order(new Form1()); //don't know if access is made correctly...
String newProduct = txtNewProduct.Text;
bool found = false;
ArrayList products = o.getProducts(); //cast error
foreach(String product in products)
{
if (product.Equals(newProduct)) found = true;
}
if (!found)
{
o.addProductInCbb(newProduct);
MessageBox.Show("Success!","", MessageBoxButtons.OK, MessageBoxIcon.Information);
//}  
//else MessageBox.Show("Error! Product already exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

}

第二个问题来了:如果我试图评论所有的块来检查产品的存在,它无论如何都不会添加它,所以在这个意义上可能还有第二个错误。

表格1中的按钮1_Click事件:

private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2(comboBox1.SelectedItem.ToString());
if (!form2.IsClose)
{
form2.ShowDialog();
}
}

在表格2中添加该代码

public partial class Form2 : Form
{
public bool IsClose;
public Form2(string Item)
{
InitializeComponent();
AddNewItem(Item);
}
private void AddNewItem(string Item)
{
if (!comboBox1.Items.Contains(Item))
{
comboBox1.Items.Add(Item);
}
else
{
MessageBox.Show("error message is displayed and no value is added.");
IsClose = true;
this.Close();
}
}
}

最新更新