简体   繁体   中英

Show selected text file from one listbox in another

This is my code:

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

but throws exception about:

Cannot convert type 'System.Web.UI.WebControls.ListItem' to 'System.IO.FileInfo'

When populating the listbox, use the filename instead instead the FileInfo Then when in Button1_Click, use ListBox1.SelectedValue to get the selected file name

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

        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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