Click here to Skip to main content
15,885,988 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello Everybody,

I have the following database design:


SQL
Employee Table: Username, Name, JobTitle, BadgeNo, IsActive, DivisionCode
    Divisions Table: SapCode, DivisionShortcut



And I have a GridView that I am using it to add, delete and update/edit the employees information. This information is employee Username, Name, BadgeNo, JobTitle, IsActive and the DivisionShortcut. IsActive is a flag that indicates if the employee is available or in an assignment. I made it as a checkbox and the column should show two values; Active and Inactive. In the Edit mode, the Checkbox will be displayed. If it is checked, then it means the employee is avaiable, otherwise it is inactive.

I wrote the code and everything works fine, but now I am facing only one problem which is the following: when the checkbox is unchecked that means the employee is inactive, so I want the row that shows his information to be in a grey color (like disabled). So how to do that?

ASP.NET code:
<%-- GridView for User Management Subsystem --%>
        <asp:GridView ID="GridView1" runat="server" AllowSorting="True" 
            AutoGenerateColumns="False" DataKeyNames="Username" 
            DataSourceID="SqlDataSource1" BorderWidth="1px" BackColor="#DEBA84" 
             CellPadding="3" CellSpacing="2" BorderStyle="None" 
             BorderColor="#DEBA84">
            <FooterStyle ForeColor="#8C4510" 
              BackColor="#F7DFB5"></FooterStyle>
            <PagerStyle ForeColor="#8C4510" 
              HorizontalAlign="Center"></PagerStyle>
            <HeaderStyle ForeColor="White" Font-Bold="True" 
              BackColor="#A55129"></HeaderStyle>
            <Columns>
                <asp:CommandField ButtonType="Image" ShowEditButton="true" ShowCancelButton="true"
                                EditImageUrl="Images/icons/edit24.png" UpdateImageUrl="Images/icons/update24.png" 
                                CancelImageUrl="Images/icons/cancel324.png" />

                <asp:TemplateField HeaderText="Division">
                    <ItemTemplate>
                        <%# Eval("DivisionShortcut")%>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:DropDownList ID="DivisionsList" runat="server" DataSourceID="DivisionsListDataSource"
                                          DataTextField="DivisionShortcut" DataValueField="SapCode"
                                          SelectedValue='<%# Bind("DivisionCode")%>'>
                        </asp:DropDownList>
                    </EditItemTemplate>
                </asp:TemplateField>

                <asp:BoundField DataField="Username" HeaderText="Network ID" ReadOnly="True" 
                    SortExpression="Username" />
                    
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <%# Eval("Name")%>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtEmployeeName" runat="server" Text='<%# Bind("Name")%>' />
                    </EditItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField HeaderText="Job Title">
                    <ItemTemplate>
                        <%# Eval("JobTitle")%>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtJobTitle" runat="server" Text='<%# Bind("JobTitle")%>' />
                    </EditItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField HeaderText="Badge No.">
                    <ItemTemplate>
                        <%# Eval("BadgeNo")%>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtBadgeNo" runat="server" Text='<%# Bind("BadgeNo")%>' />
                    </EditItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField HeaderText="Is Active?">
                    <ItemTemplate>
                        <%# Eval("IsActive")%>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:CheckBox ID="isActive" runat="server" 
                                      AutoPostBack="true" OnCheckedChanged="isActive_OnCheckedChanged"
                                      Checked='<%# Convert.ToBoolean(Eval("IsActive")) %>'
                                      Text='<%# Eval("IsActive").ToString().Equals("True") ? " Active " : " Inactive " %>'/>
                    </EditItemTemplate>
                </asp:TemplateField>
                
                <asp:TemplateField HeaderText="Delete?">
                    <ItemTemplate>
                        <span  önclick="return confirm('Are you sure to Delete the record?')">
                            <asp:ImageButton ID="lnkB" runat="server" ImageUrl="Images/icons/delete24.png" CommandName="Delete" />
                        </span>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>


Code-behind:
C#
//for updating the (IsActive) column using checkbox inside the GridView
    protected void isActive_OnCheckedChanged(object sender, EventArgs e)
    {
        CheckBox chkStatus = (CheckBox)sender;
        GridViewRow gvrow = (GridViewRow)chkStatus.NamingContainer;

        //Get the ID which is the NetworkID of the employee
        string username = gvrow.Cells[2].Text;
        bool status = chkStatus.Checked;

        string connString = ConfigurationManager.ConnectionStrings["UsersInfoDBConnectionString"].ConnectionString;
        SqlConnection conn = new SqlConnection(connString);

        string updateIsActive = "UPDATE Employee SET IsActive = @IsActive WHERE Username = @Username";

        SqlCommand cmd = new SqlCommand(updateIsActive, conn);

        cmd.Parameters.AddWithValue("@IsActive", status);
        cmd.Parameters.AddWithValue("@Username", username);

        try
        {
            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();
        }
        catch (SqlException se)
        {
            throw se;
        }
        finally
        {
            cmd.Dispose();
            conn.Close();
            conn.Dispose();
        }
    }
Posted

another solution is using a javascript (jquery) in order to change the color.

a first "scan" of the checkbox
and then check the click event.

the click event can be removed if the checkbox is readonly.

HTML
<html>
 <head>
   <meta http-equiv="content-type" content="text/html; charset=UTF-8">
   <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
   <style type="text/css">
  .highlight { background-color:gray; color:#eee;}
   </style>
  <script type="text/javascript">
    $(document).ready(function() {
     Paint();
     
     $("#tabledata :checkbox").click(function () {
      $(this).parent('td').parent('tr').toggleClass("highlight");
     });
    });
 
    function Paint() {
     $("#tabledata :checkbox:checked").each(function() {
      $(this).parent('td').parent('tr').toggleClass("highlight");
     })
    }
   </script>
 </head>
 <body>
  <table id="tabledata">
   <tbody>
    <tr><td>text1</td><td><input type="checkbox" ></td></tr>
    <tr><td>text1</td><td><input type="checkbox" checked="checked"></td></tr>
    <tr><td>text1</td><td><input type="checkbox" ></td></tr>
    <tr><td>text1</td><td><input type="checkbox" checked="checked"></td></tr>
   </tbody>
  </table>
 </body>
</html>


ps sorry for the strange view but the Preview is different from the result -.- i don't know how to change it :)
 
Share this answer
 
v5
Hi,

try like this,

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            ((CheckBox)e.Row.FindControl("checkbox1")).CheckedChanged += new EventHandler(GridView_CheckBox_CheckedChanged);
        }
    }

    void GridView_CheckBox_CheckedChanged(object sender, EventArgs e)
    {
        if (((CheckBox)sender).Checked)
        {
            GridViewRow row = (GridViewRow)((CheckBox)sender).Parent.Parent;
            row.BackColor = System.Drawing.Color.Gray;
        }
        else
        {
            GridViewRow row = (GridViewRow)((CheckBox)sender).Parent.Parent;
            row.BackColor = System.Drawing.Color.White;
        }
    }


hope it works.
 
Share this answer
 
First hook into the controls PaintEvent

C#
this.Paint += new System.Windows.Forms.PaintEventHandler(this.Paint);


Then code your appropriate logic to handle coloration.
Don't forget to cast your sender object.
C#
private void Paint(object sender, PaintEventArgs e)
{
     DataGridViewCell dgvc = (DataGridViewCell)sender;
     dgvc.Style.BackColor = (isUnChecked)? Color.Gray : Color.White;
}
 
Share this answer
 
v2
Comments
Karthik Harve 18-Jul-12 5:06am    
The question is not about windows forms datagridview. Its about ASP.NET GridView
WoodenLegNamedSmith 18-Jul-12 9:36am    
Ok, then he needs to implement the PreRender event instead, still pretty much the same thing though

http://msdn.microsoft.com/en-US/library/system.web.ui.control.prerender%28v=vs.100%29

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