0

新手在这里很抱歉听起来很愚蠢

我有一个组合框,用户选择一个值并单击提交按钮我不知道如何获取所选值并将其写入文本文件。有没有人可以帮忙?

在此先感谢... Jimbob

4

3 回答 3

1

尝试:

    string PathToFile = "c:\\File.txt";
    System.IO.File.WriteAllText(PathToFile,Combobox.SelectValue.ToString());
于 2012-11-22T13:14:22.153 回答
0

如果没有看到您的代码,并且我假设您没有使用 MVVM,我认为您需要做一些事情来实现这一点:

  1. 在 XAML 中为您的组合框命名,例如:Name="myComboBox"
  2. 同样在 XAML 中,将 Click 事件添加到您的按钮
  3. 在按钮的单击处理程序中,编写如下内容: System.IO.File.WriteAllText("selected.txt", myComboBox.SelectedValue);
于 2012-11-22T13:21:04.453 回答
0

您可以检测返回对象的ComboBoxusing的选定值。comboBox1.SelectedValue如果需要,您可以使用将其转换为字符串ToString()

例子

string _string = comboBox1.SelectedValue.ToString();

这将初始化一个名为 name 的新变量_string作为 中的选定ComboBoxString。考虑到它是 a ,您也可以使用comboBox1.SelectedIndexwhich 返回 anint来获取项目的选定索引。comboBox1ComboBox

此外,如果您想将值写入特定文件,您可以使用StreamWriterorFile.WriteAllLines但我相信 aStreamWriter会更易于管理

例子

string DestinationFile = @"D:\Resources\International\MyNewFile.txt"; //Initializes a new string of name DestinationFile as D:\Resources\International\MyNewFile.txt
StreamWriter _StreamWriter = new StreamWriter(DestinationFile); //Initializes a new StreamWriter class of name _StreamWriter
_StreamWriter.WriteLine(comboBox1.SelectedValue.ToString()); //Attempts to write the selected combo box value in string as a new line
_StreamWriter.Close(); //Closes the file and saves settings

注意:这将在 D:\Resources\International\MyNewFile.txt 中创建一个新文件。然后,用所选项目的新行覆盖ComboBox文件。如果您想将文本附加到特定文件,您可能需要在,true之后添加_StreamWriter = new StreamWriter(DestinationFile

例子

string DestinationFile = @"D:\Resources\International\MyNewFile.txt"; //Initializes a new string of name DestinationFile as D:\Resources\International\MyNewFile.txt
StreamWriter _StreamWriter = new StreamWriter(DestinationFile, true); //Initializes a new StreamWriter class of name _StreamWriter
_StreamWriter.WriteLine(comboBox1.SelectedValue.ToString()); //Attempts to write the selected combo box value in string as a new line
_StreamWriter.Close(); //Closes the file and saves settings

谢谢,
我希望你觉得这有帮助:)

于 2012-11-22T13:26:56.600 回答