I am hoping someone can help me understand what is going on in the code line below:
Table t = (Table)Page.FindControl("Panel1").Find开发者_运维技巧Control("tbl");
I understand Page.FindControl("Panel1").FindControl("tbl");
Why is there a (Table) before the Page.FindControl?
FindControl
is declared to return Control
(at a guess :) whereas you need to store the result in a variable of type Table
.
The (Table)
bit is a cast - it's basically saying, "I think this will be a Table
. Check it for me at execution time, and then let me use it accordingly."
Page.FindControl
returns a Control
type & so you will need to cast it to the relevant type of control you need to use...
Ref.: http://msdn.microsoft.com/en-us/library/31hxzsdw.aspx
HTH.
Side note:
I wish we could do:
var t = Page.FindControl<Panel>("Panel1").FindControl<Table>("tbl");
Maybe with a bit of extension method magic, we could get:
public static class Extension{
public static T FindControl<T>(this Control control, string id)
where T : Control{
return control.FindControl(id) as T;
}
}
See () Operator (C# Reference) And Casting and Type Conversions (C# Programming Guide)
FindControl returns a type of Control
.
Table in your code inherits Control
. By explicitly casting the object to it's defined Type, you get access to all properties of that Type, instead of only the inherited properties from Control
.
精彩评论