简体   繁体   English

如何在C#中将DataTable单元格值转换为对象数组

[英]How to convert DataTable Cell Value to Object Array in C#

Here is my code, 这是我的代码,

object[] objrow = new object[]{"Test","test1","test2","test3","test4"};

object[] objrow1 = new object[]{"Test","test1","test2","test3","test4"};

 DataTable dtentercodemfm = new DataTable();
 dtentercodemfm.Columns.Add("objrow");
 dtentercodemfm.Columns.Add("objrow1");
 dtentercodemfm.Rows.Add(objrow, objrow1);

While Getting this Data, 在获取此数据时,

object[] objrow = (object[])dtentercodemfm.Rows[0][0];
object[] objrow1 = (object[])dtentercodemfm.Rows[0][1];

Gives me error 给我错误

Unable to cast object of type 'System.String' to type 'System.Object[]'.

How to Solve. 怎么解决。

你可以试试

object[] objrow = (object[]) Convert.ToString(dtentercodemfm.Rows[0][0]).Split(',') ;

This would work (Tried and tested). 这将起作用(尝试并测试)。

While creating columns do this 在创建列时执行此操作

dtentercodemfm.Columns.Add("objrow", typeof (object[]));
dtentercodemfm.Columns.Add("objrow1", typeof (object[]));

在此处输入图片说明

Why this works 为什么这样做

Because when you do not provide type while creating column, default type is taken which is String. 因为当您在创建列时不提供类型时,将采用默认类型,即String。 So data was storing in DB as string which was "System.Object". 因此,数据作为字符串“ System.Object”存储在DB中。

Shouldn't you need to write your question like this 你不应该这样写你的问题吗

    dtentercodemfm.Columns.Add("objrow");

    dtentercodemfm.Rows.Add(objrow);
    dtentercodemfm.Rows.Add(objrow1);

    dtentercodemfm.AcceptChanges();

Add 2 rows and 1 columns, You're doing reverse, adding 1 column, and adding 2 rows 添加2行和1列,您正在做反向操作,添加1列,并添加2行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM