다음을 통해 공유


ASP.NET: Update Gridview with Checkbox Column

Suppose That we have a gridview containing a chekcbox and binded to a table that contain a bit column .

How we can edit that Gridview and insert changes in the checkbox column.

Parse XML of the Gridview :

<asp:GridView ID="GridView1" runat="server"  onrowcancelingedit="GridView1_RowCancelingEdit"
 onrowediting="GridView1_RowEditing"
 onrowupdating="GridView1_RowUpdating" >
  
 <Columns>
 <asp:CommandField ShowEditButton="true" />
 <asp:TemplateField HeaderText="active">
 <EditItemTemplate>
 <asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Bind("autorise") %>'  AutoPostBack="true" />
 </EditItemTemplate>
 <ItemTemplate>
 <asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Bind("autorise") %>'
 Enabled="False" />
 </ItemTemplate>
 </asp:TemplateField>
 </Columns>
 </asp:GridView>

autorise is the bit column in the database (0 or 1)

In the code behind we should find the control checkbox and update it

Protected Sub  GridView1_RowEditing(ByVal sender As Object, ByVal  e As  GridViewEditEventArgs)
 GridView1.EditIndex = e.NewEditIndex
 BindGrid()
 End Sub
 
 Protected Sub  GridView1_RowCancelingEdit(ByVal sender As Object, ByVal  e As  GridViewCancelEditEventArgs)
 GridView1.EditIndex = -1
 BindGrid()
 End Sub
 Protected Sub  GridView1_RowUpdating(ByVal sender As Object, ByVal  e As  GridViewUpdateEventArgs)
 For Each  GridViewRow In GridView1.Rows
 
 Dim row As GridViewRow = GridView1.Rows(e.RowIndex)
 Dim value As Boolean
 value = DirectCast(GridView1.Rows(e.RowIndex).Cells(0).FindControl("CheckBox1"), CheckBox).Checked
 Dim connectionString As String  = ConfigurationManager.ConnectionStrings("TABLEConnectionString").ConnectionString
 Dim com_sql As New  SqlClient.SqlCommand
 Dim insertSql As String
 insertSql = "UPDATE  mytable SET autorise='"  & value & "' "
 Using myConnection As  New SqlConnection(connectionString)
 myConnection.Open()
 Dim myCommand As New  SqlCommand(insertSql, myConnection)
 myCommand.Parameters.AddWithValue("@autorise", value)
 myCommand.ExecuteNonQuery()
 myConnection.Close()
 End Using
 Next
 GridView1.EditIndex = -1
 BindGrid()
 End Sub

BindGrid is a method that bind the gridview and TABLEConnectionString is the name of the connectionstring in the web.config that you will find in  the appropriate section.

Happy coding!

See Also