我有一个包含5列的SQL Server表。 col1
是主键。我在ASP.net 4.0工作。
我希望能够分别编辑和更新我的SQL Server表。
我对更新有点麻烦。这是我的代码:
<asp:GridView ID="GridView1" runat="server" AutoPostBack="True" AutoGenerateColumns="True" AutoGenerateEditButton="True" OnRowEditing="Gridview1_OnRowEditing" OnRowUpdating="GridView1_OnRowUpdating">
</asp:GridView>
代码:
Sub ShowGrid()
Dim connStr, cmdStr As String
connStr = "connection string works"
cmdStr = "SELECT * FROM table1;"
Dim MyDataSet As New DataSet
Dim MyDataTable As New DataTable()
Try
Using conn As New SqlConnection(connStr)
Using cmd As New SqlCommand(cmdStr, conn)
conn.Open()
cmd.ExecuteNonQuery()
Using MyDataAdaptor As New SqlDataAdapter(cmd)
MyDataAdaptor.Fill(MyDataSet)
MyDataTable = MyDataSet.Tables(0)
GridView1.EditIndex = Convert.ToInt32(ViewState("edit"))
GridView1.DataSource = MyDataTable
GridView1.DataBind()
End Using
conn.Close()
cmd.Dispose()
conn.Dispose()
End Using
End Using
Catch ex As Exception
Throw ex
End Try
End Sub
Protected Sub GridView1_OnRowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
GridView1.EditIndex = e.NewEditIndex
ViewState("edit") = GridView1.EditIndex
ShowGrid()
End Sub
Protected Sub GridView1_OnRowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
Dim connStr, cmdStr As String
connStr = "connection string works"
cmdStr = "UPDATE table1 SET (col2=@col2,col3=@col3,col4=@col4,col5=@col5) WHERE col1=@col1;"
Try
Using conn As New SqlConnection(connStr)
Using cmd As New SqlCommand(cmdStr, conn)
conn.Open()
cmd.Parameters.AddWithValue("@col1", GridView1.Rows(e.RowIndex).Cells(0).Text)
cmd.Parameters.AddWithValue("@col2", GridView1.Rows(e.RowIndex).Cells(1).Text)
cmd.Parameters.AddWithValue("@col3", GridView1.Rows(e.RowIndex).Cells(2).Text)
cmd.Parameters.AddWithValue("@col4", GridView1.Rows(e.RowIndex).Cells(3).Text)
cmd.Parameters.AddWithValue("@col5", GridView1.Rows(e.RowIndex).Cells(4).Text)
cmd.ExecuteNonQuery()
conn.Close()
cmd.Dispose()
conn.Dispose()
End Using
End Using
Catch ex As Exception
End Try
ViewState("edit") = e.RowIndex
ShowGrid()
End Sub