0

我正在为我的第一年考试做准备,我知道的一个问题是“使用文本框和按钮创建一个用户控件,并在表单上创建一个列表框”好的。现在必须发生的是 listBox 列出目录中的文件。并且用户控件中的文本框读取该文件(.txt)的内容并允许用户编辑文本框,并且单击时的保存按钮必须覆盖原始文件。现在我使用 StreamReader 读取了整个文本框。但我无法获取用户控件中的按钮以从 ListBox 获取目录路径。

我必须使用 StreamWriter 覆盖它,不能使用 FileDialog。它必须从 ListBox 中获取文件名,然后将其加载到 StreamWriter dir 路径中,该路径需要位于 UserControl 中的 btnSave 中。

userControl1.Text我尝试使用我创建的属性对 userControl 属性进行反之亦然。然后尝试像表单中的 userControl 一样调用它,Form1.ItemsName但没有用,所以我把它刮掉了。现在我有完整的编码器块。

我难住了。我已经尝试了所有方法来获取 userControl 中的 btnSave 以便能够从表单中获取数据listBox.SelectedItem.Text

表单组成:listBox和UserControl

userControl 包括:textBox 和 Button(btnSave)。

表格1代码:

    private void Form1_Load(object sender, EventArgs e)
    {
        // Reads the content from the file, 
        //listing other files in dir.

        StreamReader sr = new StreamReader(@"C:\C# Resources\Numbers.txt");
        string line = sr.ReadLine();

        try
        {
            // Adds content from Numbers.txt into the ListBox
            while (line != null)
            {
                this.listBox1.Items.Add(line);

                line = sr.ReadLine();
            }
            sr.Close();
        }
        catch (Exception Exc)
        {
            MessageBox.Show(Exc.Message.ToString());
        }
        finally
        {
            sr.Close();
        }
    }

    private void listBox1_Click(object sender, EventArgs e)
    {
        // Reads the name of the file in the list box, looking for the file in the dir.
        StreamReader file = new StreamReader(@"C:\C# Resources\" + listBox1.SelectedItem.ToString() + ".txt");
        string all = file.ReadToEnd();

        //Loads the ListBox_click file's content into the userControl textBox
        userControl11.Text = all.ToString();
    }
}

用户控制代码:

    // Creates method so the it can be loaded into form
    public string Text
    {
        set
        {
            textBox2.Text = value;
        }
        get
        {
            return textBox2.Text;
        }
    }

    //Has to overwrite/Save the content changed by the user in TextBox to the same 
    //directory/file it came from.

    private void btnSave_Click(object sender, EventArgs e)
    {
        StreamWriter sw = new StreamWriter(@"C:\C# Resources\" + /*Method to get the file path from the Form1 ListBox*/ + ".txt");
    }
}
4

2 回答 2

2

由于这是一项任务/项目工作,我只会为您指明正确的方向。

  • 向用户控件添加属性,例如public string FileToWrite {get; set;}
  • 然后访问FileToWritewhich 将是写入的路径。


private void btnSave_Click(object sender, EventArgs e)
{
    StreamWriter sw = new StreamWriter(FileToWrite);
}
于 2013-04-10T17:01:46.657 回答
0

您不能(或不应该)使用用户控件调用表单代码。您需要另一种机制,要么表单应始终让控件知道所选项目,要么用户控件应请求信息。

这两个都可以使用事件来完成

于 2013-04-15T17:08:26.227 回答