将列表框选定索引加载文本文件数据时出现问题 [英] Problem loading text file data as Listbox selected index is changed

查看:106
本文介绍了将列表框选定索引加载文本文件数据时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨所有

i表格中有2个列表框。

list_number(显示文本文件名)

list_position(显示所选文件的数据)在list_nomber中)

但是我对所选索引更改事件异常的异常是在下面



System.ArgumentNullException:值不能为null。 />
参数名称:item

在System.Windows.Forms.ListBox.ObjectCollection.AddInternal(Object item)

在System.Windows.Forms.ListBox .ObjectCollection.Add(Object item)

,位于E:\ videoPlayer \ videoDlayer \ Form1.cs中的WindowsFormsApplication1.Form1.list_nomber_SelectedIndexChanged(Object sender,EventArgs e):第395行





第395行是这个

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

listPosition = objReader.ReadLine();





和代码是这个



and code is this

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();
        }

推荐答案

你的问题是你在'while循环测试中做了额外的ReadLine:所以,当你已经读取了循环内部的最后一个文件,最后一个'while循环测试试图吃掉null。你将获得文件中的所有其他行,直到你达到错误状态。



试试这个:
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:
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();
}


这篇关于将列表框选定索引加载文本文件数据时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆