我在GridView中有一个项目模板,我想为每一行创建一个下拉列表并将其绑定到从数据库中检索的值..但我不知道该怎么做...这就是我所拥有的远..但不知道在哪里放置代码来填充每行下拉..
<ItemTemplate>
<asp:DropDownList runat="server" ID="ddlMyQuantity" SelectedValue='<%#
(DataBinder.Eval(Container.DataItem,"Quantity")) %>'>
</asp:DropDownList>
</ItemTemplate>
并且在代码后面,不知道如何或在何处放置它以便在每一行上创建..
public void BindMyQuantity()
{
for (int i = 1; i < 15; i++)
{
ddlMyQuantity.Items.Add(i.ToString());
}
}
此外我不确定我是否可以这样做,但代码并没有抱怨..在asp声明中添加SelectedValue
答案 0 :(得分:0)
您可以使用OnRowDataBound
动态绑定下拉列表:
protected void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
var dropdownList = (DropDownList)e.Row.FindControl("ddlMyQuantity");
for (int i = 1; i < 15; i++)
{
dropdownList.Items.Add(i.ToString());
}
dropdownList.SelectedValue =
Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Quantity"));
}
}
添加绑定:
<asp:GridView ... OnRowDataBound="GridView_RowDataBound">
...
</asp:GridView>
答案 1 :(得分:0)
据我所知,最好的选择是在Grid的“RowDataBound”事件中编写此代码。请参阅下面的示例代码。
protected void GridView_RowDataBound(..)
{
if (e.Row.RowType.Equals(DataControlRowType.DataRow))
{
DropDownList ddl = e.Row.FindControl("ddlMyQuantity") as DropDownList;
if (ddl != null)
{
for (int i = 1; i < 15; i++)
{
ddl.Items.Add(i.ToString());
}
}
}
}
在aspx页面中,提供此
<ItemTemplate>
<asp:DropDownList runat="server" ID="ddlMyQuantity"></asp:DropDownList>
</ItemTemplate>
希望这有助于!!
答案 2 :(得分:0)
<asp:TemplateField HeaderText="Type Cargo" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="10%" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" DataValueField="DESCRIPTION"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
后面的代码将如下所示...
Dim rowId As DropDownList
For i As Integer = 0 To gridView1.Rows.Count - 1
Dim gridrow As GridViewRow = gridView1.Rows(i)
rowId = DirectCast(gridrow.FindControl("DropDownList1"), DropDownList)
Dim dt As DataTable = Get_List()
rowId.DataSource = dt
rowId.DataBind()
Next
Get_List是一个返回数据表的函数