错误16无法将类型'object'隐式转换为'string'。存在显式转换(您是否错过了演员?) [英] Error 16 Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)

查看:81
本文介绍了错误16无法将类型'object'隐式转换为'string'。存在显式转换(您是否错过了演员?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public string generateFNo()
            {
                String str = "SELECT Max(fdk_No) From tblFeedback";
                string fNo = null;
                SqlCommand con = new SqlCommand(str, cn);
                cn.Open();

                if (con.ExecuteScalar().Equals(DBNull.Value))
                {
                    fNo = "F01";
                }
                else
                {
                     fNo = con.ExecuteScalar();

         //Display the new fdkno (by get the last fdkno  from db)+1
                    string[] splitCode = Strings.Split(fNo, "F", 2);
                  fNo = "F0" + ((Convert.ToInt32(splitCode[1])) + 1).ToString();
                }

                cn.Close();
            }
        }

推荐答案

更改自

Change from
Quote:

fNo = con.ExecuteScalar();

fNo = con.ExecuteScalar();

to

to

fNo = (string) con.ExecuteScalar();


您将对象分配给字符串。正如答案1解释你可以解决问题但是!

如果你想根据这个结果得到下一个fdk_No,你最终会遇到几个问题。

如果有两个用户连接并尝试获取最大ID,它们都将具有相同的下一个fdk_No。当他们插入记录时你会有重复记录,或者如果你有唯一或主键,那么插入就会失败。

你最好将fdkno的字符串部分和单独列中的数字部分分开。数字部分可以设置为自动递增,然后您不必担心重复,也不需要在插入之前读取当前最大值。数据库将处理所有这些。

当你需要获得fdk_No时,你可以在select语句中加入这两个列值并将其作为一个值。希望这会有所帮助。
you are assign object to a string. as the answer1 explains you can fix the issue but!
if you trying to get the next fdk_No based on this result you will end up with several issues.
if two users connect and try to get the max id, both of them will have the same next fdk_No. when they insert records you will have duplicates or if you have unique or primary key then on of the insert will fail.
you better separate the string part of the fdkno and the numeric part in separate columns. numeric part can be set auto incremented, then you don't need to worry about duplicates and also you don't need to read current maximum value before insert. database will handle all of these.
when you need to get the fdk_No you can join these two column values in the select statement and get it as one value. hope this helps.


这篇关于错误16无法将类型'object'隐式转换为'string'。存在显式转换(您是否错过了演员?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆