Home > Uncategorized > DataList and Runtime Databinding in a Web Part

DataList and Runtime Databinding in a Web Part

February 3rd, 2007 Leave a comment Go to comments

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”))
        }


    }


       



Categories: Uncategorized Tags:
  1. No comments yet.
You must be logged in to post a comment.