我有两个建议,在 ItemTemplate 创建而不是 RowInitialize 服务器事件上绑定列表,如果您要动态创建模板,请使用 Page_Init。
代码片段:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Init(object sender, EventArgs e)
{
TemplateDataField FreightField = new TemplateDataField();
FreightField.ItemTemplate = new CustomTemplate();
FreightField.VisibleIndex = 2;
FreightField.Key = "Freight";
TemplateDataField ShippedDateField = new TemplateDataField();
ShippedDateField.ItemTemplate = new CustomTemplate2();
ShippedDateField.VisibleIndex = 3;
ShippedDateField.Key = "ShippedDate";
if (this.WebDataGrid1.Columns.FromKey("Freight") != null)
{
((TemplateDataField)this.WebDataGrid1.Columns["Freight"]).ItemTemplate = new CustomTemplate();
((TemplateDataField)this.WebDataGrid1.Columns["ShippedDate"]).ItemTemplate = new CustomTemplate2();
}
else
{
this.WebDataGrid1.Columns.Add(FreightField);
this.WebDataGrid1.Columns.Add(ShippedDateField);
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
public class CustomTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
WebDropDown wdd = new WebDropDown();
wdd.ID = "WebDropDown1";
wdd.Width = Unit.Pixel(200);
wdd.Items.Add(new DropDownItem("1", "1"));
wdd.Items.Add(new DropDownItem("2", "2"));
wdd.Items.Add(new DropDownItem("3", "3"));
wdd.ClientEvents.SelectionChanged = "ctl00_WebDropDown1_SelectionChanged";
container.Controls.Add(wdd);
}
protected void btn_Click(object sender, EventArgs e)
{
var temp = 0;
}
}
public class CustomTemplate2 : ITemplate
{
public void InstantiateIn(Control container)
{
WebDropDown wdd = new WebDropDown();
wdd.ID = "WebDropDown2";
wdd.Width = Unit.Pixel(200);
wdd.Items.Add(new DropDownItem("4", "4"));
wdd.Items.Add(new DropDownItem("5", "5"));
wdd.Items.Add(new DropDownItem("6", "6"));
container.Controls.Add(wdd);
}
}