2014-10-27 97 views
-1

我正在創建新的控件並將名稱放在列表框中,我如何使用在列表框中選擇的名稱來更改控件屬性。帶有控件名稱的c#listbox更改屬性

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

+0

根據其位您有麻煩,[這也可能是使用的(http://stackoverflow.com/questions/15003095/getting -value-of-selected-item-in-list-box-as-string) – musefan 2014-10-27 10:56:07

回答

0

的問題表明,OP使用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"; 
0

呦可以使用標籤名稱下ControlBox1_SelectedIndexChanged事件,並獲得選擇索引標籤名稱的價值。

+0

-1這不僅沒有詳細說明如何獲得標籤的名稱,但它甚至沒有試圖解決要求獲得對控件的引用(使用匹配的名稱),然後更改該控件的屬性 – musefan 2014-10-27 11:12:32

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

這裏沒有檢查正確的類型或您所選擇的item..but你的想法:把東西比裸物體或ListBox中的單純字符串更有用!

你可以代替遍歷所有的控制和比較的名字,但是這是效率較低,其實並不安全,因爲該Name屬性不保證是唯一..