當Form2的AcceptChange按鈕按下,需要修改Form1中ListBox中相應列的值,因此可以考慮同時將Form1中的ListBox控件當參數也傳入Form2,所有修改工作都在Form2中完成,根據這個思路,Form2代碼如下:
publicpartial class Form2 : Form
{
private string text;
private ListBox lb;
private int index;
//構造函數接收三個參數:選中行文本,ListBox控件,選中行索引
public Form2(string text,ListBox lb,int index)
{
this.text = text;
this.lb = lb;
this.index = index;
InitializeComponent();
this.textBox1.Text = text;
}
private void btnChange_Click(object sender, EventArgs e)
{
string text = this.textBox1.Text;
this.lb.Items.RemoveAt(index);
this.lb.Items.Insert(index, text);
this.Close();
}
}
Form1中new窗體2時這么寫:
public partial class Form1 :Form
{
int index = 0;
string text = null;
public Form1()
{
InitializeComponent();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgse)
{
if (this.listBox1.SelectedItem != null)
{
text = this.listBox1.SelectedItem.ToString();
index = this.listBox1.SelectedIndex;
//構造Form2同時傳遞參數
Form2 form2 = new Form2(text, listBox1, index);
form2.ShowDialog();
}
}
OK,這樣做的好處是直觀,需要什么就傳什么,缺點也是顯而易見的,如果窗體1中需要修改的是一百個控件,難道構造的時候還傳100個參數進去?況且如果其他窗體仍然需要彈Form2,那Form2就廢了,只能供窗體1使用,除非寫重載的構造函數,不利于代碼的復用