How to manually add rows in a datagriedview populated with MySql data

1

I have a DataGridView in which I populate it with data from a mysql table and then need to add rows with data from some textbox, when I try to return the following error: "Can not add rows programmatically to the DataGridView row collection when control is associated with data ".

My code:

private void button1_Click(object sender, EventArgs e)     
{
    Hide();
    FormPai.dataGridView1.Rows.Add(txtCod.Text, servicosBox.Text, txtPreco.Text);
    FormPai.dataGridView1.Refresh();
}
    
asked by anonymous 18.06.2017 / 23:39

1 answer

1

You should instantiate a column before, I recommend creating a function for it.

private void button1_Click(object sender, EventArgs e)
{
    Hide();
    CriarRow(/*DataSource usada*/);
    FormPai.dataGridView1.Refresh();
}

private void CriarRow(DataTable tabela)
{
    DataRow row = tabela.NewRow();
    row[0] = txtCod.Text;
    row[1] = servicosBox.Text;
    row[2] = txtPreco.Text;
    tabela.Rows.Add(row);
}
    
18.06.2017 / 23:58