65.9K
CodeProject 正在变化。 阅读更多。
Home

在 GridView 中添加删除列,带确认框

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0投票)

2007 年 6 月 26 日

CPOL
viewsIcon

54157

downloadIcon

497

在本文中,我们将为 GridView 添加一个删除列,并带有图像按钮和确认框。

引言

在本文中,我们将了解如何在 GridView 中添加和删除列,并带有图像按钮和确认框。

背景

本文是对我之前文章的扩展:GridView 用户控件中的事件处理。 我将扩展同一个项目来完成本文。

Using the Code

  1. 在文章 GridView 用户控件中的事件处理 中,我们为 RowDataBound 创建了一个事件处理程序。 在本文中,我们添加了另一个 RowCommand 事件处理程序。 使用相同的方法定义事件。
  2. protected void Simple_DGV_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        OnRowCommand(e);
    }
    
    protected void OnRowCommand(GridViewCommandEventArgs e)
    {
        if (GridRowCommand != null)
            GridRowCommand(this, e);}
  3. 定义事件的委托。
  4. public delegate void RowCommand(object sender, GridViewCommandEventArgs e);
    public event RowCommand GridRowCommand;
  5. 在父页面中添加 RowDataBound 事件处理程序。
  6. 在父页面中,在 GridView 中添加一个空白的绑定字段列。
  7. BoundField b2 = new BoundField();
    Inc_GridView1.Columns.Add(b2);//blank column to add delete image
  8. 现在在 RowDataBound 事件中,在空白列中添加一个图像按钮。
  9. void Inc_GridView1_GridRowDataBound(object sender, GridViewRowEventArgs e)
    {
    	if (e.Row.RowType == DataControlRowType.DataRow)
    	{
    		int x = Inc_GridView1.Columns.Count - 1;
    		// it will give blank column index
    
    		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();
    		// argument to pass for delete command
    
    		// it will give confirmation on button click
    		img2.OnClientClick = 
    		     "return confirm('Do you want to delete this Record?');";
    	}
    }
  10. 现在添加代码来处理删除功能
  11. void Inc_GridView1_GridRowCommand(object sender, GridViewCommandEventArgs e)
    {
    	if (e.CommandName == "Delete")
    	{
    		int param = Convert.ToInt32(e.CommandArgument);
    		//function to delete row
    	}
    }

就是这样。

© . All rights reserved.