c#
  • asp.net
  • gridview
  • binding
  • drop-down-menu
  • 2012-07-05 51 views 2 likes 
    2

    我知道你可以轻松地建立一个下拉列表中使用一个SqlDataSource一个gridview,但对于只含listItems中的有限列表?如果没有DataSource,将Bind放入选定的值似乎不起作用。这是迄今为止我所得到的一个例子。绑定一个DropDownList没有一个SqlDataSource在GridView

    <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行的表在我的数据库中的点。

    回答

    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(); 
    
    +0

    确切位置在哪里我应该设置这个?我在DropdownList的onDataBinding事件中尝试过,但是我陷入某个循环中。编辑:我明白了为什么现在会导致一个循环。我在那里愚蠢地缺乏预见。 – Aerowind 2012-07-05 15:51:05

    +0

    那么,我终于通过RowCreated事件获得了使用此代码添加的DDL,但没有发生与gridview源数据绑定的情况。 – Aerowind 2012-07-05 16:07:21

    +0

    对不起,这个问题完全没有关系,只是一个完全愚蠢的错误。这是我们添加到表中的新字段,我更新了InsertCommand而不是UpdateCommand。 – Aerowind 2012-07-05 18:18:31

    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(); 
    
    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(); 
    } 
    
    相关问题