c# - 检查数据库中的值以查看它是否是 bool 值并设置组合框,这样会引发异常

标签 c# mysql

我一直在做一个小项目。我正在做的是 - 我在数据库中添加一个值,表格看起来像这样......

ProductID, ProductName, Status
1          Gold         0

状态是一个位(1)

由于“状态”下拉列表中只有两个值,因此我使用组合框.selectedIndex - 来捕获字段的值 - 0 或 1。

将值插入表后,我尝试使用数据库中此特定表中保存的所有内容填充数据网格...

这就是我正在做的事情...

MySqlDataAdapter sda = new MySqlDataAdapter("SELECT * from PRODUCTS ", con);
        DataTable dt = new DataTable();
        sda.Fill(dt);
        dataGridView1.Rows.Clear();

        foreach (DataRow item in dt.Rows)
        {
            int n = dataGridView1.Rows.Add();
            dataGridView1.Rows[n].Cells[0].Value = item["ProductCode"].ToString();
            dataGridView1.Rows[n].Cells[1].Value = item["ProductName"].ToString();
            if ((bool)item["Status"]) // Trying to capture the value from DB and set the combobox with the correct .Value
            {
                dataGridView1.Rows[n].Cells[2].Value = "Active";
            }
            else
            {
                dataGridView1.Rows[n].Cells[2].Value = "Deactive";
            }

我得到的异常来自这行代码..

if ((bool)item["ProductStatus"])

System.InvalidCastException: 'Specified cast is not valid.'

看起来这是一个常见的错误,尝试谷歌给了我一百种不同的场景。有人知道我做错了什么吗?

最佳答案

如果正如您在帖子中所说的那样,它是一个 bit 列,那么根本不应该有任何问题,但大多数情况下都不是。此外,您是绕行而不是直行...我的意思是像下面这样更改您的查询并直接绑定(bind)到您的网格

SELECT productId, productName,
case when Status = 1 then 'Active' else 'Deactive' end as Status
FROM PRODUCTS 

绑定(bind)到gridview

ySqlDataAdapter sda = new MySqlDataAdapter("query here ", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.Rows.Clear();
dataGridView1.DataSource = dt; //bind the data

关于c# - 检查数据库中的值以查看它是否是 bool 值并设置组合框,这样会引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45535737/

相关文章:

c# - 系统.Data.SqlClient.SqlException : Invalid column name 'Gender_id'

c# - 如何在 EF 中模拟和单元测试存储过程

java - 当我运行 "SELECT 0 AS COL .."时,MySQL 列类型返回 decimal 或 bigint

php - 创建 PHP iframe 表单以将数据发布到电子邮件地址以及数据库表

PHP 准备语句准备第二条语句失败

c# - 如何将网络摄像机视频流转换为视频文件?

c# - asp.net core依赖注入(inject)中注册类型时如何处理混合构造函数参数

c# - 如何使用 TestStack White 自动化单击作为菜单项一部分的按钮

php - 使用数据库检查文本字段值

mysql - 根据另一个表的 id 查询从过时的表中删除行