gridview PageIndexChanging issue
I am trying to to loop through a dataset's value through the rows in a gridview and color in the text if that row matches.
The code below works however whenever I change the page through the PageIndexChanging
and this function is ran again, the coloring doesn't work anymore. It still loops through the gridview if there is a match but the effects are not shown.
--variable initialization class instantiation--
--code to connect to db here--
mySQLCommand.CommandText = "SELECT ..."
mySQLAdapter = New SqlDataAdapter(mySQLCommand)
mySQLAdapter.Fill(myDataset)
Me.MainPageGridView.DataSource = myDataset
Me.MainPageGridView.DataBind()
mySQLCommand.CommandText = "SELECT ... The ID's to be matched"
mySQLAdapter = New SqlDataAdapter(mySQLCommand)
mySQLAdapter.Fill(myDatasetNew)
Me.MainPageGridView.DataSource = myDatasetNew
For Each dataRow In myDataset.Tables(0).Rows
thisID = dataRow("ID").ToString
For Each gvRow In Me.MainPageGridView.Rows
If gvRow.Cells(2).Text = thisID Then
For column = 0 To 14 Step 1
gvRow.Ce开发者_运维知识库lls(column).ForeColor = Drawing.Color.RosyBrown
Next
Exit For
End If
Next
Next
Why don't you use MainPageGridView_RowDataBound
event to match the id? I have re-factored your original code to something like below, please check and let me know if it works:
'In DataBind or some other method
'Load(myDataSet)
mySQLCommand.CommandText = "SELECT ..."
mySQLAdapter = New SqlDataAdapter(mySQLCommand)
mySQLAdapter.Fill(myDataset)
'Load myDatasetNew and bind it to grid
mySQLCommand.CommandText = "SELECT ... The ID's to be matched"
mySQLAdapter = New SqlDataAdapter(mySQLCommand)
mySQLAdapter.Fill(myDatasetNew)
Me.MainPageGridView.DataSource = myDatasetNew
Me.MainPageGridView.DataBind()
and perform id matching in
Protected Sub MainPageGridView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles MainPageGridView.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim id As String = DataBinder.Eval(e.Row.DataItem, "ID") 'The name of ID column in "myDatasetNew"
Dim dv As System.Data.DataView = myDataset.Tables(0).DefaultView
dv.RowFilter = "ID = " & id
If dv.Count > 0 Then 'id matches
'Change foreclor of entire row
e.Row.ForeColor = Drawing.Color.RosyBrown
End If
End If
End Sub
You really need to do your data comparison in the GridView.RowDataBound event.
精彩评论