简体   繁体   English

列表框SelectedItem从另一个表单编辑

[英]ListBox SelectedItem edit from another form

I tried below code. 我尝试下面的代码。 First I select a listbox item and then I click the edit button for text name change. 首先,我选择一个列表框项目,然后单击“编辑”按钮以更改文本名称。

Form1 Form1中

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void btnOpenForm2_Click(object sender, EventArgs e)
    {
        Form2 f2 = new Form2(this);
        f2.ShowDialog();
    }

    public string ListBoxValue
    {
        get { return listBox1.SelectedItem.ToString(); }
    }
}

Form2 窗体2

public partial class Form2 : Form
{
    Form1 f1;

    public Form2(Form1 f1)
    {
        this.f1 = f1;
        InitializeComponent();
    }

    private void Form2_Load(object sender, EventArgs e)
    {
        textBox1.Text = this.f1.ListBoxValue;
    }
}

Above code works well but after I open form2 for editng the text, it's not updated the same text in listbox selected item. 上面的代码很好用,但是在我打开form2编辑文本后,它没有更新列表框所选项目中的相同文本。 It's added as a new item in listbox. 它作为新项添加到列表框中。

You have nowhere code where you actually change the value of the selected item from the listbox. 您没有任何地方代码可以实际更改列表框中所选项目的值。 You have to move the changes back to Form1 and update the selected item of the listbox. 您必须将更改移回到Form1并更新列表框的所选项目。 You do this through a method SetSelectedItemValue for example: 您可以通过方法SetSelectedItemValue来执行此操作,例如:

Code of Form1 : Form1的代码:

private Form2 _form2;

private void button1_Click(object sender, EventArgs e)
{
    _form2 = new Form2(this);
    _form2.Show();
}

public string ItemValue
{
    get { return listBox1.SelectedItem.ToString(); }
}

public void SetSelectedItemValue(string value)
{
    listBox1.Items[listBox1.SelectedIndex] = value;
}

Code of Form2 : Form2的代码:

public Form2(Form1 form1)
{
    _form1 = form1;
    InitializeComponent();
}

private readonly Form1 _form1;

private void Form2_Load(object sender, EventArgs e)
{
    textBox1.Text = this._form1.ItemValue;
}

private void button1_Click(object sender, EventArgs e)
{
    _form1.SetSelectedItemValue(textBox1.Text);
    Close();
}

This code is for demo only, just to show how it works. 该代码仅用于演示,仅用于演示其工作原理。 You'll have to build in validation of user input in the textbox and whether an item from the listbox is selected. 您必须建立对文本框中用户输入的验证,以及是否从列表框中选择了一项。 Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM