您可以創建一個簡單的「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
屬性不保證是唯一..
來源
2014-10-27 11:19:10
TaW
根據其位您有麻煩,[這也可能是使用的(http://stackoverflow.com/questions/15003095/getting -value-of-selected-item-in-list-box-as-string) – musefan 2014-10-27 10:56:07