Format Data in an ASP.NET Repeater

2019-09-05 14:32发布

问题:

I have an ASP.NET web form that uses an ASP.NET Repeater. The data source for this repeater is a DataTable that includes a column called "City", and one called "State". In the ItemTemplate of the Repeater, I want to call a custom method I've written called "FormatLocation". This method is defined as:

protected string FormatLocation(string city, string state)
{
  string location = city;
  if (state.Length > 0)
    location += ", " + state.ToUpper();
  return location;
}

I want to call this method when the data is bound in the ItemTemplate so that the result appears in the UI. Can someone tell me how to do this? Thanks!

回答1:

You can do this way if get them from Database On the Repeater

<ItemTemplate>
    <%#FormatLocation(Container.DataItem)%>
</ItemTemplate>

On code behind

protected string FormatLocation(object oItem)
{
    string city = DataBinder.Eval(oItem, "city").ToString();
    string state = DataBinder.Eval(oItem, "state").ToString();

     string location = city;
      if (state.Length > 0)
        location += ", " + state.ToUpper();
      return location    
}

If they are not from database, but from a list, the object oItem is the data himself.