Reputation: 77
The user can click an item in a ListBox as follows:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox2.Clear();
listBox2.Items.Clear();
string[] p =
Directory.GetFiles(
textBoxDir.Text,
listBox1.SelectedItem.ToString(),
SearchOption.AllDirectories);
foreach (string open in p)
......
}
All is fine. However if the user clicks on an empty space in the ListBox, it displays the following error:
System.NullReferenceException
This is because of this line of code:
string[] p =
Directory.GetFiles(
textBoxDir.Text,
listBox1.SelectedItem.ToString(),
SearchOption.AllDirectories);
Does anyone have a clever work around? Or suggest an aalternative to my code?
Upvotes: 4
Views: 24625
Reputation: 11
I had a similar problem. This is the shortest way i fixed it.
private void button1_Click(object sender, EventArgs e)
{
radioButton1.Checked = !radioButton1.Checked;
string indicadorPais = "Something";
if (listaPaises.SelectedItem != null)
{
indicadorPais = listaPaises.SelectedItem.ToString();
label1.Text = indicadorPais;
}
As a sidenote. My condition originally was comparing listaPaises.SelectedItem.ToString() != null. This broke because i was casting null to a string. The code im sending works fine.
Upvotes: 0
Reputation: 34349
The workaround is to check for a null value, and exit early.
if (listBox1.SelectedItem == null)
{
return;
}
This avoids the nesting introduced by the other answers, which makes the code less readable.
Upvotes: 13
Reputation: 11
However none of these allow you to go back in and re-select from the list box. Still working on that issue - will update.
while (user == null) {
try {
user = this.lstAdministratorName.SelectedItem.ToString();
} catch {
lstAdministratorName.ClearSelected();
return;
}
}
Upvotes: -1
Reputation: 1275
just check first if listbox1.SelectedItem is empty or not prior to calling this line:
string[] p = Directory.GetFiles(textBoxDir.Text, listBox1.SelectedItem.ToString(), SearchOption.AllDirectories);
Upvotes: 1
Reputation: 48558
How about
if (listBox1.SelectedItem != null)
{
string[] p = Directory.GetFiles(textBoxDir.Text, listBox1.SelectedItem.ToString(), SearchOption.AllDirectories);
}
Full Code
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedItem != null)
{
textBox2.Clear();
listBox2.Items.Clear();
string[] p = Directory.GetFiles(textBoxDir.Text, listBox1.SelectedItem.ToString(), SearchOption.AllDirectories);
foreach (string open in p)
...... }
}
}
Upvotes: 1
Reputation: 32481
You can check SelectedIndex
before that line:
if(listBox2.SelectedIndex < 0)
return;
Upvotes: 4
Reputation: 43619
How about doing a
if(listBox1.SelectedItem != null){
// ... do your work with listBox1.SelectedItem here
}
that should prevent that error from happening.
Upvotes: 1