Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
Hello Everybody,
 
I have the following database design:
 

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:
//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 14-Jul-12 20:57pm
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

First hook into the controls PaintEvent
 
   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.
private void Paint(object sender, PaintEventArgs e)
{
     DataGridViewCell dgvc = (DataGridViewCell)sender;
     dgvc.Style.BackColor = (isUnChecked)? Color.Gray : Color.White;
}
  Permalink  
v2
Comments
Karthik Harve at 18-Jul-12 5:06am
   
The question is not about windows forms datagridview. Its about ASP.NET GridView
WoodenLegNamedSmith at 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
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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>
 <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 Smile | :)
  Permalink  
v5
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

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.
  Permalink  

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

  Print Answers RSS
0 BillWoodruff 309
1 CPallini 300
2 Sergey Alexandrovich Kryukov 290
3 George Jonsson 274
4 Gihan Liyanage 230
0 OriginalGriff 4,895
1 CPallini 4,010
2 Sergey Alexandrovich Kryukov 3,514
3 George Jonsson 2,826
4 Gihan Liyanage 2,386


Advertise | Privacy | Mobile
Web04 | 2.8.140916.1 | Last Updated 18 Jul 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100