Detecting input consisting of just spaces - c#

I have a wepage for a user to sign up,i have tested it and runned it,i was testing it using space not entering any words to signup,meaning a user can signup without entering any words just by using space.so i dont want this to happen to my webpage.
any one who has some code that i can use to validate this...

You can use the method: string.IsNullOrWhiteSpace to check

either the simple string.IsNullOrWhiteSpace
or if you really want to use the answer you chose, you should edit it to:
if (firstName ! = null && lastName ! = null)
{
if (firstName.Trim()=="" || lastName.Trim()=="")
{
return False;
}
else
{
return True;
}
}
else return False;

you can validate user input in many ways. One of them is to use built in Visual Studio Vaidator controls and make sure that each control is tighed to a text box in your form and its preoperty is selected to ensure the field is filled before submitting the form.
Another way is to do the validation from the code behind. Something like this:
if (firstName.Trim()=="" || lastName.Trim()=="")
{
return False;
}
else
{
return True;
}

Related

Int field in Winform does not update null values in SQL Server database using C#

In my Winforms C# application, I have fields with Int data type and they are set to accept null values in SQL Server database (allow nulls).
In the forms I have some textboxes which are bound to those int data type fields. If I don't enter anything while creating a new record, it accepts. If I enter a number in the textbox, it also accepts it, and then if I delete it, it doesn’t accept it anymore and even doesn't allow me to move to the next field.
If I set its value as null or "" through code, it simply ignores and does not even update changes which I made in other non int text fields.
I am using following method to update.
this.Validate();
this.itemsbindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.sBSDBDataSet);
What can I do for the textbox to accept null values?
I have tried following.
IDTextBox.Text = "";
IDTextBox.Text = null;
I have tried following with the help of above solutions (specially Mr. Ivan) and this is how it worked out.
To clear the int field on the form:
IDTextBox.Text = String.Empty;
Then on Designer.cs file of the form, as suggested by Mr. Ivan, I searched for 'IDtextbox.DataBindings.Add' and replaced
this.IDTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.itemsbindingSource, "PictureID", true));
with
this.IDTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.itemsbindingSource, "PictureID", true, System.Windows.Forms.DataSourceUpdateMode.OnValidation, ""));
It took me a whole day to search and finally I posted my problem here, and it got solved in 1 hour.
This seems to be one of the WF data binding bugs. I can't say what exactly is causing it, but in order to make it work one should set Binding.NullValue property to "" (empty string, the default is null).
I couldn't find a way to do that in the designer, and also it would be quite annoying to locate all text boxes needed. So I would suggest you the following quick-and-dirty approach. Create a helper method like this:
public static class ControlExtensions
{
public static void FixTextBoxBindings(this Control control)
{
if (control is TextBox)
{
foreach (Binding binding in control.DataBindings)
if (binding.NullValue == null) binding.NullValue = "";
}
foreach (Control child in control.Controls)
child.FixTextBoxBindings();
}
}
and then simply include the following in your form Load event:
this.FixTextBoxBindings();
TextBox dont accept null value.
You can check if it null and set String.Empty;
If(dbValue == null)
{
IDTextBox.Text = String.Empty;
}
else
{
// here set value to your textbox
}

Validating required fields and confirming fields in c# visual studio

I am having trouble with creating a form that requires the user to enter information in the fields, Confirm an email and password entry, and go onto the next form when all those fields are matched/filled in. Individually, the code I have works, but I cannot seem to find a way to make it so that all the requirements are met before going onto the next form. At the moment it just goes onto the next form if i click the continue button.
some excerpts of the code i have are:
if (string.IsNullOrEmpty(email))
{
lblRequirementsError.Text = ("All required fields have not been filled.");
}
if (txtBoxEmail.Text != txtBoxConfirmEmail.Text)
{
lblEmailError.Text = ("Email reentry does not match. Please reenter.");
}
if (txtBoxPassword.Text != txtBoxConfirmPassword.Text)
{
lblPasswordError.Text = ("Password reentry does not match. Please reenter.");
}
this.Hide();
frmBilling secondForm = new frmBilling();
secondForm.Show();
The problem is the form is created and opened regardless of the if results, because the code for it is outside the ifs. First, check that no fields are empty, and then, check that the validation has been met, THEN open the new window. Something like this should work:
//If both email and password are not empty
if (!string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(password))
{
//if both email and password math the re entry
if (txtBoxEmail.Text == txtBoxConfirmEmail.Text &&
txtBoxPassword.Text == txtBoxConfirmPassword.Text)
{
//execute the code to open the new form
this.Hide();
frmBilling secondForm = new frmBilling();
secondForm.Show();
}
}
if (! txtBoxEmail.Text.Equals( txtBoxConfirmEmail.Text))
{
lblEmailError.Text = ("Email reentry does not match. Please reenter.");
}
if (! txtBoxPassword.Text.Equals( txtBoxConfirmPassword.Text))
{
lblPasswordError.Text = ("Password reentry does not match. Please reenter.");
}
are you using web applications forms in visual studio 2012. You can use field validators inside the .ASPX file for any field that you want to validate before form submission. This is much easier that writing everything in C#.
You can use the DataAnnotation if you are binding or converting your controls to the data objects. Then it will be easy to validate. Please see the link for more details
http://msdn.microsoft.com/en-us/library/dd901590(VS.95).aspx
Try this:
bool validationStatus = default(bool);
if (string.IsNullOrEmpty(email))
{
lblRequirementsError.Text = ("All required fields have not been filled.");
validationStatus = true;
}
if (txtBoxEmail.Text != txtBoxConfirmEmail.Text)
{
lblEmailError.Text = ("Email reentry does not match. Please reenter.");
validationStatus = true;
}
if (txtBoxPassword.Text != txtBoxConfirmPassword.Text)
{
lblPasswordError.Text = ("Password reentry does not match. Please reenter.");
validationStatus = true;
}
if(!validationStatus)
{
Hide();
frmBilling secondForm = new frmBilling();
secondForm.Show();
}

FastColoredTextbox AutoWordSelection?

FastColoredTextbox is an user-control that can be downloaded in this url, it looks like this:
Its an amazing control but only can select one word when doubleclicking on the text, can't hold the mouse to select more words, so it only selects the entire current word over the mouse pointer even if you try to move the mouse cursor to left or right to select more text.
I have not found any information explaining the problem, and all of the official example projects has this problem.
Nobody means how to make an AutoWordSelection equivalent of a default TextBox for a FastcoloredTextbox control, but even the most important thing is:
How to select just more than one word with the mouse?
UPDATE:
#mostruash answer is very instructive but in all this time I could not carry out the modifications by myself.
I need a huge help from a C# programmer to carry out this task, my knowledge of C# is very low and the modifications that I made to the source did not work (don't compiled), I went back to the original user-control source to not end up spoiling more. I hate to say this but this time I need the job done, this source is too much for me.
If I'm requesting for too much then maybe with the necesary extended instructions of a C# developer, explaining how to accomplish this step by step, maybe I could carry it out by myself.
UPDATE
A video that demostrates the problem:
https://www.youtube.com/watch?v=Cs2Sh2tMvII
UPDATE
Another demo, I show what the FastColoredTextBox can't do but I would like to do like every other text-editor can do:
I've checked the source code of the project. Dragging is cancelled if a double click occurs and SelectWord is called.
You could modify the source code to include the feature that you request. (https://github.com/PavelTorgashov/FastColoredTextBox). In that case:
You must trace selections that start with double clicks.
Instead of calling SelectWord function, use the Selection class and draggedRange attribute to mark the selected word in OnMouseMove.
You also must handle deselection of words in OnMouseMove.
You must also select spaces between words in OnMouseMove.
The double click is handled in the code piece below:
if (!isLineSelect)
{
var p = PointToPlace(e.Location);
if (e.Clicks == 2)
{
mouseIsDrag = false; //Here, drag is cancelled.
mouseIsDragDrop = false;
draggedRange = null; //Drag range is nullified
SelectWord(p); //SelectWord is called to mark the word
return;
}
if (Selection.IsEmpty || !Selection.Contains(p) || this[p.iLine].Count <= p.iChar || ReadOnly)
OnMouseClickText(e);
else
{
mouseIsDragDrop = true;
mouseIsDrag = false;
}
}
EDIT:
This may require a lot of work to accomplish. So maybe you should use another tool/library. I have not studied the whole source code so there will probably be additional steps to those provided above.
For example, to trace double clicks you can do the following:
Define a class variable/property in FastColoredTextbox.cs: bool isDoubleClick.
Set it to true in OnMouseDown under if(e.Clicks == 2) condition. Set it to false in all other conditions.
Set it to false in OnMouseClick or OnMouseUp or in other relevant mouse event handlers.
That way you will know if series of mouse events had started with a double click event or not. Then you would act accordingly in OnMouseMove because that is where you (un)mark characters or (un)mark words.
LAST WORDS OF CAUTION:
The author of that project did not include any inline comments or any other means of documentation so you will be studying the code line by line to understand what each function/part does.
Add the following statement between Line 5276 and line 5277 in the class FastColoredTextBox.cs:
SelectWord(p);
mouseIsDrag = true; // here
return;
Note that implementing the ultimate behavior would require a good bunch of coding. Whereas the workaround mentioned above might satisfy your needs.
As #mostruash points out in his answer, that is the place where author cancels the mouse drag. Not sure why he deliberately prevents this feature. Only he knows.
if (e.Clicks == 2)//Line 5270
{
mouseIsDrag = false;
mouseIsDragDrop = false;
draggedRange = null;
SelectWord(p);
return;
}
I didn't read whole code, and I have no reason to do it. I just checked quickly and removed them. And it works as you expect.
if (e.Clicks == 2)//Line 5270
{
//Comment or remove completely.
//mouseIsDrag = false;
//mouseIsDragDrop = false;
//draggedRange = null;
SelectWord(p);
return;
}
Note: Am not sure this breaks something else, I've not tested. At least that works. Test it yourself.
My solution is a bit tweaky, but seems to work at first glance.
You have to make some changes in the Code:
Add mouseIsWholeWordSelection flag and a Range variable which can store the initial selected range after double click (best after line 100, I guess):
private bool mouseIsWholeWordSelection;
private Range mouseIsWholeWordSelectionBaseRange;
Change the selection code for double click event as stated above and extend it a bit (line 5222):
if (e.Clicks == 2)
{
//mouseIsDrag = false;
mouseIsDragDrop = false;
mouseIsWholeWordSelection = true;
//draggedRange = null;
SelectWord(p);
mouseIsWholeWordSelectionBaseRange = Selection.Clone();
return;
}
Add evaluation of dragging event for recreating selection (line 5566):
else if (place != Selection.Start)
{
if (mouseIsWholeWordSelection)
{
Selection.BeginUpdate();
var oldSelection = Selection.Clone();
SelectWord(place);
if (Selection.End >= mouseIsWholeWordSelectionBaseRange.End)
{
Selection.Start = (mouseIsWholeWordSelectionBaseRange.Start > Selection.Start) ? mouseIsWholeWordSelectionBaseRange.Start : Selection.Start;
Selection.End = mouseIsWholeWordSelectionBaseRange.End;
}
else if (Selection.Start < mouseIsWholeWordSelectionBaseRange.End)
{
Selection.Start = new Place(Selection.End.iChar, Selection.End.iLine);
Selection.End = mouseIsWholeWordSelectionBaseRange.Start;
}
Selection.EndUpdate();
DoCaretVisible();
Invalidate();
}
else
{
Place oldEnd = Selection.End;
Selection.BeginUpdate();
if (Selection.ColumnSelectionMode)
{
Selection.Start = place;
Selection.ColumnSelectionMode = true;
}
else
Selection.Start = place;
Selection.End = oldEnd;
Selection.EndUpdate();
DoCaretVisible();
Invalidate();
}
return;
}
Add at every place where isMouseDrag is being set to false:
isMouseWholeWordSelection = false;
And there you go.

validating radio button

I am programming in c# and I have some radio buttons in my form, and I want to make validation assuring that the user selected all the radio buttons in the button, so my method is :
public bool check_radiobutton(RadioButton radio1, RadioButton radio2)
{
//none of them aare selected
if ((radio1.Checked) && (radio2.Checked))
{
return false;
}
else
{
MessageBox.Show("You forgot to select a radiobutton!");
}
return true;
}
but it did not work
For each pair of radio button you have (or for each set, being it pairs for yes/no questions). You must check if at least (in fact if only) one of the options is checked. That is you want to check if:
(radio1.Checked) || (radio2.Checked)
Why is it? Because this way you are asking if radio1 is checked or else if radio2 is checked. Otherwise, if you keep:
(radio1.Checked) && (radio2.Checked)
You are asking if radio1 is checked and also if radio2 is checked. Which can't be, that's like requesting to answer both "yes" and "no". Of course this will never evaluate to true, unless there is something inherentily wrong with the universe.
From your comment:
//none of them aare selected
I guess you were trying to use D' Morgan's law, which applied to this cases states that:
(radio1.Checked) || (radio2.Checked) == !((!radio1.Checked) && (!radio2.Checked))
You can read this code:
!((!radio1.Checked) && (!radio2.Checked))
As follows: If it's false that (radio1 is not checked and also radio2 is not checked). That will be false only if both are not checked, which is the case when you want to return false (that is you want to return true when that evaluates to true):
if (!((!radio1.Checked) && (!radio2.Checked)))
{
return true;
}
else
{
return false;
}
By reversing the if, you end up with:
if ((!radio1.Checked) && (!radio2.Checked))
{
return false;
}
else
{
return true;
}
Which is close to what you have, but not quite the same thing. So, a proposed implementation for your method would be [I changed your style to mine]:
public bool CheckRadioButtons(RadioButton radioButtonA, RadioButton radioButtonB)
{
//none of them are selected
if ((!radioButtonA.Checked) && (!radioButtonB.Checked))
{
return false;
}
else
{
MessageBox.Show("You forgot to select a RadioButton!");
return true;
}
}
Also, as I think you may want to take out the MessageBox from there you can compress the method to:
public bool CheckRadioButtons(RadioButton radioButtonA, RadioButton radioButtonB)
{
return !((!radioButtonA.Checked) && (!radio2.radioButtonB));
}
A generalization would be something like:
public bool CheckRadioButtons(params RadioButton[] radioButtons)
{
foreach (RadioButton radioButton in radioButtons)
{
if (radioButton.Checked)
{
return true;
}
}
return false;
}
You may still show the messegebox in the caller if you like [Which I think is a good thing separate those concerns]. Also if you are using Linq [Remeber to add "using System.Linq" at the top of yout file or namespace block, avaliable form .NET 3.5]:
public bool CheckRadioButtons(params RadioButton[] radioButtons)
{
return radioButtons.Any(radioButton => radioButton.Checked);
}
Given the simplicity of this, you may consider skip to create a method for this altogether. Here is how you may call this with only two RadioButtons without an additional method:
(new RadioButton[]{radioButtonA, radioButtonB}).Any(radioButton => radioButton.Checked);
Of course it's an overhead for simple cases as the one with only two RadioButtons, so having a method will allow you to overload it for the simple cases (such as 2 RadioButtons and 3 RadioButtons).
In your if statement you check if both the radiobutons are checked, but this will never happen because always on of the radio buttons will be check. You should use checkboxes to make this happen or change the && to || to check that at leased one of the buttons is checked.
Radio buttons are generally used to represent options which are mutually exclusive. Checkboxes better represent what you seem to need (multiple choices).
If I try to add two radio buttons on a form I see that only one of them can be checked (the other is automatically unchecked when I do this).
This means that the two radio buttons will never be checked at the same time and the MessageBox will always show...
EDIT:
Only one of the radio buttons inside a container can be checked at a time.
You can use this to implement "either A or B" and "either C or D" by having 2 panels, one with radio buttons for A and B and another panel with radio buttons for C and D.
Since it is possible for neither radio button to be checked a valid state is the one where one of the buttons is checked. You don't check this with && (which is AND ) but with || (which is OR).
bool IsValid = radio1.Checked || radio2.Checked;

C# Text Box File Import

I've got a form with multiple text boxes which are file paths for the program to import data from. Currently they are checked for non-zero length by the following:
//this code imports the files required by the user, as specified in the
//file path text boxes
private void btImport_Click(object sender, EventArgs e)
{
bool hasPath = false;
foreach (TextBox box in this.gbPaths.Controls.OfType<TextBox>().Where(tb => tb.Text.Length > 0))
{
hasPath = true;
//import code
}//end foreach
if (!hasPath)
{
MessageBox.Show("You must enter at least one file path.");
}//end if
}//end import code
What I'm wondering is can I replace the //import code part with something like:
if(tb.Name = "txtAvF") then...
or similar, or do I have to do it outside of the foreach loop? Thanks in advance. Let me know if I need to clarify anything.
If you want to check to see if the TextBox is one of the ones on the form (which I think you are), then you are == which (taken from MSDN)
the operator == tests for reference equality by determining if two references indicate the same object
So this is what you're looking for:
if(box == textBox1 && !string.IsNullOrEmpty(box.Text))
{
// Import Textbox1
}
else if(box == textBox2 && !string.IsNullOrEmpty(box.Text))
{
// Import Textbox2
}
else if (box == textBox3....)
You should do it inside of the loop. Like this:
if (box.Name == "txtAvF")
box.Text = "What you want";
But setting hasPath inside the loop just holds state for your last path. You should also move MessageBox code inside loop.
The hasPath assignment seems correct to me; it's set for any one text box, and if not set at the end of the loop, a message is displayed. This rhymes well with the text so displayed. Moving the MessageBox call into the loop would cause the dialog box to never be displayed (or errenously displayed), at least as the code is implemented now, since the OfType<>().Where() guarantees that all text boxes iterated over have at least some content.
(I would add this as a comment to #Xaqron but don't have the necessary reputation yet.)

Categories

Resources