Load two or more rows to a DataTable by means of a Button

2

Good morning everyone, I'm using the following method to load a DataTable that in turn will show this information within a DataGridView , the problem I have is that by pressing the button I should add each new record to the DataTable and show it in DataGrid just update me the information of the first record and do not add the following line, who knows what I'm doing wrong? I attach the code.

public void CargarGrid()
{
    try
    {
        ObtenerValores();
        DataTable dtCGArt = new DataTable();
        DataTable dtCGCte = new DataTable();
        DataTable dtGridArticulos = new DataTable();
        #region ObtenerArticulo
        if (artId>0)
        {
            dtCGArt = objConsultas.MuestraArticulosID(artId);
            if (dtCGArt.Rows.Count>0)
            {
                foreach (DataRow drCGArt in dtCGArt.Rows)
                {
                    articulo = Convert.ToString(drCGArt[0]);
                }
            }
        }
        #endregion
        #region ObtenerCliente
        if (cteId>0)
        {
            dtCGCte = objConsultas.MuestraClientesID(cteId);
            if (dtCGCte.Rows.Count>0)
            {
                foreach (DataRow drCGCte in dtCGCte.Rows)
                {
                    cliente = Convert.ToString(drCGCte[0]);
                }
            }
        }
        #endregion
        dtGridArticulos.Columns.Add("Articulo");
        dtGridArticulos.Columns.Add("Cantidad");
        dtGridArticulos.Columns.Add("PrecioUnitario");
        dtGridArticulos.Columns.Add("Detalle");
        DataRow drArticulosSeleccionados = dtGridArticulos.NewRow();
        if (articulo!=""&&cliente!=""&&cantidad!=0&&preciounitario!=0&&descripcion!="")
        {                    
            drArticulosSeleccionados["Articulo"] = articulo;
            drArticulosSeleccionados["Cantidad"] = cantidad;
            drArticulosSeleccionados["PrecioUnitario"] = Convert.ToDouble(preciounitario);
            drArticulosSeleccionados["Detalle"] = Convert.ToString(descripcion);
            dtGridArticulos.Rows.Add(drArticulosSeleccionados);                    
            if (dtGridArticulos.Rows.Count > 0)
            {
                foreach (DataRow drGridArticulos in dtGridArticulos.Rows)
                {
                    cantidad1 = Convert.ToInt32(drGridArticulos[1]);
                    preciounitario1 = Convert.ToDouble(drGridArticulos[2]);
                    if (cantidad1>0&&preciounitario1>0)
                    {
                        subtotal = cantidad1 * preciounitario1;
                        txtIngSubtot.Text = subtotal.ToString();
                        if (subtotal > 0)
                        {
                            subtotal1 = subtotal * IVA;
                            totalfinal = subtotal + subtotal1;
                            if (totalfinal > 0)
                            {
                                txtIngTotal.Text = totalfinal.ToString();
                            }
                            else
                            {
                                txtIngTotal.Text = "0.0";
                            }
                        }
                        else
                        {
                            txtIngTotal.Text = "0.0";
                        }
                    }
                }
                dgvListArtIng.DataSource = dtGridArticulos;
                dgvListArtIng.AllowUserToAddRows = false;
                objValidaciones.MostrarAviso("Se agregaron los artículos de forma correcta.", false, lblAviso1);
            }
            else
            {
                dgvListArtIng.DataSource = "";
                objValidaciones.MostrarAviso("No se encontraron artículos en esta orden", true, lblAviso1);
            }
        }
    }
    catch (Exception ex)
    {
        ex.ToString();
    }
}

private void btnAgregaArt_Click(object sender, EventArgs e)
{
    CargarGrid();
}
    
asked by Alberto Arenas 28.11.2017 в 19:37
source

3 answers

3

I think the problem is that every time you run the LoadGrid () function you are initializing the datatable

DataTable dtGridArticulos = new DataTable();

You must declare it outside the function as a global variable so that the rows are added since each time you press the button when initializing the dataTable the rows are deleted.

    
answered by 28.11.2017 / 20:30
source
1

Good Alberto,

As I have seen in the code that you show, you do not have any loop that repeats the process of inserting the new lines depending on what you have returned the data functions, therefore only 1 of them will be inserted, since the code will be traveled only once per Click to the button.

You should put all the code block inside a loop so that the process is repeated for each line of data, for example:

public void CargarGrid()
{
    try
    {
        //Hacemos un bucle para recorrer todos los datos que hay que actualizar
        //Por falta de información no puedo especificar el bucle, me lo invento
        while(condición)
        {
            ObtenerValores();
            DataTable dtCGArt = new DataTable();
            DataTable dtCGCte = new DataTable();
            DataTable dtGridArticulos = new DataTable();
            #region ObtenerArticulo
            if (artId>0)
            {
                dtCGArt = objConsultas.MuestraArticulosID(artId);
                if (dtCGArt.Rows.Count>0)
                {
                    foreach (DataRow drCGArt in dtCGArt.Rows)
                    {
                        articulo = Convert.ToString(drCGArt[0]);
                    }
                }
            }
            #endregion
            #region ObtenerCliente
            if (cteId>0)
            {
                dtCGCte = objConsultas.MuestraClientesID(cteId);
                if (dtCGCte.Rows.Count>0)
                {
                    foreach (DataRow drCGCte in dtCGCte.Rows)
                    {
                        cliente = Convert.ToString(drCGCte[0]);
                    }
                }
            }
            #endregion
            dtGridArticulos.Columns.Add("Articulo");
            dtGridArticulos.Columns.Add("Cantidad");
            dtGridArticulos.Columns.Add("PrecioUnitario");
            dtGridArticulos.Columns.Add("Detalle");
            DataRow drArticulosSeleccionados = dtGridArticulos.NewRow();
            if (articulo!=""&&cliente!=""&&cantidad!=0&&preciounitario!=0&&descripcion!="")
            {                    
                drArticulosSeleccionados["Articulo"] = articulo;
                drArticulosSeleccionados["Cantidad"] = cantidad;
                drArticulosSeleccionados["PrecioUnitario"] = Convert.ToDouble(preciounitario);
                drArticulosSeleccionados["Detalle"] = Convert.ToString(descripcion);
                dtGridArticulos.Rows.Add(drArticulosSeleccionados);
            }
        }

        //Cuando termina el bucle hacemos el siguiente paso
        if (dtGridArticulos.Rows.Count > 0)
        {
            foreach (DataRow drGridArticulos in dtGridArticulos.Rows)
            {
                cantidad1 = Convert.ToInt32(drGridArticulos[1]);
                preciounitario1 = Convert.ToDouble(drGridArticulos[2]);
                if (cantidad1>0&&preciounitario1>0)
                {
                    subtotal = cantidad1 * preciounitario1;
                    txtIngSubtot.Text = subtotal.ToString();
                    if (subtotal > 0)
                    {
                        subtotal1 = subtotal * IVA;
                        totalfinal = subtotal + subtotal1;
                        if (totalfinal > 0)
                        {
                            txtIngTotal.Text = totalfinal.ToString();
                        }
                        else
                        {
                            txtIngTotal.Text = "0.0";
                        }
                    }
                    else
                    {
                        txtIngTotal.Text = "0.0";
                    }
                }
            }
            dgvListArtIng.DataSource = dtGridArticulos;
            dgvListArtIng.AllowUserToAddRows = false;
            objValidaciones.MostrarAviso("Se agregaron los artículos de forma correcta.", false, lblAviso1);
        }
        else
        {
            dgvListArtIng.DataSource = "";
            objValidaciones.MostrarAviso("No se encontraron artículos en esta orden", true, lblAviso1);
        }
    }
    catch (Exception ex)
    {
        ex.ToString();
    }
}
    
answered by 29.11.2017 в 08:53
0

The problem is in the way you fill the DataGridView(dtg) by DataSource this links the dtg with the table, this causes that when adding a new record to dtg clean and insert the new registry. Therefore your solution would be to use another method to add record in dtg . Ex:

First you define the columns of the DataGridView and then you make the Add for each record:

datagridview.rows.add("valorCol1","valorCol2","valorColn")

And on the new record button, you put the same line of code, and you will see that your previous records will not be deleted:

datagridview.rows.add("valorCol1","valorCol2","valorColn")
    
answered by 30.11.2017 в 16:09