gpt4 book ai didi

c# - 如何以编程方式选择 ListView 项目?

转载 作者:太空宇宙 更新时间:2023-11-03 10:53:24 25 4
gpt4 key购买 nike

我从今天早上开始就一直在寻找解决方案,即使在阅读了大量关于这个主题的其他帖子之后,它也不适合我。事不宜迟,让我们检查一下这个代码示例:

// Create Dictionary, Keys = Ids, Values = Names

Dictionary<int, string> ff_names = new Dictionary<int, string>();
ff_names.Add(0, "Cloud");
ff_names.Add(1, "Barret");
ff_names.Add(2, "Tifa");
ff_names.Add(3, "Aerith");
ff_names.Add(4, "Red XIII");

// Populating ListView

foreach( KeyValuePair<int, string> dict in ff_names )
{
ListViewItem lvi = new ListViewItem(dict.Key.ToString());
lvi.SubItems.Add(dict.Value);

listView1.Items.Add(lvi);
}

// Test Item Selection

listView1.Focus();
listView1.Select();
listView1.Items[0].Focused = true;
listView1.Items[0].Selected = true;

string s = listView1.SelectedItems.Count.ToString();

label1.text = s; // sadly, it's equal to 0;
textBox1.Text = listView1.SelectedItems[0].SubItems[0].Text; // program will crash

从技术上讲,我想选择 ListView 的一个项目并将其元素之一显示在文本框中。当我手动选择一个项目时它可以工作,但是当我尝试像上面所示那样以编程方式选择时它不想选择任何东西,SelectedItems 计数等于零......

感谢您的帮助,希望有人能找到我所缺少的解决方案!

最佳答案

给你。您必须为 listView1_SelectedIndexChanged 创建事件处理程序。

    public Form1() {
InitializeComponent();
listView1.View = View.Details;
listView1.Columns.Add("Key");
listView1.Columns.Add("Value");
LoadListView();
}

private void LoadListView() {
// Create Dictionary, Keys = Ids, Values = Names

Dictionary<int, string> ff_names = new Dictionary<int, string>();
ff_names.Add(0, "Cloud");
ff_names.Add(1, "Barret");
ff_names.Add(2, "Tifa");
ff_names.Add(3, "Aerith");
ff_names.Add(4, "Red XIII");

// Populating ListView

foreach (KeyValuePair<int, string> dict in ff_names) {
ListViewItem lvi = new ListViewItem(new string[] { dict.Key.ToString(), dict.Value });
listView1.Items.Add(lvi);
}

// Test Item Selection

listView1.Focus();
listView1.Select();
listView1.Items[0].Focused = true;
listView1.Items[0].Selected = true;

}

private void listView1_SelectedIndexChanged(object sender, EventArgs e) {
if (listView1.SelectedItems.Count > 0) {
label1.Text = (string)listView1.SelectedItems[0].Text; // sadly, it's equal to 0;
textBox1.Text = (string)listView1.SelectedItems[0].SubItems[1].Text;
}
}

关于c# - 如何以编程方式选择 ListView 项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20447596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com