如何使用数组创建控件 [英] How to create controls using array

查看:56
本文介绍了如何使用数组创建控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个复选框集合,在我的程序中大约有300个复选框.如果从工具箱中放置复选框控件会很费时,我认为使用循环和数组来创建控件会很好.我想更改选中的控件的颜色.如何在页面中的所有其他控件中识别复选框控件.我正在c#.Plz帮助下在Asp.net中工作.

I want to create a collection of checkboxes, about 300 checkboxes in my program.It will be time consuming if I place checkbox control from the toolbox.I think it will be good to use for loop and array to create controls.along with that I want to change the color of checked controls.How can i identify the checkbox controls among all other controls in the page.I''m working in Asp.net with c#.Plz help.

推荐答案

复选框"ID"属性可用于查找您要查找的确切控件.如果您需要知道要访问它,则可能是服务器端或任何其他地方的checkchanged事件.
Checkbox ''ID'' property can be used to find the exact one control you are looking for. Either it be a checkchanged event on server side or any other place, if you need to know in order to access it.


将此代码添加到页面中(我假设您是在这里谈论Web表单):

Add this code in your page (I''m assuming you''re talking about Web Forms here):

<asp:Panel ID="pnlCheckboxes" runat="server" ScrollBars="Auto" EnableViewState="true"></asp:Panel>



这在您的代码后面:



and this in your code behind:

protected void Page_Init(object sender, EventArgs e)
{
    for (int i = 0; i < 300; i++)
    {
        CheckBox chk = new CheckBox();
        chk.AutoPostBack = true;
        chk.ID = "checkbox_" + i.ToString();
        chk.Text = "Checkbox " + i.ToString();
        chk.ForeColor = System.Drawing.ColorTranslator.FromHtml("#696969");
        chk.CheckedChanged += new EventHandler(chk_CheckedChanged);
        pnlCheckboxes.Controls.Add(chk);
        pnlCheckboxes.Controls.Add(new LiteralControl("<br/>"));
    }
}

protected void chk_CheckedChanged(object sender, EventArgs e)
{
    CheckBox chk = sender as CheckBox;
    if (chk != null)
    {
        string color = chk.Checked ? "#FF0000" : "#696969";
        chk.ForeColor = System.Drawing.ColorTranslator.FromHtml(color);
    }
}


这篇关于如何使用数组创建控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆