今天,在vs2005下将SqlDataReader 转换为DataTable时,出现了 "值类型与列类型不匹配不能在 ID 列中存储 <30>。所需类型是 DataRow"的错误码,后来查了后,原来是这里的问题,查找相关资料后发现,(把蓝字部分修改成红字部分),修改成功

 

public static DataTable ConvertDataReaderToDataTable(OleDbDataReader dataReader)
        {
            //定义DataTable和模式
            DataTable datatableTemp = new DataTable();
            DataTable schemaTable = dataReader.GetSchemaTable();
            try
            {
                //动态添加表的数据列
                foreach (DataRow myRow in schemaTable.Rows)
                {
                    DataColumn myDataColum = new DataColumn();

                    //myDataColum.DataType = myRow.GetType(); 
                    myDataColum.DataType = System.Type.GetType("System.String"); 
                    myDataColum.ColumnName = myRow[0].ToString();
                    datatableTemp.Columns.Add(myDataColum);
                }

                //添加表的数据
                while (dataReader.Read())
                {
                    DataRow myDataRow = datatableTemp.NewRow();
                    for (int i = 0; i < schemaTable.Rows.Count; i++)
                    {
                        myDataRow[i]= dataReader[i].ToString();
                    }
                    datatableTemp.Rows.Add(myDataRow);
                    myDataRow = null;
                }
                schemaTable = null;
                dataReader.Close();
                return datatableTemp;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }

        }

posted on 2014-05-22 16:49  将来时  阅读(1528)  评论(1编辑  收藏  举报