Search code examples
asp.netdata-bindingdatatabledatasourcedatarepeater

Customizing output of datasource in repeater?


I have a Data Repeater hooked up to a datasource (datatable object). I need to change the output on the frontend for certain columns under certain conditions. What would be the most efficient way to do this?

I am currently trying to create the formatted output and assign it to another datatable and use that as the data source, but it seems overly complicated and something that would be hard to maintain.

Is there an easier way to manipulate column values for a datasource? I need the ability to check the previous and next rows for the source as that is a basis for some of the column values.


Solution

  • If you're talking about simple manipulation, the DataBinder.Eval method accepts a format string:

    <%#Eval("SomeMoneyColumn", "{0:C}")%>
    

    If the format string is not sufficient, you could create a method in the code-behind to handle the formatting, like this:

    <%#FormatData(Eval("SomeColumn"))%>
    

    In code-behind:

    protected string FormatData(object data)
    {
        return String.Format("My name is {0}", data);
    }
    

    You can also use the ItemDataBound event too. Using this technique, you can still access the datasource object, in the case that your manipulation involves other data that is bound to the repeater.

    protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        Label lblCtrl = e.Item.FindControl("SomeControl") as Label;
        if (lblCtrl != null)
        {
            lblCtrl.Text = String.Format("My name is {0}", DataBinder.Eval(e.Item.DataItem, "SomeColumn"));
        }
    }