源代码如下:
Code
/// <SUMMARY>
/// 依据反射机制从bean中取值向datatable新增行
/// </SUMMARY>
/// <PARAM name="obj" />要实例的对象
/// <PARAM name="dataTable" />DataTable
public static void InstanNewDataRowFromBean(Object obj, DataTable dataTable)
{
//DataTable列为空!
if (dataTable.Columns.Count < 1)
{
throw new Exception("DataTable列为空!");
}
DataRow dr = dataTable.NewRow();
Type type = obj.GetType(); //获取对象类型
PropertyInfo[] pInfos = type.GetProperties();
try
{
for (int i = 0; i < dataTable.Columns.Count; i++) //循环所有列
{
for (int j = 0; j < pInfos.Length; j++) //循环所有属性
{
//比较的作用是防止数据库列名的大小写和属性的大小写不一致
if (dataTable.Columns[i].ColumnName.ToLower() == pInfos[j].Name.ToLower())
{
PropertyInfo pInfo = type.GetProperty(pInfos[j].Name); //反射机制,动态检索类属性
object beanValue = pInfo.GetValue(obj, null);
//不同的基本数据类型,比如用Convert方法转换成对应类型的值
if (!Convert.IsDBNull(beanValue) && beanValue.ToString() != null) //如果数据集中此列有值
{
dr[i] = beanValue;
}
else
{
dr[i] = DBNull.Value;
}
break;
}
}
}
dataTable.Rows.Add(dr);
}
catch (Exception ex)
{ //不捕获异常,异常抛出由开发人员处理
throw ex;
}
}
/// <SUMMARY>
/// 依据反射机制从bean中取值向datatable新增行
/// </SUMMARY>
/// <PARAM name="obj" />要实例的对象
/// <PARAM name="dataTable" />DataTable
public static void InstanNewDataRowFromBean(Object obj, DataTable dataTable)
{
//DataTable列为空!
if (dataTable.Columns.Count < 1)
{
throw new Exception("DataTable列为空!");
}
DataRow dr = dataTable.NewRow();
Type type = obj.GetType(); //获取对象类型
PropertyInfo[] pInfos = type.GetProperties();
try
{
for (int i = 0; i < dataTable.Columns.Count; i++) //循环所有列
{
for (int j = 0; j < pInfos.Length; j++) //循环所有属性
{
//比较的作用是防止数据库列名的大小写和属性的大小写不一致
if (dataTable.Columns[i].ColumnName.ToLower() == pInfos[j].Name.ToLower())
{
PropertyInfo pInfo = type.GetProperty(pInfos[j].Name); //反射机制,动态检索类属性
object beanValue = pInfo.GetValue(obj, null);
//不同的基本数据类型,比如用Convert方法转换成对应类型的值
if (!Convert.IsDBNull(beanValue) && beanValue.ToString() != null) //如果数据集中此列有值
{
dr[i] = beanValue;
}
else
{
dr[i] = DBNull.Value;
}
break;
}
}
}
dataTable.Rows.Add(dr);
}
catch (Exception ex)
{ //不捕获异常,异常抛出由开发人员处理
throw ex;
}
}