[英]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 giving the error 我有多个文本框,我希望允许用户保留一些空白而不是给出错误
SqlParameterCollection only accepts non-null SqlParameter type objects.
SqlParameterCollection仅接受非空SqlParameter类型的对象。
What I use for inserting data that is in Data_Access_Layer Class 我用于插入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);
}
The Main form Code: 主要形式代码:
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 !");
}
}
}
}
you can try this command.Parameters.Add("@param", DBNull.Value);
您可以尝试使用此
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. 或者您可以在proc中将默认值设置为NULL,而不必将NULL显式传递给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 另外,如果必须从应用程序发送NULL,则可以使用DBNull.Value
您可以简单地使用
sqlcmd.Parameters.AddRange(param == null ? (object)DBNull.Value : param);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.