Dynamic control creation in datagrid based on data in that column

  • Thread starter Thread starter mitramay
  • Start date Start date
M

mitramay

I am creating a dynamic datagrid. The controls in some of the template
columns will have to be generated based on the data contained in them
(i.e. the data for that respective DataField column). For example, if I

have a column called Available, the possible values for it are Yes or
No. In case it is "Yes" I need a label in that column and in case it is

"No" I need a hyperlink. Pls help.
 
add event handler to your datagrid ItemDatabound event as below

private void dg_ItemDataBound(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)

{

if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType ==
ListItemType.AlternatingItem)

{

// get your data using your datasource for the selected index( ie,
e.Item.ItemIndex)

bool bYes = false; //Check for yes or no value here

if(bYes)

{


Label lbl = new Label();

lbl.Text = "Yes";

e.Item.Cells[0].Controls.Add(lbl); // I assume your template column is first
column , if not adjust your cell index accordingly

}

else

{

HyperLink link = new HyperLink ();

link .Text= "No";

link.NavigateUrl = "";/* set your url here */

e.Item.Cells[0].Controls.Add(link);

}

}

}
 
Back
Top