无法将类型为“System.Int32”的对象强制转换为在DataReader.GetString()中键入“System.String”
我试图将数据库中的数据添加到acombobox。
try { SqlCeCommand com = new SqlCeCommand("select * from Category_Master", con); SqlCeDataReader dr = com.ExecuteReader(); while(dr.Read()){ string name = dr.GetString(1); cmbProductCategory.Items.Add(name); } } catch(Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message, System.Windows.Forms.Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); }
我得到以下exception:
无法将“System.Int32”类型的对象强制转换为“System.String”类型
我在这里想念的是什么?
显然,您的列没有类型string
。 显然它是int
。 所以使用:
dr.getInt32(1).ToString()
甚至
dr.GetValue(1).ToString()
在数据库中输入更改应该更加粗鲁。
作为某种一般性建议,我试图至少遵循:
- 只选择您需要的。 这主要是性能原因以及您必须明确声明列名称的原因,因此如果您更改模式不兼容,至少会产生明显的错误。
-
使用他们的名称访问字段,例如
dr.GetGuid(dr.GetOrdinal("id"))
这样的事情也可以通过扩展方法很好地解决:
public T GetFieldValue
(this DbDataReader reader, string columnName) { return reader.GetFieldValue (reader.GetOrdinal(columnName)); }
附注:包括堆栈跟踪(或至少说明代码中的哪一行exception来自)可能对其他试图帮助您的人有所帮助。 正如你从疯狂猜测中看到的罪魁祸首。 我的猜测是堆栈跟踪看起来像这样:
SqlDataReader.GetString YourCode.YourMethod
并且GetString
看起来或多或少像这样:
public string GetString(int index) { return (string) GetValue(index); }
您的列似乎没有int类型。 为避免这种情况,您可以使用列名而不是索引。
try { SqlCeCommand com = new SqlCeCommand("select * from Category_Master", con); SqlCeDataReader dr = com.ExecuteReader(); while(dr.Read()){ string name = dr["yourColumnName"].ToString(); cmbProductCategory.Items.Add(name); } } catch(Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message, System.Windows.Forms.Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); }
好的好的。 它解决了….
这是代码..
try { SqlCeCommand com = new SqlCeCommand("select CategoryName from Category_Master", con); SqlCeDataReader dr = com.ExecuteReader(); while(dr.Read()){ string name = dr.GetString(0); cmbProductCategory.Items.Add(name); } } catch(Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message, System.Windows.Forms.Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); }
我将sqlcommand更改为单个值,并将dr.getstring()的列号更改为0 ..它工作正常。 谢谢你们的帮助..我期待更多,因为我只是我项目的一半..