Search code examples
c#buttonpressed

c# Button clicked second time, simpel way to get True, False?


I have a Button an its function. When the user presses a Button, a Line of Textboxes change their Backcolor to grey. When the user press the button again, the Line change back to white. But my solution for that is way to complicated and i think there is a more comfortable way to do this. Here is my Code:

 private void btnTitelRow2_Click(object sender, EventArgs e)
    {
        bool isTitel = true;
        bool checkStatus = CheckTitelStatus(row: 1);
        if (checkStatus == true)
        {
            isTitel = false;
        }
        fncLOITitelrow(row: 1, isTitel: isTitel);
    }



    public bool CheckTitelStatus(int row)
    {
        bool labelStatus = false;
        Color dimgray = System.Drawing.Color.LightGray;
        Color white = System.Drawing.Color.White;

        Label[] Titelbl = getLOILabelTitel();
        if (Titelbl[row].BackColor == white)
        {
            labelStatus = false;
            return labelStatus;
        }
        if (Titelbl[row].BackColor == dimgray)
        {
            labelStatus = true;
            return labelStatus;
        }
        else
        { return labelStatus; }

the function LOITitelrow is the one that changes the line of textboxes color. i think waht i need is a simpel way to give me a true when the button is clicked for the first time, and a false when it is pressed the second time. 3rd time true and so on...

any ideas?


Solution

  • private void btnTitelRow2_Click(object sender, EventArgs e)
    {
        const int row = 1;
        fncLOITitelrow(row, CheckTitelStatus(row));
    }
    
    public bool CheckTitelStatus(int row)
    {
        Label[] Titelbl = getLOILabelTitel();
        return Titelbl[row].BackColor == System.Drawing.Color.LightGray;
    }
    

    You're writing a lot of redundant code, such as comparing a boolean to true. The result of CheckTitelStatus returns a boolean, and an if statement expects a boolean value, therefore you can just use the return value of CheckTitelStatus. Also, in your CheckTitelStatus you can just check if the BackColor is currently LightGray, instead of checking for each color.