先看看效果:
准备数据:
http://www.cnblogs.com/insus/articles/1439030.html
.aspx:
<asp:CheckBoxList ID="CheckBoxListColour" runat="server" RepeatColumns="10" RepeatDirection="Horizontal"
OnDataBound="CheckBoxListColour_DataBound" OnSelectedIndexChanged="CheckBoxListColour_SelectedIndexChanged"
AutoPostBack="true">
</asp:CheckBoxList>
OnDataBound="CheckBoxListColour_DataBound" OnSelectedIndexChanged="CheckBoxListColour_SelectedIndexChanged"
AutoPostBack="true">
</asp:CheckBoxList>
从上面的数据,下载并放入asp.net专案中,然后读出所有图片文件:
View Code
private List<string> ImageNames
{
get
{
List<string> o = new List<string>();
DirectoryInfo di = new DirectoryInfo(Server.MapPath ("~/Colours"));
FileInfo[] fiArray = di.GetFiles();
for (int i = 0; i < fiArray.Length; i++)
{
o.Add(fiArray[i].Name);
}
return o;
}
}
{
get
{
List<string> o = new List<string>();
DirectoryInfo di = new DirectoryInfo(Server.MapPath ("~/Colours"));
FileInfo[] fiArray = di.GetFiles();
for (int i = 0; i < fiArray.Length; i++)
{
o.Add(fiArray[i].Name);
}
return o;
}
}
绑定数据至CheckBoxList控件:
View Code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Data_Binding();
}
}
private void Data_Binding()
{
this.CheckBoxListColour.DataSource = ImageNames.Select(c => new { value = c }).ToList();
this.CheckBoxListColour.DataTextField = "value";
this.CheckBoxListColour.DataBind();
}
{
if (!IsPostBack)
{
Data_Binding();
}
}
private void Data_Binding()
{
this.CheckBoxListColour.DataSource = ImageNames.Select(c => new { value = c }).ToList();
this.CheckBoxListColour.DataTextField = "value";
this.CheckBoxListColour.DataBind();
}
CheckBoxList控件的OnDataBound="CheckBoxListColour_DataBound"事件。
View Code
protected void CheckBoxListColour_DataBound(object sender, EventArgs e)
{
var cbl = sender as CheckBoxList;
foreach (ListItem li in cbl.Items)
{
li.Text = string.Format("<img src='Colours/{0}' />", li.Value);
}
}
{
var cbl = sender as CheckBoxList;
foreach (ListItem li in cbl.Items)
{
li.Text = string.Format("<img src='Colours/{0}' />", li.Value);
}
}
CheckBoxList控件的OnSelectedIndexChanged="CheckBoxListColour_SelectedIndexChanged"事件。
View Code
protected void CheckBoxListColour_SelectedIndexChanged(object sender, EventArgs e)
{
var cbl = sender as CheckBoxList;
foreach (ListItem li in cbl.Items)
{
if (li.Selected)
{
li.Attributes.Add("style", "background-color: red;");
}
}
}
{
var cbl = sender as CheckBoxList;
foreach (ListItem li in cbl.Items)
{
if (li.Selected)
{
li.Attributes.Add("style", "background-color: red;");
}
}
}