c# - 如何将 int 或 bool 转换为 checkState

标签 c# .net winforms

我需要将 int 和/或 bool 转换为 checkState

int ValueCheck;      
private void gsCheck1_CheckedChanged(object sender, EventArgs e)
{
    CheckBox box = sender as CheckBox;
    box.CheckState = ValueCheck; // doesn't work
    this.gsCheck2.CheckState = ValueCheck; // should be 1 or 0 ?
}

如您所见,我想通过更改 (this.gsCheck1) CheckState 来更改 (this.gsCheck2) CheckState,最后得到一个需要的整数值。

更新.... 问题解决了

private int ValueCheck(CheckState Check)
{
    if (Check == CheckState.Checked)
        return 1; 
    else
        return 0; 
}


private void gs_CheckedChanged(object sender, EventArgs e)
{
    CheckBox box = sender as CheckBox;
    MessageBox.Show(box.Name + "="+ ValueCheck(box.CheckState).ToString());
}

最佳答案

根据评论更新:

要么将 ValueCheck 声明为 CheckState:

CheckState ValueCheck;
private void....

或者将 int 值转换为 CheckState 值:

this.gsCheck2.CheckState = (CheckState)ValueCheck;

将 CheckState 值强制转换为 int:

CheckState cs = box.CheckState;
int ValueCheck = (int)cs;
string result = "Current state: " + ValueCheck + cs.ToString();

//You question:
MessageBox.Show(box.Name + (int)box.CheckState);

更新
仅供引用,没有编写 ValueCheck 方法,而是有一个 C# 运算符 ?: operator我在上面提到过,您可以这样做:

int result = box.CheckState == CheckState.Checked ? 1 : 0;

这是翻译:

int result;
if (box.CheckState == CheckState.Checked)
    result = 1;
else
    result = 0;

关于c# - 如何将 int 或 bool 转换为 checkState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3221137/

相关文章:

C# 在面板上绘图

c# - Trace 不为输出创建文件

c# - 使用 Json.NET 将 JObject 的一部分转换为 Dictionary<string, string>

c# - C#XML注释中的尖括号

c# - 如何关闭 resharper 中的 "Convert Extension Method to Plain Static"自动重构?

c# - 仅在轴标签中显示整数?

c# - 具有 100 个以上属性的类的设计模式

c# - 将空值传递给重载方法,其中 Object 和 String 作为 C# 中的参数

c# - "The creator of this fault did not specify a Reason"异常

c# - winforms应用程序中的Winforms WebBrowser网页触发事件