您可以创建一个类,例如 MyDataCollection,其属性对应于您的 DataGridView 列。当你按下 Edit 按钮时,创建这个类的一个新实例,用必要的数据填充它,并将它作为参数传递给 EditForm 的构造函数。
public class MyDataCollection
{
public string Name;
public string Email;
// --
}
在您的主要形式中:
void btnEdit_Click(object sender, EventArgs e)
{
// Create the MyDataCollection instance and fill it with data from the DataGridView
MyDataCollection myData = new MyDataCollection();
myData.Name = myDataGridView.CurrentRow.Cells["Name"].Value.ToString();
myData.Email = myDataGridView.CurrentRow.Cells["Email"].Value.ToString();
// --
// Send the MyDataCollection instance to the EditForm
formEdit = new formEdit(myData);
formEdit.ShowDialog(this);
}
编辑表单应如下所示:
public partial class formEdit : Form
{
// Define a MyDataCollection object to work with in **this** form
MyDataCollection myData;
public formEdit(MyDataCollection mdc)
{
InitializeComponent();
// Get the MyDataCollection instance sent as parameter
myData = mdc;
}
private void formEdit_Load(object sender, EventArgs e)
{
// and use it to show the data
textbox1.Text = myData.Name;
textbox2.Text = myData.Email;
// --
}
}
您也可以忘记 MyDataCollection 类并将整个 DataGridViewRow 传递给 formEdit 的构造函数。