Basically, I want a button that adds a new column with my controls (i.e. TextBox, DropDownList) to my GridView.
Already seems simple enough with this:
protected void btn_AddColumn_Click(object sender, EventArgs e)
{
TemplateField MyTemplateField = new TemplateField();
gv_SupplierPrices.Columns.Add(MyTemplateField);
}
Say I want to add this markup:
<asp:TemplateField>
<ItemTemplate>
<table style="width:100%;">
<tr>
<td><asp:TextBox ID="tbox_ItemPrice" runat="server"></asp:TextBox></td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
Here's the problem. How do I use a TemplateField I created in markup on my .aspx page and add it to my new column on code behind? I don't know and don't want to create my TemplateField on code behind because I will not be able to create elaborate or fancy markups. They will just look like controls that are next to each other. It's very ugly.
P.S. If anyone is curious as to what I'm actually making, I'm basically turning my GridView into an Excel-like gridsheet. New columns represent a supplier and each row represents an item the supplier is selling. They want it that way because it's easier to compare prices side-by-side whilst they're filling it up.
Update: I already figured it out. I can simply call the column of my GridView from codebehind that represents the TemplateField I created in markup, then I add it.
<asp:GridView ID="gv_SupplierTable" runat="server" AutoGenerateColumns="False"
DataKeyNames="Id" DataSourceID="TestTable_DS">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" InsertVisible="False"
ReadOnly="True" SortExpression="Id" />
<asp:BoundField DataField="AccountType" HeaderText="AccountType"
SortExpression="AccountType" />
<asp:TemplateField AccessibleHeaderText="MyTemplateFieldCreated in Markup">
<ItemTemplate>
<table style="width:100%;">
<tr>
<td><asp:TextBox ID="tbox_ItemPrice" runat="server"></asp:TextBox></td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Then in codebehind, I can access that column that represents the TemplateField created in markup and add it again on button click, like a new copy:
protected void btn_AddColumn_Click(object sender, EventArgs e)
{
DataControlField newColumn = this.gv_SupplierTable.Columns[2];
//this column at index #2 from my GridView represents
the TemplateField created in markup since the columns
at index #0 and index #1 are DataBound.
gv_SupplierTable.Columns.Add(newColumn);
}