Add rows to an asp datatable filled from a database

1

In my application I have a data table that I filled from a database registry, taking the following method:

Public Shared Function RetData(query as String) As DataTable
    Dim conn As New Connection()
    Dim tabla As New DataTable()
    Try
        conn.Connection.Open()

        Dim strcom As String = quer
        Dim sqlDa As New SqlDataAdapter(strcom, conn.Connection())
        sqlDa.Fill(tabla)
        conn.Connection.Close()
    Catch ex As Exception
        conn.Connection.Close()
    End Try
    Return tabla
End Function

This record is saved in my data table, then I save it in a datatable session to show it later in a grid.

Protected Sub btns_Click(sender As Object, e As EventArgs) Handles btns.Click
    Dim tbl As New DataTable
    tbl = clsUtilities.RetData("Select top 1 * from tabla")
    If tbl.Rows.Count > 0 Then
        Dim nrow As DataRow = tbl.Rows(0)
        lblsnum.Text = nrow("Serial_Number").ToString()
        Session("antenna") = tbl
    Else
    End If
End Sub


Protected Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
    Dim tbl As New DataTable
    tbl = Session("antenna")
    tbl.Columns.Add("Reason")
    tbl.Columns.Add("Out of the box")
    Dim row As DataRow
    row = tbl.NewRow
    Dim rowscount = tbl.Rows.Count
    For i = 0 To rowscount - 1
        tbl.Rows(i)("Reason") = ddlreason.SelectedItem.ToString
        tbl.Rows(i)("Out of the box") = ddlout.SelectedItem.ToString
    Next

    gvAntennasAdded.DataSource = tbl
    gvAntennasAdded.DataBind()
    Session("antenna") = tbl

End Sub

However, I will continue to add records to this grid, which will cause a new row to be added every time I add one. How can I do it?

    
asked by Danitza Ayala 19.11.2016 в 17:20
source

1 answer

1

Analyzing your problem, what you can do is the following:

Dim tblGlobal As New DataTable
Protected Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click

tblGlobal = Session("antenna")

If tblGlobal .Rows.Count=0 then

tblGlobal .Columns.Add("Reason")
tblGlobal .Columns.Add("Out of the box")

End If

Dim row As DataRow
row = tblGlobal.NewRow
Dim rowscount = tblGlobal.Rows.Count
For i = 0 To rowscount - 1
    tblGlobal.Rows(i)("Reason") = ddlreason.SelectedItem.ToString
    tblGlobal.Rows(i)("Out of the box") = ddlout.SelectedItem.ToString
Next


gvAntennasAdded.DataSource = tblGlobal 
gvAntennasAdded.DataBind()
Session("antenna") = tblGlobal 
End Sub

If I understood the problem, the solution is to create the DataTable globally and validate each time I add one to know if the columns will be created. In case your project is web you can have a static class to create the global datatable.

I hope it serves you

    
answered by 24.11.2016 в 21:34