【问题标题】:Holding information in hashtables or arrays then outputting在哈希表或数组中保存信息然后输出
【发布时间】:2015-06-02 11:54:46
【问题描述】:

我正在 开发一个程序,但不知道如何解决这个问题。

In my program, I have a large amount of checkboxes (Yes and No) and when No is selected, a textbox appears prompting the user to write a comment, example below:

private void checkBox48_CheckedChanged(object sender, EventArgs e)
  {
      if (checkBox48.Checked == true)
      {
          // Create an instance of the dialog
          frmInputBox input = new frmInputBox();
          // Show the dialog modally, testing the result.
          // If the user cancelled, skip past this block.
          if (input.ShowDialog() == DialogResult.OK)
          {
              // The user clicked OK or pressed Return Key
              // so display their input in this form.

              problems = problems + "23. Check Outlet Drainage : " + input.txtInput.Text + Environment.NewLine;
              this.txtProblems5.Text = problems;
              txtProblems5.Visible = true;
          }

          // Check to see if the dialog is still hanging around
          // and, if so, get rid of it.
          if (input != null)
          {
              input.Dispose();
          }
      }
  }

但是,暂时我让用户输入只是写入名为problemsString。我想将这些值分别保存在不同的位置。

哈希表或数组是否合适? (例如txtInput.Text = Problems[40]

【问题讨论】:

  • 一个建议,大部分与问题无关。我假设您的每个复选框都有一个 CheckedChanged 方法...如果您使用不同的文本/控件执行相同的操作(如上所示),您应该能够使 @987654329 @ 方法足够通用,因此您只需要一个。它会让你的程序更易于维护,也更易读。
  • 你有任何文件可以帮助我做到这一点吗?
  • 不,但如果您不知道,每个方法中的object sender 参数将保存事件来自的Checkbox 对象。这将处理checkBox48.Checked 部分。对于其他对象,我怀疑您只需要在每个复选框与相关的文本框和文本字符串之间建立关系。如果您需要更多帮助清理它,我建议将其发布到 codereview.stackexchange.com 如果您这样做,请在此处发表评论,我会提出一些更具体的建议。

标签: c# c# checkbox hashtable


【解决方案1】:

数组或哈希表都可以。 Hashtable 可能对开发人员更友好一些,并且可能占用更小的内存。这是一个小例子:

private Dictionary<int, string> problems = new Dictionary<int, string>;

// add key value pair
problems.Add(42, "your problem here");

// get value
string value = "";
if (problems.TryGetValue(42", out value))
{
    // the key was present and the value is now set
}
else
{
    // key wasn't found
}

【讨论】:

  • 是的,我想我会使用哈希表,谢谢你的帮助
【解决方案2】:

如果您使用数组,则意味着您必须按照您的示例为每个文本框创建条目。

出于偏好,我可能会使用dictionary&lt;string,string&gt;,其中键是控件名称。
那么,我的textbox 值可能是:

txtProblem1.text = dictionary.ContainsKey(txtProblem1.Name) ? dictionary[txtProblem1.Name] : "";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-26
    • 2014-03-22
    • 2014-04-14
    • 1970-01-01
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多