asp.net|datagrid ASP.net DataGrid為我們提供的內建的記錄行編輯功能,但是沒有提供內建的添加新行的功能。一個辦法就是:在DataTable中添加新行,然後再重新綁定到DataGrid,這個辦法可行,但在更新前需要進行確認,可能會產生空行。另外一個解決辦法就是:利用DataGrid footer template來提供一個空的行,這樣既可以提高速度,也可以避免其它方法帶來的不足。
Public Class InserTableDataGrid
Inherits System.Web.UI.Page
Protected WithEvents DataGrid1 As System.Web.UI.WebControls.DataGrid
#Region " Web Form Designer Generated Code "
'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
End Sub
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub
#End Region
Dim connstr As String = "Integrated Security=SSPI;User ID=sa;Initial Catalog=NorthWind;Data Source=.\netsdk"
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not Page.IsPostBack Then
BindGrid()
End If
End Sub
Sub BindGrid()
Dim cnn As New SqlConnection(connstr)
Dim da As New SqlDataAdapter("select employeeid,lastname,firstname from employees", cnn)
Dim ds As New DataSet()
da.Fill(ds, "employees")
DataGrid1.DataSource = ds
DataGrid1.DataBind()
End Sub
Private Sub DataGrid1_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs)_
Handles DataGrid1.ItemCommand
If e.CommandName = "Insert" Then
Dim cnn As New SqlConnection(connstr)
Dim t1 As TextBox = e.Item.FindControl("textbox2")
Dim t2 As TextBox = e.Item.FindControl("textbox4")
cnn.Open()
Dim cmd As New SqlCommand("insert into employees(lastname,firstname) values('" & t1.Text & "','" & t2.Text & "')", cnn)
cmd.ExecuteNonQuery()
cnn.Close()
BindGrid()
End If
End Sub
End Class