I can not add rows to a datagridview

0

I have a problem adding new rows to a datagrid I get the following error: "Can not add rows programmatically to the collection of DataGridView rows when the control is bound to data"

The code I use to add rows is this:

dataGridView1.Rows.Add(prodcod.Text, articulo.Text, talla.Text, manga.Text, unidad.Text, cantidad.Text, preciou.Text, subtotal.Text, descuento.Text, total.Text);

And the one I use to fill in the datagridview is this:

SqlConnection cn = new SqlConnection(@"Data Source=10.1.1.1\novtosa; user=usr; password=Nov; Initial Catalog=menu;");
cn.Open();
SqlCommand cmd = new SqlCommand("SELECT PRODCOD, ARTICULO, MANGA, TALLA, UNIDAD, CANTIDAD, PRECIOUNIT, SUBTOTAL, PORCEN_DESCUENTO, TOTAL, NUM_REMISION from borradorlineas where NUM_REMISION like @idd", cn);
cmd.Parameters.AddWithValue("@idd", Convert.ToString(Buscarborrador.Borradorseleccionado.Numremision));
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.Columns[0].DataPropertyName = "PRODCOD";
dataGridView1.Columns[1].DataPropertyName = "ARTICULO";
dataGridView1.Columns[2].DataPropertyName = "MANGA";
dataGridView1.Columns[3].DataPropertyName = "TALLA";
dataGridView1.Columns[4].DataPropertyName = "UNIDAD";
dataGridView1.Columns[5].DataPropertyName = "CANTIDAD";
dataGridView1.Columns[6].DataPropertyName = "PRECIOUNIT";
dataGridView1.Columns[7].DataPropertyName = "SUBTOTAL";
dataGridView1.Columns[8].DataPropertyName = "PORCEN_DESCUENTO";
dataGridView1.Columns[9].DataPropertyName = "TOTAL";
dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource = dt;
cn.Close();

How can I add new rows to that datagridview?

    
asked by p0ncho14 26.04.2018 в 18:04
source

1 answer

1

After making the assignment dataGridView1.DataSource = dt;

You must assign the data to DataTable , not directly to DatagridView , something like this:

//Agregar las Filas al DataRow y asignar el valor correspondiente. 
DataTable dt2 = new DataTable();
dt2 = dataGridView1.DataSource as DataTable;

DataRow datarow; 
datarow = dt2.NewRow(); //Con esto le indica que es una nueva fila.

datarow["PRODCOD"] =  prodcod.Text;
datarow["ARTICULO"] = articulo.Text;
datarow["MANGA"]= manga.Text;
datarow["TALLA"] = talla.Text;
datarow["UNIDAD"] = unidad.Text;
datarow["CANTIDAD"] = cantidad.Text;
datarow["PRECIOUNIT"] = preciou.Text;
datarow["SUBTOTAL"] = subtotal.Text;
datarow["PORCEN_DESCUENTO"] = descuento.Text;
datarow["TOTAL"] = total.Text;

//Esto se encargará de agregar la fila.
dt2.Rows.Add(datarow);

Which is the same as doing this:

DataTable dt = dataGridView1.Source as DataTable;
dt.Rows.Add(new object[] { ... });
    
answered by 26.04.2018 / 19:15
source