简体   繁体   中英

Can i add new row to datagrid view with a button click in ASP.Net written VB.net

let say i have 2 text box, 1 button and 1 gridview and i want to add data from textboxs to gridview with a button click.
How can I achive it.
I have tried below code but it replaced the old row.

Private dt As New DataTable

Private Sub Btnidadd_Click(sender As Object, e As EventArgs) Handles Btnidadd.Click
dt.Columns.Add("First Name")
dt.Columns.Add("Last Name")

Dim R As DataRow = dt.NewRow
R("First Name") = textbox1.Text
R("Last Name") = textbox2.Text

dt.Rows.Add(R)
GridView1.DataSource = dt
GridView.DataBind()

When you click the button in ASP.NET, a postback occurs and the page is recreated. So, you need to keep data somewhere.

For example, if you save it to a session variable like this.

Private dt As DataTable

Private Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        dt = New DataTable
        dt.Columns.Add("First Name")
        dt.Columns.Add("Last Name")
        Session("dt") = dt
    Else
        dt = CType(Session("dt"), DataTable)
    End If
End Sub

Private Sub Btnidadd_Click(sender As Object, e As EventArgs) Handles Btnidadd.Click

    Dim R As DataRow = dt.NewRow
    R("First Name") = TextBox1.Text
    R("Last Name") = TextBox2.Text

    dt.Rows.Add(R)
    GridView1.DataSource = dt
    GridView1.DataBind()

    Session("dt") = dt
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM