Fork me on GitHub

gridview中如何找到控件所在行的索引

gridview中找索引问题。

(描述:无法找到控件当前所在行,若用绑定主键的办法,行号和ID并不是一致的)

解决办法:只能用GridView中RowDataBound来找到控件(而且只能是Button),利用Button的CommandArgument属性来索引所在行。具体代码:

Button btn = (Button)e.Row.Cells[0].FindControl("btn_Reply");
btn.CommandArgument = e.Row.RowIndex.ToString();

即使这样仍然有问题,同样无法找到控件,必须加:

 if (e.Row.RowType == DataControlRowType.DataRow)
        {

        }

再在RowCommand中通过button的CommandName和CommandArgument来找,具体代码:
        if (e.CommandName == "Reply")
        {
            int index = Convert.ToInt32(e.CommandArgument);
            TextBox box = (TextBox)GVMsg.Rows[index].FindControl("txt_Reply");
            box.Visible = true;

        }

如果还要得到主键Id,可通过在GridView中用Lable绑定主键Id, 继续通过索引来找对应行的控件,具体代码如下:

 Label lab =(Label)GVMsg.Rows[index].Controls[0].FindControl("MsgId");

int MsgId = Convert.ToInt32(lab.Text);

以上代码在VV2008+sql2005下调试完成,所有控件在   <ItemTemplate></ItemTemplate>中。GVMsg为GridView的Id值。

posted @ 2008-09-08 07:02  idoku  阅读(1902)  评论(6编辑  收藏  举报