开发者

Customise Controls at runtime

I have controls on a form and I get its objects at runtime using assemblies. Now I want to change their properties at runtime like forecolor, backcolor and text.

private void button1_Click(object sender, EventArgs e)
{
    Type formtype = typeof(Form);
    foreach(Type type in Assembly.GetExecutingAssembly().GetTypes())
    {
        if (formtype.IsAssignableFrom(type))
        {
            listBox1.Items.Add(type.Name);
            Form frm = (Form)Activator.CreateInstance(type);
            f开发者_开发知识库oreach (Control cntrl in frm.Controls)
            {
                listBox1.Items.Add(cntrl.Name);
            }
        }
    }
}

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    Control cnt = (Control)listBox1.SelectedItem;
    MessageBox.Show(cnt.Name);
    cnt.ForeColor = colorDialog1.Color;
}

This code gets me the objects at runtime but when I try to change the forecolor it gives me an error. Can anyone help me?


The code you posted have several problems:

  1. listBox1.Items.Add(cntrl.Name); You are adding the control name not the control itself to the collection, and again listBox1.Items.Add(type.Name); added the form type name to the collection.
  2. In the code:

    Form frm = (Form)Activator.CreateInstance(type);
    

    You are creating a new Form(s) instance(s) each time and you are not showing them anywhere.

So How to fix it:

private void button1_Click(object sender, EventArgs e)
{
    List<Control> controls = new List<Control>();

    Type formtype = typeof(Form);
    foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())
    {
        if (formtype.IsAssignableFrom(type))
        {
            Form frm = (Form)Activator.CreateInstance(type);
            controls.Add(frm);//Add the new instance itself to the list
            foreach (Control cntrl in frm.Controls)
            {
                controls.Add(cntrl);
            }
            frm.Show();//show the new form created
        }
    }

    listBox1.DataSource = controls;
    listBox1.DisplayMember = "Name";//or "Text"
}

Edit: Also make sure that colorDialog1 is previously initialized and shown to get the colorDialog1.Color value from it.

I don't know what you are trying to achieve here, but if you want to just get the current instance of the form that is running, you can use Form.ActiveForm for that....

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜