有关数据类型的例外情况

时间:2017-07-26 08:29:18

标签: c# sql sql-server visual-studio datagridview

我创建了一个有数据网格视图的应用程序。当我单击一个按钮时,datagridview中写入的数据将被发送到表中的数据库。但我有一个例外,我迷路了。

  

错误:System.Data.SqlClient.SqlException:'无法将nvarchar值'B003382A3'转换为int值。'

我甚至不知道为什么他会尝试转换为int,因为我的数据库中的数据是nvarchar。我唯一的建议是他正在反转细胞。

我的代码:

private void metroButton1_Click(object sender, EventArgs e)
{
    SqlConnection maConnexion = new SqlConnection("Server= localhost; Database= Seica_Takaya;Integrated Security = SSPI; ");
    maConnexion.Open();

    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        if ((row.Cells[20].Value != null) && (bool)row.Cells[20].Value)
        {
            SqlCommand command = maConnexion.CreateCommand();

            command = new SqlCommand("update FailAndPass set Machine=@machine, ProgCode=@pc, BoardName=@BName, BoardNumber=@BNumber, Tester=@T, DateTest=@DT, TimeTest=@TT, TimeStart=@TS, FComponent=@FC, Message=@Mess, TotalTestProg=@TTP, ReadValue=@RV, ValueReference=@VR, PTolerance=@PT, FaultCodeByOP=@FCBO, FaultDetail=@FD,  RepairingDate=@RD, RepairingTime = @RT, ReportingOperator=@RO WHERE SerialNum=@Serial", maConnexion);
            command.Parameters.AddWithValue("@Serial", textBox1.Text);
            command.Parameters.AddWithValue("@Machine", row.Cells[0].Value != null ? row.Cells[0].Value : DBNull.Value);
            command.Parameters.AddWithValue("@pc", row.Cells[2].Value != null ? row.Cells[2].Value : DBNull.Value);
            command.Parameters.AddWithValue("@BName", row.Cells[3].Value != null ? row.Cells[3].Value : DBNull.Value);
            command.Parameters.AddWithValue("@BNumber", row.Cells[4].Value != null ? row.Cells[4].Value : DBNull.Value);
            command.Parameters.AddWithValue("@T", row.Cells[5].Value != null ? row.Cells[5].Value : DBNull.Value);
            command.Parameters.AddWithValue("@DT", row.Cells[6].Value != null ? row.Cells[6].Value : DBNull.Value);
            command.Parameters.AddWithValue("@TT", row.Cells[7].Value != null ? row.Cells[7].Value : DBNull.Value);
            command.Parameters.AddWithValue("@TS", row.Cells[8].Value != null ? row.Cells[8].Value : DBNull.Value);
            command.Parameters.AddWithValue("@FC", row.Cells[9].Value != null ? row.Cells[9].Value : DBNull.Value);
            command.Parameters.AddWithValue("@Mess", row.Cells[10].Value != null ? row.Cells[10].Value : DBNull.Value);
            command.Parameters.AddWithValue("@TTP", row.Cells[11].Value != null ? row.Cells[11].Value : DBNull.Value);
            command.Parameters.AddWithValue("@RV", row.Cells[12].Value != null ? row.Cells[12].Value : DBNull.Value);
            command.Parameters.AddWithValue("@VR", row.Cells[13].Value != null ? row.Cells[13].Value : DBNull.Value);
            command.Parameters.AddWithValue("@PT", row.Cells[14].Value != null ? row.Cells[14].Value : DBNull.Value);
            command.Parameters.AddWithValue("@FCBO", row.Cells[15].Value != null ? row.Cells[15].Value : DBNull.Value);
            command.Parameters.AddWithValue("@FD", row.Cells[16].Value != null ? row.Cells[16].Value : DBNull.Value);
            command.Parameters.AddWithValue("@RD", row.Cells[17].Value != null ? row.Cells[17].Value : DBNull.Value);
            command.Parameters.AddWithValue("@RT", row.Cells[18].Value != null ? row.Cells[18].Value : DBNull.Value);
            command.Parameters.AddWithValue("@RO", row.Cells[19].Value != null ? row.Cells[19].Value : DBNull.Value);
            command.ExecuteNonQuery();

        }
    }

    maConnexion.Close();
    this.Hide();
    Repair rep = new Repair();
    rep.Show();
}

这是我的数据库的照片:

Pics

我使用过调试器,看起来我的细胞不对。我的datagridview中的第一列是Machine,代码中的相应单元格是row.cells 1

似乎我的所有细胞都没有像它们看起来那样正确。这到底是什么?我的意思是,通常BoardName是第三个单元格,但我把row.cell [2]我不再有错误。并且它不是唯一一个出现此错误的单元格。

4 个答案:

答案 0 :(得分:1)

使用您的更新进行更新:

您选择的单元格在数据库中具有相应的int值。我建议您检查一下datagridview人口 - 对于要更改的行中的位置,代码中一定有变化。

为了将来参考,最好不要否认数据库表中有一个int,因为它确实有助于回答问题,并且可以提供更简单的解决方案并指导您在哪里查看。 / p>

答案的其余部分 - 虽然有用 - 是在这个阶段的橱窗装饰。

使用

row.Cells[0].Value.ToString() // wherever you are getting the value and it's not null.

并使用

command.Parameters.Add(.../...

for example

parameter = command.Parameters.Add("@InputParm", OleDbType.VarChar, 12);  
// which explicitly types the datatype - with the number of char.
parameter.Value = "Sample Value";  

can be issues使用AddWithValue进行数据类型转换。

答案 1 :(得分:0)

我总是使用这种代码来处理SQL

 SqlConnection connection = new 
 SqlConnection(ConfigurationManager.AppSettings["SQLConnectionString"]);

 SqlCommand command = new SqlCommand();
 command.CommandTimeout = 1000;
 command.Connection = connection;
 command.CommandType = CommandType.StoredProcedure;
 command.CommandText = "KULLANICI_OKU";

 SqlParameter parameter = new SqlParameter();
 parameter.Direction = ParameterDirection.Input;
 parameter.ParameterName = "@KULLANICI";
 parameter.DbType = DbType.String;
 parameter.Value = user;
 command.Parameters.Add(parameter);

在我看来,使用存储过程是sql的更好方法。

答案 2 :(得分:0)

您首先要知道的是:您无法将DBNull.Value分配到string(SQL中为nvarchar)或其他结构值类型,因为它们各自不相容其他。在DBNull.Value&之间使用三元运算符的常用方法string(或结构类型)将DBNull.Value投射到object类型。

以下是如何在三元运算符中对DBNull.Value执行强制转换的示例:

// a & b are cell numbers for respective cells
// change to any number representing the cell order

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    if ((row.Cells[20].Value != null) && (bool)row.Cells[20].Value)
    {
        SqlCommand command = maConnexion.CreateCommand();

        command = new SqlCommand("update FailAndPass set Machine=@machine, ProgCode=@pc, BoardName=@BName, BoardNumber=@BNumber, Tester=@T, DateTest=@DT, TimeTest=@TT, TimeStart=@TS, FComponent=@FC, Message=@Mess, TotalTestProg=@TTP, ReadValue=@RV, ValueReference=@VR, PTolerance=@PT, FaultCodeByOP=@FCBO, FaultDetail=@FD,  RepairingDate=@RD, RepairingTime = @RT, ReportingOperator=@RO WHERE SerialNum=@Serial", maConnexion);
        // other parameters

        // integer value parameter example
        command.Parameters.Add("@pc", SqlDbType.Int).Value = row.Cells[a].Value != null ? row.Cells[a]Value : (object)DBNull.Value;

        // string value parameter example
        command.Parameters.Add("@BName", SqlDbType.NVarChar).Value = (row.Cells[b].Value != null ? (object)row.Cells[b].Value : (object)DBNull.Value).ToString();

        // other parameters

        command.ExecuteNonQuery();

    }
}

// other stuff

如果编译器支持null-coalescing运算符,那就更简单了:

// integer parameter
command.Parameters.Add("@pc", SqlDbType.Int).Value = row.Cells[a].Value ?? (object)DBNull.Value;

// string parameter
command.Parameters.Add("@BName", SqlDbType.NVarChar).Value = (row.Cells[b].Value ?? (object)DBNull.Value).ToString();

参考:

How do I Parameterize a null string with DBNull.Value clearly and quickly

答案 3 :(得分:0)

好的,所以我找到了问题的解决方案。

以下是代码:

$(function filter() {
    var selectedClass = "";
    $(".link").click(function(){ 
    selectedClass = $(this).attr("data-rel"); 
$(".wrap").fadeTo(100, 0.1);
    $(".wrap section").not("."+selectedClass).fadeOut().removeClass('scale_anm');
setTimeout(function() {
  $("."+selectedClass).fadeIn().addClass('scale_anm');
  $(".wrap").fadeTo(300, 1);
}, 300);
});

}

现在我可以通过添加替换所有addwithvalue。

说明:似乎Cell不像列或索引那样计数。我虽然单元格正在等待索引[0] - > [MAX]。 或者,我看到row.cells [0]不包含机器的名称但是为NULL。 结果,如果我的单元格从索引[0]开始,我的所有数据都是偏移的。然后,果然,BoardName在ProgCode Cell中,因此在数据库中插入了ProgCode列,这是int类型,因此引发了错误!

那令人兴奋,我已经一步一步地完成了这件事。但是,谢谢大家的帮助,因为至少你已经学到了一些东西!