当前位置:编程学习 > asp >>

高亮CheckBoxList选中的项目

先看看效果:

 \


准备数据:
 
标准颜色图片,从office2000 Word的标准颜色窗口取出来,并用16进制把图片命名。
图片尺寸12X12 Pixel。

下载地址:/2012/0405/20120405092137446.zip
  

.aspx:
<asp:CheckBoxList ID="CheckBoxListColour" runat="server" RepeatColumns="10" RepeatDirection="Horizontal"
            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;
        }
    }

 
绑定数据至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();
    }

 
 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);
        }
    }

 
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;");
            }
        }
    }


 

摘自  Insus.NET 
补充:Web开发 , ASP.Net ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,