Adding data to a gridview in c# from multiple forms

1.4k Views Asked by At

How would I go about inserting the text that I have entered in to the textbox in NewActivity into the first column in the datagridview on form1?

Here is the coding I have thus far.

Form1

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.IsMdiContainer = true;
        }

        private void viewToolStripMenuItem1_Click(object sender, EventArgs e)
        {
        }

        private void newActivityToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NewActivity NewAc = new NewActivity();
            NewAc.MdiParent = this;
            NewAc.Show();
        }

        private void deleteActivityToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }
    }
}

NewActivity

 public partial class NewActivity : Form
    {
        public string activityName;

        public NewActivity()
        {
            InitializeComponent();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            activityName = "";
            this.Close(); 
        }

        private void btnAddActivity_Click(object sender, EventArgs e)
        {
            activityName = txtActivityName.Text;            
            this.Close();           
        }             
    }
}
2

There are 2 best solutions below

5
On

Here is an example of how to bind data from a textbox control to a DataGrid

// create new row
DataGridViewRow row = new DataGridViewRow();

// create cells
row.CreateCells(this.dataGridView1, textBox1.Text, textBox2.Text, textBox3.Text);

// add to data grid view
this.dataGridView1.Rows.Add(row);

---------------Below is how you would use it in your case--------------------

private void btnAddActivity_Click(object sender, EventArgs e)
{
   activityName = txtActivityName.Text;    
   int index = dgvActivityList .Rows.Add();
   DataGridViewRow row = dgvActivityList .Rows[index];
   row.Cells[0].Value = activityName;      
   this.Close();           
}   
0
On

you can insert it in your event click

private void btnAddActivity_Click(object sender, EventArgs e)
    {
        activityName = txtActivityName.Text;    
        int index = yourDataGridView.Rows.Add();
       DataGridViewRow row = yourDataGridView.Rows[index];
       row.Cells[0].Value =   activityName ;      
        this.Close();           
    }