c#
  • asp.net
  • gridview
  • binding
  • drop-down-menu
  • 2012-07-05 26 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(); 
    } 
    
    相關問題