Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I have the Gridview.
When I select the check box in the gridview, it's getting highlighted in one color and working fine.
Then, when I visit the next page, the check box is be checked but the color is gone.
When I 'mouseover' only the color will appear.
What is the problem here?
see my complete code
--------------------
ASPX Code
*********
 <script type="text/javascript" language="javascript">
    
        //Reference of the GridView. 
        var TargetBaseControl = null;
        //Total no of checkboxes in a particular column inside the GridView.
        var CheckBoxes;
        //Total no of checked checkboxes in a particular column inside the GridView.
        var CheckedCheckBoxes;
        //Array of selected item's Ids.
        var SelectedItems;
        //Hidden field that wil contain string of selected item's Ids separated by '|'.
        var SelectedValues;
        window.onload = function () {
            //Get reference of the GridView. 
            try {
                TargetBaseControl = document.getElementById('<%= gvCheckboxes.ClientID %>');
            }
            catch (err) {
                TargetBaseControl = null;
            }
            //Get total no of checkboxes in a particular column inside the GridView.
            try {
                CheckBoxes = parseInt('<%= gvCheckboxes.Rows.Count %>');
            }
            catch (err) {
                CheckBoxes = 0;
            }
            //Get total no of checked checkboxes in a particular column inside the GridView.
            CheckedCheckBoxes = 0;
            //Get hidden field that wil contain string of selected item's Ids separated by '|'.
            SelectedValues = document.getElementById('<%= hdnFldSelectedValues.ClientID %>');
            //Get an array of selected item's Ids.
            if (SelectedValues.value == '')
                SelectedItems = new Array();
            else
                SelectedItems = SelectedValues.value.split('|');
            //Restore selected CheckBoxes' states.
            if (TargetBaseControl != null)
                RestoreState();
        }
        function HeaderClick(CheckBox) {
            //Get all the control of the type INPUT in the base control.
            var Inputs = TargetBaseControl.getElementsByTagName('input');
            //Checked/Unchecked all the checkBoxes in side the GridView & modify selected items array.
            for (var n = 0; n < Inputs.length; ++n)
                if (Inputs[n].type == 'checkbox' && Inputs[n].id.indexOf('chkBxSelect', 0) >= 0) {
                    Inputs[n].checked = CheckBox.checked;
                    if (CheckBox.checked)
                        SelectedItems.push(document.getElementById(Inputs[n].id.replace('chkBxSelect', 'hdnFldId')).value);
                    else
                        DeleteItem(document.getElementById(Inputs[n].id.replace('chkBxSelect', 'hdnFldId')).value);
                }
            //Update Selected Values. 
            SelectedValues.value = SelectedItems.join('|');
            //Reset Counter
            CheckedCheckBoxes = CheckBox.checked ? CheckBoxes : 0;
        }
        function ChildClick(CheckBox, HCheckBox, Id) {
            //Modifiy Counter;            
            if (CheckBox.checked && CheckedCheckBoxes < CheckBoxes)
                CheckedCheckBoxes++;
            else if (CheckedCheckBoxes > 0)
                CheckedCheckBoxes--;
            //Change state of the header CheckBox.
            if (CheckedCheckBoxes < CheckBoxes)
                HCheckBox.checked = false;
            else if (CheckedCheckBoxes == CheckBoxes)
                HCheckBox.checked = true;
            //Modify selected items array.
            if (CheckBox.checked)
                SelectedItems.push(Id);
            else
                DeleteItem(Id);
            //Update Selected Values. 
            SelectedValues.value = SelectedItems.join('|');
        }
        function RestoreState() {
            //Get all the control of the type INPUT in the base control.
            var Inputs = TargetBaseControl.getElementsByTagName('input');
            //Header CheckBox
            var HCheckBox = null;
            //Restore previous state of the all checkBoxes in side the GridView.
            for (var n = 0; n < Inputs.length; ++n)
                if (Inputs[n].type == 'checkbox' && Inputs[n].id.indexOf('chkBxSelect', 0) >= 0)
                    if (IsItemExists(document.getElementById(Inputs[n].id.replace('chkBxSelect', 'hdnFldId')).value) > -1) {
                        Inputs[n].checked = true;
                        CheckedCheckBoxes++;
                    }
                    else
                        Inputs[n].checked = false;
                else if (Inputs[n].type == 'checkbox' && Inputs[n].id.indexOf('chkBxHeader', 0) >= 0)
                    HCheckBox = Inputs[n];
            //Change state of the header CheckBox.
            if (CheckedCheckBoxes < CheckBoxes)
                HCheckBox.checked = false;
            else if (CheckedCheckBoxes == CheckBoxes)
                HCheckBox.checked = true;
          
        }
        function DeleteItem(Text) {
            var n = IsItemExists(Text);
            if (n > -1)
                SelectedItems.splice(n, 1);
        }
        function IsItemExists(Text) {
            for (var n = 0; n < SelectedItems.length; ++n)
                if (SelectedItems[n] == Text)
                    return n;
            return -1;
        }
        function ItemMouseOver(oRow, chkBxMail) {
            oCheckBox = document.getElementById(chkBxMail);
            //oImage = document.getElementById(imgMail);
            if (!oCheckBox.checked) 
            {
                oCheckBox.style.display = '';
                //oImage.style.display = 'none';
                oRow.originalBackgroundColor = oRow.style.backgroundColor
                oRow.style.backgroundColor = 'White';
            }
            if (oCheckBox.checked) {
                oCheckBox.style.display = '';
                //oImage.style.display = 'none';
                oRow.originalBackgroundColor = oRow.style.backgroundColor
                oRow.style.backgroundColor = 'lightyellow';
            }
        }
        function ItemMouseOut(oRow, chkBxMail) {
            oCheckBox = document.getElementById(chkBxMail);
            //oImage = document.getElementById(imgMail);
            if (!oCheckBox.checked) {
                oCheckBox.style.display = 'none';
                //oImage.style.display = '';
                oRow.style.backgroundColor = oRow.originalBackgroundColor;
            }
            if (oCheckBox.checked) {
                oCheckBox.style.display = 'none';
                //oImage.style.display = '';
                oRow.style.backgroundColor = oRow.originalBackgroundColor;
                oRow.style.backgroundColor = 'lightyellow';
            }
        }
    </script>
<table>
<tr>
<td>
     <asp:GridView ID="gvCheckboxes" runat="server" AutoGenerateColumns="False" OnPageIndexChanging="gvCheckboxes_PageIndexChanging"
            OnRowDataBound="gvCheckboxes_RowDataBound" AllowPaging="True" class="tabulardata">
            <columns>
                <asp:TemplateField HeaderText="Select">
                    <itemtemplate>
                        <asp:CheckBox ID="chkBxSelect" type="checkbox" runat="server" AutoPostBack="true"/>
                        <asp:HiddenField ID="hdnFldId" runat="server" Value='<%# Eval("Id") %>' />
                    </itemtemplate>
                    <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
                    <itemstyle horizontalalign="Center" verticalalign="Middle" width="50px" />
                    <HeaderTemplate>
                        <asp:CheckBox ID="chkBxHeader" onclick="javascript:HeaderClick(this);" runat="server" />
                    </HeaderTemplate>
                
                <asp:BoundField DataField="RandomNo" HeaderText="Random Number">
                    <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="150px" />
                    <itemstyle horizontalalign="Center" verticalalign="Middle" width="150px" />
                
                <asp:BoundField DataField="Date" HeaderText="Date">
                    <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="75px" />
                    <itemstyle horizontalalign="Center" verticalalign="Middle" width="75px" />
                
                <asp:BoundField DataField="Time" HeaderText="Time">
                    <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="100px" />
                    <itemstyle horizontalalign="Center" verticalalign="Middle" width="100px" />
                
            </columns>
            <rowstyle height="25px" backcolor="#FFFDFB" horizontalalign="Center" verticalalign="Middle" />
        
        <asp:HiddenField ID="hdnFldSelectedValues" runat="server" />
</td> 
</tr> 
</table> 


ASPX.VB Code
************
Private Sub BindGridView()
        gvCheckboxes.DataSource = GetDataSource()
        gvCheckboxes.DataBind()
    End Sub
    Protected Sub gvCheckboxes_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
        gvCheckboxes.PageIndex = e.NewPageIndex
        BindGridView()
    End Sub
    Protected Sub gvCheckboxes_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
        If e.Row.RowType = DataControlRowType.DataRow AndAlso (e.Row.RowState = DataControlRowState.Normal OrElse e.Row.RowState = DataControlRowState.Alternate) Then
            Dim chkBxSelect As CheckBox = DirectCast(e.Row.Cells(0).FindControl("chkBxSelect"), CheckBox)
            Dim chkBxHeader As CheckBox = DirectCast(Me.gvCheckboxes.HeaderRow.FindControl("chkBxHeader"), CheckBox)
            Dim hdnFldId As HiddenField = DirectCast(e.Row.Cells(0).FindControl("hdnFldId"), HiddenField)
            Dim chkBxMail As CheckBox = DirectCast(e.Row.Cells(0).FindControl("chkBxSelect"), CheckBox)
            'Dim imgMail As Image = DirectCast(e.Row.Cells(1).FindControl("imgMail"), Image)
            e.Row.Attributes("onmouseover") = String.Format("javascript:ItemMouseOver(this,'{0}');", chkBxMail.ClientID)
            e.Row.Attributes("onmouseover") = String.Format("javascript:ItemMouseOver(this,'{0}');", chkBxMail.ClientID)
            chkBxSelect.Attributes("onclick") = String.Format("javascript:ChildClick(this,document.getElementById('{0}'),'{1}');", chkBxHeader.ClientID, hdnFldId.Value.Trim())
        End If
    End Sub
    Private Function GetDataSource() As DataTable
        Dim dTable As New DataTable()
        Dim dRow As DataRow = Nothing
        Dim dTime As DateTime
        Dim rnd As New Random()
        dTable.Columns.Add("Id", System.Type.[GetType]("System.Int32"))
        dTable.Columns(0).AutoIncrement = True
        dTable.Columns.Add("RandomNo")
        dTable.Columns.Add("Date")
        dTable.Columns.Add("Time")
        For n As Integer = 0 To 24
            dRow = dTable.NewRow()
            dTime = DateTime.Now
            dRow("RandomNo") = rnd.NextDouble()
            dRow("Date") = dTime.ToString("MM/dd/yyyy")
            dRow("Time") = dTime.ToString("hh:mm:ss tt")
            dTable.Rows.Add(dRow)
            dTable.AcceptChanges()
        Next
        Return dTable
    End Function
    'Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
    '    'Get Ids
    '    Dim IDs As String() = hdnFldSelectedValues.Value.Trim().Split("|"c)
    '    'Code for deleting items
    '    'Call appropiate method for deletion operation.
    '    For Each Item As String In IDs
    '    Next
    'End Sub
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            BindGridView()
        End If
    End Sub


Please help, I have been trying and waiting the half a day...
Posted
Updated 4-Aug-11 2:12am
v3

1 solution

when postback.....
in GridViewOnRowDataBound event check if your chekcbox is checked and set appropriate color.
 
Share this answer
 
Comments
gani7787 4-Aug-11 8:36am    
what is the syntax to set particular color in gridview..?
gani7787 4-Aug-11 8:36am    
what is the syntax to set particular row color in gridview..?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900