C# Changing txtBox BackColor by Length - c#

I want to write a simple "registration/login" program, just for me, just for fun.
I want to change the color of the TxtBox where a user types their name. When txtBox.Length<4 it should change its background to red.
I don't know why my code below isn't working. When I solidly change a text in txtBox properties to more than 5, it's blue at the start but doesn't change afterwards.
My code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace _4Fun
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
if (regTxtBoxName.TextLength<4) {
regTxtBoxName.BackColor = Color.Red;
}
else{
regTxtBoxName.BackColor = Color.DarkBlue;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void regBtn_Click(object sender, EventArgs e)
{
if (regTxtBoxName.TextLength < 4)
{
txtBoxStatus.Text = "Choose a name with minimal length 5. "; // Urobit txtboxname a pass v registru červene pozadie ak x<4
}
else {
txtBoxStatus.Text = "Your account has been successfully created.";
string name = regTxtBoxName.Text;
}
if (regTxtBoxPass.TextLength < 4)
{
txtBoxStatus.Text = txtBoxStatus.Text + "Choose password with minimal length 5. ";
}
else {
txtBoxStatus.Text = "Your account has been successfully created.";
string pass = regTxtBoxPass.Text;
}
}
}
}

Your code is setting the color in the constructor of the form and then you don't change it. You need to register to TextChanged event on your TextBox to change the colour while your application is running based on how many characters there are in your Textbox.

Handle your text box TextChanged event, and place this code there, not in constructor:
if (regTxtBoxName.TextLength<4) {
regTxtBoxName.BackColor = Color.Red;
}
else{
regTxtBoxName.BackColor = Color.DarkBlue;
}

You can do this in Textbox TextChanged event.
Here is code
void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.TextLength<4)
{
textBox1.BackColor = Color.Red;
}
else
{
textBox1.BackColor = Color.DarkBlue;
}
}
When you enter a text in text box TextChanged event will call. check this link http://www.dotnetperls.com/textchanged

You may want to change the regBtn_Click method to regBtnTextChanged. By doing so, then the color of the textBox will change on run time.
So the code would be:
private void regBtnTextChanged(object sender, EventArgs e)
{
if (regTxtBoxName.TextLength<4) {
regTxtBoxName.BackColor = Color.Red;
}
else{
regTxtBoxName.BackColor = Color.DarkBlue;
}
}

Related

How to change label text and color when a condition is met? (C#)

I am making a password generator and on websites when you enter certain conditions are met the strength of the password changes how can I change the color and text of the label when the password strength is >= 8, <8<10, >12?
Here is the Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Password_Generator
{
public partial class PassGen : Form
{
int currentPasswordLength = 0;
Random Character = new Random();
private void PasswordGenerator(int PasswordLength)
{
String validChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$&?";
String randomPassword = "";
//25
for(int i = 0; i < PasswordLength; i++)
{
int randomNum = Character.Next(0, validChars.Length);
randomPassword += validChars[randomNum];
}
Password.Text = randomPassword;
}
public PassGen()
{
InitializeComponent();
PasswordLengthSlider.Minimum = 5;
PasswordLengthSlider.Maximum = 22;
PasswordGenerator(5);
}
private void Label1_Click(object sender, EventArgs e)
{
}
private void Copy_Click(object sender, EventArgs e)
{
Clipboard.SetText(Password.Text);
}
//52
private void PasswordLength_Click(object sender, EventArgs e)
{
}
private void PasswordLengthSlider_Scroll(object sender, EventArgs e)
{
PasswordLength.Text = "Password Length:" + " " + PasswordLengthSlider.Value.ToString();
currentPasswordLength = PasswordLengthSlider.Value;
PasswordGenerator(currentPasswordLength);
}
private void pswdStrengthTest()
{
if (currentPasswordLength <= 8)
{
pswdStrength.Text = "weak";
pswdStrength.ForeColor = Color.Red;
} else if (currentPasswordLength<= 9)
{
pswdStrength.Text = "ok";
pswdStrength.ForeColor = Color.Blue;
}
}
//78
private void pswdStrength_Click(object sender, EventArgs e)
{
}
}
}
If anyone could help me with this it would be greatly appreciated. This is based off a tutorial I found on YouTube. I'm not sure what the video is called but if it helps I could search for it and update my posting.
Try this:
Password.TextChanged += (s1, e1) =>
{
if (Password.Text.Length > 10)
pswdStrength.ForeColor = Color.Green
else if (Password.Text.Length > 8)
pswdStrength.ForeColor = Color.Blue
else
pswdStrength.ForeColor = Color.Red
};
Your code looks like a windows form application.
If you have for example one objetc txt_password, check to code some of these events:
TextChanged: this occurs when your textbox has been changed
Others events could be:
KeyPress or KeyDown

Wanting to change a label using a combo box selection

I'm making a program that lets the user select a score/grade from a combobox and using a button click will calculate the answer for the user. However for some reason when I press calculate button the label text doesn't change at all. Also sorry if the codes messy or looks wrong as I'm still trying to learn.
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace btec_to_ucas
{
public partial class Form1 : Form
{
//These are the values i want displayed on the label
int PPP = 48;
int MPP = 64;
int MMP = 80;
int MMM = 96;
int MMD = 112;
int DDM = 128;
int DDD = 144;
public Form1()
{
InitializeComponent();
}
// below i want whenever the button is pressed it will take the selected answer and display the int onto the label
private void button1_Click(object sender, EventArgs e)
{
{
switch (comboBox1.SelectedIndex)
{
case 0:
if (comboBox1.SelectedIndex == PPP)
{
label1.Text = "48";
}
break;
case 1:
if (comboBox1.SelectedIndex == MPP)
{
label1.Text = "64";
}
break;
case 2:
if (comboBox1.SelectedIndex == MMP)
{
label1.Text = "96";
}
break;
}
}
}
private void label1_Click(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
} ```
Your switch statement should be like this:
switch (comboBox1.SelectedIndex)
{
case 0:
label1.Text = PPP.ToString();
break;
case 1:
label1.Text = MPP.ToString();
break;
...

ComboBox menu repeat bug after typing in textbox in Winform app

I have a primitive app with 2 comboBoxes. They work fine after first starting the app.
However after typing in text in the search bar and pressing enter, the comboboxes loop their contents.
It happens after I type in the textbox, even if I do not press enter. Every time I press a key another repeat list of options appends to the comboBox.
How do I prevent this comboBox malfunction? Here is my code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//Nick Knapp
//CSCI 363 Fall 2019
namespace c363_hw3_2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.Text = "Library Literature Search";
this.BackColor = Color.White;
comboBox2.Items.Add("All");
comboBox2.Items.Add("Books");
comboBox2.Items.Add("Papers");
comboBox2.Items.Add("Films");
comboBox2.Items.Add("CDs");
comboBox2.Items.Add("Other");
comboBox2.SelectedIndex = 0;
comboBox1.Items.Add("Title");
comboBox1.Items.Add("Author");
comboBox1.Items.Add("Publisher");
comboBox1.Items.Add("ISBN");
comboBox1.SelectedIndex = 0;
// this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(CheckEnter);
//this.Controls.Add(textBox1);
this.ActiveControl = textBox1;
textBox1.KeyPress += new KeyPressEventHandler(keypressed);
}
private void keypressed(Object o, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Return)
{
textBox1.Text = "";
e.Handled = true;
}
}
private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e)
{
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
I think your code is correct but have you ever tried these 2 method after calling combo boxes?
comboBox1.ResetText();
comboBox1.Items.Clear();```
i think it works
private void keypressed(Object o, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Return)
{
textBox1.Text = "";
comboBox1.Items.Clear();
e.Handled = true;
}
}

C# Hotkey Box (AHK Hotkey Style)

I am trying within C# to create a similar Hotkey function as in AHK. Just like in any video game, you click in a box, press your hotkey and get it registered.
That's what I am trying to do with the textBox:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Keybinder
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
KeyPreview = true;
textBox1.ReadOnly = true;
textBox1.Focus();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = "HELLO";
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
char key = e.KeyChar;
string keystring = Char.ToString(key);
textBox1.Text = keystring;
}
}
}
However, the problem is, that I need to turn off the basic functions of the textBox, but I don't know how. For example: the cursor is still active and I can highlight the text in it.
You can set the property of the text box, Enabled to false, and then put the background color white and the font black, so it doesn´t seems like it was disabled, but you can not focus nor click on ir.
textBox1.Enabled = false;
By the way, I have a really simple library, that may be usefull.
https://github.com/PabloHorno/HotKeyDialog
Once you have the library referenced you can use it like this
or in a more simple way
var hotKey = new HotKey();
hotKey = HotKeyMessageBox.Show("Title", "A little description");
hotKey.ToString();
Or you can check if the user closes the box
HotKey hotkey = new HotKey();
if (HotKeyMessageBox.Show("Title", "Please press the key combination", out hotkey) == DialogResult.OK)
label.Text = "You have pressed the keys: " + hotkey.ToString();
else
label.Text = "You have closed the dialog. There is no input";
Hope it helps!
Why are you using a TextBox, if you do not need its functionality?
Instead of turning off it's functions, you can create a simple custom control and put it on your form. Something like:
public class KeyInput : UserControl
{
public string KeyString { get; set; } = "HELLO";
public KeyInput() : base()
{
BorderStyle = BorderStyle.Fixed3D;
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
base.OnKeyPress(e);
KeyString = e.KeyChar.ToString();
Invalidate();
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.DrawString(KeyString, Font, SystemBrushes.ControlText, 0, 0);
}
}

Checking if a label I click, is a part of a pattern of labels

I am making a game about remembering a pattern of labels, that show up by them changing colors. The user then has to click the labels showed, in the correct order.
After the pattern has been randomly chosen, it goes into a list called the 'pattern'. My problem here is; how do I make it so that my label_Click event handler can be used to check if the correct label has been clicked for the entire list, in the correct order. Sorry that my code is clumsy and without comments, I have just started programming.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Spil
{
public partial class Form1 : Form
{
Random rnd = new Random();
Label[] labelArray;
int turn = 1;
int lives = 3;
List<Label> pattern = new List<Label>();
public Form1()
{
InitializeComponent();
labelArray = new Label[] { label1, label2, label3, label4, label5, label6, label7, label8, label9 };
}
private void DisplayOrder()
{
for (int i = 0; i < labelArray.Length; i++)
{
labelArray[i].BackColor = Color.Blue;
labelArray[i].Click += label_Click;
}
for (int i = -2; i < turn; i++)
{
int chosenNumber = rnd.Next(0, 9);
labelArray[chosenNumber].BackColor = Color.Green;
Thread.Sleep(1000);
labelArray[chosenNumber].BackColor = Color.Blue;
pattern.Add(labelArray[chosenNumber]);
}
}
private void label_Click(object sender, EventArgs e)
{
Label clickedLabel = sender as Label;
}
private void Form1_Shown(object sender, EventArgs e)
{
System.Timers.Timer t = new System.Timers.Timer(100);
t.Elapsed += t_Elapsed;
t.Start();
}
void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
((System.Timers.Timer)sender).Stop();
DisplayOrder();
}
}
}
In order to keep track of matching user label clicks, you will need to keep track of the turn, so you know what index in pattern to look for when the user clicks a label.
So for the first click/turn, you can check if pattern[0] == clickedLabel. If it is the user was right and you can increment the index to 1, because that is the next label you expect to be clicked.
You can keep track of this by making some modifications to your code as shown below. Note: It only shows the modifications for keeping track of the user's tries, the rest of your original code remains untouched.
public partial class Form1 : Form
{
// A user is allowed a maximum of 3 guesses per label.
private const int MaxTries = 3;
// The number of guesses for the current label.
private int _triesOnCurrentLabel;
// The number of labels guessed correctly so far.
// This is also the index into the patterns list.
private int _numberGuessedRight;
// The game is over if the user guessed all labels
// or used more than the maximum number of tries on a label.
private bool _gameOver;
// ... other stuff
private void label_Click(object sender, EventArgs e)
{
Label clickedLabel = sender as Label;
if (!_gameOver)
{
if (pattern[_numberGuessedRight] == clickedLabel)
{
// The user guessed right.
_triesOnCurrentLabel = 0; // reset, 3 tries for next label.
_numberGuessedRight++;
_gameOver = _numberGuessedRight == pattern.Count;
if (_gameOver)
{
// Show the user a message? "YOU WON"
}
}
else if (++_triesOnCurrentLabel >= MaxTries)
{
// User used up all tries on the current label.
_gameOver = true;
// Show the user a message? "Game over YOU LOSER"
}
}
}
// ... the rest
}

Categories