zoukankan      html  css  js  c++  java
  • GridView编辑、取消按钮自定义控件

    这个需求来自于论坛一位坛友提出的问题,他希望能够自定义编辑、取消按钮,而不是用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的内容  
    }  

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

    最后看下执行的效果。

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


    当点击取消按钮的时候,弹出10001。

  • 相关阅读:
    【转】CUDA5/CentOS6.4
    【转】centos 6.4 samba 安装配置
    【转】Install MATLAB 2013a on CentOS 6.4 x64 with mode silent
    【转】Getting xrdp to work on CentOS 6.4
    【VLFeat】使用matlab版本计算HOG
    Unofficial Windows Binaries for Python Extension Packages
    March 06th, 2018 Week 10th Tuesday
    March 05th, 2018 Week 10th Monday
    March 04th, 2018 Week 10th Sunday
    March 03rd, 2018 Week 9th Saturday
  • 原文地址:https://www.cnblogs.com/guwei4037/p/5639510.html
Copyright © 2011-2022 走看看