GridView编辑、取消按钮自定义控件
2016-07-04 09:33
148 查看
这个需求来自于论坛一位坛友提出的问题,他希望能够自定义编辑、取消按钮,而不是用GridView自带的编辑和取消。这里只当抛砖引玉,提出一些解决方案。
首先在页面前台设置一个GridView。
这里注意,我通过给按钮Edit的CommandArgument属性设置一个DataItemIndex值,这个值就是默认行的索引值。通过这个参数可以获取GridView的行号。
然后我在首页加载的时候绑定数据源。
这里很简单,就是绑定了两列,给GridView绑定上。
接下来两个按钮事件:
具体代码的含义,上面已经注释明了,这里不重复。
最后看下执行的效果。
当点击编辑按钮的时候,显示取消按钮。
当点击取消按钮的时候,弹出10001。
首先在页面前台设置一个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的内容 }
具体代码的含义,上面已经注释明了,这里不重复。
最后看下执行的效果。
当点击编辑按钮的时候,显示取消按钮。
当点击取消按钮的时候,弹出10001。
相关文章推荐
- Windows系统下用命令行编译C/C++程序过程总结
- (原) 2.2 ZkClient使用
- 连接Oracle时报错ora-01034与ORA-27101
- 数据结构-二分查找
- C# 泛型接口
- 跟王老师学MySQL:MySQL数据类型之整数类型
- JS创建对象几种不同方法详解
- 5小时搞定谷歌原生自动化框架UiAutomator1.0
- Java多线程编程中synchronized线程同步的教程
- 干货|移动端H5前端性能优化
- CNN 学习系列之 perdict 以及可视化
- Android 版本列表
- Swift网络封装库Moya中文手册之Authentication
- HTTPS加密越来越流行,为何要加密?
- 【深入浅出jQuery】源码浅析--奇技淫巧
- POJ 1625 Censored!
- storybord中得所有控件不显示
- win10无法通过IPC连接远程电脑
- String 常用方法
- 一款不错的html5网站模板案例代码下载,用于开发个人网站,兼容手机与PC