I am developing a C# VS 2008 / SQL Server website application. I am a newbie to ASP.NET. I am getting the above error, however, on the last line of the following code. Can you give me advice on how to fix this? This compiles correctly, but I encounter this error after running it.
All that I am trying to do is to store the items from the second row of "dt" into string parameters. The first row is the header, so I don't want these values. The second row is the first row of values. My SQL stored procedure requires these values as strings. So I want to parse the second row of data and load into 2 string parameters. I added more of my code below.
DataTable dt;
Hashtable ht;
string[] SingleRow;
...
SqlConnection conn2 = new SqlConnection(connString);
SqlCommand cmd = conn2.CreateCommand();
cmd.CommandText = "dbo.AppendDataCT";
cmd.Connection = conn2;
SingleRow = (string[])dt.Rows[1].ItemArray;
SqlParameter sqlParam = cmd.Parameters.AddWithValue("@" + ht[0], SingleRow[0]);
sqlParam.SqlDbType = SqlDbType.VarChar;
SqlParameter sqlParam2 = cmd.Parameters.AddWithValue("@" + ht[1], SingleRow[1]);
sqlParam2.SqlDbType = SqlDbType.DateTime;
My error:
System.InvalidCastException was caught
Message="Unable to cast object of type 'System.Object[]' to type 'System.String[]'."
Source="App_Code.g68pyuml"
StackTrace:
at ADONET_namespace.ADONET_methods.AppendDataCT(DataTable dt, Hashtable ht) in c:\Documents and Settings\Admin\My Documents\Visual Studio 2008\WebSites\Jerry\App_Code\ADONET methods.cs:line 88
InnerException:
You can't cast an array of objects into an array of strings, you have to cast each item in the array, as each items has to be checked if it can be cast. You can use the Cast
method for that:
SingleRow = dt.Rows[1].ItemArray.Cast<string>().ToArray();