C# - 在列表框中保存值
我有以下代码:
SaveFileDialog saveGC1File = new SaveFileDialog();
private void GCSavePlacementOneButton_Click(object sender, EventArgs e)
{
// Initialize the SaveFileDialog to specify the .txt extension for the file.
saveGC1File.DefaultExt = "*.txt";
saveGC1File.Filter = ".txt Files|*.txt|All Files (*.*)|*.*";
saveGC1File.RestoreDirectory = true;
try
{
string placementOneSave = placementOneListBox.Items.ToString();
// Save the contents of the formattedTextRichTextBox into the file.
if (saveGC1File.ShowDialog() == DialogResult.OK && saveGC1File.FileName.Length > 0)
placementOneSave.SaveFile(saveGC1File.FileName, RichTextBoxStreamType.PlainText);
// Throws a FileNotFoundException otherwise.
else
throw new FileNotFoundException();
}
// Catches an exception if the file was not saved.
catch (Exception)
{
MessageBox.Show("There was not a specified file path.", "Path Not Found Error",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
但是,使用 Visual Studio 2010,“if”循环中的行指出:
"placementOneSave.SaveFile(saveGC1File.FileName, RichTextBoxStreamType.PlainText);"
“SaveFile”下有一条红色行。我已使用此代码来保存文件之前,我不确定为什么它不适用于列表框。
问题
- 如何以与 RichTextBox 类似的方式保存 ListBox?
- 有什么方法可以编辑此代码以使用户选择列表框的保存位置吗?
I have the following code:
SaveFileDialog saveGC1File = new SaveFileDialog();
private void GCSavePlacementOneButton_Click(object sender, EventArgs e)
{
// Initialize the SaveFileDialog to specify the .txt extension for the file.
saveGC1File.DefaultExt = "*.txt";
saveGC1File.Filter = ".txt Files|*.txt|All Files (*.*)|*.*";
saveGC1File.RestoreDirectory = true;
try
{
string placementOneSave = placementOneListBox.Items.ToString();
// Save the contents of the formattedTextRichTextBox into the file.
if (saveGC1File.ShowDialog() == DialogResult.OK && saveGC1File.FileName.Length > 0)
placementOneSave.SaveFile(saveGC1File.FileName, RichTextBoxStreamType.PlainText);
// Throws a FileNotFoundException otherwise.
else
throw new FileNotFoundException();
}
// Catches an exception if the file was not saved.
catch (Exception)
{
MessageBox.Show("There was not a specified file path.", "Path Not Found Error",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
However, using Visual Studio 2010, the line in the "if" loop that states:
"placementOneSave.SaveFile(saveGC1File.FileName, RichTextBoxStreamType.PlainText);"
Has a red line under the "SaveFile".. I have used this code to save a file before and am unsure why it will not work for a ListBox.
QUESTIONS
- How can I save a ListBox in a similar way to a RichTextBox?
- Any way to edit this code to make it have the user choose where the ListBox will be saved?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ListBox 不提供将其所有项目保存到文件的方法。显示如何完成此操作的代码片段可在此处找到:
将文本从列表框保存到文本文件的 C# 代码 -- 已解决--
ListBox does not provide a method to save all its items to a file. The code snippet showing how this can be done is available here:
C# code to save text from listbox to a text file -- SOLVED--