开发者

Split datalist into sections

Within my datalist, I want to create a separation dividing each ItemTemplate with a new year, when a different year occurs.

I select my data using:

MySqlDataAdapter adapter = new开发者_开发百科 MySqlDataAdapter("SELECT * FROM code_post", dbcon);

And within this field, a date denotes the year it was created. For instance 2011, 2010, 2009.

How can I make a heading of a new year division when a different year occurs?


As of now the data is in a flat hierarchy i.e something like List<DataObject>. You can use Linq or for-loops to make it in Dictionary<int,List<DataObject>> where each entry in the dictionary key will be year value and the Value will be List of Dataobject for that year. Than your repeater should have a repeater inside it and then bind this Dictionary object to the outer repeater and the inner repeater data source should be DataItem.Value (i.e the Value part of the current KeyValue pair which is bound to outer repeater data item).

This is not a answer will you can directly copy/paste but I hope you got the idea


I too had an encounter with such a situation.

What i did was...

I took a repeater and fetched the DISTINCT Years from the database. Take a HiddenField and save the year inside like this along with the DataList inside your <ItemTemplate>.

<asp:HiddenField ID="hfYear" runat="server" Value='<%#Eval("year")%>' />

Then using the Repeater's ItemDataBound, i first searched for the DataList and HiddenField and binded that DataList with another method by passing the year from the HiddenField.

OnitemDataBound use

if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
    HiddenField hf = (HiddenField)e.Item.FindControl("hfYear");
    DataList dl = (DataList)e.Item.FindControl("yourDataListID");
    yourDataListBindMethod(hf.Value);
}

The only drawback in this is that there are multiple round trips to the database(number of distinct years=number of trips to database).


The way I solved this was by making one trip to the database, and having the code such as

private String previousYear;
public string outputHeader(object y){
  String year = y.ToString();
   if(!previousYear.equals(year)){
      previousYear = year;
      return year;
   }
   return "";
}

and inside the item template i did

<%# outputHeader(Eval("date")) %>

This allows for one trip to the DB, and is far more efficent/flexible than the previously suggest methods

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜