How to add Rows to a DataGridView that is already linked to data in C #

1

I have previously created a DataGridView.DataSource="a query"

and then I want to add another row to that from another query '

if (result== DialogResult.OK)
{
     DataTable tb1 = ConexionBD.Data("SELECT Id, Nombre, Cantidad as Disponibilidad, 1 Cantidad, Precio FROM Producto WHERE Id = '"+captura[0]+"'");

     if (tb1.Rows.Count == 0)
     {
           MessageBox.Show("No se encuentra ningun producto con ese Codigo");
     }
     else
     {
           if (tablaVenta.Rows.Count==0)
           {
                tablaVenta.DataSource = tb1;
           }
           else
           {
                tablaVenta.Rows.Add(tb1.Rows[0][0], tb1.Rows[0][1], tb1.Rows[0][2], tb1.Rows[0][3], tb1.Rows[0][4]);
           }
     }
}
else
{
     cxProduc.SelectedIndex = 0;
}
    
asked by srJJ 06.03.2018 в 04:22
source

2 answers

1

From what I understand, according to your code, what you want to do is add data to your DataGridView for the id, basically the query is the same, I do not understand the " 1 Quantity " in your query, but I think you bring 5 data in it.

According to what I describe, the only thing you should do is replace the following line code:

  

tableSale.Rows.Add (tb1.Rows [0] [0], tb1.Rows [0] [1], tb1.Rows [0] [2], tb1.Rows [0] [3], tb1 .Rows [0] [4]);

By:

DataRow row = tb1.Rows[0];
string[] aux = new string[] { row[0].ToString(), row[1].ToString(), row[2].ToString(), row[3].ToString(), row[4].ToString() };
tablaVenta.Rows.Insert(int.Parse(tablaVenta.Size.ToString()),aux);

It is in the last line ( tablaVenta.Rows.Insert(int.Parse(tablaVenta.Size.ToString()),aux); ) where we insert a new row at the end of our datagrid, in case you want it to be inserted at the beginning of the list you change it to: tablaVenta.Rows.Insert(0,aux); .

I hope I got it right.

    
answered by 06.03.2018 / 13:33
source
0

I can think of something like this:

//.......
//.......

if (tablaVenta.Rows.Count==0)
{
    tablaVenta.DataSource = tb1;
}
else
{
    //Crear un DataTable con las Columnas del DataGriview
    DataTable datatable = new DataTable();
    datatable = tablaVenta.DataSource as DataTable;

    //Agregar las Filas al DataRow
    DataRow datarow;
    for (int i = 0; i < 5; i++)
    {
        datarow = datatable.NewRow();
        datarow[i].ToString();
        datatable.Rows.Add(datarow);
     }
}
  

I apologize if there is an error, I am from the mobile and I have not tried the solution.

    
answered by 06.03.2018 в 14:06