Does not insert rows in DatagridView

0

I make a select in my database and it brings the values in the datagrid. But when I try to add / delete lines, it gives error:

  

You can not programmatically add rows to the DataGridView rows collection when the control is bound to data. "

Select Code:

DataSet ds = new DataSet();
string comando = "SELECT * FROM item_orcamento where id_orcamento = '"+ Convert.ToInt32(txtidos.Text) + "' and tipo_item='Produto' order by id_orcamento";
MySqlDataAdapter da = new MySqlDataAdapter(comando, stringCon);
MySqlCommandBuilder cmdb = new MySqlCommandBuilder(da);
da.Fill(ds, "item_orcamento");
dataGridProdutos.DataSource = ds.Tables["item_orcamento"];
da.Dispose();

Insert Button Code:

private void addDataServicos(string codServico, string nomeServico, string qtdServico, string valorServico, string valorTotalServico)
{
    String[] row = { codServico, nomeServico, qtdServico, valorServico, valorTotalServico };
    dataGridServicos.Rows.Add(row);
}

How do I enter new lines?

    private void CriarRow(DataTable source)
    {
        string valor = txtprecoServico.Text;
        valor = valor.Replace("R$", "");
        int qtd = 0;
        qtd = Convert.ToInt32(txtquantidades.Text);
        double soma = Convert.ToDouble(valor);
        double valorTotalServico = qtd * soma;
        var row = source.NewRow();
        row[0] = 0;
        row[1] = txtcodServico.Text;
        row[2] = 0;//2-tipo_item,
        row[3] = txtnomeServico.Text;
        row[4] = txtquantidades.Text; 
        row[5] = (valor);//5-valor_item,
        row[6] = valorTotalServico.ToString();
        row[7] = txtidos.Text;
        source.Rows.Add(row);
    }
    
asked by anonymous 01.08.2017 / 23:11

1 answer

1

You need to add the line to the object that does the binding of the data and not directly to the DataGridView .

In your case, you need to add the lines to DataTable

Something like

private void CriarRow(DataTable source)
{
    var row = source.NewRow();
    row[0] = "Alguma coisa";
    row[1] = "E assim por diante";
    source.Rows.Add(row);
}

Use

var dataTable = (DataTable)dataGridProdutos.DataSource;
CriarRow(dataTable);
    
02.08.2017 / 23:09