窗体2
private void btnOk_Click(object sender, EventArgs e)
{
form1.datagridview.Rows.Add("firstname", "lastname", "Success", "Userid", DateTime.Now.ToString());
}
答案 0 :(得分:3)
将其放在Form1
private void button1_Click(object sender, EventArgs e) {
Form2 f2 = new Form2(this);
f2.Show();
}
将其放在Form2
private Form1 form1;
public Form2(Form1 form1) {
InitializeComponent();
this.form1 = form1;
}
private void button1_Click(object sender, EventArgs e) {
form1.dataGridView1.Columns.Add("FirstName", "First Name");
form1.dataGridView1.Columns.Add("LastName", "Last Name");
form1.dataGridView1.Columns.Add("UserId", "Userid");
form1.dataGridView1.Columns.Add("Success", "Success");
object[] row = new object[] {"1","Product 1","1000",DateTime.Now.ToString()};
form1.dataGridView1.Rows.Add(row);
}
应该这样做
和datagridview修饰符应该是公共的
答案 1 :(得分:0)
你需要在form2的某处添加对form1的引用,这样做的一个简单方法是将它添加到form2的顶部
public Form1 form1 {get;set;}
然后当你创建你的form2时我想从form1
这样的东西Form2 form2 = new Form2();
form2.ShowDialog();
您可以在ShowDialog()之后或
之前添加此项form2.form1 = this;
然后,您可以使用form1作为form2内部的变量来引用form1
答案 2 :(得分:0)
这是我建议你最简单的方法:
表单1
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var firstName = txtFirstName.Text;
var lastName = txtLastName.Text;
var success = txtSuccess.Text;
var userId = txtUserId.Text;
var frm2 = new Form2();
frm2.AddGridViewRows(firstName, lastName, success, userId);
}
表格2
public Form2()
{
InitializeComponent();
}
public void AddGridViewRows(string firstName, string lastName, string success, string userId)
{
// Add rows to grid view.
dataGridView1.Rows.Add(firstName, lastName, success, userId);
// Refresh the grid
dataGridView1.Update();
}