Heyah

Does anyone know how can I change the bacground color of my textfield by using :
the commands if & else

It's for one of my school assignments but I really can't get to solve it by myself i searched through web but nothing :S

We must use the

textBox1.BackColor = System.Drawing.Color.Black;
&
if (textBox1.BackColor.Equals(System.Drawing.Color.Black))

lines but from what you can see in my way of writing and asking for so (I suppose) simple question I'm pretty new to coding so any help or tips would be appreciated

my assignment is to
create a button and a textfield in Visual Studio 2008

and make the colour of the textfield change whenever i press the button
(while the color is red and i press the buttong the color haves to change to green then again to yellow, blue and so on)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace opdracht2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            textBox1.BackColor = System.Drawing.Color.Red;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.BackColor.Equals(System.Drawing.Color.Red))
            {
                
            }
        }
    }
}

sorry for my bad english and thanks

Recommended Answers

All 3 Replies

Hi katsurou, welcome on Daniweb!
If and else are not commands, they are reserved words of a language.
Did not find it so hard to get info about them: http://msdn.microsoft.com/en-us/library/5011f09h.aspx
Another thing :you don't have to use System.Drawing.Color.Red fully written out. You can simply use Color.Red, because you use a using clause on line 5 of your code. It makes code easier to read that way.

Thank you ddanbe! ^.^
I removed the System.Drawing and added the correct line of code and its working now =)

btw. Do i have to use ElseIf now if I want to change it to another colours from the color its stayed on so for example:

private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.BackColor.Equals(Color.Red))
            {
                textBox1.BackColor = Color.Green;
            }
            ElseIf (textbox1.BackColor.Equals(Color.Green))
            {
                 textBox1.BackColor = Color.Yellow;
              }
}

and so on?

Yes and so on.:) I assume the ElseIf on line is a typo or a habbit from visual basic, must be else if
It goes like this:
if...
else if... // as many as needed
else if...
...
...
else if
else ... // if needed

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.