You can add the Itemtemplate to the grid dynamically.
Add Placeholder and Link buttons in the place holder.
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvTest" AutoGenerateColumns="false" runat="server">
</asp:GridView>
</div>
</form>
In the code behind just add the item template.
public partial class _Default : System.Web.UI.Page
{
private static DataTable tblTemp = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
BindGrid();
}
public void BindGrid()
{
DataTable tbl = new DataTable();
tbl.Columns.Add("Places",typeof(string));
tbl.Columns.Add("State",typeof(string));
tbl.Rows.Add("Mumbai,Pune,Nasik", "Maharashtra");
tbl.Rows.Add("Amritsar,Jalandhar", "Punjab");
tblTemp = tbl;
TemplateField objTemplateFieldState = new TemplateField();
objTemplateFieldState.HeaderText = "State";
objTemplateFieldState.HeaderStyle.Width = Unit.Percentage(30);
objTemplateFieldState.ItemTemplate = new CreateItemTemplate(ListItemType.Item, new Label());
gvTest.Columns.Add(objTemplateFieldState);
TemplateField objTemplateFieldCities = new TemplateField();
objTemplateFieldCities.HeaderText = "Cities";
objTemplateFieldCities.HeaderStyle.Width = Unit.Percentage(30);
objTemplateFieldCities.ItemTemplate = new CreateItemTemplate(ListItemType.Item, new PlaceHolder());
gvTest.Columns.Add(objTemplateFieldCities);
gvTest.DataSource = tbl;
gvTest.DataBind();
}
public class CreateItemTemplate : ITemplate
{
private ListItemType myListItemType;
private Control cntrlType;
int i = 0;
public CreateItemTemplate()
{
}
public CreateItemTemplate(ListItemType Item, Control cntrlTypeTemp)
{
myListItemType = Item;
cntrlType = cntrlTypeTemp;
}
public void InstantiateIn(System.Web.UI.Control container)
{
if (myListItemType == ListItemType.Item)
{
if (cntrlType is PlaceHolder)
{
PlaceHolder phCities = new PlaceHolder();
string[] strCities = tblTemp.Rows[i][0].ToString().Split(',');
foreach (string strCity in strCities)
{
LinkButton lnkCity = new LinkButton();
lnkCity.Text = strCity.Trim();
phCities.Controls.Add(lnkCity);
Literal ltr = new Literal();
ltr.Text = " | ";
phCities.Controls.Add(ltr);
}
container.Controls.Add(phCities);
i++;
}
if (cntrlType is Label)
{
Label lblState = new Label();
lblState.Text = tblTemp.Rows[i][1].ToString();
container.Controls.Add(lblState);
i++;
}
}
}
}
}
It's simple and will help you to create seperate events for every link button.