C#列表框设置选定项

6
我有一个 C# 的列表框,其中包含一些值。
Profile 1
Profile 2
Profile 3

当表单加载时,我希望选择个人资料 2。我该怎么做?


2
你是指Winforms列表框吗?C#本身可以与许多不同的UI框架一起使用... - Adrian Grigore
3个回答

23

Form.Shown 事件中设置 ListBox.SelectedIndex 属性。
例如:

public Form1()
{
    InitializeComponent();

    // Adding the event handler in the constructor
    this.Shown += new EventHandler(Form1_Shown);
}    

private void Form1_Shown(object sender, EventArgs e)
{
    myListBox.SelectedIndex = 1;
}

6
将以下代码放置在 Form.Loaded 事件中:
``` // 这里是代码示例 ```
listBox1.SelectedItem = "Profile 2";

0
listBox1.Items.Add("Profile 1");

listBox1.Items.Add("Profile 2");

listBox1.Items.Add("Profile 3");

listBox1.SelectedIndex = 1;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接