When exactly is a value returned from Eval() converted to a string?
I thought Eval("JobTitle")
converts returned value to type String
, but that doesn’t seem to be the case, since value (returned by Eval("JobTitle")
) passed to GetSelectedJobTitle()
was of type Object
and not String
, which caused an error saying “cannot convert from object to string”.
<EditItemTemplate>
<asp:DropDownList ID="EditJob" runat="server"
SelectedIndex='<%# GetSelectedJobTitle(Eval("JobTitle")) %>'
DataSource=’<%# Titles %>’>
</asp:DropDownList>
</EditItemTemplate>
public int GetSelectedJobTitle(string title)
{
...
}
public string[] Titles
{
...
}
a) So when does the conversion (from Object
to String
) of value returne开发者_运维百科d from Eval("JobTitle")
) happen then?
b) And if Eval
doesn’t do the conversion, what method does?
thanx
EDIT:
I assume that in our example GetSelectedJobTitle() is called before Asp.Net evaluates ( and converts it to string ) the expression contained inside <%# %>?
Eval returns "object". You have to cast it to a string if you know that you'll get a string.
<EditItemTemplate>
<asp:DropDownList ID="EditJob" runat="server"
SelectedIndex='<%# GetSelectedJobTitle((string)Eval("JobTitle")) %>'
DataSource=’<%# Titles %>’>
</asp:DropDownList>
</EditItemTemplate>
The conversion happens during the DataBind Event.
EDIT: Better answer the comments here.
Our big difference is that statement:
Yours:
<%# GetSelectedJobTitle(Eval("JobTitle")) %>
gives me also a
Error 2 Argument '1': cannot convert from 'object' to 'string' p:\WebSite1\Default.aspx 19
Mine:
<%# GetSelectedJobTitle((string)Eval("JobTitle")) %>
Compiles!
精彩评论