We have discuss here how to create dynamic DataTable and it is used to populate GridView
control in the Page Load event.
The GridView RowDataBound event :
The RowDataBound event handler accepts the following two parameters.
1. Object :
A. It is the reference of the GridView whose row is raising the event.
2. GridViewRowEventArgs :
A. This is the Event Argument object and it contains the reference of the GridView Row raising the event.
B. It also contains the information about the type GridView Row i.e. Header Row, DataRow, FooterRow etc.
C. Inside the OnRowDataBound event handler of the GridView.
GridViewAll.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridviewAll.aspx.cs" Inherits="GridviewAll"
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML
1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server" align="center">
<div style="width:100%">
<div style="width:auto;height:auto">
<label id="lblHeading" style="color:Blue">GridView Events And Properties </label>
</div>
<div>
<asp:GridView ID="MyGrid" runat="server" AutoGenerateColumns="false"
OnRowDataBound="OnRowDataBound" AllowPaging="True" PageSize="5" HorizontalAlign="Center">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="100" />
<asp:BoundField DataField="Weight" HeaderText="Weight" ItemStyle-Width="100" />
</Columns>
</asp:GridView>
</div>
</div>
</form>
</body>
</html>
GridviewAll.aspx.cs
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.Drawing;
public partial class GridviewAll : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt=new DataTable();
dt.Columns.AddRange(new DataColumn[2]{new DataColumn("Name"),new DataColumn("Weight")});
dt.Rows.Add("Sandeep",70);
dt.Rows.Add("Pankaj", 40);
dt.Rows.Add("chatane", 80);
dt.Rows.Add("jaswal", 70);
dt.Rows.Add("Pankaj", 50);
dt.Rows.Add("omkar", 80);
dt.Rows.Add("koti", 70);
dt.Rows.Add("Raja", 40);
dt.Rows.Add("Muthu", 30);
MyGrid.DataSource=dt;
MyGrid.DataBind();
}
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TableCell cell = e.Row.Cells[1];
int Weight = int.Parse(cell.Text);
if (Weight == 0)
{
cell.BackColor = Color.Red;
}
if (Weight > 0 && Weight <= 50)
{
cell.BackColor = Color.Yellow;
}
if (Weight > 50 && Weight <= 100)
{
cell.BackColor = Color.Orange;
}
}
}
}
No comments:
Post a Comment