【发布时间】:2021-09-11 09:12:18
【问题描述】:
我正在尝试通过另一种形式在组合框中添加用户选择的新值,用户必须将所需的值写入文本框。我还想检查如果值已经存在,会显示一条错误消息并且没有添加任何值。
在带有要更新的组合框的表单中我写了这个方法:
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);
}
第二个问题来了:如果我尝试评论所有块以检查产品存在,它无论如何都不会添加它,所以在这个意义上可能存在第二个错误。
【问题讨论】:
-
这可能会有所帮助。看看这个 - stackoverflow.com/questions/45327125/…
-
new Form1()是访问现有表单的错误方式。您需要以某种方式传递/提供可用实例。理想情况下,您不应该直接处理视图,列表应该位于具有所有功能的模型中,并且都可以访问模型实例。 -
this related (but not duplicate) thread 中的一些答案可能会有所帮助。
-
您必须在 btnConfirmNewProduct_Click 所在的表单中创建一个 Form1 作为类字段(私有 Form1 frm1)。显示 frm1,只有这样所有其他 Form1 控件才能正确实例化和填充。然后调用 getProducts() 并根据需要隐藏或销毁 form1。
标签: c# winforms methods windows-forms-designer