无法将参数值从 Int32 转换为日期时间



我搜索了所有网站,但没有找到任何解决我问题的方法。我是 c# 和堆栈溢出社区的新手,但真的陷入了这个问题。

我有一个按钮可以将日期和时间分别添加到datagridview中。在填充行时,我正在 SQL Server 中保存行值,但是当我发送它时,它给出的异常Failed to convert parameter value from a Int32 to a DateTime 数据库.c# 和 SQL Server 中的数据类型是Datetime

这是将日期和时间添加到数据网格视图的代码

private void addDateTime2_Click(object sender, EventArgs e)
{
    int n = dataGridView2.Rows.Add();
    dataGridView2.Rows[n].Cells[0].Value =  dateTimePicker9.Value.ToString("dd-MM-yyyy");
    dataGridView2.Rows[n].Cells[1].Value = dateTimePicker7.Value.ToString("HH:mm:ss"); 
}

这是我插入到数据库的代码:

for (int i = 0; i < dataGridView2.Rows.Count; i++)
    {
    string StrQuery = "INSERT INTO [dbo].[callRedirect]  (ISFsectionId, callRedirectDate, incidentNo, callRedirectTime, callRedirectGrade, callRedirectFName, callRedirectLName, callRedirectSerialNo, callRedirectRemark) VALUES (@ISFsectionId, @callRedirectDate, @incidentNo, @callRedirectTime, '" 
+ dataGridView2.Rows[i].Cells["Column12"].Tag + "', '" + dataGridView2.Rows[i].Cells["Column13"].Value + "', '" + dataGridView2.Rows[i].Cells["Column14"].Value + "', '" + dataGridView2.Rows[i].Cells["Column20"].Value + "', '" + dataGridView2.Rows[i].Cells["Column19"].Value + "')";
    SqlCommand cmd = cnn.CreateCommand();
    cmd.CommandText = StrQuery;
    cmd.Parameters.AddWithValue("@incidentNo", textBox4.Text);
    cmd.Parameters.AddWithValue("@callRedirectDate",  dataGridView2.Rows[i].Cells[0].Value);
    cmd.Parameters.AddWithValue("@callRedirectTime", dataGridView2.Rows[i].Cells[1].Value);
    cmd.Parameters.Add("@ISFsectionId", SqlDbType.DateTime).Value = dataGridView2.Rows[i].Cells["Column11"].Tag;
    cmd.Connection = cnn;
    cmd.ExecuteNonQuery();
    }

唯一可能引发此错误的行是

cmd.Parameters.Add("@ISFsectionId", SqlDbType.DateTime).Value = 
                    dataGridView2.Rows[i].Cells["Column11"].Tag;

我严重怀疑你的ISFsectionIddatetime.我也敢打赌Tag包含一个整数。

另请注意,网格包含字符串值而不是日期时间。这意味着要么使用实际datetime的字符串字段,要么 ADO.NET 意外地将字符串解析为底层类型。我说是意外的,因为如果代码在具有不同格式的区域设置上运行,这可能会中断。

若要避免转换问题,请在数据库中使用 datetime 类型,并且在加载它们并将其绑定到网格时不要将它们转换为字符串。使用每列的 DataGridViewStyle.Format 属性指定其显示方式

最新更新