簡體   English   中英

如何將listBox1.SelectedIndex設置為0,僅對部分代碼有效?

[英]How can i set the listBox1.SelectedIndex to 0 only to be effected on part of the code?

這是代碼:

private void Lightnings_Mode_Load(object sender, EventArgs e)
        {
            this.Size = new Size(416, 506);
            this.Location = new Point(23, 258);
            listBoxIndexs();
            this.listBox1.SelectedIndex = 0; // This will make the listBox when showing it first time first item to be already selected !!!!!!
        }

        private void listBoxIndexs()
        {
            for (int i = 0; i < Form1.lightningsRegions.Count; i++)
            {

                    listBox1.Items.Add(Form1.lightningsRegions[i]);

            }
        }

        private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            item = listBox1.SelectedItem.ToString();
            this.f1.PlayLightnings();
            f1.pdftoolsmenu();
            if (item != null && !pdf1.Lightnings.Contains(item.ToString()))
            {
                pdf1.Lightnings.Add(item.ToString());             
            }
        }

我在Form1的兩個地方使用變量項。 一次提取字符串並在其中播放數字,一次將項目添加到“列表閃電”。

第一次玩數字游戲時,我希望它是:

this.listBox1.SelectedIndex = 0;

因為我希望一旦單擊按鈕並顯示/打開listBox,已經可以播放第一個項目。

在第二個地方,我將項目添加到閃電列表中,我希望它僅在我首先單擊任何項​​目時才添加該項目。 自從我做了:

this.listBox1.SelectedIndex = 0;

一旦我顯示/打開列表框,它將自動將項目添加到閃電中。只有在我首先單擊另一項時,我才需要將其添加到列表中,我也希望被選擇索引= 0,因為我希望選擇它,因此我可以玩。

那么,如何在SelectedIndex = 0進行播放以及將該項目添加到列表之間進行區分呢?

如果我理解正確,則只需添加一個標志即可。

bool allowItemAdding;

private void Lightnings_Mode_Load(object sender, EventArgs e)
{
    allowItemAdding = false; //setting false here because *sometimes* Load event is called multiple times.

    this.Size = new Size(416, 506);
    this.Location = new Point(23, 258);
    listBoxIndexs();
    this.listBox1.SelectedIndex = 0;  
    allowItemAdding = true; //set flag to true after selecting the index initially
}

private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{          
     item = listBox1.SelectedItem.ToString();
     this.f1.PlayLightnings();
     f1.pdftoolsmenu();
     if (allowItemAdding)
     {
         if (item != null && !pdf1.Lightnings.Contains(item.ToString()))
         {
             pdf1.Lightnings.Add(item.ToString());             
         }
     }
}

該標志將一直保持為true,直到您將其顯式更改為false,這樣您就可以控制何時應添加項目。

使用_SelectionChangeCommitted而不是listBox1_SelectedIndexChanged

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM