Reputation: 11
I'm selecting items from one ListBox
and adding them to second ListBox
on button click. The problem is that when I want to deselect the selected items from listbox2, it gives "Object reference not set to an instance of an object" error. Below is the code I added behind SELECT button. I have used the same code for deselecting with listbox1 replaced by listbox2 and vice versa.
NOTE: Items in listbbox1 are being retrieved from database and items that got selected in listbox2 will be saved to database
List<int> rowIndexes = new List<int>();
foreach (int index in listBox1.SelectedIndices)
{
DataRowView view = listBox1.Items[index] as DataRowView;
string id = view["Course_Id"].ToString();
string name = view["Course_Name"].ToString();
listBox2.Items.Add(name);
rowIndexes.Add(index);
}
try
{
for (int i = rowIndexes.Count; i > 0; i--)
{
dt.Rows.RemoveAt(rowIndexes[i - 1]);
dt.AcceptChanges();
}
}
catch (Exception er)
{
MessageBox.Show(er.Message);
}
Upvotes: 1
Views: 458
Reputation: 3360
This is a guess, at best, because the claim that it fails on the first line makes no sense.
My psychic powers tell me that this actually failing at
string id = view["Course_Id"].ToString();
because view is null. The problem is that
DataRowView view = listBox1.Items[index] as DataRowView;
is trying to cast the items from a ListBox to DataRowView. This will always return null, unless for some (odd) reason you populated your ListBox.Items with a collection of DataRowView.
EDIT
You may be filling listBox1 with DataRowView, but you're filling listBox2 with System.String:
string name = view["Course_Name"].ToString();
listBox2.Items.Add(name);
Try changing that to
//string id = view["Course_Id"].ToString();
//string name = view["Course_Name"].ToString();
listBox2.Items.Add(view);
Upvotes: 6
Reputation: 9209
Assuming that this is copied exactly from your code. This line is incorrect:
List<int> row Indexes = new List<int>();
its should be:
List<int> rowIndexes = new List<int>();
Also what is dt
?
edit
If it really is failing on:
List<int> rowIndexes = new List<int>();
The perhaps you're not:
using System.Collections.Generic;
Or have a reference to System
in your project references.
Upvotes: 0