【问题标题】:C# add new value in comboBox from another formC# 从另一个表单在组合框中添加新值
【发布时间】: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() 是访问现有表单的错误方式。您需要以某种方式传递/提供可用实例。理想情况下,您不应该直接处理视图,列表应该位于具有所有功能的模型中,并且都可以访问模型实例。
  • 这能回答你的问题吗? How to access a form control for another form?
  • this related (but not duplicate) thread 中的一些答案可能会有所帮助。
  • 您必须在 btnConfirmNewProduct_Click 所在的表单中创建一个 Form1 作为类字段(私有 Form1 frm1)。显示 frm1,只有这样所有其他 Form1 控件才能正确实例化和填充。然后调用 getProducts() 并根据需要隐藏或销毁 form1。

标签: c# winforms methods windows-forms-designer


【解决方案1】:

在 form1 中 button1_Click 事件:

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

在 form2 中添加该代码

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();
        }
    }
}

【讨论】:

  • 谢谢!只是一件事,我为什么要输入“isClose=true”?据此,下次我尝试添加新项目时,它不应该显示“form2.ShowDialog();”还是我错了?
  • 你是对的,如果你不需要显示 form2 那么就不需要布尔变量
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多