c#listbox,其中包含用于更改属性的控件名称

时间:2014-10-27 10:48:29

标签: c# properties listbox controls

我正在创建新控件并将名称放在列表框中,如何使用列表框中选择的名称来更改控件属性。



//creating the label
 LabelNumber++;
 label label=new Label();
 label.BackColor=Color.Transparent;
 label.Location=new System.Drawing.Point(1,
1);
 label.Name="Label" + LabelNumber;
 label.Text=LabelNumber.ToString();
 label.Size=new System.Drawing.Size(20,
20);
 label.TextAlign=ContentAlignment.MiddleCenter;
 ProjectPanel.Controls.Add(label);
 ControlBox1.Items.Add(label.Name);




3 个答案:

答案 0 :(得分:0)

Yo可以使用ControlBox1_SelectedIndexChanged事件下的标签名称,并获取所选索引标签名称的值。

答案 1 :(得分:0)

您可以创建一个简单的“listboxitem”结构并像这样使用它:

struct lbo
{
    // make the structure immutable
    public readonly Control ctl;
    // a simple constructor
    public lbo(Control ctl_) { ctl = ctl_; }
    // make it show the Name in the ListBox
    public override string ToString() { return ctl.Name; }
}

private void button1_Click(object sender, EventArgs e)
{
    // add a control:
    listBox1.Items.Add(new lbo(button1));
}

private void button2_Click(object sender, EventArgs e)
{
    // to just change the _Name (or Text or other properties present in all Controls)
    ((lbo)listBox1.SelectedItem).ctl.Text = button2.Text;

    // to use it as a certain Control you need to cast it to the correct control type!!
    ((Button)((lbo)listBox1.SelectedItem).ctl).FlatStyle = yourStyle;

    // to make the cast safe you can use as
    Button btn = ((lbo)listBox1.SelectedItem).ctl as Button;
    if (btn != null) btn.FlatStyle = FlatStyle.Flat;
}

这里没有检查正确的类型或你选择了一个项目..但是你明白了:把一些比赤裸的对象或纯粹的字符串更有用的东西放到ListBox中!

您可以循环遍历所有控件并比较名称,但效率较低且实际上不安全,因为Name属性不能保证是唯一的。

答案 2 :(得分:0)

问题表明OP正在使用ListBox,因此我的代码就是这样做的假设。

基本上你需要做的是如下:从ListBox中获取所选文本,找到具有相同名称的控件(我们假设这始终是唯一的),然后更改该控件的属性。

以下代码将满足这些要求:

// Get the selected text from the ListBox.
string name = ControlBox1.GetItemText(ControlBox1.SelectedItem);

// Find the control that matches that Name. Assumes there is only ever 1 single match.
Control control = ProjectPanel.Controls.Find(name, true).FirstOrDefault();

// Set properties of the Control.
control.Name = "new name";

// If you know it's a Label, you can cast to Label and use Label specific properties.
Label label = control as Label;
label.Text = "some new text";