Reza on blogging [MVP]

THIS BLOG HAS MOVED TO: http://blogs.devhorizon.com/reza

Subscriptions

<January 2009>
SuMoTuWeThFrSa
28293031123
45678910
11121314151617
18192021222324
25262728293031
1234567

News



toronto.sharepoint.camp


Navigation

Post Categories

Other Bloggers

Personal Links

Saturday, February 03, 2007 - Posts

DataList and Runtime Databinding in a Web Part

In order to bind data returned from database or a search query to a datalist at runtime in your web part , there are certain steps that you should take,otherwise data list won't render its content.The most important step is setting the ItemTemplate property to a proper template:

Web Part:

protected DataList _dtList;

protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
        {
                           EnsureChildControls();

                          // Database connection and populating a datatable called prDT for example

                           this._dtList.ItemTemplate = new ProductTemplate();       
                           this._dtList.DataSource = prDT; 
                           this._dtList.DataBind();
                           this._dtList.RenderControl(writer);

                               
        }

protected override void CreateChildControls()
        {
                           this._dtList = new DataList();
                           this._dtList.RepeatDirection = RepeatDirection.Horizontal;
                           this._dtList.RepeatColumns = 2;
                          Controls.Add(this._dtList);
        }

 

ProductTemplate.cs:


  public class ProductTemplate : ITemplate
    {

        void ITemplate.InstantiateIn(Control container)
        {

                        Label itemlbl = new Label();
                        itemlbl.Width = 110;
                        itemlbl.DataBinding += new EventHandler(itemlbl_DataBinding);
                        container.Controls.Add(itemlbl);
   
        }

      void itemlbl_DataBinding(object sender, EventArgs e)
        {
                     Label lbldata = (Label)sender;
                     DataListItem container = (DataListItem)lbldata.NamingContainer;
                     lbldata.Text= Convert.ToString(DataBinder.Eval(((DataListItem)container).DataItem,"ProductName"))
        }

    }

       


posted Saturday, February 03, 2007 5:48 AM by admin with 0 Comments

Powered by Community Server, by Telligent Systems