gridview 按钮事件

在GridView中添加按钮后,如何触发按钮的各种事件?


1.在GridView的“编辑列”属性窗口中,增加新的Botton列。

2.然后在该窗口右边属性中,将外观项下的ButtonType设置一下,设置项有:如:Link、Button、Image。

3.属性设置完成后,在右边属性列表窗口的下方有这样一行超链接蓝字:“将此字段转换为TemplateField”,单击这个超链接,把该列插入进来的字段转换为模版。

//添加了一个删除控件,并将其转换为模版后的代码,该控件还和在GridView所在行的主键进行绑定,把主键作为参数带到该控件的各个事件函数中。

<asp:TemplateFieldShowHeader="False" HeaderText="删除">

            <ItemTemplate>

                   <asp:LinkButton runat="server" CausesValidation="False"CommandArgument='<%# Eval("ClientID") %>'

                           Text="删除"></asp:LinkButton>

               </ItemTemplate>

      </asp:TemplateField>

 

//这是一个没有绑定字段值的新增Button列,将其转换为模版后的代码如下:

<asp:TemplateField>

            <ItemTemplate>

                <asp:Button runat="server" CausesValidation="false"CommandName="" Text="按钮" />

            </ItemTemplate>

    </asp:TemplateField>

4.  然后即可在编辑模版状态下,编辑、设置这个控件的各种事件了,比如双击这个控件按钮,系统则会自动在.cs文件中添加该控件的OnClick事件触发的函数。

注意:如果你的GridView中加入了多个转换为模版的列,进入编辑模版状态后,要选择相应的转换为模版的列,才能进行编辑。如下图:

                             

另:在cs文件中调用Gridview中按钮绑定的值:

 1 protected void LinkButton2_Click(object sender, EventArgs e)
 2       {
 3         SqlConnection myconn;
 4         SqlCommand mycommand;
 5         myconn = new SqlConnection(ConfigurationManager.ConnectionStrings["BaseConnectionString"].ConnectionString);
 6         string sql = "update Bbs_Message set ISTOP=1 where Bbs_MessageIS=" + ((LinkButton)sender).CommandArgument.ToString();
 7         //Response.Write(sql);
 8         myconn.Open();
 9         mycommand = new SqlCommand(sql, myconn);
10         mycommand.ExecuteNonQuery();
11         myconn.Close();
12
13         Response.Redirect("SQS_ADD3.aspx?XkzSqsID=" + Request.QueryString["XkzSqsID"].ToString());
14     }


 按照这个例子我没有做成功

我的代码:

aspx代码:

               <asp:TemplateField HeaderText="借还">

                   <ItemTemplate>

                         <asp:Button runat="server" CausesValidation="True"CommandName="button2_click" CommandArgument='<%#Eval("ST_RoomId") %>'

                           Text="借还"></asp:Button>

                   </ItemTemplate>

             </asp:TemplateField>

cs代码:

 

    protected voidbutton2_click(object sender, EventArgs e)
    {
        Response.Redirect("http://www.csdn.net");
 
    }

posted @ 2011-11-23 20:51  SOD_QWER  阅读(189)  评论(0编辑  收藏  举报