繁体   English   中英

在另一个列表框中显示所选文本文件

[英]Show selected text file from one listbox in another

这是我的代码:

protected void Button1_Click(object sender, EventArgs e)
{


    FileInfo SelectedFileInfo = (FileInfo)ListBox1.SelectedItem;

    StreamReader FileRead = new StreamReader(SelectedFileInfo.FullName);
    string CurrentLine = "";
    //int LineCount = 0;
    while(FileRead.Peek() != -1)
    {
        CurrentLine = FileRead.ReadLine();
        //LineCount++;
        //if(LineCount % 5 == 2)
        {
            ListBox2.Items.Add(CurrentLine);
        }
    }
    FileRead.Close(); 
}

但引发以下异常:

无法将类型“ System.Web.UI.WebControls.ListItem”转换为“ System.IO.FileInfo”

填充列表框时,使用文件名代替FileInfo,然后在Button1_Click中使用ListBox1.SelectedValue获取选定的文件名

    protected void Button1_Click(object sender, EventArgs e)
    {
        ListBox2.Items.Clear();
        if (ListBox1.SelectedIndex > -1)
        {
            string filename = ListBox1.SelectedValue;

            StreamReader FileRead = new StreamReader(filename);
            string CurrentLine = "";
            //int LineCount = 0;
            while (FileRead.Peek() != -1)
            {
                CurrentLine = FileRead.ReadLine();
                ListBox2.Items.Add(CurrentLine);
            }
            FileRead.Close();
        }
        else
        {
            ListBox2.Items.Add("Please select a file first");
        }
    }

    protected void Btn_Load_Click(object sender, EventArgs e)
    {
        DirectoryInfo dinfo = new DirectoryInfo(@"C:\errorlog");
        FileInfo[] Files = dinfo.GetFiles("*.txt");
        foreach (FileInfo file in Files)
        {
            ListBox1.Items.Add(file.FullName);

        }
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM