Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert int or bool to checkState

Tags:

c#

.net

winforms

I need to convert int and or bool to 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 ?
}

As you can see I want to change (this.gsCheck2) CheckState by changeing (this.gsCheck1) CheckState and end up with a integer value which is need.

Update.... problem solved

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());
}
like image 371
User6996 Avatar asked Jul 10 '10 22:07

User6996


1 Answers

  • Consider CheckBox.Checked which is the boolean property.
  • Use box.CheckState = (CheckState)ValueCheck;
  • You can also use the ?: operator.

Update according to comments:

Either declare the ValueCheck as a CheckState:

CheckState ValueCheck;
private void....

Or convert the int value to a CheckState value:

this.gsCheck2.CheckState = (CheckState)ValueCheck;

The cast back the CheckState value to 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);

Update
FYI, instead of writing the ValueCheck method, there is a C# operator ?: operator I mentioned above, which you can do:

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

Which is a translation of:

int result;
if (box.CheckState == CheckState.Checked)
    result = 1;
else
    result = 0;
like image 103
Shimmy Weitzhandler Avatar answered Oct 13 '22 02:10

Shimmy Weitzhandler