i have 2 forms. form1 contains the datagridview. the second(form2) form contains textboxs. when i click Ok button in form2, the values should get added in datagridview as new row. This is the code i am trying to use to pass the data,but its neither showing error nor result.
Form2
private void btnOk_Click(object sender, EventArgs e)
{
form1.datagridview.Rows.Add("firstname", "lastname", "Success", "Userid", DateTime.Now.ToString());
}
put this on Form1
private void button1_Click(object sender, EventArgs e) {
Form2 f2 = new Form2(this);
f2.Show();
}
put this on 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);
}
that should do it
and datagridview Modifier should be public
You need to add a reference to your form1 somewhere in form2 a somewhat easy way of doing this is to add this to form2 on top
public Form1 form1 {get;set;}
And then when you create your form2 with i suppose something like this from form1
Form2 form2 = new Form2();
form2.ShowDialog();
You add this right after ShowDialog() or before
form2.form1 = this;
Then you can use form1 as a variable inside of form2 to reference to form1
This is easiest way I can suggest you:
Form 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);
}
Form 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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.