C# 如何将listBox1.SelectedIndex设置为0,使其仅对部分代码有效?
代码如下:C# 如何将listBox1.SelectedIndex设置为0,使其仅对部分代码有效?,c#,winforms,C#,Winforms,代码如下: 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; // Thi
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());
}
}
因为我想在单击按钮并显示/打开列表框后能够播放第一个项目
在第二个地方,我将项目添加到Lightings列表中,我希望只有在我首先单击任何项目时,它才会添加项目。
既然我这样做了:
this.listBox1.SelectedIndex = 0;
一旦我显示/打开列表框,它将自动向Lightings添加项目
我需要将其添加到列表中,仅当我首先单击一个项目时。另一方面,我也希望被选择索引=0,因为我希望它被选择,以便我可以播放它
那么,我如何区分用于播放的SelectedIndex=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\u-SelectedIndexChanged
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());
}
}
}