簡介
此控制項是封裝一個標準的HTML控制項,但是ASP.NET缺沒有提供此控制項的伺服器版,因為我自己的項目中用到了這樣的控制項,所以趁這幾天有空整理了一下,先體驗一下設計時和運行時的效果:
此控制項與我前些日子介紹的ComboBox原理相同。區別在於:
- ComboBox只實現了一層控制項階層,而GroupList實現了嵌套的二層控制項階層。我還想實現如多級菜單和樹的無限級控制項階層,通過這兩個控制項的開發我發現這不難實現。
- 實現了一個SelectedIndexChanged事件。
特點
相對於DropDownList來說有如下兩個有趣的特點:
- 實現了選擇項的分組
- 分組項不能被選擇
我也是因為項目中要這樣的控制項,後來有網友告訴我有這樣的html控制項,而奇怪的是asp.net並沒有提供它的伺服器版,於是封裝成一個伺服器控制項來方便使用。
使用樣本
- 編程方式動態添加分組選擇項for(int i=1; i < 4; i++)
{
GroupItem gItem = new GroupItem("Group_"+i.ToString());
for(int j=1; j < 6; j++)
{
GroupListItem item = new GroupListItem(gItem.Label + "_Item_" + j.ToString());
gItem.Items.Add(item);
}
GroupList1.GroupItems.Add(gItem);
}
- 設計時頁面聲明<bestcomy:grouplist id="Grouplist3" runat="server">
<bestcomy:GroupItem Label="Group1">
<bestcomy:GroupListItem Text="Group1_Item1" Value="Group1_Item1" Selected="False"></bestcomy:GroupListItem>
<bestcomy:GroupListItem Text="Group1_Item2" Value="Group1_Item2" Selected="False"></bestcomy:GroupListItem>
</bestcomy:GroupItem>
<bestcomy:GroupItem Label="Group2">
<bestcomy:GroupListItem Text="Group2_Item1" Value="Group2_Item1" Selected="False"></bestcomy:GroupListItem>
<bestcomy:GroupListItem Text="Group2_Item2" Value="Group2_Item2" Selected="True"></bestcomy:GroupListItem>
</bestcomy:GroupItem>
</bestcomy:grouplist>
- 資料繫結DataTable dt = new DataTable();
dt.Columns.Add("group", typeof(string));
dt.Columns.Add("text", typeof(string));
dt.Columns.Add("value", typeof(string)); for(int i=0; i < 10; i++)
{
DataRow ndr = dt.NewRow();
ndr["group"] = "Group_" + ((int)(i%2)+1).ToString();
ndr["text"] = "Text_" + ((int)(i+1)).ToString();
ndr["value"] = "value_" + ((int)(i+1)).ToString();
dt.Rows.Add(ndr);
}
this.Grouplist2.DataGroupField = "group";
this.Grouplist2.DataTextField = "text";
this.Grouplist2.DataValueField = "value";
this.Grouplist2.DataSource = dt.DefaultView;
this.Grouplist2.DataBind();
原始碼
http://files.cnblogs.com/bestcomy/WebControlTest.rar