HI
我正在尝试将文本框放入listBox中进行搜索。 我有一个TextBox:SearchText,代码如下:
private void SearchText_TextChanged(object sender, EventArgs e)
{
int i = listBox3.FindString(SearchText.Text);
listBox3.SelectedIndex = i;
}
和一个ListBox在加载我有这个代码
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行中收到错误(“对象引用未设置为对象的实例。”)。 您是否知道在listBox中找到另一种方法作为我的案例? 谢谢你的分享。 不错的问候
答案 0 :(得分:2)
听起来好像找不到该项,所以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));
}
}
}
}