Link to home
Start Free TrialLog in
Avatar of shieldguy
shieldguyFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Datagrid How to set the alternate column style without in sequence

I have one datagrid I need to change the alternate column style in a way that its just not change after every row.

But as you can see in the picture I like to set the same color for 1 and the row before to 2 and same for
13 and the next row should be same color and then 14 should be the other color is it possible to do ?

Thanks
Avatar of Velio
Velio
Flag of South Africa image

yes, it's possible to set the styling of the rows in the ItemDataBound event, according to whatever criteria you need.

set one or more of these property, as per your requirements:
for per item styling, use these:
DataGrid.Items(index).CssClass,
DataGrid.Items(index).Style,

for per cell styling, use these:
DataGrid.Items(index).Cells(index).CssClass,
DataGrid.Items(index).Cells(index).Style.
Avatar of shieldguy

ASKER

so I need to loop through the each item of datagrid,

Actually I am binding the datagrid with the Dataset, is it possible that I set some settings in the dataset and when I bind the grid with it , the grid do the alternate column settings itself
This is my datagrid
DataGrid.jpg
yes,

here's a quick sample which shows some possible permutations.
<%@ Page Language="VB" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<script runat="server">
    Public Overrides Sub DataBind()
        Dim numbers(17) As Integer
        Dim index As Integer
        For index = 0 To 17
            numbers(index) = index
        Next
        dataGrid.DataSource = numbers
        MyBase.DataBind()
    End Sub
    
    Public Sub Page_Load()
        If Not IsPostBack Then
            DataBind()
        End If
    End Sub
 
    Protected Sub dataGrid_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs)
        Dim data As Integer = CInt(e.Item.DataItem)
        If (data Mod 3 = 0) Then
            e.Item.CssClass = "red"
        ElseIf (data Mod 3 = 1) Then
            e.Item.Style.Add(HtmlTextWriterStyle.BackgroundColor, "#00FF00;")
        ElseIf (e.Item.ItemIndex Mod 3 = 2) Then
            e.Item.Cells(0).Style.Add(HtmlTextWriterStyle.BackgroundColor, "#0000FF;")
        End If
    End Sub
</script>
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <style type="text/css">
        .red { background: red; }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:DataGrid runat="server" id="dataGrid" OnItemDataBound="dataGrid_ItemDataBound">
    </asp:DataGrid>
    </div>
    </form>
</body>
</html>

Open in new window

I am now getting error in this line of code

RowNum = TryCast(e.Item.FindControl("RowNum"), Label)

The RowNum is comming nothing how can I read the rowNum value actually its a label which name is RowNum
Thanks
    Private Sub GridSearch_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles GridSearch.ItemDataBound
        Dim RowNum As Label
        RowNum = TryCast(e.Item.FindControl("RowNum"), Label)
 
        If (Trim(RowNum.Text) <> "") Then
            If e.Item.CssClass = "tableItem" Then
                e.Item.CssClass = "alternatingItem"
            ElseIf e.Item.CssClass = "alternatingItem" Then
                e.Item.CssClass = "tableItem"
            End If
        End If
 
    End Sub

Open in new window

How can I read the first column value of the selected data item
this probably happens when the e.Item is a header or footer.

put a check around it, like so
if (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) then
..
.. your code
..
end if
Now I am having problem in setting the style as you can see in the style of my datagrid I had defined the style SelectedItemStyle and AlternatingItemStyle

how can I uset them is it possible to do it trhough the follwoing code

        If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then

            Dim RowNum As Label
            RowNum = TryCast(e.Item.FindControl("RowNum"), Label)

            If (Trim(RowNum.Text) <> "") Then
                If e.Item.CssClass = "tableItem" Then
                    e.Item.Cells(0).Style.Add(HtmlTextWriterStyle.BackgroundColor, "PaleGoldenrod")
                ElseIf e.Item.CssClass = "alternatingItem" Then
                    e.Item.Cells(0).Style.Add(HtmlTextWriterStyle.BackgroundColor, "DarkSlateBlue")
                Else
                    e.Item.Cells(0).Style.Add(HtmlTextWriterStyle.BackgroundColor, "DarkSlateBlue")
                End If
            End If
        End If

                   <asp:DataGrid ID="GridSearch" runat="server" HeaderStyle-HorizontalAlign="Center"
                        ItemStyle-HorizontalAlign="Center" ShowFooter="True" AllowSorting="True" ForeColor="Black"
                        GridLines="None" CellPadding="2" BackColor="LightGoldenrodYellow" BorderWidth="1px"
                        BorderColor="Tan" Width="800px" AutoGenerateColumns="False" DataKeyField=""
                        Font-Size="Small" OnSortCommand="SortCommand_OnClick" PagerStyle-Mode="NumericPages" PagerStyle-Font-Bold="true" 
                        PagerStyle-Font-Size="Medium" PagerStyle-HorizontalAlign="Right" AllowPaging="true" OnPageIndexChanged="PageIndexChanged_OnClick" 
                        PageSize="32" PagerStyle-Visible="False">
 
                       <SelectedItemStyle ForeColor="GhostWhite" BackColor="DarkSlateBlue"></SelectedItemStyle>
                        <AlternatingItemStyle BackColor="PaleGoldenrod"></AlternatingItemStyle>
                         <HeaderStyle Font-Size="Small" Font-Bold="True" BackColor="Tan"></HeaderStyle>
                        <FooterStyle BackColor="Tan"></FooterStyle>
        

Open in new window

1. if you want to include selected items, include the ListItemType.SelectedItem in your check
2. you're only settings Cell(0)'s style... is that cell visible?
Oh no thats a mistake I need to set the whole item row value not the cell can you tell me how to do it as well

Can you give me some code example

Thanks
what do u mean by "if you want to include selected items, include the ListItemType.SelectedItem in your check"

I didnt understand

Explain please
the above check would skip the styling you're doing on the selected item,

ie
use this instead.
If (e.Item.ItemType = ListItemType.AlternatingItem Or e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.SelectedItem) Then
.
.
.
both
e.Item and e.Item.Cells(..)
have the Style attribute, just take out Cell(0) and it'll style the entire row.

Actually their are two styles I defined with in the datagrid as you can see in my datagrid code in previous post and I want to use these two styles How can I set the Style of the selected Item in if check to either SelectedItemStyle or AlternatingItemStyle


 The styles
                     <SelectedItemStyle ForeColor="GhostWhite" BackColor="DarkSlateBlue"></SelectedItemStyle>
                        <AlternatingItemStyle BackColor="PaleGoldenrod"></AlternatingItemStyle>
 
-- to set the style to the selected item style:
e.Item.Style.Style.Add(HtmlTextWriterStyle.BackgroundColor, "DarkSlateBlue")
e.Item.Style.Style.Add(HtmlTextWriterStyle.Color, "GhostWhite")

-- to set the style to the selected item
e.Item.Style.Style.Add(HtmlTextWriterStyle.BackgroundColor, "PaleGoldenrod")

oh thanks can you tell me one more thing

how can I check the current backgorund color now

Like in this check what changes i need to make

If e.Item.CssClass = "tableItem" Then
...
...
the pre-set styling is applied after the data is bound,
which means it's not available in the RowDataBound event.

you could use the ItemIndex to determine the color...
all even items would be item and all odd indexes would be alternate items... (this is for 0-based indexing)

if (e.Item.ItemIndex mod 2 = 0) then
 '<ItemStyle> would normally be applied
else
 '<alternateitemstyle> would normally be applied
end if
thats the problem bevause i have random item like if u check the datagrid picture i posted before No 1 should be of same color and also the row just after it they belong to same set but the 2 should be the other color

is their any other way ?
what you can do is keep another index, which gets reset after every blank item.

some pseudo code:

if (item is blank) then
 set item style
 reset item counter
else
 if (item counter mod 2 = 0)
  set item style
 else
  set item alternative style
 end if
 increment counter
end if
Now my datagrid looks like this after changes,

why the color are so different now

Can you please tell me whats the problem

Thanks

 
    Private Sub GridSearch_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles GridSearch.ItemDataBound
 
        If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
 
            Dim RowNum As Label
            RowNum = TryCast(e.Item.FindControl("RowNum"), Label)
 
            If (Trim(RowNum.Text) <> "") Then
                If lblItemStatus.Text = "" Then
                    e.Item.Style.Add(HtmlTextWriterStyle.BackgroundColor, "DarkSlateBlue")
                    e.Item.Style.Add(HtmlTextWriterStyle.Color, "GhostWhite")
                    lblItemStatus.Text = "SELECTEDITEMSTYLE"
                ElseIf UCase(lblItemStatus.Text) = "SELECTEDITEMSTYLE" Then
                    e.Item.Style.Add(HtmlTextWriterStyle.BackgroundColor, "DarkSlateBlue")
                    e.Item.Style.Add(HtmlTextWriterStyle.Color, "GhostWhite")
                    lblItemStatus.Text = "ALTERNATINGITEMSTYLE"
                ElseIf UCase(lblItemStatus.Text) = "ALTERNATINGITEMSTYLE" Then
                    e.Item.Style.Add(HtmlTextWriterStyle.BackgroundColor, "PaleGoldenrod")
                    lblItemStatus.Text = "SELECTEDITEMSTYLE"
                End If
            End If
        End If
    End Sub
 
 
 
 
                  <asp:DataGrid ID="GridSearch" runat="server" HeaderStyle-HorizontalAlign="Center"
                        ItemStyle-HorizontalAlign="Center" ShowFooter="True" AllowSorting="True" ForeColor="Black"
                        GridLines="None" CellPadding="2" BackColor="LightGoldenrodYellow" BorderWidth="1px"
                        BorderColor="Tan" Width="800px" AutoGenerateColumns="False" DataKeyField=""
                        Font-Size="Small" OnSortCommand="SortCommand_OnClick" PagerStyle-Mode="NumericPages" PagerStyle-Font-Bold="true" 
                        PagerStyle-Font-Size="Medium" PagerStyle-HorizontalAlign="Right" AllowPaging="true" OnPageIndexChanged="PageIndexChanged_OnClick" 
                        PageSize="32" PagerStyle-Visible="False">
 
                        <HeaderStyle Font-Size="Small" Font-Bold="True" BackColor="Tan"></HeaderStyle>
                        <FooterStyle BackColor="Tan"></FooterStyle>

Open in new window

DataGrid1.jpg
ok, let's back track a bit and clarify things up a bit.
this is how i understand the problem:
1. if the RowNum text is blank, it must have the same color as the row above it
2. the items must alternate between the two beige shades
3. if an item is selected, it must be blue (together with any blank items below it)

is that right?
No

Actually I am displaying the records which have the orders and each order can be consists of more than one records so let say if RowNum has 1 so this is a order and its consists of two products so I row 1 and the one after it showing its product so I like to set each order with alternate color so its more readable

I hope you understand
ok, please indicate in your original data grid, where each order begins and ends (which rows must be colored to the same order)
eg:
row 1-2: order 1
row 3-6: order 2
row 7-8: order 3
... and so on.
OK I make it simple In the attach pic all I wanted is to set the different color for when ever the value comes in to the RowNum Column

Like first row have 1 so the let say we set the color to green
Then next row is empty so we keep the same color

Then comes 2 we change the color
then comes 3 we again change the color
and its gies on this way
when 13  comes we again chage the color
next row after 13 is same so we keep the color and didnt change it
then in 14 we again chnage color

These gaps can occur randomly

I hope u understand


DataGrid.jpg
ASKER CERTIFIED SOLUTION
Avatar of Velio
Velio
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
oh great can you please tell me what this line doing

alternateItem = Not alternateItem

as I am getting error that alternateItem is not declared

Thanks
Ok I understand what you mean by alternateItem
yes, alternateitem is our internal way of keeping track when the item's colour should be changed.

basically the flag is switched every time a number is encountered. the result is that all "blank" rows will be rendered with the same background as the last row with a number.
there is one issue with this sample... selected items will not show up with any specific color.
I think I dont need the selected item in this report

Your code work fine, I am very thankful to you

its really take a long time but we got it working fine

Thanks to everone
Great support , Thank alot
heh, quite a while indeed, glad you got it working in the end :)