Introduction
This article explains how to create a GridView
as a user control so you can customize it columns and events (using event bubbling) in the parent page.
If you create a generic GridView
as a user control, then you can extend it in its parent page as per your requirements.
Background
We will use event bubbling to implement our solution. It is used to pass an event from the user control (ASCX page) to the parent page (ASPX page).
Using the Code
- Create a user control with a
GridView
. - To access its column collection in the parent page, create a
Columns
property.
public DataControlFieldCollection Columns
{
get { return Simple_DGV.Columns; }
}
- Created a function to bind the datasource to the
GridView
.
public void BindData(DataTable dt)
{
Simple_DGV.DataSource = dt;
Simple_DGV.DataBind();
}
- Now our basic
GridView
is done. Open the ASPX page where you are using this control and drag and drop this control. - Now open the aspx.cs file. There, you can add the columns to the grid and pass the datasource to bind to.
private void BindData()
{
Inc_GridView1.Columns.Clear();
BoundField b = new BoundField();
b.HeaderText = "Column1";
b.DataField = "c";
Inc_GridView1.Columns.Add(b);
BoundField b1 = new BoundField();
b1.HeaderText = "Column2";
b1.DataField = "c1";
Inc_GridView1.Columns.Add(b1);
Inc_GridView1.BindData(dt);
}
- Now create the events in the User control to access it on the parent (ASPX) page. We will create a
RowDataBound
event which gets fired at the time of databinding. - Add an event handler for
RowDataBound
and specify the event.
protected void Simple_DGV_RowDataBound(object sender, GridViewRowEventArgs e)
{
OnRowDataBound(e);
}
- Then in the event function, check that no one else is using the event.
protected void OnRowDataBound(GridViewRowEventArgs e)
{
if (GridRowDataBound != null)
GridRowDataBound(this, e);
}
- To access this event in the parent page, we need to use a delegate, so define a delegate and its event in the user control.
public delegate void RowDataBound(object sender, GridViewRowEventArgs e);
public event RowDataBound GridRowDataBound;
- To use this event in the parent page, we need to add an event handler in the
InitializeComponent
method of the parent page.
#region generate code for delegate
protected override void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
Inc_GridView1.GridRowDataBound +=
new Inc_GridView.RowDataBound(Inc_GridView1_GridRowDataBound);
}#endregion
- Now we are ready to access the event. I am changing the color of the row here. We can also specify a condition when to change the color.
void Inc_GridView1_GridRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.BackColor = System.Drawing.Color.FromArgb(236, 245, 248);
}
}
Points of Interest
Event bubbling can be applied to any User Control for event handling.