asp.net中如何给按钮添加事件

    技术2022-05-11  60

     ButtonType obj = (ButtonType) e.Row.Cells[commandFieldIndex].Controls[controlIndex];

    ButtonType是被CommandField使用的一种按钮类型,可以是Button,LinkButton,或者ImageButton。默认情况下,CommandField使用LinkButton,但也可以通过CommandField的ButtonType属性来定制。CommandFieldIndex是CommandField在GridView中Columns集合中的原始索引,而controlIndex是删除按钮在CommandField的Controls集合中的索引。controlIndex的值由按钮在CommandField中和其他按钮的相对位置决定。例如,如果在CommandField中只有一个删除按钮,那么它的索引就是0。然而,如果在删除按钮前面还有一个编辑按钮,那么索引值是2。因为在删除按钮前面有两个控件,一个是编辑按钮,另一个是LiteralControl,用来隔离编辑按钮和删除按钮。

    使用TemplateFields

    ButtonType obj = (ButtonType) e.Row.FindControl("controlID");

    < asp:TemplateColumn HeaderText = " 删除 " >                                                  < ItemTemplate >                                                      < asp:ImageButton ID = " delete "  Runat = " server "  CommandName = " DelInfo "  ImageAlign = " Middle "  ImageUrl = " Images/btn_del.gif " ></ asp:ImageButton >                                                  </ ItemTemplate >    </ asp:TemplateColumn > private   void  DataGrid_ItemDataBound( object  sender, System.Web.UI.WebControls.DataGridItemEventArgs e)         {            if (e.Item.ItemType==ListItemType.Item || e.Item.ItemType==ListItemType.AlternatingItem)            {                DataRowView drv=(DataRowView)e.Item.DataItem;                            ImageButton l=(ImageButton)e.Item.Cells[4].FindControl("delete");                l.Attributes.Add("onclick","javascript:return confirm('你确认要删除"+drv.Row["SName"].ToString()+"吗?')");            }        }

    注意:"SName"确认中要添加确认数据的列名,此例中用的是ImageButton其它按钮与此类似。

    再说2.0的GridView,添加GridView的RowDataBound事件并添加以下类似代码

    < asp:CommandField ShowDeleteButton = " True "   />

     

    protected   void  GridView1_RowDataBound( object  sender, GridViewRowEventArgs e)     {        if (e.Row.RowType == DataControlRowType.DataRow)            e.Row.Cells[10].Attributes.Add("onclick""javascript:return confirm('你确认要删除"" + e.Row.Cells[1].Text + ""吗?')");    }

     

     


    最新回复(0)