无法将类型为“System.Web.UI.LiteralControl”的对象强制转换为类型

使用GridView的时候,相信很多朋友都遇到过“无法将类型为“System.Web.UI.LiteralControl”的对象强制转换为...类型”

在一次项目中我在TemplateField列中加入一个imagebutton控件,在RowDataBound事件中使用(( System.Web.UI.WebControls.ImageButton)e.Row.Cells[2].Controls[0]).Style.Add("FILTER", "gray");

结果编译时 报上述错误

后改成:((System.Web.UI.WebControls.ImageButton)e.Row.Cells[2].FindControl("btnLocat")).Style.Add("FILTER", "gray");编译通过!

这里的区别是:Controls[0]和FindControl(id) 。.NET智能提示:

Controls[0]为System.Web.UI.ControlCollection 类,是UI层次结构中服务器控件的子控件。

FindControl()的功能是在当前命名容器中搜索指定ID的服务器控件。

这样就非常清楚了两者的作用,因为TemplateField中添加的控件是GridView这个容器中的控件而非子控件,而buttonfield则是属于子控件。但是当buttonfield强制转换为TemplateField列后就不再是子控件了。

 

 

 

posted @ 2010-07-14 12:50  草市江田  阅读(8778)  评论(1编辑  收藏  举报