如何修复 C# 中的“指定转换无效”错误?

问题是,我需要在我的应用程序中显示一个列表。

我按照要求制作了一个 SQLint类型IsAdmin,在学校里他们告诉我在应用程序中制作 int show bool,更准确地说是显示IsAdmin=TrueFalse?

但是当我启动应用程序并通过登录屏幕时,异常显示为消息:

“指定的演员表无效!”

我需要做什么?

  • 我尝试转换它(bool)reader["IsAdmin"].ToInt32,但它显示错误。

  • 我尝试将其更改为整数,但它显示了 1 和 0。

     public static List<Korisnik> GetAllUsers() {


            List<Korisnik> korisnici = new List<Korisnik>();

            Korisnik korisnik = null;


            using (SqlConnection conn = new SqlConnection()) {


                conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnString"].ToString();

                conn.Open();


                SqlCommand command = new SqlCommand("SELECT ID, UserName, UserPass, IsAdmin FROM Users01", conn);


                using (SqlDataReader reader = command.ExecuteReader()) {


                    while (reader.Read()){


                        korisnik = new Korisnik((int)reader["ID"], (string)reader["UserName"], (string)reader["UserPass"], (bool)reader["IsAdmin"]);

                        korisnici.Add(korisnik);


                    }


                }


            }


            return korisnici;


        }


幕布斯6054654
浏览 279回答 1
1回答

拉丁的传说

更改此行:korisnik = new Korisnik((int)reader["ID"],&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (string)reader["UserName"],&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (string)reader["UserPass"],&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (bool)reader["IsAdmin"]);...至:korisnik = new Korisnik((int)reader["ID"], (string)reader["UserName"],&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (string)reader["UserPass"],&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ((int)reader["IsAdmin"]) > 0 ? true : false ); // convert from int to bool转换是必要的,因为您不能只将 an 分配int给 a bool。我假设在数据库中,大于0意味着用户是管理员。我知道这是一个家庭作业问题,但展望未来,最好在数据库中使用布尔类型(在本例中BIT),因为他们在数据库中占用的空间更少(效率更高)使专栏的目的更加明显消除了问题中发布的转换问题告诉我更多关于BIT
打开App,查看更多内容
随时随地看视频慕课网APP