Click here to Skip to main content
16,013,581 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I Have form 1 with 4 textboxes and 1 button, and I have form 2 which contains dataGridView, I want to add new row to the datagridview from the other form.

the problem is When I click on Add button it open the main form with empty datagridview and add the row alone there, what should I do to make the new row be added to the datagridview in original form with the rest of rows.


C#
Main frm = new Main();
            StockDBDataSet ds = new StockDBDataSet();
            DataRow obj = ds.Tables[0].NewRow();
            obj[0] = textBox1.Text;
            obj[1] = textBox2.Text;
            obj[2] = textBox4.Text;
            obj[3] = dateTimePicker1.Value;
            ds.Tables[0].Rows.Add(obj);
            ds.Tables[0].AcceptChanges();
            frm.dataGridView1.DataSource = null;
            frm.dataGridView1.DataSource = ds.Tables[0];
            this.Hide();
            frm.Show();
Posted

In your programm you are creating a new main form object instance.

public partial class Form1 : Form
{

Form2 frm2=new Form2();
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
frm2.AddNewRow();
frm2.Show();
}
}


public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public void AddNewRow()
{
dataGridView1.Rows.Add();
}
}

worked try this.
 
Share this answer
 
Comments
R.M49 31-Oct-15 14:54pm    
<pre lang="c#">dataGridView1.Rows.Add();</pre>

<pre lang="c#">Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound.</pre>
R.M49 31-Oct-15 14:54pm    
dataGridView1.Rows.Add()


Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound.
public partial class Form1 : Form
{

Form2 frm2=new Form2();
DataSet ds = new DataSet();

public Form1()
{
InitializeComponent();
ds.Tables.Add();
ds.Tables[0].Columns.Add();
ds.Tables[0].Columns.Add();
}

private void button1_Click(object sender, EventArgs e)
{

DataRow dr = ds.Tables[0].NewRow();
dr[0] = "1";
dr[1] = "3";
ds.Tables[0].Rows.Add(dr);
frm2.dataGridView1.DataSource = ds.Tables[0];
frm2.Show();
}

public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}

}

form 2 contains grid.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900