Introduction
In this article, we will see how to add and delete columns in a GridView
, with an image button and a confirmation box.
Background
This article is an extension of my previous article: Event handling in Gridview User Control. I am extending the same project for this article.
Using the Code
- In the article Event handling in Gridview User Control, we created an event handler for
RowDataBound
. In this article, we are adding one more event handler for RowCommand
. Use the same procedure to define the event.
protected void Simple_DGV_RowCommand(object sender, GridViewCommandEventArgs e)
{
OnRowCommand(e);
}
protected void OnRowCommand(GridViewCommandEventArgs e)
{
if (GridRowCommand != null)
GridRowCommand(this, e);}
- Define the delegates for the event.
public delegate void RowCommand(object sender, GridViewCommandEventArgs e);
public event RowCommand GridRowCommand;
- Add an event handler for
RowDataBound
in the parent page. - In the parent page, add a blank boundfield column in the
GridView
.
BoundField b2 = new BoundField();
Inc_GridView1.Columns.Add(b2);
- Now in the
RowDataBound
event, add an image button in the blank column.
void Inc_GridView1_GridRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int x = Inc_GridView1.Columns.Count - 1;
ImageButton img1 = new ImageButton();
img1.ID = "img1";
img1.ToolTip = "Delete";
img1.ImageUrl = "icons-del.gif";
e.Row.Cells[x].Controls.Add(img1);
ImageButton img2 = new ImageButton();
img2 = (ImageButton)e.Row.Cells[x].Controls[0];
img2.CommandName = "Delete";
img2.CommandArgument =
DataBinder.Eval(e.Row.DataItem, "c").ToString();
img2.OnClientClick =
"return confirm('Do you want to delete this Record?');";
}
}
- Now add code for handling the delete functionality:
void Inc_GridView1_GridRowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int param = Convert.ToInt32(e.CommandArgument);
}
}
That's all.