sal*_*ere 3 c# sql-server-2005-express visual-studio-2008
我正在开发一个C#VS 2008/SQL Server网站应用程序.我是ASP.NET的新手.但是,我在以下代码的最后一行收到了上述错误.你能给我一些如何解决这个问题的建议吗?这编译正确,但运行后遇到此错误.
我想要做的就是将第二行"dt"中的项目存储到字符串参数中.第一行是标题,所以我不想要这些值.第二行是第一行值.我的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;
Run Code Online (Sandbox Code Playgroud)
我的错误:
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:
Run Code Online (Sandbox Code Playgroud)
您不能将对象数组转换为字符串数组,您必须在数组中转换每个项目,因为必须检查每个项目是否可以转换.你可以使用这个Cast方法:
SingleRow = dt.Rows[1].ItemArray.Cast<string>().ToArray();
Run Code Online (Sandbox Code Playgroud)