我需要检查datatable是否为null然后将行复制到datatable,否则需要将行追加到datatable。 [英] I have a requirement to check if datatable is null then copy the row to datatable otherwise need to append the row to the datatable.

查看:105
本文介绍了我需要检查datatable是否为null然后将行复制到datatable,否则需要将行追加到datatable。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

i have a requirement to check if DataTable is null then copy the row to DataTable otherwise need to append the row to the DataTable.





我尝试过:





What I have tried:

if (dtTable == null)
    {
        dtTable = (from DataRow dr in dtDetails.Rows
                   where dr["ID"].ToString() == Id
                   select dr).CopyToDataTable();
    }
    else
    {
       // Here Need to Add a new row in DataTable and append the output of 
         query into DataTable ie dtTable.

       DataRow row = selectedTable.NewRow();

        dtTable  = (from DataRow dr in dtDetails.Rows
        where dr["ID"].ToString() == Id
        select dr)
        // Need help here

    }

推荐答案

如果DataTable是 null 然后你不能复制任何东西:没有任何东西要复制!



它有点像一个口袋:你有一个口袋里面你的衬衫,用来握笔。如果你进入口袋并发现那里没有笔,你就不能在一张纸上签名 - 如果你尝试的话,你会得到非常有趣的外观!

但是你要做的就是伸进口袋,而你甚至不穿衬衫!你不能检查口袋的笔,因为口袋根本不存在。



如果你想将数据复制到DataTable并且变量是 null ,你必须创建一个表的实例来添加它。



在这种情况下,所有你需要做的是使用Add方法:

If a DataTable is null then you can't copy anything to it: there isn't anything to copy into!

It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try!
But what you are trying to do is reach into a pocket while you aren't even wearing a shirt! You can't check the pocket for a pen, because the pocket isn't there at all.

If you want to copy data to a DataTable and the variable is null, you have to create an instance of a table to add it to.

In this case, all you need to do is use the Add method:
else
    {
        dtTable.Rows.Add (from DataRow dr in dtDetails.Rows
        where dr["ID"].ToString() == Id
        select dr)


这篇关于我需要检查datatable是否为null然后将行复制到datatable,否则需要将行追加到datatable。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆