Adding multiple GridView rows

1

I'm trying to include multiple rows in a GridView, but it does not add rows, it always overrides the first.

I'd like to know how I can add multiple rows, not replace the first rows.

Follow the code for what I'm currently doing:

dt.Columns.Add("ID");
dt.Columns.Add("Nome");
dt.Columns.Add("Quantidade");
dt.Columns.Add("Valor");
dt.Columns.Add("Desconto");
dt.Columns.Add("Valor Final");
dt.Columns.Add("Quitar", typeof(bool));
DataRow dataRow = dt.NewRow();
dataRow[0] = txtidprodutoAdd.Text;
dataRow[1] = cbProdutoAdd.SelectedItem;
dataRow[2] = UpQuantidade.Text;
dataRow[3] = txtValorAdd.Text;
dataRow[4] = txtDescontoAdd.Text;
dataRow[5] = txtValorFinalAdd.Text;
dataRow[6] = true;
dt.Rows.Add(dataRow);
GridView5.DataSource = dt;
GridView5.DataBind();
    
asked by anonymous 05.06.2017 / 16:00

2 answers

0

I was able to solve it, I did it this way:

 if (Session["dt1"] != null)
            {
                dt1 = (DataTable)Session["dt1"];
            }
            else
            {
                dt1.Columns.Add("ID");
                dt1.Columns.Add("Nome");
                dt1.Columns.Add("Quantidade");
                dt1.Columns.Add("Valor");
                dt1.Columns.Add("Desconto");
                dt1.Columns.Add("Valor Final");
                dt1.Columns.Add("Quitar", typeof(bool));

            }



            dr1 = dt1.NewRow();
            dr1["ID"] = txtidprodutoAdd.Text;
            dr1["Nome"] = cbProdutoAdd.SelectedItem;
            dr1["Quantidade"] = UpQuantidade.Text;
            dr1["Valor"] = txtValorAdd.Text;
            dr1["Desconto"] = txtDescontoAdd.Text;
            dr1["Valor Final"] = txtValorFinalAdd.Text;
            dr1["Quitar"] = true;
            dt1.Rows.Add(dr1);
            GridView5.DataSource = dt1;
            GridView5.DataBind();
            Session["dt1"] = dt1;
    
05.06.2017 / 20:38
1

The problem is that you are treating a web application as if it were a normal desktop application. It should be noted that a web application is always stateless , that is, no type of state is maintained between one request and another, they are independent.

So whenever the request is received, a new DataTable is created, regardless of whether the previous request has already been created or not. There are a few ways to deal with this, and most likely a WebForms mechanism already exists, since the GUI components maintain a sort of state between one request and another (ie: TextBoxes keep the values entered).

As I do not know WebForms, I do not know if my solution is the best, but by the way, it works. What should be done is to capture DataSource of DataGridView and add a line in this DataSource .

DataTable dataTable = (DataTable) GridView5.DataSource;

DataRow dataRow = dt.NewRow();
dataRow[0] = 123;
dataRow[1] = "asd";
dataRow[2] = 123;
dataRow[3] = 50.0;
dataRow[4] = 0;
dataRow[5] = 50;
dataRow[6] = true;
dataTable.Rows.Add(dataRow);
    
05.06.2017 / 16:20