【问题标题】:using textbox data to check a radiobutton使用文本框数据检查单选按钮
【发布时间】:2013-07-23 23:40:21
【问题描述】:

我有一个从数据库中获取性别值的文本框。根据 textchanged 事件,单选按钮做出相应的响应。

private void txtInvisibleGender_TextChanged(object sender, EventArgs e)
{
    if (txtInvisibleGender.Text == "Female")
        rbFemale.Checked = true;
    else
        rbMale.Checked = true;
}

问题是当文本框中的数据是女性时,为什么要选中男性单选按钮?它不会根据文本框中的数据进行检查。我该如何完成这项工作?

【问题讨论】:

  • 向我们展示这个txtInvisibleGender.Text的文本
  • txtInvisibleGender.Text = read["Gender"].ToString();
  • 试试我的答案。并始终使用 equals 进行字符串比较

标签: c# winforms radio-button


【解决方案1】:

您应该使用 string.Compare 而不是 ==。

这意味着你的文本框没有这个值,至少不在同一个大小写中。试试这个

private void txtInvisibleGender_TextChanged(object sender, EventArgs e)
{
 if(string.Compare(txtInvisibleGender.Text.Trim(), "Female", StringComparison.OrdinalIgnoreCase) == 0)     
    rbFemale.Checked = true;
else
    rbMale.Checked = true;
}

【讨论】:

【解决方案2】:

您的false branch 始终处于执行状态,因为您的条件永远不是true

if (txtInvisibleGender.Text == "Female")
    rbFemale.Checked = true;
else
    rbMale.Checked = true; // we are reaching here.

建议改成

if (txtInvisibleGender.Text.Trim().ToLower().Contains("female"))
    rbFemale.Checked = true;
else
    rbMale.Checked = true; 

值得注意的是,if-elsetxtInvisibleGender 不包含"female" 的所有情况下都会检查男性。所以输入"foobar" 将检查男性。

我会改成:

// "female" contains "male" so Contains() cannot be used!
if (txtInvisibleGender.Text.Trim().ToLower().Equals("female"))
    rbFemale.Checked = true;

if (txtInvisibleGender.Text.Trim().ToLower().Equals("male"))
    rbMale.Checked = true;

那么如果它不是"male""female" 它不会检查任何东西。

【讨论】:

  • 即使我为 Male 和 Else-If 尝试另一个 If 语句,它也无法正常工作..
  • 查看我的更新答案。改为txtInvisibleGender.Text.ToLower().Contains("female")。
  • 您的代码不起作用,因为文本框不完全包含字符串“女性”。它可能有其他字符,如“/n”或大小写错误。 “女”!=“女”
  • Trim() 删除空格,ToLower() 删除大写,Contains() 表示字符串中某处包含字符串“女性”。
  • 我不太确定底部代码是否正确。如果您在字符串“female”上调用.Contains("male"),那么它将返回true,并选中male 单选按钮。我认为.Equals 会更好。那个,或者它需要是else-if
猜你喜欢
  • 2016-12-10
  • 1970-01-01
  • 1970-01-01
  • 2019-05-29
  • 2013-02-09
  • 1970-01-01
  • 1970-01-01
  • 2014-02-05
  • 2013-09-29
相关资源
最近更新 更多