0

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()

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.