asp.ent gridview 自定义按钮使用
gridview使用中 ,会用到多个按钮的情况,而且每个按钮要根据业务来做不同的操作 。可以直接在TemplateField中定于这个按钮 ,在后台只要根据对应的做相应的操作就可以了 。
前台的代码中在column中如下定义
<asp:TemplateField HeaderText="操作"> <ItemTemplate> <asp:Button Height="25px" Width="100px" runat="server" ID="btntj" Text='<%# Eval("VGuanZhu").ToString()=="0"?"置顶关注":"取消关注" %>' CommandName="btntj_Click" CommandArgument='<%# Eval("VID") %>' /> <asp:Button Height="25px" Width="100px" runat="server" ID="btnrm" Text='<%# Eval("VRecom").ToString()=="0"?"推荐热门":"取消热门" %>' CommandName="btnrm_Click" CommandArgument='<%# Eval("VID") %>' /> <asp:Button Height="25px" Width="60px" runat="server" ID="btnsh" Text='<%# Eval("State").ToString()=="0"?"通过":"驳回" %>' CommandName="btnsh_Click" CommandArgument='<%# Eval("VID") %>' /> <asp:Button runat="server" Height="25px" Width="60px" ID="btnck" Text="编辑" CommandName="btnck_Click" CommandArgument='<%# Eval("VID") %>' /> <asp:Button runat="server" Height="25px" Width="60px" ID="btndelete" Text="删除" CommandName="btndelete_Click" CommandArgument='<%# Eval("VID") %>' /> </ItemTemplate> </asp:TemplateField>
后台代码中 ,只要根据CommandName就可以操作
if (e.CommandName == "btnrm_Click")//热门 { try { Button btn = GridviewMInter.Rows[drv.RowIndex].Cells[11].FindControl("btnrm") as Button; string text = btn.Text; if (text == "推荐热门") { minter.UpdateMInterview(vid, title, desc, host, DateTime.Parse(stime), DateTime.Parse(etime), pic, state, guanzhu, "1"); MicroBlog.Common.MessageBox.Show(this, "已成功推荐为近期热门!"); } else { minter.UpdateMInterview(vid, title, desc, host, DateTime.Parse(stime), DateTime.Parse(etime), pic, state, guanzhu, "0"); MicroBlog.Common.MessageBox.Show(this, "已成功取消近期热门!"); } BindGridview(); } catch (Exception ex) { MicroBlog.Common.MessageBox.Show(this, ex.Message); } } if (e.CommandName == "btnck_Click")//查看详细 { Response.Redirect("../MicroInterview/MInterviewDetail.aspx?vid=" + e.CommandArgument, false); } if (e.CommandName == "btndelete_Click")//删除 { try { minter.DeleteByvid(vid); MicroBlog.Common.MessageBox.Show(this, "删除成功!"); BindGridview(); } catch (Exception ex) { MicroBlog.Common.MessageBox.Show(this, ex.Message); } }
取当前操作行的数据时候 ,因为是button ,所以如下定义
GridViewRow drv = (GridViewRow)((Button)e.CommandSource).NamingContainer; string title = GridviewMInter.Rows[drv.RowIndex].Cells[1].Text; string desc = GridviewMInter.Rows[drv.RowIndex].Cells[2].Text; string host = GridviewMInter.Rows[drv.RowIndex].Cells[3].Text;