简体   繁体   English

无法转换类型的对象

[英]Unable to cast object of type

i want to get the maximum number 我想获得最大数量

so i did this code 所以我做了这个代码

 public int autoIncrement()
    {
        int no = 0;
        odbcCon.OpenCon();
        SqlCommand cmd = new SqlCommand("SELECT MAX (CustomerCode) FROM TBLM_CUSTOMER",odbcCon.MainCon);

        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.Read())
        {
            if (!dr.IsDBNull(0)) {

                 no = Convert.ToInt32(dr);

            }

        }
        dr.Close();
        return no;

    }

but

no = Convert.ToInt32(dr);

says

Unable to cast object of type 'System.Data.SqlClient.SqlDataReader' to type 'System.IConvertible'. 无法将类型为“System.Data.SqlClient.SqlDataReader”的对象强制转换为“System.IConvertible”。

how can i solve this ? 我怎么能解决这个问题? please tell me 请告诉我

You're trying to convert your data reader to an integer. 您正在尝试将数据读取器转换为整数。

Try this instead: 试试这个:

if (!dr.IsDBNull(0)) {
    no = dr.GetInt32(0);
}

您需要为DataReader指定索引0

no = Convert.ToInt32(dr[0]);

你需要给索引:

no = Convert.ToInt32(dr[0]);

尝试获取GetSqlInt32属性

no = dr.GetSqlInt32(0);

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

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