gpt4 book ai didi

c# - 在列表框中搜索

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

你好

我正在尝试将一个文本框放入列表框中进行搜索。我有一个 TextBox: SearchText,代码如下:

 private void SearchText_TextChanged(object sender, EventArgs e)
{
int i = listBox3.FindString(SearchText.Text);
listBox3.SelectedIndex = i;
}

和一个 ListBox On the Load 我有这段代码

List<string> str = GetListOfFiles(@"D:\\Music\\massive attack - collected");        
listBox3.DataSource = str;
listBox3.DisplayMember = "str";

在 selectedIndexChanged 上:

private void listBox3_SelectedIndexChanged(object sender, EventArgs e)
{
player1.URL = listBox3.SelectedItem.ToString(); // HERE APPEAR THE ERROR "Object reference not set to an instance of an object."

// provaTxt.Text = listBox3.SelectedValue.ToString();
}

当我在 SeachText 中记下要查找的歌曲时,我在 ListBox 的 selectedIndexChanged 行中收到错误消息(“对象引用未设置为对象的实例。”)。你知道另一种在列表框中查找的方法吗?感谢您的分享。亲切的问候

最佳答案

听起来好像没有找到该项目,所以 SelectedItem 为空;尝试使用:

player1.URL = Convert.ToString(listBox3.SelectedItem);

我相信这可以处理 null 情况(或者,先测试 null)。

我也很想查看基础列表:

List<string> items = (List<string>)listbox3.DataSource;
listbox3.SelectedIndex = items.FindIndex(s => s.StartsWith(searchFor));

例如:

using System;
using System.Collections.Generic;
using System.Windows.Forms;
class MyForm : Form
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new MyForm());
}

ListBox listbox;
TextBox textbox;
CheckBox multi;
public MyForm()
{
textbox = new TextBox { Dock = DockStyle.Top };
List<string> strings = new List<string> { "abc", "abd", "abed", "ab" };
listbox = new ListBox { Dock = DockStyle.Fill, DataSource = strings };
textbox.KeyDown += textbox_KeyDown;
Controls.Add(listbox);
Controls.Add(textbox);
listbox.SelectedIndexChanged += listbox_SelectedIndexChanged;
listbox.SelectionMode = SelectionMode.MultiExtended;
multi = new CheckBox { Text = "select multiple", Dock = DockStyle.Bottom };
Controls.Add(multi);
}

void listbox_SelectedIndexChanged(object sender, EventArgs e)
{
Text = Convert.ToString(listbox.SelectedItem);
}

void textbox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Return)
{
string searchFor = textbox.Text;
List<string> strings = (List<string>)listbox.DataSource;
if (multi.Checked)
{
for (int i = 0; i < strings.Count; i++)
{
listbox.SetSelected(i, strings[i].Contains(searchFor));
}
}
else
{
listbox.ClearSelected();
listbox.SelectedIndex = strings.FindIndex(
s => s.Contains(searchFor));
}
}
}
}

关于c# - 在列表框中搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/695269/

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