I was trying to add data from a database to a ComboBox.
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);
}
I get the following exception:
Unable to cast object of type 'System.Int32' to type 'System.String'
What am I missing here?
Convert.ToString(value)rather thevalue.ToString()*may very well end up getting the wrong column if someone changes the database schema later. I suspect you're not getting the column you're expecting, but anintcolumn that is at that position.System.Int32, not aSystem.String.