任何人都可以帮助我如何在asp中添加gridview中的新记录 这是我的代码:
Partial Class _Default
Inherits System.Web.UI.Page
Dim drow As DataRow
Dim dt As New DataTable
Dim x As Integer
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
drow = dt.NewRow
drow("fname") = TextBox1.Text
drow("mname") = TextBox2.Text
drow("lname") = TextBox3.Text
dt.Rows.Add(drow)
GridView1.DataSource = dt
GridView1.DataBind()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack = False Then
binds()
End If
End Sub
Protected Sub binds()
dt.Columns.Add("fname")
dt.Columns.Add("mname")
dt.Columns.Add("lname")
drow = dt.NewRow
drow("fname") = TextBox1.Text
drow("mname") = TextBox2.Text
drow("lname") = TextBox3.Text
dt.Rows.Add(drow)
GridView1.DataSource = dt
GridView1.DataBind()
End Sub
End Class
当我点击按钮时,错误表明fname不属于该表。感谢
答案 0 :(得分:0)
原因是所有对象都在页面生命周期的末尾处理,包括DataTable
,DataRow
和ineteger。它们将在每次回发时使用默认值进行初始化。
但是你在Page_Load
中有这个初始化代码:
If Page.IsPostBack = False
binds() ' which creates the table and adds the columns '
End If
解决方案不是使用字段而是使用局部变量。
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
binds()
End Sub
Private Sub binds()
Dim drow As DataRow
Dim dt As New DataTable
dt.Columns.Add("fname")
dt.Columns.Add("mname")
dt.Columns.Add("lname")
drow = dt.NewRow
drow("fname") = TextBox1.Text
drow("mname") = TextBox2.Text
drow("lname") = TextBox3.Text
dt.Rows.Add(drow)
GridView1.DataSource = dt
GridView1.DataBind()
End Sub
答案 1 :(得分:0)
现在是我的代码。
Partial Class _Default
Inherits System.Web.UI.Page
Dim dcl As DataRowCollection
Dim drow As DataRow
Dim dt As New DataTable
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
binds()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack = False Then
addcolumns()
GridView1.DataSource = dt
GridView1.DataBind()
End If
End Sub
Private Sub addcolumns()
dt.Columns.Add("fname")
dt.Columns.Add("mname")
dt.Columns.Add("lname")
Session("dtInSession") = dt
End Sub
Protected Sub binds()
If Session("dtInSession") IsNot Nothing Then
dt = Session("dtInSession")
End If
drow = dt.NewRow
drow("fname") = TextBox1.Text
drow("mname") = TextBox2.Text
drow("lname") = TextBox3.Text
dt.Rows.Add(drow)
Session("dtInSession") = dt
GridView1.DataSource = dt
GridView1.DataBind()
End Sub
结束班
答案 2 :(得分:-2)
## Heading ##
public DataTable SearchStudents(string studFirstname)
{
logOBj.conn.Close();
logOBj.conn.Open();
logOBj.DA = new SqlDataAdapter("Select * From STUDENT where studFirstname LIKE '%" + studFirstname + "%'", logOBj.conn);
logOBj.DT = new DataTable();
logOBj.DA.Fill(logOBj.DT);//data adapter fills the datatable
return logOBj.DT;
}