c# - 从第二种形式将项目添加到列表框

标签 c# listbox

我正在尝试从另一个表单向列表框添加项目。 Form1 有一个带有“虚拟”项目的列表框,当我尝试从该表单添加更多项目时,一切正常。但是,当我尝试从不同的表单 (AddContact.cs) 添加项目时,没有添加任何项目。我将提供两种形式的代码。

PS:列表框设置为公共(public),以便能够从 Form1 外部访问它。

表格 1:

    public Form1()
    {
        InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        list_names.Items.Add("Dummy");
    }

    private void btn_check_Click(object sender, EventArgs e)
    {
        if (list_names.SelectedItem == null)
        {
            MessageBox.Show("No item has been selected.", "Error",
                MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        else if (list_names.SelectedItem.ToString() == "Dummy")
        {
            //Dummy code for testing
            MessageBox.Show("Dummy has been selected!");
        }
    }

    private void btn_add_Click(object sender, EventArgs e)
    {
        new AddContact().Show();
    }

    private void btn_remove_Click(object sender, EventArgs e)
    {
        //TODO: Remove items from listbox
    }

添加联系人:

    Form1 form;

    public AddContact()
    {
        InitializeComponent();
        form = new Form1();
    }

    private void btn_add_Click(object sender, EventArgs e)
    {
        if (textBox1.Text == string.Empty)
        {
            MessageBox.Show("No input has been given.");
        }
        else
        {
            //This doesn't work
            string s = textBox1.Text;
            form.list_names.Items.Add(s);
            textBox1.Text = "";
        }
    }

最佳答案

问题是您在 AddContact 中创建新表单,您需要引用 Form1

Form1 form;

public AddContact(Form1 frm)
{
    InitializeComponent();
    form = frm;
}

还有

private void btn_add_Click(object sender, EventArgs e)
{
    new AddContact(this).Show();
}

关于c# - 从第二种形式将项目添加到列表框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12818581/

相关文章:

c# - 如何更改列表框中项目的名称/字符串?

mvvm - RaisePropertyChanged不适用于ObservableCollection

c# - PowerShell,读/写 SSH.NET 流

c# - Mahapps,不适用于用户控件的主题

c# - JsonServiceClient 不使用放置在 cookiecontainer 中的 cookie

c# - WPF ListBox 在用户滚动时生成项目

c# - WPF ListBox,SelectedIndex 不是突出显示的行

c# - 仅当 switch 语句未达到默认情况时才可以中断它吗?

c# - 通过套接字 API 将 C 结构体传输到 C# 结构体

c# - asp.net 中的列表框未获取选定的项目