我一直在做一个小项目。我正在做的是 - 我在数据库中添加一个值,表格看起来像这样......
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/