Click here to Skip to main content
15,886,664 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I m selecting items from one listbox and adding them to second listbox on button click.the problem is tht 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 deselting with listbox1 replaced by listbox2 and vice versa.

NOTE: items in listbbox1 are being retrieved from database. and itmes tht got selected in listbox2 will be saved to databse

C#
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);
}

Any help would be appreciated.
Posted
Updated 27-Oct-11 8:19am
v5
Comments
phil.o 27-Oct-11 5:10am    
This is only a small code snippet without any context information.
Please include the method in which it is placed, as well as the code from where you are calling this method.

Do you know the magic tool called "Debugger" :) use it and will be amaze by the results.. use the Debugger in your button click code and see where the value that you are assigning is null. that's why it is throwing that error.
 
Share this answer
 
XML
List<int> row Indexes = new List<int>();

This line wont even compile.
So make sure you have copy pasted the right code here. This will help someone assist you better.
 
Share this answer
 
Comments
ariez88 27-Oct-11 3:53am    
its rowIndexes i dont know why its giving space between this.and it does compile easily but gives error at runtime
C#
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);

}


You have an issue there.Your assignment on rowindexes variable should return null.So when you try to reach it you 've got an exception.Check your index value with a MessageBox.Show(index); Method first.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900