Empty Textbox still saves data in SQL Server even columns in table are not allowed null Empty Textbox still saves data in SQL Server even columns in table are not allowed null database database

Empty Textbox still saves data in SQL Server even columns in table are not allowed null


As I'm understanding it, what appears to be the main problem is that you check all fields in different if statements, but only the last has an else. As I'm assuming from your post, this is your problem; you want every textbox to have a value, before you start inserting it in the database, right?

This is better explained if break up your code into something a bit more reusable, incidentally cleaning up stuff a bit as well.

First, start off by introducing a variable in your class that we can use to see if there are any empty fields:

private bool HasEmptyFields = false;

Next, let's create a simple helper that checks if the textbox is empty/null, updates the appropriate label's visiblity state and set 'HasEmptyFields' to true if it is indeed empty:

private void ValidateField(TextBox textBox, Label label) {    // check if the textbox actually is null - or empty (""), which is a difference    // the nifty helper string.IsNullOrEmpty() will help with that    var fieldIsEmpty = string.IsNullOrEmpty(textBox.Text.Trim());    // next, based on if the field is empty,  set the visibility of the label    // don't worry, this is fancy syntax for a simple if...then...else    label.Visibility = fieldIsEmpty ? Visibility.Visible : Visibility.Hidden;    if (fieldIsEmpty) {        // ONLY if this field is actually null, or empty, we make sure to         // inform the rest of the code this occ        HasEmptyFields = true;    }}

With this in place, we can do something like:

ValidateField(tbIDCardNum, lblStarIDCardNum);ValidateField(tbFirstName, lblStarFirstName);// etc... continue doing this for all you fieldsif (HasEmptyFields) {    // ONLY if there is any field detected as being empty/null    // we simply stop here (and skip the insert-into-db stuff)    return;} try {    // if all fields indeed have a value, let's    // continue with the insert-into-db stuff here    conn.Open();    ...} 

Now there are certainly ways to makes this even prettier. But this might help you a bit in the right direction. Also worth mentioning are some other comments, like preventing SQL injection (which is bound to happen), as well as looking into data validation tools so you don't have to code all this validation yourself. But that is not in the scope of this answer, obviously.


If you want to require fields to be filled, then you really should use a required field validator - see https://msdn.microsoft.com/en-us/library/5hbw267h%28VS.80%29.aspx?f=255&MSPPError=-2147217396