Changing from one button to another button when they have similar names - c#

I am making the game Mastermind where you need to guess a secret code with colours.
I am trying to have it when I click a button that has a colour on it, to change other buttons colour. So if you click the Red button it will change the first button on the form to Red, then if you clicked the Blue button it will change the second button on the form to Blue.
I have tried coding this before but I used only if statements, which is long and not clean at all. Especially when it comes to hundreds of statements.
Button btn = (Button)sender;
if (btn.Text == "Red")
{
// I want it to automatically go to Colour2 next,
// instead of me having to write it a bunch of times
Colour1.BackColor = Color.Red;
}
I want to be able to smoothly go through all the different buttons on the form and change all of there colours.
Thank you for the help.

Using your existing code as an example, you could parse the text from the button into the correct enum value (assuming the Text value is a known color enum string) using the static Enum.TryParse method, which tries to parse a string to an enum. If the parsing is successful, it returns true and sets the out parameter to the parsed value:
Color selectedColor;
if (Enum.TryParse((sender as Button).Text, out selectedColor))
{
Colour1.BackColor = selectedColor;
}
If you're certain that the Text property will always be a valid color (which you should be since you control it), then you could reduce that to just one line, using the static Enum.Parse method, which takes in the type of enum to return and a string value to parse:
Colour1.BackColor = Enum.Parse(typeof(Color), (sender as Button).Text);
Alternatively, instead of using the Text property, you could use the button's backcolor itself to assign the value (assuming you set it to the same color as the text):
Color1.BackColor = (sender as Button).BackColor;

Related

Why is the "RichTextBox.SelectionBackColor" not reverting to default on the new and unselected text, after the SelectionBackColor was changed?

I have a RichTextBox. I'm working on changing the SelectionBackColor only of the selected text.
Then, I have a ToolStripMenuItem(let's call it 'buttonA' for now) which is responsible to change the SelectionBackColor of the selected text. The problem I'm facing is after I click buttonA, the background color of the selected text in the RichTextBox can be successfully done. However, when I add some other characters or text right after the changed background color text, it doesn't use the default background color. Instead, it continues to use the same background color as assigned from buttonA, which I don't want to happen.
At first, I thought that my start index and end index of the selected text was problematic. But, I don't think there's any problems in its codes. Below shows the code example:
SolidBrush textBgCol; //a variable to keep color
this.richTextBox1.Select = this.richTextBox1.SelectionStart, this.richTextBox1.SelectionLength;
this.richTextBox1.SelectionBackColor = Color.FromArgb(textBgCol.Color.A, textBgCol.Color.R, textBgCol.Color.G, textBgCol.Color.B);
One of my efforts was to change the SelectionBackColor to default in the KeyDown event of richTextBox1. However, the background color of the new or successive characters and text were still the same as assigned from buttonA. Below shows the code example:
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
this.richTextBox1.SelectionBackColor = default;
}
I've also tried to refer to this but, I don't think it helps me to solve my case here.
Other than that, just to confirm that my richTextBox1's SelectionStart and SelectionLength were okay, I've even referred to these: ref1, ref2, and ref3.
May I know any other workarounds for this please? Or, were there anything inside my codes that I've missed?
Based on comment by #Jimi:
I just need to change the codes in my richTextBox1's KeyDown event handler to:
if(richTextBox1.SelectionBackColor != richTextBox1.BackColor)
{
richTextBox1.SelectionBackColor = richTextBox1.BackColor;
}
Below shows the demo:
Thanks!

How can I continue adding an integer with a free response textbox?

I am working with c#.
My goal is to be able to add an integer to a free response textbox. Allow me to explain.
I have a textbox called (Red,Green,Blue). Each color will be replaced using the Replace(); method.
Like this:
private void RedTextBox_TextChanged(object sender, EventArgs e) //ActualFogColor is Result
{
string ActualColorFog = "game.Lighting.FogColor = Color3.new(Red,Green,Blue)";
string Red = RedTextBox.Text;
string FogColorRed = ActualColorFog.Replace("Red", Red);
ActualColorFogScript.Text = FogColorRed;
}
This repeats for all other colors and it works fine. The problem I have is that I have a brightness button that when you click it, it adds 1 to the inputted number, but of course I had to convert it into an integer. It is basically initial + 1 = the new color. Replace Initial with new color and print that on the textbox.
Unfortunately i can't do
public partial class main : Form
{
int red = Convert.ToInt32(RedTextbox.Text); }
This is at the very top of the code which is why when doing this, it doesn't recognize RedTextBox.
The reason I am trying to assign the integer to the textbox is so that when the " RedTextBox.Text = '5' " It will take that 5 and add 1(by a button) which then prints the sum which I set equal to Red in string ActualColorFog = "game.Lighting.FogColor = Color3.new(Red,Green,Blue)";
I hope this make sense to you all, if you are confused on my plan, please leave your question.
I'd suggest you take one step back and think about the usability of your inputs. What I mean if you allow the user to freely enter the text, you have to tackle the input values like negative numbers, literals, numbers outside of the range (0-255 I presume), non-integer input, etc. Furthermore it would be nice if the user can use mouse scroll to increase/decrease the value. Perhaps a numeric up-down would be solution for your problem? It's not a standard control but there are enough implementations of it freely available.
Should you insist on using the text input, do the following:
define 3 integer member variables in your code for the components.
provide the Changed event handler for each textbox where you int.TyParse the input, check the ranges and if all goes well and update the respective member variable if it differs from the new value
probably add mouse scroll event handler
your button's Click event handler will update the member variables and the text values in the textboxes
A nicer solution would be to use the dependency properties instead of member variables, the content of the textboxes is bound to the dependency variables one way and the textboxes' Checked event handler does the parsing.
I am not getting into that if your method is good or not but just how to solve this problem.
As i can see, ideal for you would be that you can assign int red = Convert.ToInt32(RedTextbox.Text); and you cannot because it is at top of your code?
It is not recognizing because that part of code is accessed before RedTextBox is even initialized. Solution for this is to put int red = -1; and then
public main() //Your form constructor
{
InitializeComponents();
// I guess you somehow add some value to RedTextbox on form
showing so it need to be before assigning red variable
red = Convert.ToInt32(RedTextbox.Text); //It is important to be after Initializecomponents()
}

Button not highlighting

I create a set of prefabs at runtime via script. They are held in an array called newObj. Each one has some text UIs and some buttons, which I retrieve with GetComponentsInChildren. When a user clicks the first button in the prefab, I want to run a function that changes the text of the button and highlights that button.
Everything is working except the button doesn't highlight.
public void SelectPlayer(int rowSelected)
{
var buttons = newObj[rowSelected].GetComponentsInChildren<Button>();
var texts = newObj[rowSelected].GetComponentsInChildren<Text>();
texts[0].text = "1";
buttons[0].Select();
buttons[0].OnDeselect(null);
}
Oops. I'm still new to Unity and forgot that Unity sets the default highlight color to white (for some reason). Once I changed it for my prefab using the editor, all was well.

How can I change the color of the text of a button?

I want to click a button and change its text's color and message properties.
I got the button to change its color, but I need to change one of its text's colors.
private void TurnGreen(Button button)
{
ColorBlock colors = button.colors;
colors.normalColor = Color.green;
button.colors = colors;
}
The above code changed the button's color which I liked, but I would rather change the button's text. Note however that my button has two text-childs. The text I want to change has a name of "Ore".
Haven't done Unity for ages, so my knowledge is bit rusty.
Make sure using System.Linq; is set in your script.
// Considering that "button" is the one on which you clicked.
// By definition, we have 2 Text children (for single Text, we
// could use button.GetComponentInChildren<Text>().color directly, as it returns single element.
var oreText = button.GetComponentsInChildren<Text>().FirstOrDefault(o => o.name == "Ore"); // Unity allows same naming...
// I had 2 Text components initially returned: Ore and Wood.
// Got the Ore text component with FirstOrDefault. Now check it really exists and set color.
if (oreText != null) // Long way to compare. For illustration.
{
oreText.color = Color.green;
}
// Also, if "Ore" button really exists, you can directly set it from "Single" method:
// button.GetComponentsInChildren<Text>().Single(o => o.name == "Ore").color = Color.green;
A better way to do this might be to identify the text component in question from the editor (assuming your button is a Prefab), rather than iterating through the components via Linq. If you do it that way, it's scales a little better if you want to use that type of behavior on other components/buttons but don't want to have to change the Linq search text each time.
To do this, create a new field like this:
public Text textToChange;
Then drag the component in question form your button into your component script from the editor, then in code do this:
textToChange?.color = Color.green;
And then boom, you're done...the '?.' also checks for null for you without the if block.

How can I change the color of all my forms from just one of my forms?

I have tried:
//this code is triggered when i click a button on the form(lets call it form3)
// the first line works, but the second line is ReadOnly
this.BackColor = System.Drawing.Color.Crimson;
DefaultBackColor = this.BackColor;
On form1, i have a button with the following code, without comments, triggered when i click it:
//this button is basically a refresh button for the background
this.BackColor = form3.DefaultBackColor;
I'm new to stackoverflow so help would be greatly appreciated, especially if an alternate code could be provided. :)
Maybe this could be of use?: Application.OpenForms
You could iterate through the collection and set the form colour that way.
You could create a class that gets and sets the color of a form.
When the user changes the color the global variable will change to (depending on how it's handled) probably the hexadecimal color value. Whenever another form is called just get the value that was set.

Categories

Resources