How to add lines manually in a datagriedview populated with Mysql data

Asked

Viewed 1,810 times

1

I have a Datagridview where I fill it with data from a mysql table and then need to add lines with some textbox data, when I try returns the following error: "It is not possible to add lines programmatically to the collection of Datagridview lines when the 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();
}

1 answer

2


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

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);
}
  • Hello Francisco, gave the following error when I tried to use your code: cannot Convert from 'System.Windows.Forms.Datagridview' to 'System.Data.Datatable'

  • I made a mistake, you have to pass the datasource in the parameters, instead of the datagridview.

  • I didn’t understand this part of passing the Datasource in the parameters, I used the following code to fill my Datagridview: Mysqlcommand command2 = new Mysqlcommand("select Cod,servico,preco from guardaservicos Where Codos=@Codos ", conect.conexao); command2.Parameters.Add("@Codos", Mysqldbtype.Varchar). Value = lblNumOS.Text; Mysqldataadapter adapter2 = new Mysqldataadapter(command2); Datatable data2 = new Datatable(); adapter2.Fill(data2); dataGridView1.Datasource = data2;

  • I didn’t find what I have to put as a parameter there.

  • In your case, the variable data2, because she is your Datasource

  • Thank you very much,.

  • Don’t forget to mark the answer as correct to close the topic and also help those who have the same problem!

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.