如何将新行添加到数据表 vb.net
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9297506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to add new rows into a datatable vb.net
提问by lawphotog
I have a form with a textbox and a "add" button.
我有一个带有文本框和“添加”按钮的表单。
- The user can write a name down on the textbox and click the "add" button. It will save in a datatable with auto ID.
- After that, the textbox is cleared and the user can write another name in the text box and click the button.
- This should add to the existing datatable in memory with existing ID + 1.
- Then show in the gridview. (this is just for display purpose to confirm it works)
- 用户可以在文本框上写下名称,然后单击“添加”按钮。它将保存在具有自动 ID 的数据表中。
- 之后,文本框被清除,用户可以在文本框中输入另一个名称并单击按钮。
- 这应该添加到内存中现有 ID + 1 的现有数据表中。
- 然后在gridview中显示。(这只是为了显示目的,以确认它的工作原理)
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.
和这个 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.
非常感谢。
回答by Jay
Here is an example of adding a new row to a datatable that uses AutoIncrement on the first column:
以下是向数据表添加新行的示例,该数据表在第一列上使用 AutoIncrement:
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
回答by iRekk Team
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()