Masked Text Box - make comma optional - c#

Please see the screenshot below for a MaskedTextBox:
and the code below:
public Form1()
{
InitializeComponent();
this.Load += Form1_Load;
}
private void Form1_Load(object sender, EventArgs e)
{
maskedTextBox1.ValidatingType = typeof(System.Decimal);
maskedTextBox1.TypeValidationCompleted += new TypeValidationEventHandler(maskedTextBox1_TypeValidationCompleted);
}
void maskedTextBox1_TypeValidationCompleted(object sender, TypeValidationEventArgs e)
{
if (!e.IsValidInput)
{
MessageBox.Show("Validation failed");
}
else
{
Decimal value = (Decimal)e.ReturnValue;
MessageBox.Show("Validation suceeded");
}
}
}
e.IsValidInput is always false if I enter a value less than 1000. If I enter a value above 1,000 then it works i.e. the cast to a decimal works. I believe this is because the comma is missing with values less than 1,000. How do I make the comma optional?

Related

Taking Value From Text Box Into Total (VS - C#)

I am new to the C# scene, so don't really have much knowledge - This is my first project.
I am looking to create a very basic calorie counter, which eventually will include other functions.
Here's what I have so far;
I want to know how to take the value from the text box on the click of the 'Add' button - Which adds to the total value (bottom right)
I'm looking for any tips/videos to help so anything is appreciated.
TIA
I made a simple implementation for you, you could refer to it:
using System;
using System.Windows.Forms;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
bool Flag = Int32.TryParse(textBox1.Text, out int result);//Determine if it is a number
if (textBox1.Text == "")//If it is null, falg takes true and skips the next judgment
{ Flag = true; }
else if (!Flag)
{
MessageBox.Show("Input Error");
textBox1.Text = null;
}
}
private void button1_Click(object sender, EventArgs e)
{
Int32.TryParse(textBox1.Text, out int result);
int total =result + Convert.ToInt32(label3.Text);
label3.Text = total.ToString();
}
private void button2_Click(object sender, EventArgs e)
{
label3.Text = "0";
}
}
}

NumericupDown comparison Visual Studio c#

I have to make a quantile configuration and I have to set a condition so that the second value is higher than the first, the third value is higher than the second and so on. I am using numericupdowns and the value is set by the user. I tried to implement this code but it always shows a message box error even if the values are correct. This is my code so far (using Visual studio and C#):
decimal min = 1;
//when the first numeric is changed:
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
numericUpDown1.Minimum = min;
min = numericUpDown1.Value;
}
private void numericUpDown2_ValueChanged(object sender, EventArgs e)
{
min++;
numericUpDown2.Minimum = min;
min = numericUpDown2.Value;
}
private void numericUpDown3_ValueChanged(object sender, EventArgs e)
{
min++;
numericUpDown3.Minimum = min;
min = numericUpDown3.Value;
}
private void numericUpDown4_ValueChanged(object sender, EventArgs e)
{
min++;
numericUpDown4.Minimum = min;
numericUpDown4.Maximum = 99;
}
private void button_OK_Click(object sender, EventArgs e)
{
if (
numericUpDown1.Value > numericUpDown2.Value ||
numericUpDown2.Value > numericUpDown3.Value ||
numericUpDown3.Value > numericUpDown4.Value )
{
MessageBox.Show(
"Quantiles are not filled correctly",
"The quantiles aren't filled in correctly", MessageBoxButtons.OK, MessageBoxIcon.Error);
textBoxName.Select();
DialogResult = DialogResult.None;
return;
}
}
You need to keep all the NumericUpDown value inside a List or an array where you can manipulate them like a single entity trhough a loop.
Of course changing the minimum value of one of the numeric elements should be linked to a check for the current value inside that control because you can't have a current value lesser than the new minimum value.
So the first thing to do is to create a global variable inside your form class where you keep the references to all the numeric controls that you want to synchronize
public class Form1
{
private List<NumericUpDown> numbers = new List<NumericUpDown>();
public Form1 : Form
{
InitializeComponent();
numbers.AddRange(new [] {n1, n2,n3,n4,n5});
}
......
}
Now you can write a method like this one that adjust the minimum on all the numeric included in the list
private void UpdateMinimum()
{
for (int x = 0; x < numbers.Count-1; x++)
{
if(numbers[x].Value > numbers[x+1].Value)
numbers[x+1].Value = numbers[x].Value;
numbers[x+1].Minimum = numbers[x].Value;
}
}
finally you have all your NumericUpDown event ValueChanged call the same method
void numerics_ValueChanged(object sender, EventArgs e)
{
UpdateMinimum();
}
If you want to set a condition so that the second value is higher than the first, the third value is higher than the second and so on, you can refer to the following code:
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
numericUpDown1.Minimum = 1;
}
private void numericUpDown2_ValueChanged(object sender, EventArgs e)
{
numericUpDown2.Minimum = numericUpDown1.Value + 1;
}
private void numericUpDown3_ValueChanged(object sender, EventArgs e)
{
numericUpDown3.Minimum = numericUpDown2.Value + 1;
}
private void numericUpDown4_ValueChanged(object sender, EventArgs e)
{
numericUpDown4.Minimum = numericUpDown3.Value + 1;
numericUpDown4.Maximum = 99;
}
private void button_OK_Click(object sender, EventArgs e)
{
if (
numericUpDown1.Value > numericUpDown2.Value ||
numericUpDown2.Value > numericUpDown3.Value ||
numericUpDown3.Value > numericUpDown4.Value)
{
MessageBox.Show(
"Quantiles are not filled correctly",
"The quantiles aren't filled in correctly", MessageBoxButtons.OK, MessageBoxIcon.Error);
textBoxName.Select();
DialogResult = DialogResult.None;
return;
}
}
Here is the test result:

What is the C# data type that allows complex and imaginary numbers?

I am creating a C# project which takes two user inputs of complex numbers and completes a mathematical operation on them. The problem I am running into is how to parse i as the square root of -1.
double operandA = 0;
double operandB = 0;
double result = 0;
string textA, textB;
string error = "The value you entered is invalid, try again";
private void plus_Btn_Click(object sender, EventArgs e)
{
result = operandA + operandB;
}
private void Subtract_btn_Click(object sender, EventArgs e)
{
result = operandA - operandB;
}
private void mult_Btn_Click(object sender, EventArgs e)
{
result = operandA * operandB;
}
private void divide_Btn_Click(object sender, EventArgs e)
{
result = operandA / operandB;
}
private void textBox2_Leave(object sender, EventArgs e)
{
textB = textBox2.Text;
if (double.TryParse(textB, out operandB))
operandB = double.Parse(textB);
else
{
MessageBox.Show(error);
textBox2.Select();
}
}
private void textBox1_Leave(object sender, EventArgs e)
{
textA = textBox1.Text;
if (double.TryParse(textA, out operandA))
operandA = double.Parse(textA);
else
{
MessageBox.Show(error);
textBox1.Select();
}
}
It works fine on regular numbers, decimals, and negative numbers, but I can't figure out how to do the value of i that I need. Can anyone help? It has been suggested that I use System.Numeric.Complex, but whenever I try to do this using "Using System.Numerics.Complex" or simply "Using System.Numerics", it says this type/namespace does not exist inside 'System'.
If you want to support operations on complex numbers, you should consider using System.Numerics.Complex
Complex c = Complex.Sqrt(-1);
Console.WriteLine(c + 1);
For documentation on this type see here
You can use Complex in System.Numerics
https://msdn.microsoft.com/en-us/library/system.numerics.complex(v=vs.110).aspx

How to display input from textbox in a multiple lined textbox?

I need to make a program that takes the input of a textbox (tb_1) and puts it in the second textbox (tb_2, multilined) when a button is pressed. It also needs to paste the code a specific amount of times, depending on the numericupdown digit. I have come this far, what do i do next? Thanks in advance.
(Note: it should probably be done within a class.)
{
public Form1()
{
InitializeComponent();
}
private void tb_1_TextChanged(object sender, EventArgs e)
{
}
private void btn_1_Click(object sender, EventArgs e)
{
string tekst = tb_1.Text;
tb_2.Text = tekst + Environment.NewLine;
tb_1.Clear();
tb_2.Text = tekst + Environment.NewLine;
}
}
}

Sentence Builder app in c#

I am trying to complete an assignment for a new C# class using VS doing a windows form application (all new to me, code and all). We were assigned to creating a sentence builder with various words that were buttons; and then when the app runs, the user could click the buttons to build a sentence; which is then shown in the Label control.
Well, I have the form built, and from other info I found on this site for a similar question; have made it to this point. BUT my problem is - my instructor said we should be concatenating the results within the Label output, but FIRST I dont' know how to do that with someone just randomly clicking letters or words**(with what we have learned so far).
I got it to run with the following code(without concatenationin Label); except the "spaceButton" event puts IN the text of "(Space)" because that is it's text... I changed it to " " in the code and If I click on it running, it will now put in spaces but changes the text in the running app to a blank button. I don't know how to fix that.
I have had this instructor before and while I might be able to work around the concatenation in the "sentenceOutputLabel" - I might very well get a zero because I didn't concatenate in the output label.
Laura
Here is all 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 Sentence_Builder
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void upperCaseAButton_Click(object sender, EventArgs e)
{
string output;
output = upperCaseAButton.Text;
sentenceOutputLabel.Text += output;
}
private void lowerCaseAButton_Click(object sender, EventArgs e)
{
string output;
output = lowerCaseAButton.Text;
sentenceOutputLabel.Text += output;
}
private void upperCaseAnButton_Click(object sender, EventArgs e)
{
string output;
output = upperCaseAnButton.Text;
sentenceOutputLabel.Text += output;
}
private void lowerCaseAnButton_Click(object sender, EventArgs e)
{
string output;
output = lowerCaseAnButton.Text;
sentenceOutputLabel.Text += output;
}
private void upperCaseTheButton_Click(object sender, EventArgs e)
{
string output;
output = upperCaseTheButton.Text;
sentenceOutputLabel.Text += output;
}
private void lowerCaseTheButton_Click(object sender, EventArgs e)
{
string output;
output = lowerCaseTheButton.Text;
sentenceOutputLabel.Text += output;
}
private void manWordButton_Click(object sender, EventArgs e)
{
string output;
output = manWordButton.Text;
sentenceOutputLabel.Text += output;
}
private void womanWordButton_Click(object sender, EventArgs e)
{
string output;
output = womanWordButton.Text;
sentenceOutputLabel.Text += output;
}
private void dogWordButton_Click(object sender, EventArgs e)
{
string output;
output = dogWordButton.Text;
sentenceOutputLabel.Text += output;
}
private void catWordButton_Click(object sender, EventArgs e)
{
string output;
output = catWordButton.Text;
sentenceOutputLabel.Text += output;
}
private void carWordButton_Click(object sender, EventArgs e)
{
string output;
output = carWordButton.Text;
sentenceOutputLabel.Text += output;
}
private void bicycleWordButton_Click(object sender, EventArgs e)
{
string output;
output = bicycleWordButton.Text;
sentenceOutputLabel.Text += output;
}
private void beautifulWordButton_Click(object sender, EventArgs e)
{
string output;
output = beautifulWordButton.Text;
sentenceOutputLabel.Text += output;
}
private void bigWordButton_Click(object sender, EventArgs e)
{
string output;
output = bigWordButton.Text;
sentenceOutputLabel.Text += output;
}
private void smallWordButton_Click(object sender, EventArgs e)
{
string output;
output = smallWordButton.Text;
sentenceOutputLabel.Text += output;
}
private void strangeWordButton_Click(object sender, EventArgs e)
{
string output;
output = strangeWordButton.Text;
sentenceOutputLabel.Text += output;
}
private void lookedAtWordButton_Click(object sender, EventArgs e)
{
string output;
output = lookedAtWordButton.Text;
sentenceOutputLabel.Text += output;
}
private void rodeWordButton_Click(object sender, EventArgs e)
{
string output;
output = rodeWordButton.Text;
sentenceOutputLabel.Text += output;
}
private void spokeToWordButton_Click(object sender, EventArgs e)
{
string output;
output = spokeToWordButton.Text;
sentenceOutputLabel.Text += output;
}
private void laughedAtWordButton_Click(object sender, EventArgs e)
{
string output;
output = laughedAtWordButton.Text;
sentenceOutputLabel.Text += output;
}
private void droveWordButton_Click(object sender, EventArgs e)
{
string output;
output = droveWordButton.Text;
sentenceOutputLabel.Text += output;
}
private void spaceButton_Click(object sender, EventArgs e)
{
string output;
output = spaceButton.Text = " ";
sentenceOutputLabel.Text += output;
}
private void periodButton_Click(object sender, EventArgs e)
{
string output;
output = periodButton.Text;
sentenceOutputLabel.Text += output;
}
private void exclamButton_Click(object sender, EventArgs e)
{
string output;
output = exclamButton.Text;
sentenceOutputLabel.Text += output;
}
/ I DON'T EVEN KNOW WHAT I NEED THIS below FOR NOW
private void sentenceOutputLabel_Click(object sender, EventArgs e)
{
//string output;
// sentenceOutputLabel.Text = sentenceOutputLabel.Text;
}
private void clearButton_Click(object sender, EventArgs e)
{
sentenceOutputLabel.Text = "";
}
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
}
}`
If I understood the assignment description correctly, this is what I would do:
using System;
using System.Windows.Forms;
namespace StringBuilder
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void btnInput_Click(object sender, EventArgs e)
{
Button button = sender as Button;
if (button != null)
{
if (button.Text == "Space")
lblOutput.Text += " ";
else
lblOutput.Text += button.Text;
}
}
}
}
With this code, every single button can be assigned to the btnInput_Click event handler, and lblOutput is just the output.
I think the solution might just be so simple, it didn't occur to you it was allowed:
private void spaceButton_Click(object sender, EventArgs e)
{
string output;
output = " "; // don't necessarily have to use the Text property of the button ...
sentenceOutputLabel.Text += output;
}
I won't give you the solution, but maybe I can provide a bit more guidance and assist in the learning process.
First off, the value you're concatenating doesn't have to come from the button itself. The way you have it setup, each button has a designated event (*_CLick(object,EventArgs)). If you already know what button's being click, using that button's .Text isn't really necessary. So, feel free to use the desired result within this method and not stick to the button's .Text.
Also, based on what you've described, you're fulfilling the concatenation part (you seem reluctant to believe this). Every time you append (+=) the clicked item's text to the label's current value you're concatenating (just C# is doing to work for you).
To take it a step further though, each control has a Tag property. This allows you to specify metadata and bind it to that specific control. You may want to consider specifying the desired output (with regards to what's added to the final label) as the button's tag, then appending that value (over the button's Text). You could also re-use a single *_Click(object,EventArgs) method and just concatenate ((Button)sender).Tag.
Here's an example of how you can use a common click event, and how you can use the Tag property to store the value to be added to the label (which may be different than the value displayed on the Button text).
I'm dynamically adding the buttons, which you wouldn't have to do, but this way you can copy/past the code into a new project and run it. Hopefully it is instructive, but not something you would turn in as your own work.
public partial class Form1 : Form
{
Label sentenceOutputLabel = new Label();
public Form1()
{
InitializeComponent();
int padding = 10;
// Add a label to the form
sentenceOutputLabel.Width = ClientSize.Width - (padding * 2);
sentenceOutputLabel.Top = padding;
sentenceOutputLabel.Left = padding;
sentenceOutputLabel.BorderStyle = BorderStyle.FixedSingle;
Controls.Add(sentenceOutputLabel);
// List of words that, for each one, we'll add a button to the form
// Note that some words have two parts: the first part is the button
// text, followed by a colon, then followed by the tag text. We split
// these out later, when assigning button properties
var words = new List<string>
{
"A", "a", "An", "an", "The", "the", "man", "woman", "dog", "cat",
"car", "bicycle", "beautiful", "big", "small", "strange", "looked",
"rode", "spoke", "laughed at", "drove", "[space]: ", "[period]:.",
"[exclamation]:!"
};
// Get the width of the longest word so we size the buttons accordingly
int width;
using (Graphics cg = CreateGraphics())
{
width = Convert.ToInt32(cg.MeasureString(words.Aggregate("", (max, cur) =>
(cg.MeasureString(max, new Button().Font).Width) >
(cg.MeasureString(cur, new Button().Font).Width)
? max
: cur), new Button().Font).Width);
}
// Add the buttons to the form, spacing them evenly
int left = padding;
int top = sentenceOutputLabel.Bottom + padding;
int bottomOfLastButton = 0;
foreach (var word in words)
{
// For some words, we have a colon-separated symbol that we
// will use instead of the word (like 'space', for example)
// So we store the symbol in the 'Tag' property and the word
// in the text property.
var wordParts = word.Split(':');
var text = wordParts[0];
var tag = wordParts.Length > 1 ? wordParts[1] : text;
var button = new Button
{
Text = text,
Tag = tag,
Left = left,
Top = top,
Width = width,
Visible = true
};
// HERE WE ADD A COMMON CLICK EVENT
button.Click += wordButton_Click;
// Add the button to the form
Controls.Add(button);
// Reset left and top if we're going past the width of the form
left += (width + padding);
if (left + width + padding > ClientSize.Width)
{
left = padding;
top += button.Height + padding;
}
bottomOfLastButton = button.Bottom;
}
// Add a clear and exit button
var exitButton = new Button
{
Top = bottomOfLastButton + (padding * 2),
Text = "Exit",
Left = ClientSize.Width - padding - width,
Width = width
};
exitButton.Click += exitButton_Click;
var clearButton = new Button
{
Top = bottomOfLastButton + (padding * 2),
Text = "Clear",
Left = exitButton.Left - padding - width,
Width = width
};
clearButton.Click += clearButton_Click;
Controls.Add(exitButton);
Controls.Add(clearButton);
}
void clearButton_Click(object sender, EventArgs e)
{
sentenceOutputLabel.Text = "";
}
void exitButton_Click(object sender, EventArgs e)
{
Close();
}
void wordButton_Click(object sender, EventArgs e)
{
var wordButton = sender as Button;
if (wordButton != null)
{
sentenceOutputLabel.Text += wordButton.Tag;
}
}
}

Categories

Resources