views:

150

answers:

3

I'm working with Databinding in ASP.Net 2.0, and I've come across an issue with the Eval command.

I have a class that I'm 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 databinding to):

public class Situation
{
  public Address ObjAddress;
  public string OtherInformation;
}

Now, when I have a databound control, e.g.

<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 doesn't my ToString() class get called when this field is Eval'ed? I just get the type name when that eval runs.

+2  A: 

Instead of using:

public new string ToString()

Use the override keyword:

public override string ToString()
Wayne Hartman
+1  A: 

Use override keyword instead of new in ToString method.

bbmud
A: 

So I was under the impression that the new keyword would override implementations even when the object was called as though it were a superclass:

e.g.

Address test = new Address();
Object aFurtherTest = test;
aFurtherTest.ToString();

Would require me to use the new keyword. What this keyword actually does is effectively create a method with the same name as one defined in the base class.

So if I used to new keyword in the above example, I would get object's ToString method. In other words, depending on the type I was treating this as (base class or subclass), the ToString method would call a different method.

Obviously a case where I should have RTFM...

Khanzor