如何通过C#将NULL值传递给存储过程

Moh*_*mis 1 c# sql-server stored-procedures

我有多个文本框,我想让用户留下一些空而不是给出错误

SqlParameterCollection只接受非null的SqlParameter类型对象.

我用于插入Data_Access_Layer类中的数据的内容

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);
        }
Run Code Online (Sandbox Code Playgroud)

主表格代码:

namespace M_Weight_System.Presentation_Layer
{
    public partial class Main : Form
    {
        Bussiness_Layer.Cls_Data dta = new Bussiness_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 !");
            }

        }
        }
}
Run Code Online (Sandbox Code Playgroud)

Jea*_*nez 6

你可以尝试这个,command.Parameters.Add("@param", DBNull.Value);或者你可以在proc中将默认值设置为NULL,而不必显式地将NULL传递给proc.

CREATE PROC ..dbo.Proc ( @param1 int =NULL, @param2 varchar(40) = NULL ...)
Run Code Online (Sandbox Code Playgroud)

此外,如果您必须从您的应用程序发送NULL,您将使用DBNull.Value