【问题标题】:C# List text files in a listbox and let user open them in a textboxC# 在列表框中列出文本文件并让用户在文本框中打开它们
【发布时间】:2013-05-11 21:01:02
【问题描述】:

我是 C# 的新手,我想要一个包含文件夹中所有文本文件的列表框,如果用户双击列出的文件,该文件将显示在文本框中。

我不想使用 openFileDialog 函数,因为文本文件位于我使用 username:password@server.com/folder 访问的网络服务器上。

有点像文本编辑器,仅限于编辑 1 个文件夹中的文件 :)
如果使用 openFileDialog 可以做到这一点,请告诉我如何操作。

希望你能明白我想做什么。

您好,

【问题讨论】:

  • 这很简单,列出ListBoxListView中文件夹中的所有文本文件并处理MouseDoubleClick以读取内容并将其显示在您的TextBox中,所以有什么问题?

标签: c# .net listbox openfiledialog text-editor


【解决方案1】:

据我了解,您希望遍历特定目录中的文件,然后允许在列表框中双击打开它们后对其进行编辑。

这可以使用var Files = Directory.GetFiles("path", ".txt");来完成

Files 将是文件名的string[]

然后用类似这样的文件填充列表框:

ListBox lbx = new ListBox();
lbx.Size = new System.Drawing.Size(X,Y); //Set to desired Size.
lbx.Location = new System.Drawing.Point(X,Y); //Set to desired Location.
this.Controls.Add(listBox1); //Add to the window control list.
lbx.DoubleClick += OpenFileandBeginEditingDelegate;
lbx.BeginUpdate();
for(int i = 0; i < numfiles; i++)
  lbx.Items.Add(Files[i]);
lbx.EndUpdate();

现在您的事件委托应该如下所示:

OpenFileandBeginEditingDelegate(object sender, EventArgs e)
{
    string file = lbx.SelectedItem.ToString();
    FileStream fs = new FileStream(Path + file, FileMode.Open);

    //Now add this to the textbox 
    byte[] b = new byte[1024];
    UTF8Encoding temp = new UTF8Encoding(true);
    while (fs.Read(b,0,b.Length) > 0)
    {
        tbx.Text += temp.GetString(b);//tbx being the textbox you want to use as the editor.
    }
}

现在要通过 VS 窗口编辑器添加事件处理程序,请单击相关控件并转到该控件的属性窗格。然后,您需要切换到事件窗格并滚动直到找到 DoubleClick 事件,如果您使用该设计器应该自动插入有效的委托签名并允许您编写事件的逻辑。

【讨论】:

  • 谢谢,我花了一段时间才让它与我的代码一起工作,但现在它可以工作了 ;)
猜你喜欢
  • 1970-01-01
  • 2013-11-05
  • 1970-01-01
  • 1970-01-01
  • 2014-06-06
  • 1970-01-01
  • 2021-12-30
  • 1970-01-01
  • 2013-02-04
相关资源
最近更新 更多