Error check for non-numerical data - c#

I was hoping someone could help with an error check for my paste method. I would like to prevent pasting anything that is not a numeric value from clipboard into my textBox. The coding for pasting is listed below.
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
// Determine if there is any text in the Clipboard to paste into the text box.
if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text) == true)
{
// Determine if any text is selected in the text box.
if (textBox1.SelectionLength > 0)
{
// Ask user if they want to paste over currently selected text.
if (MessageBox.Show("Do you want to paste over current selection?", "Cut Example", MessageBoxButtons.YesNo) == DialogResult.No)
// Move selection to the point after the current selection and paste.
textBox1.SelectionStart = textBox1.SelectionStart + textBox1.SelectionLength;
} // end if
} // Paste current text in Clipboard into text box.
textBox1.Paste();
} // end pasteToolStripMenuItem

If you want to include Currency symbols, decimal places, Thousand seperators etc. Int.Parse is probably your best bet
public bool IsValidNumber(string input)
{
int val = 0;
return int.TryParse(input.Trim(), NumberStyles.Any, null, out val);
}
"$100,000" = true
"100.002" = true
"1000,44j" = false
etc.

Related

How to use RichTextBox.SelectionColor property to identify multiple text's background colors in C#?

I have a RichTextBox. I'm trying to code so that if a specific color is found in the SelectionBackColor property of the RTB, the background color of the words/ texts to be removed. For that, I need to detect if there exists multiple colors in the RTB. However, according to the documentation,
If the current text selection has more than one color specified, this property returns Color.Empty.
This is what I've tried so far:
private void randomBtn_Click(object sender, EventArgs e)
{
int startIndex = 0; //start from beginning of the richTextBox1
int endIndex = this.richTextBox1.TextLength; //until the end of all text available
this.richTextBox1.Select(startIndex, endIndex); //select from start until the end
if(endIndex != 0)
{
for(int i=startIndex; i< endIndex; i++)
{
if (this.richTextBox1.Text[i].ToString().Contains(" ")) //skips white spaces
{
continue;
}
else
{
while ((this.richTextBox1.BackColor != Color.Empty))
{
if (this.richTextBox1.SelectionBackColor.R == 155 && this.richTextBox1.SelectionBackColor.G == 255 && this.richTextBox1.SelectionBackColor.B == 255)
{
this.richTextBox1.HideSelection = true; //to prevent text highlighted
MessageBox.Show(this, "Texts with RGB(155, 255, 255) found!", "", MessageBoxButtons.OK);
break;
}
else
{
this.richTextBox1.HideSelection = true;
MessageBox.Show(this, "Error!", "", MessageBoxButtons.OK);
break;
}
}
}
}
}
else
{
MessageBox.Show(this, "richTextBox1 is empty!", "Alert!", MessageBoxButtons.OK);
}
}
To test, I added a breakpoint at the code containing the while line. Below shows the success and fail criterion,
The code works if:
There is no whitespace(at all)
There is only one color in the RTB
The code fails if:
There are whitespaces in between texts/ words/ characters
There are multiple colors in the RTB
Below shows the program execution examples:
This is when only one color is applied in the RTB(success),
This is when only one color and a whitespace are applied in the RTB(fail),
This is when multiple colors and whitespaces are applied in the RTB(fail),
So, is there any ways to override the return value of the SelectionColor property to be able to detect multiple colors, or are there any other ways of doing this? Just so you know, I've searched for this kind of problem over the internet, but I didn't think I've find any related issues.
It took me a while to figure out what #TaW meant in the comment section, but thanks to him, I've managed to solve this issue.
Actually, based on my reply in the comment section that I asked #TaW, what I thought as the same concept, was actually wrong. In the post above, what I did was entirely wrong:
I was supposed to assess each text one by one to know what their colors are. However, the codes below were already wrong to begin with.:
int startIndex = 0;
int endIndex = this.richTextBox1.TextLength;
this.richTextBox1.Select(startIndex, endIndex);
To analyze how RTB.SelectionColor, RTB.SelectionStart, and RTB.SelectionLength work, I decided to create another project. The project is a simple program containing an RTB, and some other buttons to manage the RTB's SelectionColor. If you want to check for the project that I've done, you're always welcomed to visit this link.
From "2", I re-used all the codes to suit the original project that I was working on. Now, it's all fine and working as it should.
To note, there are two important concepts/ ideas on managing the Selection property of the RTB.
If you are concerned of assessing each and every text in the RTB, you should code it like this:
private void methodA(RichTextBox localRTB)
{
//go through text one by one
int startIndex = 0;
int endIndex = localRTB.TextLength;
localRTB.SelectionStart = startIndex;
localRTB.SelectionLength = 1; //always 1 'cuz we want to assess each text one by one
while (localRTB.SelectionStart < endIndex)
{
//if the SelectionBackColor is red, change it to white
if (localRTB.SelectionBackColor == Color.Red) //take red color for example
{
localRTB.SelectionBackColor = Color.White;
}
//--manage bg color of selected text in RTB--
//so that able to go to next text
localRTB.SelectionStart += 1;
}
//finally...
localRTB.DeselectAll(); //unselect text in RTB
localRTB.Select(); //set focus back to the RTB
}
Below shows the result of the codes above(1):
If you don't really care about assessing each and every text in the RTB, you should code it like this instead:
private void methodB(RichTextBox localRTB)
{
int startIndex;
int endIndex;
if (localRTB.SelectionLength.Equals(0)) //if user don't select any text
{
startIndex = 0; //from beginning of RTB
endIndex = localRTB.TextLength; //'til the end of RTB
//--manage selected text in the RTB--
localRTB.SelectionStart = startIndex;
localRTB.SelectionLength = endIndex;
localRTB.Select(localRTB.SelectionStart, localRTB.SelectionLength);
//--manage selected text in the RTB--
}
else if (!(localRTB.SelectionLength.Equals(0))) //if user has text selected
{
startIndex = localRTB.SelectionStart; //from beginning of RTB
endIndex = localRTB.SelectionLength; //'til the end of RTB
if (localRTB.SelectedText.Contains(" ")) //skips whitespaces if selected together with text
{
if (localRTB.SelectedText.EndsWith(" "))
{
endIndex -= 1;
}
}
//--manage selected text in the RTB--
localRTB.Select(startIndex, endIndex);
//--manage selected text in the RTB--
}
}
Below shows the result of the codes above(2):
Peace...✌️

How to assign values for check boxes for a formula calculation which includes a text box in the formula

I am a new programmer learning to code in C# and I have an C# assignment to be finished and for that I need to make some formulas to calculate rent for tours and for that I decided to use text boxes and check boxes in C# but I cant figure out how to make a formula with the combination of check boxes and a text box.
private void button1_Click_1(object sender, EventArgs e)
{
checkBox1.Text = "50000";
checkBox2.Text = "250000";
checkBox3.Text = "2500";
checkBox4.Text = "10000";
checkBox5.Text = "1500";
if (checkBox1.CheckState == CheckState.Checked &&
checkBox2.CheckState == CheckState.Checked)
{
}
}
The type of control has little to do with creating a formula. To create the formula, you need to know all it's possible inputs and how they should be combined to produce the output. This could be done in a method, for example:
private int GetTotalValue(int vehiclePrice, int driverPrice, int rentDuration)
{
// This is where your formula would go
return (vehiclePrice + driverPrice) * rentDuration;
}
The trick then, is to convert the state of the form controls into values that you can plug into the method. One way to do this (not necessarily the best way, but probably easiest to understand when you're starting) is to check the value of each control and set the appropriate value in the Click event for your Submit button.
For the rent duration, we can use the int.TryParse method, which takes in a string and an "out" int parameter, and returns true if the string is a valid integer, or false if it's not. When it exits, if the conversion was successful, the out parameter will contain the int value.
For the other controls, we could use simple if / else if statements to determine which control was checked, and then set our value accordingly. In this example, we're using temporary variables inside the click event to store the value for each parameter to the method. If none of the required controls are checked, we can show a message to the user and wait for them to finish filling out the form.
In this example I used radio buttons (and used the opt prefix, which is a naming convention from a long time ago that I'm not sure still exists - they used to be called option buttons):
private void btnSubmit_Click(object sender, EventArgs e)
{
// Validate that rent textbox contains a number
int rentDuration;
if (!int.TryParse(txtRentDuration.Text, out rentDuration))
{
MessageBox.Show("Please enter a valid number for rent duration");
return;
}
// Determine vehicle price based on which option was selected
int vehiclePrice;
if (optToyotaPrado.Checked) vehiclePrice = 50000;
else if (optRollsRoyce.Checked) vehiclePrice = 250000;
else if (optSuzikiWagonR.Checked) vehiclePrice = 2500;
else if (optToyotaCorolla.Checked) vehiclePrice = 10000;
else
{
MessageBox.Show("Please select a vehicle");
return;
}
// Determine driver price
int driverPrice;
if (optWithDriver.Checked) driverPrice = 1500;
else if (optWithoutDriver.Checked) driverPrice = 0;
else
{
MessageBox.Show("Please select a driver option");
return;
}
// Finally set the text to the return value of our original method,
// passing in the appropriate values based on the user's selections
txtTotalValue.Text = GetTotalValue(vehiclePrice, driverPrice, rentDuration).ToString();
}
As Rufus said, I'd go with RadioButtons, instead of CheckBoxes. Set the Tag property of the RadioButtons to the vaule you want associated with them and then use a function like this to get the value of the checked item. Just pass in the GroupBox to the function and get back the value of the checked RadioButton.
private int GetGroupBoxValue(GroupBox gb)
{
int nReturn = 0;
foreach (Control ctl in gb.Controls)
{
if (ctl.GetType() == typeof(RadioButton))
{
if (((RadioButton)ctl).Checked)
{
nReturn = Convert.ToInt32(ctl.Tag);
break;
}
}
}
return nReturn;
}
Now all you have to do is use the excellent code Rufus provided for checking for an integer in the rentDuration TextBox and you're golden.

Wpf Richtextbox selection starting column and row number returns different values

I am initializing my Richtextbox,
void InitRTBFlowDocument()
{
Style noSpaceStyle = new Style(typeof(Paragraph));
noSpaceStyle.Setters.Add(new Setter(Paragraph.MarginProperty, new Thickness(0)));
rtbTextEditor.Resources.Add(typeof(Paragraph), noSpaceStyle);
}
I want to get Richtext box selection words row and column numbers. I wrote the code as follows, First time it is returning correctly.
void rtbTextEditor_SelectionChanged(object sender, RoutedEventArgs e)
{
//Get the richtext box selected text
Init.RTBSelectionText = rtbTextEditor.Selection.Text.Trim();
Init.SelectionText = rtbTextEditor.Selection.Text.Trim();
Init.isSelect = true;
if (Init.RTBSelectionText != string.Empty)
{
TextPointer tp = rtbTextEditor.Selection.Start.GetPositionAtOffset(-2, LogicalDirection.Forward);
if (tp != null)
GetStartingIndex();
}
Init.RTBContent = new TextRange(rtbTextEditor.Document.ContentStart, rtbTextEditor.Document.ContentEnd).Text;
}
void GetStartingIndex()
{
TextPointer tp1 = rtbTextEditor.Selection.Start.GetLineStartPosition(0);
TextPointer tp2 = rtbTextEditor.Selection.Start;
int SelectionColumnIndex = tp1.GetOffsetToPosition(tp2)-1;//column number
int someBigNumber = int.MaxValue;
int lineMoved;
rtbTextEditor.Selection.Start.GetLineStartPosition(-someBigNumber, out lineMoved); //Line number
int SelectionRowIndex = -lineMoved;
Init.RTBTextPoint = new RTBTextPointer();
Init.RTBTextPoint.Row = SelectionRowIndex;
Init.RTBTextPoint.Column = SelectionColumnIndex;
}
After clearing and added new content, The position returns wrong number,
public void DisplayContent(string content)
{
//Clear the rich text box
rtbTextEditor.Document.Blocks.Clear();
rtbTextEditor.Document.Blocks.Add(new Paragraph(new Run(content)));
}
Is anything rong in the above code.
Please help me
Thanks in advance!
This is because the contents in the RTB does not only contain text, it contains these things called TextPointerContext's. TextPointer's take this into account. You can check what the TextPointer is adjacent to by using:
TextPointer.GetPointerContext(LogicalDirection);
To get the next TextPointer:
TextPointer.GetNextContextPosition(LogicalDirection);
Some sample code I used in a recent project, this makes sure that the pointer context is of type Text:
while (start.GetPointerContext(LogicalDirection.Forward)
!= TextPointerContext.Text)
{
start = start.GetNextContextPosition(LogicalDirection.Forward);
if (start == null) return;
}
When you clear your RTB, you're probably removing some of these pointer contexts. So be careful when using GetPositionAtOffset(). This should give you a "pointer" in the right direction. If you need any more help me know.
Good hunting!

What button pressed inputbox C#

I am using the input box from visual basic in c# and I couldn't figure out how I know what button has been pressed. The input box return the string that has been written.
How I know if the cancel button has been clicked or the OK button?
Thank you very much for the help, I didn't find the answer :)
This is what I tried:
string notineName = Interaction.InputBox("Enter the notice name:", "Enter notice name", "");
If you have another way to do input box ( I wanted to make my own but I don't know how to return what button has been clicked) please write it here.
If the user clicks Cancel, a zero-length string is returned.
Try having a look at this documentation. MSDN
As an alternative you could use dialog boxes.
InputDialog dialog = new InputDialog("Caption Here", "Label Text Here", "Default Textbox String");
if (dialog.ShowDialog() == DialogResult.OK)
{
string result_text = dialog.ResultText;
// use result_text...
}
else
{
// user cancelled out, do something...
}
Here an enum result determines what button was selected.
string a;
a = Interaction.InputBox("message", "message");
if (a.Length > 0)
{
comboBox2.Items.Add(a);
// ok
}
else
{
// cancel
}

Filtering paste in Silverlight 4

I have TextBox which allow insert only numeric values (filtering), But when I paste copied text it's allow any kind of symbol. How can I prevent or filter text before pasting?
You could backup your text before any manual input and then when the input provided isn't valid restore the previous text like so:
_backupText = string.Empty;
doNotPasteTextBox.TextInputStart += (sender, e) =>
{
int textParsed;
if(int.TryParse(e.Text,out textParsed))
{
_backupText = doNotPasteTextBox.Text.Insert(doNotPasteTextBox.SelectionStart, e.Text);
}else
{
e.Handled = true;
}
};
doNotPasteTextBox.TextChanged += (sender, e) =>
{
int textParsed;
int selectionStart = doNotPasteTextBox.SelectionStart;
if(!int.TryParse(doNotPasteTextBox.Text, out textParsed))
{
doNotPasteTextBox.Text = _backupText;
}
doNotPasteTextBox.SelectionStart = selectionStart;
};
I wouldn't recommend trying to capture the control keys or anything because when you're on a mac or on linux then you're screwed.
Adjust my sample and pour it inside a new textbox control to make it cleaner but you get the idea.
You could use Clipboard.GetText() to get the text that is inserted into the textbox, but this will pop up a message, and the user must give the application access to the Clipboard.
If its no problem for you then i would use this.

Categories

Resources