Overriding ToString for an object for use in a DataBinding
I am working with Databinding in ASP.Net 2.0 and I am facing an issue with the Eval command.
I have a class that I am binding to databinding that looks like this:
public class Address
{
public string Street;
public string City;
public string Country;
public new string ToString()
{
return String.Format("{0}, {1}, {2}", Street, City, Country);
}
}
And another class (the one I'm linking to):
public class Situation
{
public Address ObjAddress;
public string OtherInformation;
}
Now that I have a data binding control like
<asp:DetailsView ID="dvSituation" DataSourceID="dataSourceThatPullsSituations" AutoGenerateRows="false"runat="server">
<EmptyDataTemplate>
No situation selected
</EmptyDataTemplate>
<Fields>
<asp:BoundField HeaderText="Other data" DataField="OtherInformation" />
<asp:TemplateField>
<HeaderTemplate>
Address
</HeaderTemplate>
<ItemTemplate>
<%-- This will work --%>
<%# ((Situation)Container.DataItem).ObjAddress.ToString() %>
<%-- This won't --%>
<%# Eval("ObjAddress") %>
</ItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
Why isn't my ToString () class called when this field is Eval'ed? I just get the type name when this eval works.
a source to share
So, I was under the impression that the new keyword would override implementations even when the object was called, as if it were a superclass:
eg.
Address test = new Address();
Object aFurtherTest = test;
aFurtherTest.ToString();
I will need to use a new keyword. In fact, this keyword effectively creates a method with the same name as in the base class.
So, if I used the new keyword in the above example, I would get the ToString method of the object. In other words, depending on the type I was treating it like (base class or subclass), the ToString method would call a different method.
Obviously I must have RTFM ...
a source to share