Cannot pass an object of type "System.Object []" to enter "System.String []"

I am developing a C # VS 2008 / SQL Server web application. I am new to ASP.NET. However, I get the above error in the last line of the following code. Can you give me some advice on how to fix this? This runs correctly, but I encountered this error after it started.

All I'm trying to do is save the elements from the second line of "dt" into string parameters. The first line is the title, so I do not want these values. The second line is the first line of values. My SQL stored procedure requires these values ​​to be strings. Therefore, I want to parse the second row of data and load into 2 string parameters. I have 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 mistake:

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: 
+3
6

. DataTable dt, , , AppendDataCT. . : # 0, dt.Rows[1] .

, DataRow.ItemArray. , . , , - , . , :

foreach (string s in dt.Rows[1].ItemArray)
{
  //...
}

EDIT: , , , . , HashTables , Dictionary - , . , :

DataRow dr = dt.Rows[1]; // second row
SqlParameter p1 = cmd.Parameters.AddWithValue((string)ht[0], (string)dr[0]);
SqlParameter p2 = ...

"@"; ADO.NET . (string) , 0 ( -), - ), datatable .

. .

+1

, , , . Cast :

SingleRow = dt.Rows[1].ItemArray.Cast<string>().ToArray();
+9
string[] arr = Array.ConvertAll(dt.Rows[1].ItemArray, o => (string)o);

( Cast<T>().ToArray(), , )

+3

, String, , , LINQ ( haven 't , ):

(from columnVal in dt.Rows[1].ItemArray
select columnVal.ToString()).ToArray();
+1

LINQ :

var yourStringArray = dt.Rows[1].ItemArray
    .Select(o => (o ?? (object)String.Emtpy).ToString())
    .ToArray();

ToString() , null.

0

: make string[] SingleRow object[] SingleRow,

SingleRow = (object[])dt.Rows[1].ItemArray;

. , , LINQ, :

objectArray.Select<object, string>
   (c => (c != null ? c.ToString() : "")).ToArray();

:

using System.Linq;
using System.Collections.Generic;
0
source

Source: https://habr.com/ru/post/1748772/


All Articles