我有一个gridview,在gridview中我得到了一个项目模板如下
<ItemTemplate>
<asp:DropDownList runat="server" ID="ddlProductNames">
</asp:DropDownList>
</ItemTemplate>
现在在gridview的每一行我需要将它绑定到数据,但是我无法找到它并将其绑定到数据。
gridview有4个模板字段,每个模板字段中有1个itemtemplate,如下所示
<asp:TemplateField HeaderText="Product Name" ItemStyle-HorizontalAlign = "Center" >
<ItemTemplate>
<asp:TextBox runat="server" ID="txt1" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Products" ItemStyle-HorizontalAlign = "Center" >
<ItemTemplate>
<asp:DropDownList runat="server" ID="ddlProductNames">
</asp:DropDownList>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Image" ItemStyle-HorizontalAlign = "Center" >
<ItemTemplate>
<asp:FileUpload runat="server" ID="image" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Active" ItemStyle-HorizontalAlign = "Center">
<ItemTemplate>
<asp:CheckBox Text="Active" runat="server" ID="active" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
我正试图将下拉列表绑定如下
protected void Grid_OnRowDataBound(Object sender, GridViewRowEventArgs e)
{
// Bind Products
Product productManager = new Product();
TList<Product> dsProduct= productManager.GetAll();
DropDownList ddlProducts = Grid.Rows[e.Row.RowIndex].Cells[1].Controls[0].FindControl("ddlProductNames") as DropDownList;
if (dsProduct != null)
{
DataView dvProduct = new DataView(dsProduct.ToDataSet(true).Tables[0]);
dvProduct.Sort = "name asc";
ddlProducts.DataSource = dvBrand;
ddlProducts.DataTextField = "name";
ddlProducts.DataValueField = "productId";
ddlProducts.DataBind();
ListItem li = new ListItem("No Product Selected", "0");
ddlProducts.Items.Insert(0, li);
}
}
我正在排除DropDownList ddlProducts = Grid.Rows[e.Row.RowIndex].Cells[1].Controls[0].FindControl("ddlProductNames") as DropDownList;
行中的索引。我正在学习这个过程,所以我会感谢一些帮助,包括我做错了什么以及我需要改变什么。我真的很感激任何帮助。
答案 0 :(得分:1)
您必须使用FindControl
在TemplateField中查找控件。您还需要排除标题行:
protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRow row = ((DataRowView)e.Row.DataItem).Row;
DropDownList ddlProducts = (DropDownList)e.Row.FindControl("ddlProductNames");
ddlProducts.DataSource = someDataSource;
ddlProducts.DataTextField = "name";
ddlProducts.DataValueField = "productId";
ddlProducts.DataBind();
}
}
您也无需为网格中的每一行调用productManager.GetAll()
。您只需要获取当前行的产品。如果每行的源都相同,则应在将GridView绑定为成员变量之前创建它。然后,您不需要为每一行检索相同的数据。