将 DateTimePicker 值传递给存储过程

Pass DateTimePicker Value to a stored procedure

我的表格上有两个 DateTimePicker dtp_VacationStartdtp_VacationEnd 。我想将其值传递给存储过程

我的SQL代码

CREATE PROC [ADD_VACATION]  @vacationStart date ,@vacationEnd date ,@vacationMem nvarchar (100) = NULL ,@idVacationKind_L int ,@idMember_L int

AS INSERT INTO [tblVacation]
           ([vacationStart]
           ,[vacationEnd]
           ,[vacationMem]
           ,[idVacationKind_L]
           ,[idMember_L])
     VALUES
           (@vacationStart
           ,@vacationEnd
           ,@vacationMem
           ,@idVacationKind_L
           ,@idMember_L)

C# 代码:

public void ADD_VACATION(string vacationStart,string vacationEnd, string vacationMem, int idVacationKind_L, int idMember_L)
{

    DAL.open();

    SqlParameter[] param = new SqlParameter[5];

    param[0] = new SqlParameter("@vacationStart", SqlDbType.Date);
    param[0].Value = vacationStart;

    param[1] = new SqlParameter("@vacationEnd", SqlDbType.Date);
    param[1].Value = vacationEnd;

    param[2] = new SqlParameter("@vacationMem ", SqlDbType.NVarChar, 100);
    param[2].Value = vacationMem;

    param[3] = new SqlParameter("@idVacationKind_L", SqlDbType.Int);
    param[3].Value = idVacationKind_L;

    param[4] = new SqlParameter("@idMember_L", SqlDbType.Int);
    param[4].Value = idMember_L;

    DAL.ExecuteCommand("ADD_VACATION", param);
    DAL.close();

}

和事件

private void btnAddVacation_Click(object sender, EventArgs e)
{

    cms.ADD_VACATION( dtp_VacationStart.Text, dtp_VacationEnd.Text, txtVacationMemory.Text,
                    Convert.ToInt32(cmbVacationKind.SelectedValue)
                   ,Convert.ToInt32(dgMember_Grade.CurrentRow.Cells[0].Value.ToString()));

    MessageBox.Show("Added Successfuly", " ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

这段代码给我一个错误:输入字符串的格式不正确。

谢谢大家...抱歉混淆..这是我的第一个问题

你的 SqlParameter @vacationStartDateTime 类型,但你给它分配了一个字符串。

您应该得到 DateTimePickerDateTime 值(而不是 DateTimePicker.Text 中的字符串表示):

DateTime vacationStart = dtp_VacationStart.Value;

并更改 ADD_VACATION 的签名:

public void ADD_VACATION(DateTime vacationStart, ...

现在可以使用了:

private void btnAddVacation_Click(object sender, EventArgs e)
{
    DateTime vacationStart = dtp_VacationStart.Value;
    cms.ADD_VACATION(vacationStart, ...

我认为您输入的数据格式错误...
以正确的格式输入数据或更改数据类型

您必须将 dtp_VationStart.Text 和 dtp_VacationEnd.Text 转换为日期。

cms.ADD_VACATION( Convert.ToDateTime(dtp_VacationStart.Text), Convert.ToDateTime(dtp_VacationEnd.Text), txtVacationMemory.Text,
                Convert.ToInt32(cmbVacationKind.SelectedValue)
               ,Convert.ToInt32(dgMember_Grade.CurrentRow.Cells[0].Value.ToString()));

您还可以使用DateTime.Parse功能。更多信息可以here.

函数 ADD_VACATION() vacationStartvacationEnd 的参数是 string 类型,而您将它们作为 SqlDbType.Date 传递给参数。将参数的类型更改为 DateTime 并在调用函数 ADD_VACATION() 中,使用 .Value 作为 DateTimePicker 控件。这应该可以解决您的问题。