C#中要使ListBox使用AddRange()时,能够触发SelectedValueChanged事件

时间:2022-09-01 05:04:50

1. 要触发 SelectedValueChanged事件,必须要当ListBox所选中的值发生改变

基本思路是:

当AddRange()后,就马上指定ListBox的SelectedIndex,这样就能够触发SelectedValueChanged事件了

相当于人工在代码中选中了一个选项

2. 例子代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms; namespace ListBoxAddRangeTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void listBox1_SelectedValueChanged(object sender, EventArgs e)
{
if (listBox1.SelectedItems.Count > 0)
{
System.Windows.Forms.MessageBox.Show(listBox1.SelectedItems[0].ToString());
}
} private void button1_Click(object sender, EventArgs e)
{ string[] testArray = new string[] { "me", "you" }; listBox1.Items.AddRange(testArray);
listBox1.SelectedIndex = 0;//就是这里,人工选中
}
}
}