2016-05-26 29 views
0

すべてのWebを検索しましたが、私の問題の解決策は見つかりませんでした。私はC#とスタックオーバーフローコミュニティの新人ですが、本当にこの問題に悩まされています。Int32からDateTimeにパラメータ値を変換できません

私はdatagridviewに日付と時刻を別々に追加するボタンがあります。行私はSQL Serverで行の値を保存していますが、その例外Failed to convert parameter value from a Int32 to a DateTimeを与えることを充填しながら、私はそれは、C#でdatabase.dataタイプを送信し、SQL Serverは、ここでDatetime

でのDataGridViewする日付と時刻を追加するコードだとき

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(); 

    } 
+0

デバッガでは、dataGridView2.Rows [i] .Cells [0] .Valueの値は何ですか? –

+0

あなたは試してみましたか?cmd.Parameters.AddWithValue( "@ callRedirectDate"、Convert.ToDatetime(dataGridView2.Rows [i] .Cells [0] .Value)); –

+0

エラーは、データ型が* DateTimeではなく 'int'であることを示します。あなたのコードはグリッド内の日付の代わりに*文字列*を格納しますが、これは別の(深刻な)バグです。このエラーをスローできる行は 'cmd.Parameters.Add(" @ ISFsectionId "、SqlDbType.DateTime)です.Value = dataGridView2.Rows [i] .Cells [" Column11 "]。Tag;' I'd betその 'Tag'にはintが入っています –

答えて

1

が目を投げることができる唯一のラインエラーは、私は真剣にあなたのISFsectionIddatetimeであることを疑う

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

です。 Tagには整数が含まれているとも賭けています。

グリッドには、DateTimesではなく文字列値が含まれています。これは、実際にdatetimeの文字列フィールドを使用するか、ADO.NETが誤って文字列を基になる型に解析できないことを意味します。コードが異なる書式のロケールで実行されると、これが壊れる可能性があるため、私は誤って言う。

は、変換の問題を避けるため、データベースに datetime型を使用し、それらをロードし、グリッドにそれらを結合するとき は、文字列に変換しないですることができません。各列の DataGridViewStyle.Formatプロパティを使用して、表示方法を指定します。

+0

本当にPanagiotis Kanavosそれは私の間違いIntsorsorryである必要があります。みんなありがとう –

関連する問題