Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add new rows into a datatable vb.net

I have a form with a textbox and a "add" button.

  1. The user can write a name down on the textbox and click the "add" button. It will save in a datatable with auto ID.
  2. After that, the textbox is cleared and the user can write another name in the text box and click the button.
  3. This should add to the existing datatable in memory with existing ID + 1.
  4. Then show in the gridview. (this is just for display purpose to confirm it works)

I have a datatable like this.

    Button1.click() event      Dim name = txtname.Text     Dim dt As New DataTable     dt.Columns.Add("ID", GetType(Integer))     dt.Columns.Add("Name", GetType(String))     Dim N As Integer = dt.Columns("ID").AutoIncrement     dt.Rows.Add(N, name)     GridView1.DataSource = dt     GridView1.DataBind()     txtname.Text = "" 

At the moment I have sometime like the code above. in the real program, it is not just name and it is not just one datatable so i just mock up some code.

and this code for aspx.

        <asp:TextBox ID="txtname" runat="server">         </asp:TextBox><asp:Button ID="Button1" runat="server" Text="Button" />         <asp:GridView ID="GridView1" runat="server">         </asp:GridView> 

can anyone advice me how to do it ? i understand my code is crapped and not correct but i just have to put some code so that you guys not need to work from scratch for me.

Thanks so much.

like image 848
Laurence Avatar asked Feb 15 '12 16:02

Laurence


People also ask

How do I add data to a row?

To add a new row, declare a new variable as type DataRow. A new DataRow object is returned when you call the NewRow method. The DataTable then creates the DataRow object based on the structure of the table, as defined by the DataColumnCollection.

How do you add a row at the top in the DataTable in C#?

Rows is a DataRowCollection which has an InsertAt extension method: DataTable. Rows. InsertAt(DataRow, pos);


2 Answers

Here is an example of adding a new row to a datatable that uses AutoIncrement on the first column:

Define the table structure:

    Dim dt As New DataTable     dt.Columns.Add("ID")     dt.Columns.Add("Name")     dt.Columns(0).AutoIncrement = True 

Add a New row:

    Dim R As DataRow = dt.NewRow     R("Name") = txtName.Text     dt.Rows.Add(R)     DataGridView1.DataSource = dt 
like image 80
Jay Avatar answered Sep 27 '22 22:09

Jay


First You need to define the data table structure as like the following:

Dim dt As New DataTable dt.Columns.Add("ID", Type.GetType("System.String")) dt.Columns.Add("Name",Type.GetType("System.String")) 

And Then add row like:

Dim dr As DataRow = dt.NewRow dr("ID") = System.GUID.NewGUID() dr("Name") = txtName.Text dt.Rows.Add(dr) DataGridView1.DataSource = dt DataGridView1.DataBind() 
like image 44
iRekk Team Avatar answered Sep 27 '22 21:09

iRekk Team