我有一個窗體中包含一個列表框的用戶控件。我想在列表框自動選擇第一項(假設有至少一個項目),但我不能得到下面的代碼來工作:如何使ListBox中的第一項自動選中?
private void Lightnings_Mode_Load(object sender, EventArgs e)
{
this.Size = new Size(416, 506);
this.Location = new Point(23, 258);
listBoxIndexs();
listBoxControl1.MyListBox.SelectedIndex = 0;
if (this.listBoxControl1.MyListBox.Items.Count > 0)
this.listBoxControl1.MyListBox.SelectedIndex = 0;
listBoxControl1.MyListBox.SelectedIndexChanged += new EventHandler(listBox1_SelectedIndexChanged);
this.listBoxControl1.ItemRemoved += new EventHandler<ItemEventArgs>(listBoxControl1_ItemRemoved);
}
這條線:listBoxControl1.MyListBox.SelectedIndex = 0;會將第一個ListBox項目標記爲藍色,就像它被選中一樣。但它不是真的選擇這個項目!
於是,我就補充一點:
if (this.listBoxControl1.MyListBox.Items.Count > 0)
this.listBoxControl1.MyListBox.SelectedIndex = 0;
但它不工作要麼。
這是SelectedIndex的事件:
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
item = listBoxControl1.MyListBox.SelectedItem.ToString();
this.f1.PlayLightnings();
f1.pdftoolsmenu();
int indx = listBoxControl1.MyListBox.SelectedIndex;
if (listBoxControl1.Indices.Contains(indx))
{
if (item != null && !pdf1.Lightnings.Contains(item.ToString()))
{
pdf1.Lightnings.Add(item.ToString());
}
}
}
事件的名稱是不正確的我必須要改變它,因爲它的列表框在用戶控件,但它是正確的。
當我在SelectedIndex事件中放置一個斷點並點擊一個項目時,它會停在斷點處。但是我希望它在使用UserControl和ListBox顯示/打開新窗體時自動轉到selectedIndex事件。
因此,如果我在SelectedIndex事件中放置斷點,當我單擊Form1中的按鈕以顯示/打開新窗體時,它將自動停止在斷點上,就像我單擊第一個項目一樣。
這是在Form1中,展示了新形式的代碼:
if (toolStripComboBox2.SelectedIndex == -1 && toolStripComboBox1.SelectedIndex == -1)
{
}
else
{
Lightnings_Extractor.Lightnings_Mode lightningsmode1 = new Lightnings_Extractor.Lightnings_Mode(this);
lightningsmode1.Show();
}
一切工作除了自動選擇第一項。
ScruffyDuck不,它沒有進入SelectedIndex事件。 –
Duck answer和Josh W的組合工作。在行之間交換並使用SetSelected:listBoxControl1.MyListBox.SelectedIndexChanged + = new EventHandler(listBox1_SelectedIndexChanged);如果(this.listBoxControl1.MyListBox.Items.Count> 0) this.listBoxControl1.MyListBox.SetSelected(0,true); –
好吧 - 那很好 – ScruffyDuck