Click here to Skip to main content
15,898,538 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
hi all
i have 2 list boxes in form.
list_number (displaying text file name)
list_position (displaying data of file selected in list_nomber)
but i m getting exception on selected index changed event exception is below

System.ArgumentNullException: Value cannot be null.
Parameter name: item
at System.Windows.Forms.ListBox.ObjectCollection.AddInternal(Object item)
at System.Windows.Forms.ListBox.ObjectCollection.Add(Object item)
at WindowsFormsApplication1.Form1.list_nomber_SelectedIndexChanged(Object sender, EventArgs e) in E:\videoPlayer\videoPlayer\Form1.cs:line 395


line 395 is this
C#
listPosition = objReader.ReadLine();


and code is this
C#
private void list_nomber_SelectedIndexChanged(object sender, EventArgs e)
        {
            string listPosition="abc";
            list_position.Items.Clear();
            string file = "e:\\" + list_nomber.Text + ".txt";
            System.IO.StreamReader objReader;
            objReader = new System.IO.StreamReader(file);
            while (objReader.ReadLine() != null)
            {

                listPosition = objReader.ReadLine();
                list_position.Items.Add(listPosition);
            }
            objReader.Close();
        }
Posted
Comments
Sergey Alexandrovich Kryukov 7-Dec-13 1:08am    
In what line?
—SA

1 solution

Your problem is that you are doing an extra ReadLine in the 'while loop test: so, when you've read the last of the file inside the loop, the last 'while loop test tries to "eat" null. You are going to get every other line in the file until you reach the error condition.

Try this:
C#
using System.IO;

//somewhere in a method
string file = @"e:\" + list_nomber.Text + ".txt";

string currentLine;

list_position.Items.Clear();

using (StreamReader objReader = new StreamReader(file))
{
    while ((currentLine = objReader.ReadLine()) != null)
    {
        list_position.Items.Add(currentLine);
    }

    objReader.Close();
}
 
Share this answer
 
Comments
mehdilahori 7-Dec-13 2:14am    
thanks brother
it worked

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