温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

GridView编辑、取消按钮自定义控件

发布时间:2020-07-11 08:16:00 来源:网络 阅读:765 作者:guwei4037 栏目:编程语言

这个需求来自于论坛一位坛友提出的问题,他希望能够自定义编辑、取消按钮,而不是用GridView自带的编辑和取消。这里只当抛砖引玉,提出一些解决方案。

首先在页面前台设置一个GridView。

<div> 
    <asp:GridView ID="GridView1" runat="server"> 
        <Columns> 
            <asp:TemplateField HeaderText="操作"> 
                <ItemTemplate> 
                    <table> 
                        <td align="center"> 
                            <asp:Button ID="Edit" runat="server" Text="编辑" Visible="true" OnClick="Edit_Click" 
                                CommandArgument="<%# Container.DataItemIndex %>" /> 
                            <asp:Button ID="Cancel" runat="server" Text="取消" Visible="false" OnClick="Cancel_Click" /> 
                        </td> 
                    </table> 
                </ItemTemplate> 
            </asp:TemplateField> 
        </Columns> 
    </asp:GridView> 
</div>

这里注意,我通过给按钮Edit的CommandArgument属性设置一个DataItemIndex值,这个值就是默认行的索引值。通过这个参数可以获取GridView的行号。

然后我在首页加载的时候绑定数据源。

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!Page.IsPostBack) 
    { 
        DataTable dt = new DataTable(); 
        dt.Columns.Add("id", typeof(int)); 
        dt.Columns.Add("name", typeof(string)); 
              
        dt.Rows.Add(10001, "guwei40371"); 
        dt.Rows.Add(10002, "guwei40372"); 
              
        this.GridView1.DataSource = dt.DefaultView; 
        this.GridView1.DataBind(); 
    } 
}

这里很简单,就是绑定了两列,给GridView绑定上。

接下来两个按钮事件:

protected void Edit_Click(object sender, EventArgs e) 
{ 
    int index = Convert.ToInt32((sender as Button).CommandArgument);//获取到行号 
    Button button = this.GridView1.Rows[index].FindControl("Cancel") as Button;//找到当前行的Cancel按钮 
    button.Visible = true;//设置按钮的Visible为true 
} 
        
protected void Cancel_Click(object sender, EventArgs e) 
{ 
    int row = ((GridViewRow)((Button)sender).NamingContainer).RowIndex;//通过按钮直接找到命名容器(GridViewRow)的RowIndex 
    Response.Write("<script>alert('" + this.GridView1.Rows[row].Cells[1].Text + "')</script>");//直接弹出当前行单元格索引为1的内容 
}

具体代码的含义,上面已经注释明了,这里不重复。


最后看下执行的效果。

当点击编辑按钮的时候,显示取消按钮。

GridView编辑、取消按钮自定义控件
当点击取消按钮的时候,弹出10001。

GridView编辑、取消按钮自定义控件

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI