c#去除DataTable空列

网上搜了好多,没找到能用的,自己写一个,有发现错误的给我留言。

  private void RemoveNULLColumns(ref DataTable data)//删除空列
        {
            try
            {
                DataTable newData = new DataTable();

                for (int n = 0; n < data.Rows.Count-1; n++)//添加行
                {
                    newData.Rows.Add();
                }
                for (int i = 0; i < data.Columns.Count; i++)//遍历列
                {
                    for (int r = 0; r < data.Rows.Count; r++)//查询行内的数据
                    {
                        if (data.Rows[r][i].ToString() != "")//不是空的话
                        {
                            string columnName = data.Columns[i].ColumnName;
                            newData.Columns.Add(columnName);
                            for (int n = 0; n < data.Rows.Count; n++)
                            {
                                newData.Rows[n][newData.Columns.Count - 1] = data.Rows[n][i];
                            }
                            break;
                        }
                    }
                }
                data = newData;
            }
            catch { }
        }

 

posted @ 2018-12-11 16:06  张统  阅读(2898)  评论(0编辑  收藏  举报