0

Whenever I type nothing or null value in textboxes there is an error coming out. My code is like this:

 SqlCommand cmd = con.CreateCommand();
 cmd.CommandText = "INSERT INTO Records 
                   ([Student ID], [First Name], [Last Name], [Middle Initial], 
                     Gender, Address, Status, Year, Email, Course, 
                    [Contact Number]) 
                    VALUES (@StudentID, @FirstName, @LastName , @MiddleInitial, 
                            @Gender, @Address, @Status, @Year, @Email, @Course, 
                            @ContactNumber)";

   SqlParameter p1 = new SqlParameter("@StudentID", SqlDbType.NChar);
   p1.Value = textBox1.Text;
   cmd.Parameters.Add(p1);
   SqlParameter p2 = new SqlParameter("@FirstName", SqlDbType.NVarChar);
   p2.Value = textBox2.Text;
   cmd.Parameters.Add(p2);
   SqlParameter p3 = new SqlParameter("@LastName", SqlDbType.NVarChar);
   p3.Value = textBox3.Text;
   cmd.Parameters.Add(p3);
   SqlParameter p4 = new SqlParameter("@MiddleInitial", SqlDbType.NChar);
   p4.Value = comboBox1.Text;
   cmd.Parameters.Add(p4);
   SqlParameter p5 = new SqlParameter("@Gender", SqlDbType.NChar);
   p5.Value = comboBox2.Text;
   cmd.Parameters.Add(p5);
   SqlParameter p6 = new SqlParameter("@Address", SqlDbType.VarChar);
   p6.Value = textBox4.Text;
   cmd.Parameters.Add(p6);
   SqlParameter p7 = new SqlParameter("@Status", SqlDbType.NChar);
   p7.Value = comboBox3.Text;
   cmd.Parameters.Add(p7);
   SqlParameter p8 = new SqlParameter("@Year", SqlDbType.VarChar);
   p8.Value = comboBox4.Text;
   cmd.Parameters.Add(p8);
   SqlParameter p9 = new SqlParameter("@Email", SqlDbType.VarChar);
   p9.Value = textBox5.Text;
   cmd.Parameters.Add(p9);
   SqlParameter p10 = new SqlParameter("@Course", SqlDbType.VarChar);
   p10.Value = comboBox5.Text;
   cmd.Parameters.Add(p10);
   SqlParameter p11 = new SqlParameter("@ContactNumber", SqlDbType.VarChar);
   p11.Value = textBox6.Text;
   cmd.Parameters.Add(p11);

   textBox1.Text = "";
   textBox2.Text = "";
   textBox3.Text = "";
   textBox4.Text = "";
   textBox5.Text = "";
   textBox6.Text = "";
   comboBox1.Text = "";
   comboBox2.Text = "";
   comboBox3.Text = "";
   comboBox4.Text = "";
   comboBox5.Text = "";
   if (cmd.Parameters.Contains(System.DBNull.Value))
   {
       MessageBox.Show("Please complete the fields", "Information...", 
                       MessageBoxButtons.OK, MessageBoxIcon.Warning, 
                       MessageBoxDefaultButton.Button1);
    }
    else
    {
       MessageBox.Show("Data Inserted!", "Information ... ", 
                       MessageBoxButtons.OK, MessageBoxIcon.Information, 
                       MessageBoxDefaultButton.Button1);
    }
    cmd.ExecuteNonQuery();
    con.Close();

The error is on:

if(cmd.Parameters.Contains(System.DBNull.Value))

I'm using SQL Server and C#.

2
  • You need to check whether the value you are setting is null before you assign anything to the Command Parameter. If its a textbox then you might want to check if(!string.IsNullOrEmpty(textbox.text)) //Then add the parameter Commented Aug 25, 2013 at 3:30
  • I did what you have said but it keeps on inserting a data even though it is a null. Commented Aug 25, 2013 at 3:48

4 Answers 4

1
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "INSERT INTO Records 
               ([Student ID], [First Name], [Last Name], [Middle Initial], 
                 Gender, Address, Status, Year, Email, Course, 
                [Contact Number]) 
                VALUES (@StudentID, @FirstName, @LastName , @MiddleInitial, 
                        @Gender, @Address, @Status, @Year, @Email, @Course, 
                        @ContactNumber)";
Control[] controls = {textBox1,textBox2, textBox3, textBox4, textBox5, textBox6, comboBox1, comboBox2, comboBox3, comboBox4, comboBox5};
foreach(Control c in controls){
  if(c.Text.Trim() == "") {
      MessageBox.Show("Please complete the fields", "Information...", 
                   MessageBoxButtons.OK, MessageBoxIcon.Warning, 
                   MessageBoxDefaultButton.Button1);
      c.Focus();//Focus it to let user enter some value again.
      return;

  }
}
//Initialize your parameters here
//....
//....
//....

try {
  cmd.ExecuteNonQuery();        
  MessageBox.Show("Data Inserted!", "Information ... ", 
                   MessageBoxButtons.OK, MessageBoxIcon.Information, 
                   MessageBoxDefaultButton.Button1);
  foreach(Control c in controls) c.Text = "";
}catch{}
finally {
  con.Close();
}
Sign up to request clarification or add additional context in comments.

Comments

0

Why don't you start over again and do some proper validation before getting to this point? You should never ever start creating objects and stuff if there is no need to do so. So, make yourself a favor and add a validation method like in

private bool IsValid()
{
    return !Controls.OfType<TextBox>().Any(c=> String.IsNullOrEmpty(c.Text));
}

and then add a call just before the code to construct the sqlcommand and parameter collection

if(IsValid())
{
    // do you stuff here
}
else
{
   MessageBox.Show("Please complete the fields", "Information...", 
                   MessageBoxButtons.OK, MessageBoxIcon.Warning, 
                   MessageBoxDefaultButton.Button1);
}

Keep in mind this is not tested, I don't have VS right now and all is written manually, so maybe Control collection is not accessed that way.

Comments

0

First of all, you need to look for whether the value property of any of the parameters is DBNull. You're trying check whether parameter object itself is DBNull, but you should be looking at the Value property. You can do that like this:

if ( cmd.Parameters.Any(p => DBNull.Value.Equals(p.Value)) )

Secondly, the .Text property of your textbox controls will never be null. At worst, it will be the empty string. So what you really want is code like this:

if ( cmd.Parameters.Any(p => string.IsNullOrWhiteSpace((string)p.Value)) )

Finally, as an aside, even if the .Text property could be null, this is not the same as DBNull. They are two different things.

1 Comment

Joel, nice piece of code, but I thought this must be good for the intermediate developers and above, as from the piece of code of OP, it seems he is starter and is not in position to start with LINQ and Anonymous kind of things..But if he understands then really it will be helpful for him.
0

Clean and effective approach. Will help you in later developments. Change your code something like this:

  1. Create a class called student and inside that class create properties for FirstName, LastName and others as required. Something like this:

    public class Student
    {
        public int StudentId {get;set;}
        public string FirstName {get;set;}
        public string FirstName {get;set;}
        public string MiddleInitial{get;set;} // upto ContactNumber or as required.
     }
    
  2. Create a separate method for assigning parameters to SqlCommand. Here in these methods you can also put validations if you required using ternary operations i.e ?,:

    private void CreateParameterList(ref Student s, ref SqlCommand cmd)
           {
              var parameters = new []
                                   {
                                     new SqlParameter("@FirstName",s.FirstName),
                                     new SqlParameter("@LastName",s.LastName),
                                     :
                                     :
                                      new SqlParameter("@ContactNumber",s.ContactNumber)
                                    }
              cmd.Parameters.AddRange(parameters);
           }
    
  3. Create a Method for Save and pass the above class as parameter. You can also create a separate partial class in name of Student so as to access the members using same instance. Call the method in step 2, so as to use the parameters.

    protected void MySaveFunction(Student s)
    {
        using(SqlConnection con= new SqlConnection(your_Connection_String))
        {
            using(SqlCommmand cmd = new SqlCommand())
            {
                cmd.CommandType = CommandType.Text/StoredProcedure;
                // it depends on what you are using
                cmd.Connection = con;
                cmd.CommandText=Your Query or Name of SP;
                con.Open();
                CreateParameterList(ref s, ref cmd);
                try
                {
                    int i = cmd.ExecuteNonQuery();
                    if(i>0)
                    {
                        //Show Success or return Success
                    }        
                }
                catch(SqlException sqlex)
                {
                    //catch and log exception
                }
                finally
                {  con.Close(); con.Dispose() }
            }
        }
    }
    

3 Comments

Why declare Student and SqlCommand as ref parameters in CreateParameterList?
Both Student and SqlCommand are classes so are passed by reference by default. There is no need to use ref. See albahari.com/valuevsreftypes.aspx
@tuzo its not mandatory that I write ref and he must have to use ref. If you can see my code, I have skipped so many properties and parameters, so that doesnot mean that OP should also skip those. The above piece of code is just a suggestion or hint given for exploring the new ways of implementation of stuffs. If he can do research then he must be able to come across , dozens of ways of doing the same. It depends on him, what way he needs and he prefers?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.