Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c# - Unable to cast object of type 'System.Int32' to type 'System.String' in DataReader.GetString()

I was trying to add data from a database to 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);
        }

I get the following exception:

Unable to cast object of type 'System.Int32' to type 'System.String'

What am I missing here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your column doesn't have the type string. Apparently it's int. So use:

dr.getInt32(1).ToString()

or even

dr.GetValue(1).ToString()

which should be more roubst to type changes in the database.

As some sort of general advice I try to follow at least:

  • Select only what you need. This has mostly performance reasons and the reason that you have to state the column names explicitly, thereby getting at least a sensible error if you change your schema incompatibly.
  • Access the fields using their names, e.g.

    dr.GetGuid(dr.GetOrdinal("id"))
    

    Such a thing can also be nicely solved by an extension method:

    public T GetFieldValue<T>(this DbDataReader reader, string columnName)
    {
        return reader.GetFieldValue<T>(reader.GetOrdinal(columnName));
    }
    

Side note: Including stack traces (or at least saying which line in your code the exception comes from) can be helpful to others trying to help you. As you can see from the wild guesses what the culprit could be. My guess would be that the stack trace looks somewhat like this:

SqlDataReader.GetString
YourCode.YourMethod

and that GetString looks more or less like this:

public string GetString(int index)
{
    return (string) GetValue(index);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...