在Gridview中绑定没有SqlDataSource的DropDownList

时间:2012-07-05 15:15:49

标签: c# asp.net gridview binding drop-down-menu

我意识到您可以使用SqlDataSource轻松地在gridview中设置下拉列表,但是仅包含listitems的有限列表呢?如果没有DataSource,将绑定置于选定的值似乎不起作用。这是我到目前为止所得到的一个例子。

<EditItemTemplate>
   <asp:DropDownList ID="Fund"  runat="server" SelectedValue='<%# Bind("Fund") %>' >
      <asp:ListItem  Value="">---</asp:ListItem>
      <asp:ListItem Value="Test1">Test</asp:ListItem>
      <asp:ListItem Value="Test2">Test2</asp:ListItem>
   </asp:DropDownList>
</EditItemTemplate>

这似乎是一个非常愚蠢的小问题,我要在我的数据库中制作一个静态的10行表。

3 个答案:

答案 0 :(得分:3)

最简单的解决方案是在代码中创建Dictionary<TKey,TValue>并将其绑定到DropDownList,或者如您所述,将其绑定到静态表...

示例代码:

Dictionary<string, string> list = new Dictionary<string, string>();
list.Add("item 1", "Item 1");
list.Add("item 2", "Item 2");
list.Add("item 3", "Item 3");
list.Add("item 4", "Item 4");

ddl.DataSource = list;
ddl.DataTextField = "Value";
ddl.DataValueField = "Key";
ddl.DataBind();

答案 1 :(得分:1)

试试这个:

Dictionary<string, string> items= new Dictionary<string, string>();
items.Add("-1","-Select-");
items.Add("Test1", "Test1");
items.Add("Test2", "Test2");
ddl.DataSource = items;
ddl.DataValueField = "Key";
ddl.DataTextField = "Value";
ddl.DataBind();

答案 2 :(得分:0)

您想以编程方式设置DropDownList。我真的建议避免使用SqlDataSource控件的用户。它非常笨重,在重用方面也不是很好。

以下代码使用实体框架通过用户名从数据库中检索数据。使用此功能,您可以将所需数据绑定到DropDownList,而无需在每次需要调用此过程时创建SqlDataSource

public List<Record> GetAllRecordsByUserName(string credentials)
{
    List<Record> recordList;
    using (CustomEntities context = new CustomEntities())
    {

        IQueryable<Section> recordQuery = from records in context.Records
                                              where records.UserName == credentials
                                              select records; 
        recordList = recordQuery.ToList<Record>();
    }
    return recordList;
}

public void BindDropDown()
{
    DropDownList1.DataSource = GetAllRecordsByUserName("test.user");
    DropDownList1.DataBind();
}
相关问题