Handle user number input value condition with ReadOnly false of numericUpDown - c#

In C# WinForms desktop application I use 2 interdependent numericUpDown1 min and numericUpDown2 max value numericUpDown controls:
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
if (numericUpDown1.Value <= numericUpDown2.Value)
{
min = (int)numericUpDown1.Value;
}
else
{
numericUpDown1.Value = min - 1;
}
}
private void numericUpDown2_ValueChanged(object sender, EventArgs e)
{
if (numericUpDown2.Value >= numericUpDown1.Value)
{
max = (int)numericUpDown2.Value;
}
else
{
numericUpDown2.Value = max + 1;
}
}
with using of ReadOnly = true; to avoid making the maximal number less than minimal manually from numericUpDown input.:
min = 20;
max = 1999;
numericUpDown1.Value = min;
numericUpDown2.Value = max;
numericUpDown1.ReadOnly = true;
numericUpDown2.ReadOnly = true;
numericUpDown1.Increment = 1;
numericUpDown2.Increment = 1;
numericUpDown1.Maximum = 2000;
numericUpDown1.Minimum = 1;
numericUpDown2.Maximum = 2000;
numericUpDown2.Minimum = 1;
but I use a big range from 1 to 2000, and want to allow the user to change the number of numericUpDown manually with ReadOnly = false;.
I'm trying to figure out, how to control the user input condition with ReadOnly = false; of numericUpDown to avoid the input of maximal number less than minimal or minimal bigger then maximal.

Try this solution:
First of all Set your numericUpDown property ReadOnly=false or write a line of code in your FormLoad_Function,
numericUpDown1.ReadOnly = false;
numericUpDown2.ReadOnly = false;
Then
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
if (numericUpDown1.Value > numericUpDown2.Value)
{
numericUpDown1.Value = numericUpDown1.Value - 1;
MessageBox.Show("Min value always less then Max value");
}
}
private void numericUpDown2_ValueChanged(object sender, EventArgs e)
{
if (numericUpDown1.Value > numericUpDown2.Value)
{
numericUpDown2.Value = numericUpDown2.Value + 1;
MessageBox.Show("Max value always greater then Min value");
}
}

Related

How can I connect multiple TextBoxes with a ProgressBar?

I just started with the programming language C# a week ago and used the program Visual Studio with win Forms. I've had a problem for a few days.
I want to connect a ProgressBar to different TextBoxes. So that with each filled textBox the ProgressBar increases. When the text is removed, the progressBar should go down again.
So far I've only managed to get the progressBar to increase in general or that the progress bar increases with each letter in a textBox.
Textboxes are Vorname,Nachname,PLZ,Wohnort,Hausnummer,Straße
ProgressBar is Fortschrittsanzeige
private void button1_Click(object sender, EventArgs e)
{
Fortschrittsanzeige.Dock = DockStyle.Bottom;
Fortschrittsanzeige.Maximum = 60;
Fortschrittsanzeige.Minimum = 0;
Fortschrittsanzeige.Style = ProgressBarStyle.Continuous;
if (
Vorname.Text.Length <= 0 ||
Nachname.Text.Length <= 0 ||
PLZ.Text.Length < 4 ||
Wohnort.Text.Length <= 0 ||
Hausnummer.Text.Length <= 0 ||
Straße.Text.Length <= 0
)
{
textBox7.Text = ("Bitte überprüfe deine Eingabe");
}
else
{
Sendebutton.Text = "Gesendet";
textBox7.Text = "Vielen Dank" + Vorname.Text + " " + Nachname.Text + ", wir
haben deine Daten erhalten.";
}
if (Vorname.Text.Length <= 0)
{
Vorname.BackColor = Color.IndianRed;
}
else
{
Vorname.BackColor = Color.White;
Fortschrittsanzeige.Value += 10;
}
if (Nachname.Text.Length <= 0)
{
Nachname.BackColor = Color.IndianRed;
}
else
{
Nachname.BackColor = Color.White;
Fortschrittsanzeige.Step += 10;
}
if (PLZ.Text.Length < 4)
{
PLZ.BackColor = Color.IndianRed;
}
else
{
PLZ.BackColor = Color.White;
Fortschrittsanzeige.Step += 10;
}
if (Wohnort.Text.Length <= 0)
{
Wohnort.BackColor = Color.IndianRed;
}
else
{
Wohnort.BackColor = Color.White;
Fortschrittsanzeige.Step += 10;
}
if (Hausnummer.Text.Length <= 0)
{
Hausnummer.BackColor = Color.IndianRed;
}
else
{
Hausnummer.BackColor = Color.White;
Fortschrittsanzeige.Step += 10;
}
if (Straße.Text.Length <= 0)
{
Straße.BackColor = Color.IndianRed;
}
else
{
Straße.BackColor = Color.White;
Fortschrittsanzeige.Step += 10;
}
}
You can handle the TextChanged event on each TextBox like so
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text.Length > 0 && _textbox1IsEmpty)
{
progressBar1.Value += 10;
_textbox1IsEmpty = false;
}
else if (textBox1.Text.Length <= 0)
{
progressBar1.Value -= 10;
_textbox1IsEmpty = true;
}
}
and add a private property in your class
private bool _textbox1IsEmpty = true;
You can make a function to optimize it and don't have duplicate code
Here are a few tips to get you started with WinForms and make it easier to connect multiple TextBoxes with a ProgressBar.
The textboxes (and other controls) that are on a Form can be found in the Controls collection of the form.
All of the textboxes on the form can be obtained with a simple query.
For example, in the form Constructor you could go though all the textboxes and attach a TextChanged handler to each.
public MainForm()
{
InitializeComponent();
foreach (TextBox textBox in Controls.OfType<TextBox>())
{
textBox.TextChanged += onAnyTextChanged;
onAnyTextChanged(textBox, EventArgs.Empty); // Initialize
}
ActiveControl = Fortschrittsanzeige;
}
Multiple text boxes can all point to a common event handler.
System.Linq reduces the amount of code needed for things like matching and sorting.
What we're able to do is perform a validation based on all the textboxes whenever any textbox changes.
const int TEXTBOX_COUNT = 6;
private void onAnyTextChanged(object? sender, EventArgs e)
{
if(sender is TextBox textbox)
{
bool isValid;
if(textbox.PlaceholderText == "PLZ")
{
isValid = textbox.TextLength > 3;
}
else
{
isValid = !string.IsNullOrWhiteSpace(textbox.Text);
}
textbox.BackColor = isValid ? Color.White : Color.LightSalmon;
}
// Use System.Linq to count the number of valid textboxes (based on BackColor).
float countValid =
Controls
.OfType<TextBox>()
.Count(_=>_.BackColor== Color.White);
var pct = countValid / TEXTBOX_COUNT;
Fortschrittsanzeige.Value = (int)(pct * Fortschrittsanzeige.Maximum);
Sendebutton.Enabled = countValid.Equals(TEXTBOX_COUNT);
Fortschrittsanzeige.Visible = !Sendebutton.Enabled;
}
The handler allows for "special cases" and will make the Fortschrittsanzeige go backwards if the changed value is no longer valid.
When all textboxes are valid hide Fortschrittsanzeige and enable Sendebutton.

C# Calculator using List Array error at some operations Windows Form Application

Hello I'm still new to programming and yes this is not the best code you will see... I tried making calculator on C# windows form for fun and I'm having trouble on the subtraction and division operations, but the addition and multiplication works perfectly fine for me. I decided to have a list array so that I would be able to input numbers as much as I want.
The error for the subtraction is when I input for example 5 - 2 the result will be -3
As for the division the error is that the result is always 1
Please tell me where did I go wrong and give a detailed explanation if possible so that I would understand more about programming. Thanks in advance!
namespace CalculatorTestForm1
{
public partial class Form1 : Form
{
public static List<int> Numlist = new List<int>();
public static string operation;
public Form1()
{
InitializeComponent();
}
private void Button_Click(object sender, EventArgs e)
{
Button Num = (Button)sender;
TXTBox.Text += Num.Text;
}
private void BPlus_Click(object sender, EventArgs e)
{
operation = "add";
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
TXTBox.Text = "";
}
private void BEquals_Click(object sender, EventArgs e)
{
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
int sum = 0;
int product = 1;
int quotient = 1;
int difference = 0;
if (operation == "add"){
foreach (int value in Numlist)
{
sum += value;
}
string Answer = sum.ToString();
TXTBox.Text = Answer;
}else if(operation == "minus"){
foreach (int value in Numlist)
{
difference = value - difference;
}
string Answer = difference.ToString();
TXTBox.Text = Answer;
}
else if (operation == "multiply")
{
foreach (int value in Numlist)
{
product *= value;
}
string Answer = product.ToString();
TXTBox.Text = Answer;
}
else if (operation == "divide")
{
foreach (int value in Numlist)
{
quotient = value / value;
}
string Answer = quotient.ToString();
TXTBox.Text = Answer;
}
Numlist.Clear();
}
private void BClear_Click(object sender, EventArgs e)
{
TXTBox.Text = "";
Numlist.Clear();
}
private void BMinus_Click(object sender, EventArgs e)
{
operation = "minus";
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
TXTBox.Text = "";
}
private void BDivide_Click(object sender, EventArgs e)
{
operation = "divide";
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
TXTBox.Text = "";
}
private void BMulti_Click(object sender, EventArgs e)
{
operation = "multiply";
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
TXTBox.Text = "";
}
}
}
For the division it's obvious:
quotient = value / value;
value/value will always be 1.
There must be quotient in that loop somewhere...
For the subtraction the problem is that because of the way you do it, the order of the numbers are reversed.
lets say 5 - 2:
foreach (int value in Numlist)
{
difference = value - difference;
}
NumList = {5,2}
1st iteration:
difference = value(5) - difference(0) = 5
2nd iteration:
difference = value(2) - difference(5) = -3
You should reverse the order of the loop: NumList.Reverse()
And for the division as well:
Division:
foreach (int value in Numlist.Reverse())
{
quotient = value / quotient;
}
Subtraction:
foreach (int value in Numlist)
{
difference = value - difference;
}

Min and max button and label

I'm trying to build a exam grader using C#. I'm new to this and don't know very much. What code would I use to add min and max buttons and to add a label stating whether it's a min or max?
private void btnAdd_Click(object sender, EventArgs e)
{
int points;
try
{
points = int.Parse(txtPoints.Text);
lstPoints.Items.Add(points);
txtPoints.Clear();
txtPoints.Focus();
if (lstPoints.Items.Count == 12)
{
txtPoints.Enabled = false;
btnAdd.Enabled = false;
}
if (lblResult.Text != "")
{
lblResult.Text = "";
}
}
catch
{
MessageBox.Show("Please enter only whole numbers");
txtPoints.Clear();
txtPoints.Focus();
}
}
private void btnAvg_Click(object sender, EventArgs e)
{
double total = 0;
for (int i = 0; i < lstPoints.Items.Count; i++)
{
total += (int)lstPoints.Items[i];
}
total /= lstPoints.Items.Count;
lblResult.Text = total.ToString();
}
private void btnClear_Click(object sender, EventArgs e)
{
lstPoints.Items.Clear();
txtPoints.Enabled = true;
btnAdd.Enabled = true;
}
}
}
hope this works
private void getMax()
{
int max=0;
for (int i = 0; i < lstPoints.Items.Count; i++)
{
if(max<(int)lstPoints.Items[i])
{
max=(int)lstPoints.Items[i];
}
}
lblResult.Text = max.ToString();
}
}
private void getMin()
{
int min=(int)lstPoints.Items[0];
for (int i = 1; i < lstPoints.Items.Count; i++)
{
if(min>(int)lstPoints.Items[i])
{
min=(int)lstPoints.Items[i];
}
}
lblResult.Text = min.ToString();
}
}
There are two possiblities as I see:
1) When you are writing this:
lstPoints.Items.Add(points);
Instead of adding to List(Of Integer) use SortedList. So the
list will always have the sorted result sets.
2) Use Array.Sort() to sort the records.
Once you have sorted records the first one is the minimum and the last one is the maximum (Assuming sorted in ascending order).
Take out two buttons and placed on the form, set Text Property from property window to Min and Max respectively and in event handler handle the Click event and pick the relevant resultset from lstPoints array.
Hope it helps!

C# Array "circle"

I have an array:
class Words
{
public static string[] wordsArray = { "one", "two", "three", "four" };
}
TextBlock which displays an array of values, and button that displays the next value of the array:
private int counter = 0;
private void goButton_Click(object sender, RoutedEventArgs e)
{
if (counter < Words.wordsArray.Length)
{
enWordTextBlock.Text = Words.wordsArray[counter++];
}
}
When the box appears on the last value of the array, the program will continue to not work, how to make it work in a "circle"?
Thanks all!
This should work:
private void goButton_Click(object sender, RoutedEventArgs e)
{
counter++; //increase the counter
int i = counter % Words.wordsArray.Length; //modulo operation
enWordTextBlock.Text = Words.wordsArray[i]; //set text
}
private int counter = 0;
private void goButton_Click(object sender, RoutedEventArgs e)
{
enWordTextBlock.Text = Words.wordsArray[counter++ % Words.wordsArray.Length];
}
[Edit]
Ok, this is an edit related to user1397396 comment. I'm not sure I understand you correctly, but you might have a problem with negative value modulus. For example:
int counter = 0;
int mod = 4;
counter--; // counter is -1 after this line is executed
int result = counter % mod; // result is -1
result = (counter + mod) % mod; // result is now 3 as desired
Here is how I would implement these Next and Previous buttons.
private int counter = 0;
private void NextButton_Click(object sender, RoutedEventArgs e)
{
enWordTextBlock.Text = Words.wordsArray[counter % Words.wordsArray.Length];
counter++; // put ++ operator in new line to avoid confusion
}
private void PreviousButton_Click(object sender, RoutedEventArgs e)
{
int wordCount = Words.wordsArray.Length;
// add wordCount before applying modulus (%) to avoid negative results
// -1 % 5 = -1; -2 % 5 = -2; -6 % 5 = -1 etc
// negative values would cause exception when accessing array
counter = ((counter - 1) + wordCount) % wordCount;
enWordTextBlock.Text = Words.wordsArray[counter];
}
For example, this code would cause pressing Next, Previous, Next to give you this: "one", "four", "one".
Even better solution would be to use a method (or to inline code) such as this:
private static int GetPositiveIntModulus(int value, int mod)
{
return ((value % mod) + mod) % mod;
}
It will give you a positive result for any value, even when value < -mod. So you could write the code above like this:
private int counter = 0;
private void NextButton_Click(object sender, RoutedEventArgs e)
{
// uncomment this to ensure valid counter
// if it is changed somewhere else in the program
//counter = GetPositiveIntModulus(counter, Words.wordsArray.Length);
enWordTextBlock.Text = Words.wordsArray[counter];
counter = GetPositiveIntModulus(counter + 1, Words.wordsArray.Length);
}
private void PreviousButton_Click(object sender, RoutedEventArgs e)
{
counter = GetPositiveIntModulus(counter - 1, Words.wordsArray.Length);
enWordTextBlock.Text = Words.wordsArray[counter];
}

Textbox display formatting

I want to add "," to after every group of 3 digits. Eg : when I type 3000000 the textbox will display 3,000,000 but the value still is 3000000.
I tried to use maskedtexbox, there is a drawback that the maskedtexbox displayed a number like _,__,__ .
Try adding this code to KeyUp event handler of your TextBox
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text))
{
System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US");
int valueBefore = Int32.Parse(textBox1.Text, System.Globalization.NumberStyles.AllowThousands);
textBox1.Text = String.Format(culture, "{0:N0}", valueBefore);
textBox1.Select(textBox1.Text.Length, 0);
}
}
Yes, it will change the value stored in a texbox, but whenever you need the actual number you can use the following line to get it from the text:
int integerValue = Int32.Parse(textBox1.Text, System.Globalization.NumberStyles.AllowThousands);
Of course do not forget to check that what the user inputs into the textbox is actually a valid integer number.
Use String.Format
int value = 300000
String.Format("{0:#,###0}", value);
// will return 300,000
http://msdn.microsoft.com/en-us/library/system.string.format.aspx
This may work fine for your scenario I hope.
private string text
{
get
{
return text;
}
set
{
try
{
string temp = string.Empty;
for (int i = 0; i < value.Length; i++)
{
int p = (int)value[i];
if (p >= 48 && p <= 57)
{
temp += value[i];
}
}
value = temp;
myTxt.Text = value;
}
catch
{
}
}
}
private void digitTextBox1_TextChanged(object sender, EventArgs e)
{
if (myTxt.Text == "")
return;
int n = myTxt.SelectionStart;
decimal text = Convert.ToDecimal(myTxt.Text);
myTxt.Text = String.Format("{0:#,###0}", text);
myTxt.SelectionStart = n + 1;
}
Here, myTxt = your Textbox. Set Textchanged event as given below and create a property text as in the post.
Hope it helps.
You could hook up to OnKeyUp event like this:
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (!(e.KeyCode == Keys.Back))
{
string text = textBox1.Text.Replace(",", "");
if (text.Length % 3 == 0)
{
textBox1.Text += ",";
textBox1.SelectionStart = textBox1.Text.Length;
}
}
}
Get Decimal Value Then set
DecimalValue.ToString("#,#");

Categories

Resources