【问题标题】:c# listbox with control names to change properties [duplicate]c# 带有控件名称的列表框以更改属性[重复]
【发布时间】:2014-12-22 12:44:44
【问题描述】:

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

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

【问题讨论】:

标签: c# properties listbox controls


【解决方案1】:

您可以创建一个简单的“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】:

    问题表明 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";
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • -1 这不仅没有详细说明如何获取标签的名称,而且甚至没有尝试解决获取控件引用的要求(使用匹配名称),然后更改该控件的属性
      猜你喜欢
      • 2011-09-29
      • 1970-01-01
      • 1970-01-01
      • 2018-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-26
      • 1970-01-01
      相关资源
      最近更新 更多