Search code examples
c#sql-serverstored-procedures

How to pass NULL Value to Stored Procedure Through C#


I have multiple textboxes and I want to allow the user to leave some empty instead of throwing the error:

SqlParameterCollection only accepts non-null SqlParameter type objects.

What I use for inserting data that is in Data_Access_Layer class:

public void ExecuteCommand(string Data, SqlParameter[] param)
{
        SqlCommand sqlcmd = new SqlCommand();
        sqlcmd.CommandType = CommandType.StoredProcedure;
        sqlcmd.CommandText = Data;
        sqlcmd.Connection = sqlconnection;

        if (param != null)
        {
            sqlcmd.Parameters.AddRange(param);
        }
}

The main form code:

namespace M_Weight_System.Presentation_Layer
{
    public partial class Main : Form
    {
        Business_Layer.Cls_Data dta = new Business_Layer.Cls_Data();

        public Main()
        {
            InitializeComponent();
        }
    
        private void bSave_Click(object sender, EventArgs e)
        {
            try
            {
              dta.Add_Data(tId.Text, tNumber.Text, tClient.Text, tDriver.Text, Convert.ToInt32(tFirst.Text), Convert.ToInt32(tSecond.Text), Convert.ToInt32(rt2.Text), tDate1.Text,tCity.Text, tType.Text,tDate2.Text);
                MessageBox.Show("Success");
                bEdit.Enabled = true;
                NewToolStripMenuItem.Enabled = true;
                PrintToolStripMenuItem.Enabled = false;
            }
            catch
            {
                MessageBox.Show("Problem !");
            }
        }

        private void bEdit_Click(object sender, EventArgs e)
        {
            try
            {
                dta.Update_Data(tId.Text, tNumber.Text, tClient.Text, tDriver.Text, Convert.ToInt32(tFirst.Text), Convert.ToInt32(tSecond.Text), Convert.ToInt32(rt2.Text), tDate1.Text, tCity.Text, tType.Text, tDate2.Text);
                MessageBox.Show("Success");
                
            }
            catch
            {
                MessageBox.Show("Problem !");
            }
        }
    }
}

Solution

  • you can try this command.Parameters.Add("@param", DBNull.Value); or you can Set the defaults to NULL in the proc and you don't have to explicitly pass NULL to a proc.

    CREATE PROC ..dbo.Proc ( @param1 int =NULL, @param2 varchar(40) = NULL ...)
    

    Also, if you have to send NULL from your app you would use DBNull.Value