在用户控件中加入表单方法
本文关键字:表单 方法 用户 控件 | 更新日期: 2023-09-27 18:08:25
我正在为我的第一年测试做准备,我知道的一个问题是"创建一个带有文本框和按钮的用户控件,并在表单上创建一个列表框"好吧。现在要做的是listBox从目录中列出文件。用户控制中的文本框读取该文件(.txt)的内容,允许用户编辑文本框,并且单击保存按钮时必须覆盖原始文件。现在我用StreamReader读取了整个文本框。但是我不能让用户控件中的按钮从列表框中获取目录路径。
我必须使用StreamWriter覆盖它,不能使用FileDialog。它必须从ListBox中获取文件名,然后将其加载到StreamWriter目录路径中,该路径需要位于UserControl中的btnSave中。
我尝试用userControl userControl1.Text
属性与我所做的属性做反之亦然。然后试图调用它像userControl从表单Form1.ItemsName
,但没有工作,所以我刮了。现在我有完整的编码块。
我被难住了。我已经尝试了一切,以获得btnSave在userControl中能够从表单listBox.SelectedItem.Text
表单包含:listBox和UserControl
userControl包含:textBox和Button(btnSave)。
Form1代码:
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");
}
}
既然这是一项任务/项目工作,我就给你指出正确的方向。
- 为用户控件添加属性,如
public string FileToWrite {get; set;}
- 然后访问
FileToWrite
,这将是写入路径。
private void btnSave_Click(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter(FileToWrite);
}
您不能(或不应该)从用户控件调用表单代码。您需要另一种机制,或者表单应该让控件始终知道所选项目,或者用户控件应该请求该信息。
这两个都可以使用events