【问题标题】:Get user input from web form to save to text file从 Web 表单获取用户输入以保存到文本文件
【发布时间】:2011-07-18 09:49:38
【问题描述】:

我有一个由复选框、单选按钮和 dateTimePicker 组成的网络表单。

所有选项都适用于表单,但是我需要以某种方式获取所有用户输入,例如当有人选中“checkBox1”以保存到文本文件时。我不确定如何在 C# 中执行此操作。

到目前为止,我有 -

string path = "path";

        try
        {

            if (File.Exists(path))
            {

                File.Delete(path);
            }

            using (FileStream fs = File.Create(path))
            {
                Byte[] info = new UTF8Encoding(true).GetBytes("");
                // Add some information to the file.
                fs.Write(info, 0, info.Length);

我可以让文件写出每个特定的复选框名称,但我希望能够只写出已选中的复选框。

我认为它会像 - if checkbox1.checkedstate = true

非常感谢任何帮助。

【问题讨论】:

  • 你能澄清你的问题吗?

标签: c# winforms checkbox


【解决方案1】:

如果要在选中复选框时立即写入文件,请将AutoPostBack 设置为true 并添加oncheckedchanged 事件

已编辑

示例(带有两个复选框):

<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack=true OnCheckedChanged="CheckBox_CheckedChanged"/>
<asp:CheckBox ID="CheckBox2" runat="server" AutoPostBack=true OnCheckedChanged="CheckBox_CheckedChanged"/>

在代码隐藏中

    protected void CheckBox_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox chb = (CheckBox)sender;
        if (chb.Checked)
        {
            //checkbox is checked
            //chb.ID gets the ID of the sender (i.e. checkbox1, checkbox2, etc)
            //write to file
        }
    }

【讨论】:

  • 这很好,但有没有办法做到这一点,而不必为所有复选框、单选按钮等设置一个受保护的空白?也许在程序开始时读取文件并在最后关闭它并写出所有选择?
  • @Jambo 至于第一个问题:是的,有办法。无需为所有复选框硬编码oncheckedchanged 事件处理程序。 (我会更新答案)。对于第二个问题:您能详细说明一下吗?
  • 对不起,我看到的有点模糊,例如,一旦 usr 选中了一个特定的复选框,我需要该复选框名称“checkBox1”来写入文件。 Butit 必须对所有文本框都是通用的,而不仅仅是第一个文本框。感谢您的意见。
【解决方案2】:

你要检查

if(checkbox1.Checked)
   write code

【讨论】:

    【解决方案3】:

    虽然你的问题不是很清楚,但我假设你想在找到CheckBoxchecked 时做一些事情,所以你可以这样做

    if(myCheckBox.Checked) //Checked is a boolean 
    /////// do something
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-19
      • 2014-03-06
      • 2012-05-29
      • 2012-10-31
      • 2011-02-01
      • 2014-10-17
      • 2015-07-17
      • 1970-01-01
      相关资源
      最近更新 更多