在.net2.0中,怎么样实现对gridview删除行时弹出确认对话框

本文介绍了在.NET 2.0的GridView中实现删除行时弹出确认对话框的三种方法:通过转换CommandField为TemplateField并添加OnClientClick事件,使用GridView的RowDataBound事件,以及在RowDeleting事件中添加确认提示。这些方法可以在用户点击删除按钮时显示确认消息,防止误操作。
摘要由CSDN通过智能技术生成

 1,GridView中如何使用CommandField删除时,弹出确认框?

在.net2005提供的GridView中我们可以直接添加一个CommandField删除列:<asp:CommandField ShowDeleteButton="True" />,完后在它的RowDeleting事件中完成删除。但在多半我们在做这种删除操作时都需要先让操作者再确认下,完后再进行删除,以避免误操作引起的误删除。

可以通过下面方法给GridView删除前加上个确认对话框。

首先,在GridView的属性对框话框中点击“Columns”进入它的“字段”设计器。接着在“字段”设计器中选择以前已加上的那个CommandField“删除”列,这时在它的属性列表下会看到一个“将此它段转换为 TemplateFied”的项,点击将它转换为TemplateFied列。

完后退出该字段设计器,切换到源码视图你会发现该列已由原来的:<asp:CommandField ShowDeleteButton="True" />
变为了:
<asp:TemplateField ShowHeader="False">
                                <ItemTemplate>
                                    <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Delete"  Text="删除"></asp:LinkButton>
 </ItemTemplate>

最后在<asp:LinkButton>中加入:OnClientClick="return confirm('确认要删除吗?');"

这样点击删除时就会先在客户端弹出“确认要删除吗?”对话框,而原来在RowDeleting事件中写的代码完全不用改变。

2,

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowIndex > -1)
{
int id = Convert.ToInt32(GridView1.DataKeys[e.Row.RowIndex].Value);
LinkButton lbtnDelete = (LinkButton)e.Row.FindControl("lbtnDelete");
if (lbtnDelete != null)
{
lbtnDelete.CommandArgument = id.ToString();
lbtnDelete.Attributes.Add("onClick", "<script>return confirm('是否确认删除!')</script>");
}
}
}

}
3,先引用System.windwos.Forms,然后在进行处理.
using System.Windows.Forms;

protected void gvNewList_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DialogResult result = MessageBox.Show("确定要删除本行吗?", "信息提示!", MessageBoxButtons.YesNo, MessageBoxIcon.Question,MessageBoxDefaultButton.Button2,MessageBoxOptions.ServiceNotification);
if (result == DialogResult.Yes)
{
e.Cancel = false;
}
else
{
e.Cancel = true;
}
}
4,添加一个删除列

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
TableCell tc = (TableCell)e.Row.Cells[e.Row.Cells.Count - 1];
for (int i = 0; i < tc.Controls.Count; i += 2)
{
// cerco il controllo ImageButton (ho utilizzato quello)
Object o = tc.Controls[i];
if (o is ImageButton)
{
// controllo trovato!
// ora aggiungo l'evento js onClick per chiedere conferma all'utente
ImageButton lb = (ImageButton) o;
((ImageButton)lb).Attributes.Add("onclick", @"javascript:return confirm('Attenzione: sicuro di voler cancellare?');");
}
}
}
-------------------------------------------------------------
<asp:TemplateField ShowHeader="False">
<ItemStyle HorizontalAlign="Center" Width="16px" />
<ItemTemplate>
<asp:ImageButton ID="imgDelete" runat="server" CausesValidation="False" CommandName="Delete" ImageUrl="~/img/ico_elimina.gif" AlternateText="Cancella data" OnClientClick="return confirm('Sicuro di voler cancellare?');" />
</ItemTemplate>
</asp:TemplateField>

以上方法总结

---------Template way-----------------------------------------------

<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Delete"
Text="删除" OnClientClick='return confirm("Are you sure you want to delete this record?");'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>

-------------RowDeleting method------------------------------------------------

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
Response.Write("<script>window.confirm('确定删除吗?');</script>");
}

-------------RowDataBound method--------------------------------------------------------------
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
((LinkButton)e.Row.Cells[4].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('确实要删除该记录吗?')");
}

}

-------------------------Total three ways-------------------end-------------------------------

补充:完全代码下使GridView中的删除按钮实现删除提示的功能

首先,HTML代码:

< asp:GridView ID = " SubjectGrid "  runat = " server " >
    
</ asp:GridView >

第二步,初始化GridView Columns:

void  Page_Load(Object sender, EventArgs e)
{
    ShowGrid();
}

private   void  ShowGrid()
        {
            DataTable customerTable 
=   new  DataTable( " Customers " );
            
            grdSubject.AutoGenerateColumns 
=   false ;
            grdSubject.ShowHeader 
=   false ;
            grdSubject.DataKeyNames 
=   new  String[] {  " Id "  };
            DataControlFieldCollection dcfc 
=  grdSubject.Columns;
            dcfc.Clear();
            BoundField bf;

            bf 
=   new  BoundField();
            bf.DataField 
=   " Id " ;
            bf.Visible 
=   false ;
            dcfc.Add(bf);

            bf 
=   new  BoundField();
            bf.DataField 
=   " Title " ;
            dcfc.Add(bf);

            bf 
=   new  BoundField();
            bf.DataField 
=   " BeginDate " ;
            bf.SortExpression 
=   " BeginDate " ;
            bf.HtmlEncode 
=   false ;
            bf.DataFormatString 
=   " {0:yyyy-MM-dd} " ;
            dcfc.Add(bf);

            bf 
=   new  BoundField();
            bf.DataField 
=   " EndDate " ;
            bf.HtmlEncode 
=   false ;
            bf.DataFormatString 
=   " {0:yyyy-MM-dd} " ;
            dcfc.Add(bf);

            ButtonField selectRow 
=   new  ButtonField();
            selectRow.ButtonType 
=  ButtonType.Button;
            selectRow.CommandName 
=   " Select " ;
            selectRow.Text 
=   " 选择 " ;
            dcfc.Add(selectRow);

            ButtonField delRow 
=   new  ButtonField();
            delRow.ButtonType 
=  ButtonType.Button;
            delRow.AccessibleHeaderText 
=   " Delete " ;
            delRow.CommandName 
=   " Delete " ;
            delRow.Text 
=   " 删除 " ;
            delRow.CausesValidation 
=   true ;
            dcfc.Add(delRow);

            grdSubject.DataSource 
=  dt.DefaultView;
            grdSubject.DataBind();
        }

第三步:RowDataBound

void  grdSubject_RowDataBound( object  sender, GridViewRowEventArgs e)
        {
            
// 判断是否是DataRow
             if  (e.Row.RowType  ==  DataControlRowType.DataRow)
            {
                
// 鼠标经过Row时的效果
                e.Row.Attributes.Add( " onmouseover " " e=this.style.backgroundColor; this.style.backgroundColor='linen' " );
                e.Row.Attributes.Add(
" onmouseout " " this.style.backgroundColor=e " );

                
// 当开始时间大于现在时间,显示行为蓝色
                 if  (DateTime.Parse(e.Row.Cells[ 2 ].Text)  >  DateTime.Now)
                {
                    e.Row.BackColor 
=  Color.LightSkyBlue;
                }
                
// 当结束时间小于现在时间,显示行为灰色
                 if  (DateTime.Parse(e.Row.Cells[ 3 ].Text)  <  DateTime.Now)
                {
                    e.Row.BackColor 
=  Color.Silver;
                }

                
// 当点击删除按钮时激活提示
                Button btn  =  (Button)e.Row.Cells[ 5 ].Controls[ 0 ];
                btn.Attributes.Add(
" onclick " " javascript:return confirm('你确认要删除:/ ""  + e.Row.Cells[1].Text +  " / " 吗?') " );
            }
        }

其中的关键是Button btn=(Button)e.Row.Cells[5].Controls[0]; 即声明此事件是由第6列中的第一个控件调用。

第四步:执行

void  grdSubject_RowDeleting( object  sender, GridViewDeleteEventArgs e)
        {

        }

        
void  grdSubject_RowCommand( object  sender, GridViewCommandEventArgs e)
        {
            
// 单击Grid中按钮时发生throw new Exception("The method or operation is not implemented.");
             int  selIndex  =  Convert.ToInt32(e.CommandArgument);
            GridViewRow selectedRow 
=  grdSubject.Rows[selIndex];

            
if  (e.CommandName  ==   " Select " )
            {
                txtSubjectTitle.Text 
=  selectedRow.Cells[ 1 ].Text;
                dateBegin.Value 
=  selectedRow.Cells[ 2 ].Text;
                dateEnd.Value 
=  selectedRow.Cells[ 3 ].Text;

            }
            
if  (e.CommandName  ==   " Delete " )
            {
                Hsf.Touch.Dto.Subject item 
=   new  Hsf.Touch.Dto.Subject();
                item.Id 
=   int .Parse(grdSubject.DataKeys[selIndex].Value.ToString());
                
try
                {
                    TouchFactory.CreateSubjectManage().Delete(item);
                    
// 删除成功,清除输入框内容
                    Clear();
                }
                
catch  (Exception err)
                {
                    ShowMessageBox(
" 删除失败 /n "   +  err.Message);
                }
            }
            
            ShowGrid();
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值