开发者

How to reuse list items for asp:DropDownList controls?

I have an .aspx page which contains two <asp:DropDownList> controls which are filled with static items like so:

<asp:DropDownList ID="ddl1" ...>
    <asp:ListItem Value="A" Text="..." />
    <asp:ListItem Value="B" Text="..." />
    ....
    <asp:ListItem Value="X" Text="..." />
</asp:DropDownList>

.....

<asp:DropDownList ID="ddl2" ...>
    <asp:ListItem Value="A" Text="..." />
    <asp:ListItem Value="B" Text="..." />
    ....
    <asp:ListItem Value="X" Text="..." />
</asp:DropDownList>

The list items for ddl1 and ddl2 are the same. As such, I would like to reuse them and remove the duplication.

开发者_开发知识库I could fill the combos in the code behind .aspx.cs but I really don't want to have some dumb data in there filling plain combos. I just want the logic of the page there.

Is there a way to resue the list items inside the .aspx?


Create a class to represent the data in the DDL and then call a get method. Use the same ObjectDataSource for both DDL's or use separate ObjectDataSources. You could optimize the class to use static members, but it's probably overkill.

This strategy would nicely refactor into a db call in the future...

In the Web Form:

<asp:ObjectDataSource ID="obj1" runat="server"
    TypeName="WebApplication1.Data.MyDdlItem"
    SelectMethod = "GetAll" />
<asp:DropDownList ID="ddl1" runat="server" DataSourceID="obj1" DataTextField="Name" DataValueField="Id" />
<asp:DropDownList ID="ddl2" runat="server" DataSourceID="obj1" DataTextField="Name" DataValueField="Id" />

The corresponding Object:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1.Data
{
    public class MyDdlItem
    {
        public string Id { get; set; }
        public string Name { get; set; }

        public static List<MyDdlItem> GetAll()
        {
            List<MyDdlItem> list = new List<MyDdlItem>();
            list.Add(new MyDdlItem { Id = "1", Name = "Option 1" });
            list.Add(new MyDdlItem { Id = "2", Name = "Option 2" });
            list.Add(new MyDdlItem { Id = "3", Name = "Option 3" });
            list.Add(new MyDdlItem { Id = "4", Name = "Option 4" });
            return list;
        }
    }
}


Just create a datatable and bind both dropdown with the same datatable.


Why don't you use Java script array to bind them later to both the drop downs?

<script>
  var arr = new Array(new Array('A','value1'),new Array('B','value2'),new Array('C','value3'));
var elem = document.getElementById("ddl1");
var elem1 = document.getElementById("ddl2");
 for(i=0;i<arr.length;i++)
 {
    elem.add(new Option(arr[i][0, 1], arr[i][0, 0]),false);
    elem1.add(new Option(arr[i][0, 1], arr[i][0, 0]),false);
 }
</script>


Try something like ddl2.DataSource=ddl1.DataSource then once ddl1 has all its items ddl2 should as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜