Datagrid question

G

Guest

In a datagrid on a webform, I display item_id, item_type, and item_description.
My item_types are numeric values ranging from 1-4. What I would like to do
is, for each item_type, I would like to display a different back color(for
the row). On each page I display 50 items of different types. Currently I
just assign a Data Table to my datagrids data source and bind:

dgrItemDetails.DataSource = SP that gets the Data Table.
dgrItemDetails.DataBind()

I am not sure at what point I should traverse through each row of data grid
and set a different back color depending on the item_type.... any tips are
greatly appreciated. TIA.
 
G

Guest

Hi

There is more than one way to do this, I would advise the following.
(I Assume that you are not using any template columns)
Here follows an explanation and then the example code (very easy)

In the ItemDataBound event do the following:
----------------------------------------------------
First you must know which column index contains the value you want to
validate.
(Remember the first column is 0)
In my example the 13th field contains a number so that is index 12

Secondly you must now check which row/item we are working with that is done
by interrogating the e.item.itemtype constant (remember an item is a ROW) we
do this so that we do not try and validate the number field of
headers/footers etc.

Thirdly we look at the item's cell text property - e.item.cells(13).text
this 'should' contain the value from your datasource for that field so we
can directly put down a conditional if statement checking the value of that
text field.

In my example below you will see I was setting the background color of an
entire item/row to RED if the value equals 5.

Check out the code and happy programming!!


Example Code:
-----------------



Private Sub dg_ItemDataBound(ByVal sender As Object, ByVal e As _
System.Web.UI.WebControls.DataGridItemEventArgs) Handles dg.ItemDataBound
'
'The valueColumn contains the value I want to validate
Const valueColumn As Integer = 12
'
Select Case e.Item.ItemType
'
'This ensure that you do not look at headers, footers etc.
Case ListItemType.AlternatingItem, ListItemType.EditItem,
ListItemType.Item, ListItemType.SelectedItem
'
'If my valueColumn contains the number 5 I want the
background color to be RED
If e.Item.Cells(valueColumn).Text = 5 Then
'
'set the background color if the entire row(item) to
RED!!!
e.Item.BackColor = Color.Red
End If
End Select
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top