Related Posts Plugin for WordPress, Blogger...

About

Follow Us

Tuesday 24 February 2015

Sometimes it is needed to highlight data row in GridView so that we can clearly differentiate some data against the large number of records being displayed in GridView.

Suppose in case of Employee record we want to highlight the where age of the employee is greater than “30”.  We can change the color of the row in code behind on this condition by doing some code on “Row Data Bound” Event of gridview.
In this article I will explain the following points:
1.       Save data to database.
2.       Show data in gridview.
3.       Highlight rows based on some condition i.e. Age>30

Implementation:  Let's create a demo website to demonstrate the concept.
Create a database “Test”, Then create one table i.e. Emp_Personal
  
Column Name
Data Type
EmpPer_Id
Int(Primary Key. So set is identity=true)
EmpName
varchar(100)
Age
Int
Address
varchar(500)

Create a stored procedure to save Employee details in sql server database table

create PROCEDURE SaveEmp_SP

                @EmpName  VARCHAR(100),              
                @age   INT,
                @Address VARCHAR(500)

AS
BEGIN
                INSERT INTO dbo.Emp_Personal(EmpName,Age,Address)
                VALUES(@EmpName,@age,@Address)
END

Create another stored procedure to get Employee details to be filled in GridView Data Control.

CREATE PROCEDURE GetEmp_SP              
AS
BEGIN
                SELECT * FROM dbo.Emp_Personal
END

create the connection string in Webconfig as: 
<connectionStrings>
    <add name="Empcon" connectionString="Data Source=localhost;Initial Catalog=test;IntegratedSecurity=True"/>
  </connectionStrings>

Asp.Net C# Section
Design Part:
    <div>
fieldset style="width:370px;">
    <legend><strong>Change Color of Gridview Row based on condition</strong></legend>
    <table>
    <tr>
    <td>&nbsp;</td>
    <td>
        &nbsp;</td>
    </tr>
 
    <tr>
    <td>Employee Name:</td>
    <td>
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>
    </tr>
 
    <tr>
    <td>Age:</td>
    <td>
        <asp:TextBox ID="txtAge" runat="server"></asp:TextBox></td>      
    </tr>
  
    <tr>
    <td>Address:</td>
    <td>
        <asp:TextBox ID="txtAddress" runat="server"></asp:TextBox></td>
    </tr>
    <tr>
    <td>&nbsp;</td>
    <td>
        <asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />
        <asp:Button ID="btnReset" runat="server" Text="Reset"
            onclick="btnReset_Click" />
        </td>
    </tr>

    <tr>
    <td colspan="2">
        &nbsp;</td>
    </tr>

    <tr>
    <td colspan="2">
        <asp:GridView ID="grdEmp" runat="server" AutoGenerateColumns="False" Width="100%"
            onrowdatabound="grdEmp_RowDataBound">
        <Columns>
        <asp:BoundField HeaderText="EmpName"  DataField="EmpName" />
        <asp:BoundField HeaderText="Age"  DataField="Age" />
        <asp:BoundField HeaderText="Address"  DataField="Address" />      
        </Columns>
        </asp:GridView>  
    </td>
    </tr>
    </table>
    </fieldset>
    </div>
  
Case2: If you are using Template Fields

        <asp:GridView ID="grdEmp" runat="server" AutoGenerateColumns="False" Width="100%"
            onrowdatabound="grdEmp_RowDataBound">
        <Columns>      
        <asp:TemplateField HeaderText="Name">
        <ItemTemplate>
        <asp:Label ID="lblName" runat="server" Text='<%#Eval("EmpName") %>'></asp:Label>     
        </ItemTemplate>
        </asp:TemplateField>
                <asp:TemplateField HeaderText="Age">
        <ItemTemplate>      
        <asp:Label ID="lblAge" runat="server" Text='<%#Eval("Age") %>'></asp:Label>      
        </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Address">
        <ItemTemplate>      
        <asp:Label ID="lblAddress" runat="server" Text='<%#Eval("Address") %>'></asp:Label>
        </ItemTemplate>
        </asp:TemplateField>
        </Columns>
        </asp:GridView>

In code behind file (default.aspx.cs) write the code as;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;


public partial class Coloredgrid : System.Web.UI.Page

{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["EmpCon"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindGridView();
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand();
        try
        {
            cmd = new SqlCommand("SaveEmp_SP", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@EmpName", txtName.Text.Trim());
            cmd.Parameters.AddWithValue("@age", txtAge.Text.Trim());
            cmd.Parameters.AddWithValue("@Address", txtAddress.Text.Trim());
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
            Clear_Controls();
            BindGridView();
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured: " + ex.Message.ToString() + "');", true);
        }
        finally
        {
            cmd.Dispose();
            con.Close();
            con.Dispose();
        }
    }

    private void BindGridView()
    {
        DataTable dt = new DataTable();
        SqlDataAdapter adp = new SqlDataAdapter();
        try
        {
            adp = new SqlDataAdapter("GetEmp_SP", con);
            adp.SelectCommand.CommandType = CommandType.StoredProcedure;
            adp.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                grdEmp.DataSource = dt;
                grdEmp.DataBind();
            }
            else
            {
                grdEmp.DataSource = null;
                grdEmp.DataBind();
            }
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured: " + ex.Message.ToString() + "');", true);
        }
        finally
        {
            con.Close();
            dt.Clear();
            dt.Dispose();
            adp.Dispose();
        }
    }

    protected void btnReset_Click(object sender, EventArgs e)
    {
        Clear_Controls();
    }
    protected void grdEmp_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataRowView drv = e.Row.DataItem as DataRowView;
            int age = Convert.ToInt32(drv["age"]);

            if (age > 30 )
            {
                e.Row.ForeColor = System.Drawing.Color.White;
                e.Row.BackColor = System.Drawing.Color.Black;
            }
            else
            {
                e.Row.ForeColor = System.Drawing.Color.Black;
                e.Row.BackColor = System.Drawing.Color.Orange;
            }
        }


////If you are using Template field instead of BoundField then uncomment below code block and comment or remove above code block

// if (e.Row.RowType == DataControlRowType.DataRow)
//        {       
//            Label lblage = (Label)e.Row.FindControl("lblage");

//            int age = Convert.ToInt32(lblage.Text);

//            if (age > 30)
//            {
//                e.Row.ForeColor = System.Drawing.Color.Black;
//                e.Row.BackColor = System.Drawing.Color.Cyan;
//            }
//            else
//            {
//                e.Row.ForeColor = System.Drawing.Color.Black;
//                e.Row.BackColor = System.Drawing.Color.Orange;
//            }         

//        }    
    }
  
    private void Clear_Controls()
    {
        txtName.Text = string.Empty;    
        txtAge.Text = string.Empty;     
        txtAddress.Text = string.Empty;
      
    }
}

Asp.Net VB Section: 
Design the page (default.aspx) as  in above Asp.net C#  section but replace the lines

<asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />
<asp:Button ID="btnReset" runat="server" Text="Reset" onclick="btnReset_Click" />
with the following lines
<asp:Button ID="btnSave" runat="server" Text="Save"/>
<asp:Button ID="btnReset" runat="server" Text="Reset" />

In the code behind file(e.g. default.aspx.vb) write the code as:

Imports System.Data

Imports System.Data.SqlClient

Imports System.Configuration

  

Public partial Class Coloredgrid

                 Inherits System.Web.UI.Page

Dim con As SqlConnection =  New SqlConnection(ConfigurationManager.ConnectionStrings("EmpCon").ConnectionString)

    Protected  Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

        If Not Page.IsPostBack Then

            BindGridView()

        End If

    End Sub

    Protected  Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs)

        Dim cmd As SqlCommand =  New SqlCommand()

        Try

            cmd = New SqlCommand("SaveEmp_SP", con)

            cmd.CommandType = CommandType.StoredProcedure

            cmd.Parameters.AddWithValue("@EmpName", txtName.Text.Trim())

            cmd.Parameters.AddWithValue("@age", txtAge.Text.Trim())

            cmd.Parameters.AddWithValue("@Address", txtAddress.Text.Trim())

            con.Open()

            cmd.ExecuteNonQuery()

            con.Close()

            Clear_Controls()

            BindGridView()

        Catch ex As Exception

            ScriptManager.RegisterStartupScript(this, Me.GetType(), "Message", "alert('Error occured: " + ex.Message.ToString() + "');", True)

        Finally

            cmd.Dispose()

            con.Close()

            con.Dispose()

        End Try

    End Sub

 

    Private  Sub BindGridView()

        Dim dt As DataTable =  New DataTable()

        Dim adp As SqlDataAdapter =  New SqlDataAdapter()

        Try

            adp = New SqlDataAdapter("GetEmp_SP", con)

            adp.SelectCommand.CommandType = CommandType.StoredProcedure

            adp.Fill(dt)

            If dt.Rows.Count > 0 Then

                grdEmp.DataSource = dt

                grdEmp.DataBind()

            Else

                grdEmp.DataSource = Nothing

                grdEmp.DataBind()

            End If

        Catch ex As Exception

            ScriptManager.RegisterStartupScript(this, Me.GetType(), "Message", "alert('Error occured: " + ex.Message.ToString() + "');", True)

        Finally

            con.Close()

            dt.Clear()

            dt.Dispose()

            adp.Dispose()

        End Try

    End Sub

 

    Protected  Sub btnReset_Click(ByVal sender As Object, ByVal e As EventArgs)

        Clear_Controls()

    End Sub

    Protected  Sub grdEmp_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)

        If e.Row.RowType = DataControlRowType.DataRow Then

            Dim drv As DataRowView =  e.Row.DataItem as DataRowView

            Dim age As Integer =  Convert.ToInt32(drv("age"))

 

            If age > 30 Then

                e.Row.ForeColor = System.Drawing.Color.White

                e.Row.BackColor = System.Drawing.Color.Black

            Else

                e.Row.ForeColor = System.Drawing.Color.Black

                e.Row.BackColor = System.Drawing.Color.Orange

            End If

        End If

 

 

'If you are using Template field instead of BoundField then uncomment below code block and comment or remove above code block

 

' if (e.Row.RowType == DataControlRowType.DataRow)

'        {       

'            Label lblage = (Label)e.Row.FindControl("lblage");

 

'            int age = Convert.ToInt32(lblage.Text);

 

'            if (age > 30)

'            {

'                e.Row.ForeColor = System.Drawing.Color.Black;

'                e.Row.BackColor = System.Drawing.Color.Cyan;

'            }

'            else

'            {

'                e.Row.ForeColor = System.Drawing.Color.Black;

'                e.Row.BackColor = System.Drawing.Color.Orange;

'            }         

 

'        }    

    End Sub

 

    Private  Sub Clear_Controls()

        txtName.Text = String.Empty    

        txtAge.Text = String.Empty     

        txtAddress.Text = String.Empty

 

    End Sub

End Class


 

0 comments:

Post a Comment