Search code examples
c#stringlistviewintdataadapter

Convert an int to a string saved in a SQL Server database


I have a SQL Server database with a table Event_Tab with an Int column Code. I want to associate this Code with a specific string and this so I don't save string variable in my table.

So, I wrote a procedure GetStringCode with In16 input parameter and it returns the string that I need, then I fill it in a listview with the other parameter saved in my table

This is my code to do it :

using (SqlConnection connection = new SqlConnection(connectionstring))
using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))
{
    DataTable table = new DataTable();
    adapter.Fill(table);

    foreach(DataRow dr in table.Rows)
    {
        ListViewItem items = new ListViewItem(dr["Machine"].ToString());                    
        items.SubItems.Add(GetStringCode((short)dr["Code"]).ToString());
        items.SubItems.Add(dr["Date_time"].ToString());
        listview.Items.Add(items);
    }
}  

If you notice, I did a cast to get rid of an error

Cannot convert from object to short

and so far everything seems okay. But when a try to run this code, I am getting an error

The specific cast is invalid

What is the problem because I can't seem to find it...


Solution

  • You may be running into an issue with unboxing, rather than type casting. A variable of type int will cast to short. However, a boxed int will not cast directly to short. A boxed value type can be directly cast only to the exact boxed type.

    int i = 100;
    object o = i; // Boxed int.
    short s1 = (short) i; // Works.
    short s2 = (short) o; // Throws InvalidCastException.
    short s3 = (short) (int) o; // Works.
    

    DataRow stores field values as object, so value types are boxed. That means that attempting to cast a field value that is a boxed int, directly to short, is causing the issue. A two-stage cast (as in s3 above) may solve the problem.

    What is the difference between boxing/unboxing and type casting?