Introduction
This article will demonstrate how to change the value of a DataGrid
column in multiple rows using checkboxes. This is a very common problem and it's easily implementable, so without much ado, let's get to the point.
Before I start, though, I'll put forward one assumption I make in this article, make sure your code meets the underlying requirement, otherwise you'll have to do some extra work.
I'll assume that the data bound to the grid is also editable through some object in your code (in other words, DataGrid
columns are properties of one object) and you have an update routine for this object. For example, in our case, the object we're using is PurchaseOrder
, and the column (property) is ApprovalStatus
.
First off, let's start with a simple bind routine. The getApproverPOs
function simply returns a DataTable
object, you can replace it with your own DataTable
.
Sub BindGrid()
dgPO.DataSource = PurchaseOrder.getApproverPOs
dgPO.DataBind()
End Sub
In our example, we have a dropdown named lstStatus
and a button named btnApply
.
The Iterate
routine which follows next will loop through each row and see if the checkbox (named chk
) in the DataGrid
's first template column is checked, if so, it will load PurchaseOrder
, set a new ApprovalStatus
, and update the changes.
Public Sub Iterate()
Dim DGItem As DataGridItem
Dim chkSel As System.Web.UI.WebControls.CheckBox
Dim po As PurchaseOrder
For Each DGItem In dgPO.Items
chkSel = DGItem.FindControl("chk")
If chkSel.Checked Then
po = PurchaseOrder.getPO(DGItem.Cells(1).Text)
po.ApprovalStatus = lstStatus.SelectedItem.Value
PurchaseOrder.NotifyPoster(po)
po.Update()
End If
Next
End Sub
And finally, we need an event handler for our button which will point to the Sub
above. We use Response.Redirect
in the end to refresh the checkboxes, as well as the ApprovalStatus
column.
Private Sub btnApply_Click(ByVal sender _
As System.Object, ByVal e As System.EventArgs) _
Handles btnApply.Click
Iterate()
Response.Redirect("thissamefile.aspx")
End Sub
That's all there is! Hope this was helpful.