添加处理函数代码如下:
private void buttonAdd_Click(object sender, System.EventArgs e)
{
if(this.textBoxAdd.Text.Trim().Length>0)
{
this.listData2.Add(this.textBoxAdd.Text.Trim());
this.listBoxFrm2.Items.Add(this.textBoxAdd.Text.Trim());
}
else
MessageBox.Show(请输入添加的内容!);
}
删除处理代码如下:
private void buttonDel_Click(object sender, System.EventArgs e)
{
int index = this.listBoxFrm2.SelectedIndex;
if(index!=-1)
{
this.listData2.RemoveAt(index);
this.listBoxFrm2.Items.RemoveAt(index);
}
else
MessageBox.Show(请选择删除项或者没有可删除的项!);
}
退出Form2子窗体:
private void buttonOK_Click(object sender, System.EventArgs e)
{
this.Close();
}
编译运行程序,在子窗体中对数据进行修改,关闭后,主窗体就会显示更新后的数据。
这里有一点要提醒一下,比较两个例子,我们都传的是引用类型,一个是String,另一个是ArrayList,为什么string类型不能修改主窗体的数据呢?其实在.Net中对string类型的修改并不是修改原来的值,原来的值没有变化,而是重新生成一个新的字符串,下面是一个很好的说明。
public class ZZConsole
{
[STAThread]
static void Main(string[] args)
{
string str1 = abc;
string str2 = str1;
str1 = 123;
Console.WriteLine(str1);
Console.WriteLine(--------------);
Console.WriteLine(str2);
Console.WriteLine(--------------);
ArrayList al1 = new ArrayList();
al1.Add(abc);
ArrayList al2 = al1;
al2.Add(123);
foreach(object o in al1)
Console.WriteLine((string)o);
Console.WriteLine(--------------);
foreach(object o in al2)
Console.WriteLine((string)o);
Console.ReadLine();
}
}
运行一下看看输出结果就明白了,另外对值类型的数据操作要使用ref关键字。
总结,我们通过带参数的构造函数实现了窗体间的数据交互,代码看上去也比较清楚,在实际开发过程中,可以把DataSet,DataTable,或者是DataView当作参数,当然如果只是想修改一行,可以传个DataRow或者DataRowView。在下面的文章中我们来看看怎样使用另外两种方法来实现数据的交互。

