无法转换“System.Object[]”类型的对象输入“System.String[]”

发布于 2024-09-04 02:45:38 字数 1233 浏览 6 评论 0 原文

我正在开发一个 C# VS 2008 / SQL Server 网站应用程序。我是 ASP.NET 的新手。但是,我在以下代码的最后一行收到上述错误。您能给我如何解决这个问题的建议吗?编译正确,但运行后遇到此错误。

我想做的就是将“dt”第二行中的项目存储到字符串参数中。第一行是标题,所以我不需要这些值。第二行是第一行值。 My SQL 存储过程需要这些值作为字符串。所以我想解析第二行数据并加载到2个字符串参数中。我在下面添加了更多代码。

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;

我的错误:

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: 

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: 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

握住你手 2024-09-11 02:45:38

您不能将对象数组转换为字符串数组,您必须转换数组中的每个项目,因为必须检查每个项目是否可以转换。您可以使用 Cast 方法来实现:

SingleRow = dt.Rows[1].ItemArray.Cast<string>().ToArray();

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();
回忆追雨的时光 2024-09-11 02:45:38
string[] arr = Array.ConvertAll(dt.Rows[1].ItemArray, o => (string)o);

(您还可以使用 Cast().ToArray(),但此方法适用于更多框架版本,并且从一开始就获取正确的数组大小,而不是调整其大小)

string[] arr = Array.ConvertAll(dt.Rows[1].ItemArray, o => (string)o);

(you can also use Cast<T>().ToArray(), but this approach works on more framework versions, and gets the array size correct from the start, rather than resizing it)

那些过往 2024-09-11 02:45:38

嗯。您正在尝试访问 DataTable dt 的属性,但看起来您可能希望该表包含 AppendDataCT 查询的结果。事实并非如此。也要小心行索引访问:C# 中的数组是从 0 开始的,dt.Rows[1] 将检索表中的第二行。

除此之外,请查看 DataRow.ItemArray。该方法返回一个对象数组,而不是字符串数组。即使您的行只包含字符串,您仍然在处理对象数组,并且您必须以这种方式对待它。您可以将行中的每个单独项目转换为字符串,如果这是该列的正确数据类型:

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

编辑:好的,为了响应您的编辑,我看到了您的内容正在努力做。有很多不同的方法可以做到这一点,我特别建议您放弃 HashTables 并转向通用的等效项,例如 字典 - 你会节省很多运行时的痛苦。也就是说,这是对代码最简单的修改:

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

您不需要前导“@”; ADO.NET 将为您添加该内容。只要键 0 处有一个字符串(这是使用哈希表的一种相当非标准的方式 - 您通常会有某种描述性键),并且如果数据表中的第一列包含字符串。

我建议您查看类型化数据集和< a href="http://msdn.microsoft.com/en-us/library/ms379564(VS.80).aspx" rel="nofollow noreferrer">通用集合。缺少它们会使您的代码有些脆弱。

Hmmm. You're trying to access properties of the DataTable dt, but it looks like you might be expecting that table to contain the results of the AppendDataCT query. It doesn't. Be careful with your row index accesses, too: Arrays in C# are 0-based, and dt.Rows[1] will retrieve the second row in the table.

That aside, review the documentation for DataRow.ItemArray. That method returns an array of objects, not an array of strings. Even if your row contains nothing but strings, you're still dealing with an array of objects, and you'll have to treat it that way. You can cast each individual item in the row to a string, if that's the proper datatype for that column:

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

EDIT: Ok, in response to your edit, I see what you're trying to do. There are many different ways to do this, and I'd particularly recommend that you move away from HashTables and towards generic equivalents like Dictionary - you'll save yourself much runtime casting grief. That said, here's the simplest adaption of your code:

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

You don't need the leading "@"; ADO.NET will add that for you. The (string) casts will work as long as there's a string at key 0 (which is a fairly non-standard way to use hashtables - you'd usually have some kind of descriptive key), and if the first column in your datatable contains strings.

I recommend you look at typed datasets and generic collections. The lack of them here makes your code somewhat brittle.

怕倦 2024-09-11 02:45:38

每个列项都有自己的类型,可以与 String 不同,因此如果要将每个行值存储到数组中,则必须使用循环或 LINQ 逐一执行此操作(我还没有测试过)这个片段但应该完成它的工作):

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

Each column item have it's own type, that can be different from String, so if you want to store each row value into an array you have to do it one-by-one with a loop, or with LINQ (I haven't tested this snippet but should do it's job):

(from columnVal in dt.Rows[1].ItemArray
select columnVal.ToString()).ToArray();
千里故人稀 2024-09-11 02:45:38

为此,您可以使用 LINQ:

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

这将使用 ToString() 将数组的每个项目转换为字符串,如果该项目为 null,则返回一个空字符串。

You can use LINQ for that:

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

This converts each item of the array to a string by using ToString() and returns an empty string if the item is null.

单挑你×的.吻 2024-09-11 02:45:38

怎么样:将 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;

How about this: make string[] SingleRow into object[] SingleRow, which will let the line

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

execute properly. Subsequently when you need to access its values as an array of strings, cast it or LINQ select it like this:

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

Make sure to add the following usings:

using System.Linq;
using System.Collections.Generic;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文