正文

ArrayList

(2007-08-12 20:43:54) 下一個
A datagrid(say from a data table in sql server database) is loaded onto a page in page load procedure. One of the columns (each cell in the column contains a check box and only one check box) contains check boxes. Some of the check boxes are already checked when page is loaded. Here client can check more. The work is to insert a message into database table when any check box is newly checked but not those already checked when the page is loaded.

I put the checked ones in an arraylist in page load procedure. when insert button is clicked call the arraylist's Contains() method, which checks arraylist items one by one: if it exists in the arraylist, do nothing. if it is not that is to say this is newly checked, so insert a message into database table.

Array has a fixed size. Arraylist doesn't. So I use Arraylist here.

Datagrid is like a data table in database. Its DataKeyField, like a primary key in a data table, uniquely identifies a row. There is no duplication. So, add DataKeyField into the arraylist. And use the Contains() method check the the cell that contains DataKeyField of the newly checked rows.

This is a good website: http://msdn2.microsoft.com/en-us/library
It has almost every topic and provides simple implimentations.




Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim myAL As New ArrayList
Try
With datagrid1

'these 3 lines populate datagrid

.DataSource = CallStoreProcedure
.DataKeyField = UsePrimaryKey
.DataBind()

Dim iCount As Int32
For iCount = 0 To .Items.Count - 1

'if it is checked, add DataKeyField to arraylist. CType(,)converts 1st parameter to the type of 2nd parameter.
'for each row in datagrid, column 3 (Cells(2)) contains checkbox control (Controls(1))

If CType(.Items(iCount).Cells(2).Controls(1), System.Web.UI.WebControls.CheckBox).Checked= True Then
myAL.Add(CType(.Items(iCount).Cells(0).Text, Int32))

End If
Next



'put arraylist in viewstate variable, when page is reload we still can retrieve the arraylist.

ViewState("myArrayList") = myAL
End With
Catch ex As Exception
...
Finally
...
End Try
End Sub



Private Sub InsertButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles _
InsertButton.Click

Try
With dgNotes
For iCount = 0 To .Items.Count - 1
If CType(.Items(iCount).Cells(2).Controls(1), System.Web.UI.WebControls.CheckBox).Checked = True Then
Dim myAL As New ArrayList
myAL = CType(ViewState("myArrayList"), ArrayList)
If myAL.Contains(CType(.Items(iCount).Cells(0).Text, Int32)) = False Then
CallInsertProcedure
End If
End If
Next
End With
Catch ex As Exception
...
Finally
...
End Try
End Sub
[ 打印 ]
閱讀 ()評論 (1)
評論
目前還沒有任何評論
登錄後才可評論.