Monday, 24 November 2014

RowDataBound Event in GridView in ASP.Net

This example shows how to use RowDataBound Event in a GridView for highlighting the Rows or Cell in ASP.NET. This example is helpful in situations where you have to Highlight the GridView Rows or cell based on specific condition. For demonstration, I have created a database (named Database.mdf) in which we have a table (named tbl_Employee).

Table Schema used in this Example:

CREATE TABLE [dbo].[tbl_Employee] (
    [Id]     INT          NOT NULL,
    [Name]   VARCHAR (50) NULL,
    [City]   VARCHAR (50) NULL,
    [Salary] INT          NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);
Let's Begin:
1) Drop a GridView Control from the toolbox and set the AutoGenerateColumns property to false.
2) Add a Columns Collection (element) to manage the collection of Column fields.
3) Inside the Columns tag, add a column field (BoundField) that displays the value of a field in a data source.
4) Set the DataField property to the name of the column in the table for binding to the BoundField object and set the HeaderText value for displaying it on the GridView's Header.
5) Add RowDataBound Event in GridView.

Default.aspx Code:
<form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" CellPadding="6" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">
            <Columns>
                <asp:BoundField DataField="Id" HeaderText="Id"/>
                <asp:BoundField DataField="Name" HeaderText="Name"/>
                <asp:BoundField DataField="City" HeaderText="City"/>
                <asp:BoundField DataField="Salary" HeaderText="Salary"/>
            </Columns>
        </asp:GridView>
    </div>
</form>
In this Example, I am going to Highlight the complete Row for the Employee who have Salary less than 10000.

Default.aspx.cs Code:
using System;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Drawing;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con;
    //Connection String from Web.config file
    string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            ShowData();
        }
    }
    //method for Displaying Data in Gridview
    protected void ShowData()
    {
        DataTable dt = new DataTable();
        con = new SqlConnection(cs);
        SqlDataAdapter adapt = new SqlDataAdapter("select * from tbl_Employee",con);
        con.Open();
        adapt.Fill(dt);
        con.Close();
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
    //RowDataBound Event
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //Checking the RowType of the Row
        if(e.Row.RowType==DataControlRowType.DataRow)
        {
            //If Salary is less than 10000 than set the row Background Color to Cyan
            if(Convert.ToInt32(e.Row.Cells[3].Text)<10000)
            {
                e.Row.BackColor = Color.Cyan;
            }
        }
    }
}
Preview:
RowDataBound Event in GridView image1

Example 2:
Suppose, We have to highlight the Name of Employee not the Entire Row of the Gridview. We can achieve this using the Code given below:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
        //Checking the RowType of the Row
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //If Salary is less than 10000 than set the Cell BackColor to Red and ForeColor to White
            if (Convert.ToInt32(e.Row.Cells[3].Text) < 10000)
            {
                e.Row.Cells[1].BackColor = Color.Red;
                e.Row.Cells[1].ForeColor = Color.White;
            }
        }
}
Preview:
RowDataBound Event in GridView Image2
I hope you like it. Thanks.
[Download Source Code via Google Drive]

Thursday, 13 November 2014

Display Number of Online Users in ASP.NET

All of us have seen many Websites displaying the number of online users. In this Article, We will learn how to Display Number of Online Users in ASP.NET Web Application / WebSite.

Let's Begin:
1) Go to File -> New -> Website -> Select ASP.NET Empty Web Site
2) Right Click on Website Project (in Solution Explorer) -> Add -> Click on Add New Item
3) Select Global Application Class (Global.asax) -> Click on Add Button.

Global.asax

You will see various events of Global.asax file like Application_Start, Application_End etc. Application_Start event called once when application starts. Session_Start event called every time when a new session is start. Session_End event called when a user session ends. In Application_Start Event, We will initialize our Application state variable.

Global.asax Code:

<%@ Application Language="C#" %>

<script runat="server">

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        Application["TotalOnlineUsers"] = 0;
    }
   
    void Application_End(object sender, EventArgs e)
    {
        //  Code that runs on application shutdown

    }
       
    void Application_Error(object sender, EventArgs e)
    {
        // Code that runs when an unhandled error occurs

    }

    void Session_Start(object sender, EventArgs e)
    {
        // Code that runs when a new session is started
        Application.Lock();
        Application["TotalOnlineUsers"] = (int)Application["TotalOnlineUsers"] + 1;
        Application.UnLock();
    }

    void Session_End(object sender, EventArgs e)
    {
        // Code that runs when a session ends.
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer
        // or SQLServer, the event is not raised.
        Application.Lock();
        Application["TotalOnlineUsers"] = (int)Application["TotalOnlineUsers"] - 1;
        Application.UnLock();
    }
      
</script>
In Web.config file, Add SessionState within system.web element. By Default Session uses Cookies (cookieless="false") and Default timeout period is of 20 minutes.

<system.web>
<sessionState mode="InProc" cookieless="false" timeout="20"></sessionState>
</system.web>
4) Add a Webform and drop a label control from the Toolbox.

Default.aspx Code:

<form id="form1" runat="server">
    <div>
    <p>No. of Online Users:<asp:Label ID="Label1" runat="server" Text="Label" ForeColor="#CC0000"></asp:Label></p>
    </div>
</form>
Default.aspx.cs:

protected void Page_Load(object sender, EventArgs e)
{
        Label1.Text = Application["TotalOnlineUsers"].ToString();
}
Run the Application (ctrl+ F5). For checking, copy the url and paste it in the new instance of different browser. When a visitor visit your website, a new session is started for him and Application["TotalOnlineUsers"] variable increased by 1. When user session expires than Application["TotalOnlineUsers"] variable decreased by 1.
Preview:
Online user in Asp.net
We can also use Cookieless session by setting cookieless property to true.

<sessionState mode="InProc" cookieless="true" timeout="20"></sessionState>
On running the application, you will see Session ID in URL which is different for all users, sessions, for the new instance of different browser. The session ID is embedded in the URL in the format shown below.
http://yourserver/(session ID here)/default.aspx

Preview:
Online user in Asp.Net
Hope you like it. Thanks. 
[Download Source Code via Google Drive]

Video:

Monday, 10 November 2014

Edit and Update Record in Gridview Asp.Net

This Article shows how to Edit and Update record in a Gridview in ASP.NET. This example is helpful in situations where an administrator have to edit the several records from the database. For demonstration I have created a database (named Database.mdf) in which we have a table named tbl_Employee.

Table Schema used in this example:


CREATE TABLE [dbo].[tbl_Employee] (
    [ID]   INT          NOT NULL,
    [Name] VARCHAR (50) NULL,
    [City] VARCHAR (50) NULL,
    PRIMARY KEY CLUSTERED ([ID] ASC)
);
Let's Begin:
1) Drop a GridView Control from the toolbox and set AutoGenerateColumns to false.
2) Add the Columns Collection (tag) that manages the collection of column fields.
3) Add TemplateField inside the Columns Collection that is used to display custom content in a data-bound control.
4) Add an ItemTemplate in the TemplateField that specifies the content to display for the items in a TemplateField.
5) Add an EditItemTemplate in the TemplateField that specifies a custom user interface (UI) for the item in edit mode.
6) Set Command name property to Edit in Edit buttton, Update in Update button and Cancel in Cancel Button according to their respective Events.
7) Add OnRowEditing, OnRowUpdating, OnRowCancelingEdit Event in Gridview.


Default.aspx Code:


<form id="form1" runat="server">
    <div>
   
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="6" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Button ID="btn_Edit" runat="server" Text="Edit" CommandName="Edit" />
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:Button ID="btn_Update" runat="server" Text="Update" CommandName="Update"/>
                        <asp:Button ID="btn_Cancel" runat="server" Text="Cancel" CommandName="Cancel"/>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="ID">
                    <ItemTemplate>
                        <asp:Label ID="lbl_ID" runat="server" Text='<%#Eval("ID") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <asp:Label ID="lbl_Name" runat="server" Text='<%#Eval("Name") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txt_Name" runat="server" Text='<%#Eval("Name") %>'></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="City">
                    <ItemTemplate>
                        <asp:Label ID="lbl_City" runat="server" Text='<%#Eval("City") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txt_City" runat="server" Text='<%#Eval("City") %>'></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
            </Columns>
            <HeaderStyle BackColor="#663300" ForeColor="#ffffff"/>
            <RowStyle BackColor="#e7ceb6"/>
        </asp:GridView>
   
    </div>
</form>
Default.aspx.cs Code:


using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    //Connection String from web.config File
    string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
    SqlConnection con;
    SqlDataAdapter adapt;
    DataTable dt;
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            ShowData();
        }
    }
    //ShowData method for Displaying Data in Gridview
    protected void ShowData()
    {
        dt = new DataTable();
        con = new SqlConnection(cs);
        con.Open();
        adapt = new SqlDataAdapter("Select ID,Name,City from tbl_Employee",con);
        adapt.Fill(dt);
        if(dt.Rows.Count>0)
        {
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
        con.Close();
    }

    protected void GridView1_RowEditing(object sender, System.Web.UI.WebControls.GridViewEditEventArgs e)
    {
        //NewEditIndex property used to determine the index of the row being edited.
        GridView1.EditIndex = e.NewEditIndex;
        ShowData();
    }
    protected void GridView1_RowUpdating(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
    {
        //Finding the controls from Gridview for the row which is going to update
        Label id=GridView1.Rows[e.RowIndex].FindControl("lbl_ID") as Label;
        TextBox name = GridView1.Rows[e.RowIndex].FindControl("txt_Name") as TextBox;
        TextBox city = GridView1.Rows[e.RowIndex].FindControl("txt_City") as TextBox;
        con = new SqlConnection(cs);
        con.Open();
        //updating the record
        SqlCommand cmd = new SqlCommand("Update tbl_Employee set Name='"+name.Text+"',City='"+city.Text+"' where ID="+Convert.ToInt32(id.Text),con);
        cmd.ExecuteNonQuery();
        con.Close();
        //Setting the EditIndex property to -1 to cancel the Edit mode in Gridview
        GridView1.EditIndex = -1;
        //Call ShowData method for displaying updated data
        ShowData();
    }
    protected void GridView1_RowCancelingEdit(object sender, System.Web.UI.WebControls.GridViewCancelEditEventArgs e)
    {
        //Setting the EditIndex property to -1 to cancel the Edit mode in Gridview
        GridView1.EditIndex = -1;
        ShowData();
    }
}
Final Preview:
Edit and Update Record in Gridview ASP>NET
Hope you like it. Thanks.
[Download Source Code via Google Drive]

Watch Video:

Subscribe Now

Popular Posts

Contact us

Name

Email *

Message *

Subscribe us on YouTube

Like us on Facebook

Follow us on Google+