用vs2008中进行窗体之间数据的传递
首先用form1体作为主窗体,当主窗体之间修改数据时,子窗体也可以和主窗体数据相同,使用构造函数进行数据传递
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Form2 array = new Form2(this.textBox1, this.checkBox1);
array.ShowDialog();
}
}
}
两个引用类型的数据:TextBox类型,和CheckBox;另外在Form2中增加了两个类数据成员,在.NET中有两种类型,值类型和引用类型。值类型是从ValueType继承而来,而ValueType又是从Object继承;对于引用类型它直接继承Object类型。这下让我们看看怎样通过Form2来修改Form1里的数据。
public partial class Form2 : Form
{
private TextBox txt;
private CheckBox cht;
public Form2(TextBox textBox, CheckBox checkbox)
{
InitializeComponent();
this.textBox1.Text = textBox.Text;
this.checkBox1.Checked= checkbox.Checked;
txt = textBox;
cht = checkbox;
}
private void button1_Click(object sender, EventArgs e)
{
txt.Text = textBox1.Text;
cht.Checked = checkBox1.Checked;
this.Close();
}
定义txt 和 cht 变量,存储变量TextBox,CheckBox。然后通过txt,cht把子窗体的数据传输到主窗体,
因为它们所使用的同一个引用。
举一个例子
主窗体
public partial class Form1 : Form
{
public ArrayList listdata1;
public Form1()
{
InitializeComponent();
this.listdata1 = new ArrayList();
this.listdata1.Add("DotNet");
this.listdata1.Add("PHP");
this.listdata1.Add("XML");
this.listdata1.Add("ASP");
this.listdata1.Add(">NET");
this.listdata1.Add("Dot");
this.listBox1.DataSource = this.listdata1;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Form2 fchild = new Form2(this.listdata1);
fchild.ShowDialog();
this.listBox1.DataSource = null;
this.listBox1.DataSource = this.listdata1;
}
子窗体
public ArrayList listdata2;
public Form2(ArrayList listdata)
{
InitializeComponent();
this.listdata2 = listdata;
foreach (object o in this.listdata2)
{
this.listBox1.Items.Add(o);
}
}
private void Form2_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Trim().Length > 0)
{
listdata2.Add(textBox1.Text.Trim());
listBox1.Items.Add(textBox1.Text.Trim());
}
else
{
MessageBox.Show("请输入要添加的内容");
}
}
private void button2_Click(object sender, EventArgs e)
{
int index = listBox1.SelectedIndex;
if (index != -1)
{
listBox1.Items.RemoveAt(index);
listdata2.RemoveAt(index);
}
else
{
MessageBox.Show("请选择内容");
}
}
private void button3_Click(object sender, EventArgs e)
{
this.Close();
}