0

I have an Employee model/class and an equivalent Employee database. When I insert a new Employee into the database, without values for age, it does not work. I am using windowsform and I have defined age and maritalStatus columns in my database and c# code as nullable.

  • When I fill all 4 textbox values in my form, it works.
  • When I fill textboxes for Firstname, Lastname, age & leave Married textbox empty in my form, it works (ie it creates a new employee and set Married column to null in the database).
  • When I fill textboxes values for Firstname, Lastname, Married and leave Age textbox empty in my form, it doesn't work.

Please kindly help, I don't know what I'm doing wrong.

EMPLOYEE CLASS:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NullableTypeDatabase
{
    public class Employee
    {
        int empID;
        string firstName;
        string lastName;
        int? married;
        int? age;


        public int EmpID
        {
            get { return empID; }
            set { empID = value; }
        }


        public string FirstName
        {
            get { return firstName; }
            set { firstName = value; }
        }


        public string LastName
        {
            get { return lastName; }
            set { lastName = value; }
        }


        public int? Married
        {
            get { return married; }
            set { married = value; }
        }

        public int? Age
        {
            get { return age; }
            set { age = value; }
        }
    }
}

WINFORM 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 NullableTypeDatabase
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void ClickSaveNewUser(object sender, EventArgs e)
        {
            if (ValidateStringInputFields() && ValidateIntInputFields())
            {
                int? convertAge = int.Parse(txtAge.Text);
                if(NullableTypeDB.AddNewEmployee(txtFname.Text, txtLname.Text, comBoxMaritalStatus.SelectedIndex, convertAge) == 1)
                {
                    MessageBox.Show("A New Employee Record has been Successfully Added");
                }
            }


        }

        private bool ValidateStringInputFields()
        {
            var controls = new[] { txtFname, txtLname};

            bool isValid = true;
            foreach (var control in controls.Where(e => String.IsNullOrEmpty(e.Text)))
            {
                errorProviderTxtBoxes.SetError(control, "Please fill the required field");

                isValid = false;
            }

            return isValid;
        }



        private bool ValidateIntInputFields()
        {
            bool isValid = false;
            int resultAge; 
            if(int.TryParse(txtAge.Text, out resultAge))
            {
                isValid = true;
            }

            return isValid;
        }




    }
}

CLASS FOR ACCESSING THE DATABASE:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;

namespace NullableTypeDatabase
{
    public class NullableTypeDB
    {
        public static SqlConnection GetConnection()
        {
            string connectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\Z\documents\visual studio 2013\Projects\NullableTypeDatabase\NullableTypeDatabase\EmployeeInfo.mdf;Integrated Security=True";

            SqlConnection connection = new SqlConnection(connectionString);
            return connection;

        }


        public static int AddNewEmployee(string fname, string lname, int? maritalStat, int? age)
        {

            int returnAffectedRow;

            SqlConnection con = GetConnection();
            string queryStatement = "INSERT INTO Employee(firstname, lastname, married, age) VALUES (@fname, @lname, @maritalStat, @age)";
            SqlCommand sqlCmd = new SqlCommand(queryStatement, con);
            sqlCmd.Parameters.AddWithValue("@fname", fname);
            sqlCmd.Parameters.AddWithValue("@lname", lname);

            if(maritalStat == 0)
            {
                string convertIndex0 = "True";
                sqlCmd.Parameters.AddWithValue("@maritalStat", convertIndex0);
            }

            else if (maritalStat == 1)
            {
                string convertIndex1 = "False";
                sqlCmd.Parameters.AddWithValue("@maritalStat", convertIndex1);
            }

            else
            {
                sqlCmd.Parameters.AddWithValue("@maritalStat", DBNull.Value);
            }



            //if (age.HasValue)
            //{
            //    sqlCmd.Parameters.AddWithValue("@age", age.Value);

            //}
            //else if (age.GetValueOrDefault() == 0)
            //{
            //    sqlCmd.Parameters.AddWithValue("@age", DBNull.Value);

            //}

           // sqlCmd.Parameters.AddWithValue("@age", age == 0? DBNull.Value : (object)age);
            sqlCmd.Parameters.AddWithValue("@age", age.HasValue? age.Value : (object)DBNull.Value);

            try
            {
                con.Open();
               returnAffectedRow = sqlCmd.ExecuteNonQuery();

            }
            catch (SqlException ex)
            {

                throw ex;
            }
            finally
            {
                con.Close();
            }
            return returnAffectedRow;
        }




    }
}
Community
  • 1
  • 1
FaithN
  • 57
  • 1
  • 8
  • Age may be defined as not null in the database, meaning it cannot have null values. – Shadow Nov 09 '15 at 19:17
  • 1
    "it doesn't work" is generally not enough information - you should tell us **how** it does not work. Are there error-messages? exceptions? – guntbert Nov 09 '15 at 19:17
  • Can you show your `CREATE TABLE` statement? – wogsland Nov 09 '15 at 19:18
  • 2
    You might want to use `sqlCmd.Parameters.Add("@age", SqlDbType.Int).Value = age.HasValue ? age.Value : (object)DBNull.Value;` instead of `AddWithValue`. – juharr Nov 09 '15 at 19:19
  • I tried to redefine the method and it works better now: private int ValidateAgeInput(string ageInput) { int result = 0; if (string.IsNullOrEmpty(ageInput)) { result = 0; } else if (!string.IsNullOrEmpty(ageInput)) { int resultAge; if (int.TryParse(txtAge.Text, out resultAge)) { result = resultAge; } } return result; } – FaithN Nov 10 '15 at 10:47

2 Answers2

2
int? convertAge = int.Parse(txtAge.Text);

This line is your problem. You're parsing an empty string and it's just failing (i assume). Look up int.TryParse() here How to parse a string into a nullable int

Community
  • 1
  • 1
Darren Gourley
  • 1,798
  • 11
  • 11
  • thanks for the input. I tried something different and it works now. private int ValidateAgeInput(string ageInput) { int result = 0; if (string.IsNullOrEmpty(ageInput)) { result = 0; } else if (!string.IsNullOrEmpty(ageInput)) { int resultAge; if (int.TryParse(txtAge.Text, out resultAge)) { result = resultAge; } } return result; } – FaithN Nov 10 '15 at 10:43
1

You say the code allows it to be null, but it actually doesn't. In your Validate method below, if you don't put in a valid Age into the text box, this method will return false, so your update won't be performed.

    private bool ValidateIntInputFields()
    {
        bool isValid = false;
        int resultAge; 
        if(int.TryParse(txtAge.Text, out resultAge))
        {
            isValid = true;
        }

        return isValid;
    }

Also, your code code inside your button assumes that there will always be an age by this line:

 int? convertAge = int.Parse(txtAge.Text);

If you want to allow age to be null, you need to do things like this:

    private bool ValidateIntInputFields()
    {
        if(string.IsNullOrEmpty(txtAge.Text))
             return true;

        bool isValid = false;
        int resultAge; 
        if(int.TryParse(txtAge.Text, out resultAge))
        {
            isValid = true;
        }

        return isValid;
    }

and

    private void ClickSaveNewUser(object sender, EventArgs e)
    {
        if (ValidateStringInputFields() && ValidateIntInputFields())
        {
            int? convertAge = null;

            if( !string.IsNullOrEmpty(txtAge.Text) )
                convertAge = int.Parse(txtAge.Text);

            if(NullableTypeDB.AddNewEmployee(txtFname.Text, txtLname.Text, comBoxMaritalStatus.SelectedIndex, convertAge) == 1)
            {
                MessageBox.Show("A New Employee Record has been Successfully Added");
            }
        }
    }
John
  • 374
  • 2
  • 6