将数据从一个窗体传递到另一个窗体






3.54/5 (14投票s)
如何将数据从一个窗体传递到另一个窗体
引言
对于某些应用程序,有时很常见的是拥有父表单和子表单,用户被引导到子表单输入某些内容,然后他所做的更改可以被看到
在父表单中,而不关闭子表单。
如果程序不允许这样做,唯一的解决方案是通过编程方式关闭子表单,并将用户返回到父表单。
假设我们有一个程序,用户将在一天结束时输入 1000 个客户名称。 在用户输入每个客户名称后将用户返回到父表单是否有效且用户友好?
答案是否定的!
这是因为用户将不得不打开子表单 1000 次以输入 1000 个客户名称。
与其多次打开子表单,我知道有一种方法可以在不关闭子表单的情况下将数据从子表单传递到父表单。 用户所做的更改可以在子表单的后面看到,也就是在父表单中。
好吧,这个简单的应用程序将数据从一个表单传递到另一个表单。 许多程序员在需要将数据从一个表单传递到另一个表单时都会遇到这种问题。
我见过很多文章,其中许多有经验的程序员写了关于数据传递的文章,但这个是最简单的(我希望 :-))。
首先,您必须创建一个数据库。 我创建了一个数据库并将其命名为 CustomerInfo
。
然后添加一个名为 Customer
的表,并在其中添加一个名为 CustomerName(Varchar(50))
的字段。

Using the Code
创建两个表单 frmCustomers
和 frmCustomer
。 一个应该保存所有 Customers
,另一个应该简单地保存 customer
,如下所示

以下是 frmCustomers
表单,它在 Datagrid
视图列表中显示所有 customers
//This code is for the frmCustomers Form
private void frmCustomers_Load(object sender, EventArgs e)
{
//load all customers
loadCustomer();
}
public void loadCustomer()
{
//load all customers
SqlConnection con = new SqlConnection("Data Source=localhost;
Database=CustomerInfo; UID=achakraborty; Integrated Security = True;");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Customer", con);
//SQL query
DataSet ds = new DataSet("Customer");
da.Fill(ds, "Customer");
//Fill the dataset
grd.DataSource = ds.Tables["Customer"];
//set the grid source to customer data table
}
private void btnAdd_Click(object sender, EventArgs e)
{
//During this operation, bind the Customer form event with a method
//which will fire from Customer form
frmCustomer c = new frmCustomer();
c.CustomerEventHandler += new EventHandler(RefreshCustomerList);
//This is the method which will fire upon any change
c.ShowDialog();
}
void RefreshCustomerList(object sender, EventArgs e)
{
//load all customers
SqlConnection con = new SqlConnection("Data Source=localhost;
Database=CustomerInfo; UID=achakraborty; Integrated Security = True;");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Customer", con);
DataSet ds = new DataSet("Customer");
da.Fill(ds, "Customer");
grd.DataSource = ds.Tables["Customer"];
con.Close();
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
//The following code is for frmCustomer form
public event System.EventHandler CustomerEventHandler;
private void btnSave_Click(object sender, EventArgs e)
{
//First of all open a database connection
SqlConnection con = new SqlConnection("Data Source=localhost;
Database=CustomerInfo; UID=achakraborty; Integrated Security = True;");
con.Open();
//Execute Command object to insert data in the corresponding customer table
SqlCommand cmd = new SqlCommand("Insert Into Customer VALUES
('" + txtCustomerName.Text.ToString().Trim() + "')", con);
cmd.ExecuteNonQuery();
con.Close();
if (CustomerEventHandler != null)
{
CustomerEventHandler(sender, e);
//firing if any change made
}
txtCustomerName.Clear();
txtCustomerName.Focus();
}
我很高兴在 The Code Project 上发表我的第一篇文章。 我希望利用这个经验来改进我的写作风格。 所以非常欢迎您的评论、建议和批评。
历史
- 2009 年 3 月 26 日:初始帖子