MohD MohD - 28 days ago 26
ASP.NET (C#) Question

How To Override Datalist To Be Rendered Into Divs Instead Of Table?

I want to render datalist to divs instead of table and the repeat columns will fixed by float style on div.

So any one knows an override render method to do that.

Thanks.

Answer

I found this solution but I posted it to help others;

Some users suggest to use repeater and that is right, but for that case to replace div instead of table in datalist

RepeatLayout=RepeatLayout.Flow 

This will make it span with br. But using Horizontal for RepeatDirection wil remove br but still items rendered with span.

RepeatDirection=RepeatDirection.Horizontal 

This statement will remove br but still items rendered with span.

So override RenderContents to create your own divs outside span and remove br if you do not want to use Horizontal RepeatDirection, as follow:

protected override void RenderContents(HtmlTextWriter w)
{
    writer.WriteBeginTag("div");
    writer.WriteAttribute("id", this.ClientID);
    writer.WriteAttribute("class", cssClass);
    writer.Write(HtmlTextWriter.TagRightChar);
    foreach (DataListItem li in this.Items)
    {
        writer.WriteBeginTag("div");
        writer.WriteAttribute("id", li.ClientID);
        writer.WriteAttribute("class", li.CssClass);
        writer.Write(HtmlTextWriter.TagRightChar);
        li.CssClass = null; // clear css not to added in span
        li.RenderControl(w);
        writer.WriteEndTag("div");
    }
    writer.WriteEndTag("div");

}

My Regards

Comments