[英]How to add a ComboBox to an asp.net unbound GridView
我不知道如何在运行时通过代码将ComboBox列添加到未绑定的GridView中。
Programmatically: 以编程方式:
I've used the following class (but for DropDown and CheckBox binding) in the past which implements ITemplate. 过去,我使用以下类(但用于DropDown和CheckBox绑定)来实现ITemplate。
public class AddTemplateToGridView : ITemplate
{
String columnName;
public AddTemplateToGridView(String colname)
{
columnName = colname;
}
void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
if (columnName == "yourField")
{
ComboBox cb = new ComboBox();
cb.DataBinding += new EventHandler(cb_DataBinding);
container.Controls.Add(cb);
}
}
void cb_DataBinding(object sender, EventArgs e)
{
ComboBox cb = (ComboBox)sender;
GridViewRow container = (GridViewRow)cb.NamingContainer;
Object dataValue = DataBinder.Eval(container.DataItem, columnName);
if (dataValue != DBNull.Value)
{
// Assign ComboBox vals if necessary
... = dataValue
}
}
}
Use by declaring your GridView and TemplateField in the codebehind: 通过在后面的代码中声明GridView和TemplateField来使用:
GridView newGrid = new GridView();
TemplateField field = new TemplateField();
field.HeaderText = "columnName";
field.ItemTemplate = // some item template
field.EditItemTemplate = new AddTemplateToGridView("yourField");
newGrid.Columns.Add(field);
or Declaratively: 或声明式地:
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField HeaderText="yourField">
<ItemTemplate>
<asp:Label runat="server" Text ='<%# Eval("yourField") %>' />
</ItemTemplate>
<EditItemTemplate>
<%--Your ComboBox--%>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.