繁体   English   中英

使用C#的ms访问查询中指定的强制转换无效无效

[英]Specified cast is not valid exception in ms access query using C#

嘿,尽管我的数据类型在db中是正确的,但我的转换类型却很奇怪:

string sql =
            string.Format(
                @"select aim_network_id,aim_network_name,oxinetwork_id,pack_id,pack_name,p_face_value,pm_prefix from Operator where aim_network_id='{0}'",
                gridbackOffice["aim_network_id", gridbackOffice.CurrentCell.RowIndex].Value);
        OleDbCommand getSelectedGridDatecmd = new OleDbCommand(sql, conn);
        OleDbDataReader reader = getSelectedGridDatecmd.ExecuteReader();
        while (reader.Read())
        {
            txtAimNetworkID.Text = reader.GetString(0);
            txtAimNetworkName.Text = reader.GetString(1);
            txtPARNetworkID.Text = reader.GetString(2);
            txtPARFaceValue.Text = reader["p_face_value"].ToString();
           //in above line if i'm doing this `reader.GetString(5)` then i'm getting specified cast exception and that to randomly i.e some time it works fine and suddenly sometime gives this exception
            txtPARPackID.Text = reader.GetString(3);
            txtPARPackName.Text = reader.GetString(4);
            txtPARPMPrefix.Text = reader["pm_prefix"].ToString();
        }

我有点困惑,如果m使用这个reader["p_face_value"].ToString()然后我的代码运行得非常顺利,但是使用这个reader.GetString(5)的问题是什么,据我两个方法都返回字符串nebody曾经遇到过这个错误b4吗? ....错误在while循环的第4行和第7行。

异常 :指定的强制转换无效(未处理InvalidCastException)

根据MSDN, OleDbDataReader.GetString()在尝试转换为字符串之前不会执行任何转换-因此,检索到的数据必须已经是字符串。

如果该列中的值可能为null ,则文档建议您首先检查该值是否为null

if (  !reader.IsDBNull(5) ) {
    txtPARFaceValue.Text = reader.GetString(5); 
}

呼唤reader["p_face_value"]在一个空值返回的DBNull -当你调用上的DBNull的ToString() ,你会得到一个空字符串。

MSDN

不执行任何转换; 因此,检索到的数据必须已经是字符串。

如果该列不是字符串类型,则需要使用.ToString()方法进行转换。

数据库中p_face_value的数据类型是什么?

根据给出的错误描述,这似乎不是字符串类型,因此在您调用时:

reader.GetString(5)

由于无法将任何类型的内容转换为字符串,因此代码出错了。 .ToString()方法将起作用,因为它不使用强制转换。

仅当列是数据库中的字符串等效类型(如varchar)时,才应使用GetString,在这种情况下,“ p_face_value”似乎是数字类型,因此不能简单地将其转换为字符串。

您现在的做法是正确的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM