![](/img/trans.png)
[英]Getting values from datetimepicker wont work in SQL Server in C#
[英]Saving values from datetimepicker to SQL Server database
當我嘗試保存詳細信息時,我收到一條錯誤消息,內容如下。
如何將其轉換為字符串值? 提前致謝! 這是我的C#代碼和錯誤消息。
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA\GCSCFC.mdf;Integrated Security=True;Connect Timeout=30");
try
{
string sql = "INSERT INTO Leave (Employee_ID, Leave_Type,Leave_Date,Leave_Time_From, Leave_Time_To) values('" + txtEmpID.Text + "','" + cmbLeaveType.Text + "','" + PickerLeaveDate.Text + "','" + txtTimeFrom.Text + "','" + txtTimeTo.Text + "')";
SqlCommand exesql = new SqlCommand(sql, cn);
cn.Open();
exesql.ExecuteNonQuery();
MessageBox.Show("New Employee Added Successfully!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
cn.Close();
}
}
當數據庫列是DataTime之類的代碼時使用參數
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA\GCSCFC.mdf;Integrated Security=True;Connect Timeout=30");
try
{
string sql = "INSERT INTO Leave (Employee_ID, Leave_Type,Leave_Date,Leave_Time_From, Leave_Time_To) values('" + @txtEmpID + "','" + @cmbLeaveType + "','" + @PickerLeaveDate + "','" + @txtTimeFrom + "','" + @txtTimeTo + "')";
SqlCommand exesql = new SqlCommand(sql, cn);
exesql.Parameters.Add("@txtEmpID", SqlDbType.VarChar);
exesql.Parameters.Add("@cmbLeaveType", SqlDbType.VarChar);
exesql.Parameters.Add("@PickerLeaveDate", SqlDbType.DateTime);
exesql.Parameters.Add("@txtTimeFrom", SqlDbType.VarChar);
exesql.Parameters.Add("@txtTimeTo", SqlDbType.VarChar);
exesql.Parameters["@txtEmpID"].Value = txtEmpID.Text;
exesql.Parameters["@cmbLeaveType"].Value = cmbLeaveType.Text;
exesql.Parameters["@PickerLeaveDate"].Value = PickerLeaveDate.Value;
exesql.Parameters["@txtTimeFrom"].Value = txtTimeFrom;
exesql.Parameters["@txtTimeTo"].Value = txtTimeTo.Text;
cn.Open();
exesql.ExecuteNonQuery();
MessageBox.Show("New Employee Added Successfully!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
cn.Close();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.