I tried below code. First I select a listbox item and then I click the edit button for text name change.
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
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. 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. You do this through a method SetSelectedItemValue
for example:
Code of 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 :
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!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.