GridView 中RowCommand 事件的好方法

1.在模板列中放一个Button和TextBox,TextBox用来存放产品名,将Button的CommandName设置为add并且在html中将他的CommandArguments属性和RowIndex进行绑定:


                   
                       
                       
                   

               

后台中输出模板列中TextBox中的值(保存的产品的id):

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "add")
        {
           
            int i = Convert.ToInt32(e.CommandArgument.ToString());

             // int i = ((GridViewRow)((Button)e.CommandSource).NamingContainer).RowIndex;//(该方法不需要html中的绑定,取id.刚刚看到的,加上来,好方法.......)


            TextBox tb = (TextBox)GridView1.Rows[i].FindControl("TextBox");
            
            string str = tb.Text.Trim();
            Response.Write(str);

         }

    }

注解:

int rowIndex = ((GridViewRow)((Button)e.CommandSource).NamingContainer).RowIndex;


e.CommandSource传的是按下去的Button,不过由于传回的是Object,就得自行转化Button,但我们想知道的是RowIndex,而Button是包含在GridViewRow內,所以通过NamingContainer传回目前的GridViewRow,得到是Control,所以需在转成GridViewRow后才能有RowIndex 属性。

原理是:将当前行索引和Button的commandargument绑定,用的时候只要取出当前行的索引即可,gridview的rowcommand事件和datalist的itemcommand事件相似

..........

你可能感兴趣的:(C#/.NET)