这个例子主要的思路是建立一个类和数据库查询语句的字段结构是一致的
然后利用反射直接用数据字段名称进行拼凑给类对象的字段进行赋值
类的定义
namespace CCB_DonetClassFolder
{
public class FieldRuleInfo
{
public string gStrFNo;
public string gStrFName;
public string gStrFLock;
public string gStrFCaption;
public string gStrFType;
public string gStrFMust;
public string gStrFMin;
public string gStrFMax;
public string gStrFDefault;
public string gStrFDate;
public string gStrFDB;
public string gStrFAllow;
public string gStrFDisallow;
public string gStrFSB;
public string gStrFBig;
public string gStrFSmall;
public string gStrFInputMethod;
public string gStrFCHK;
public string gStrFRelation;
public string gStrFDesc;
public string gStrFSecond;
public string gStrFQC;
public string gStrFException;
public string gStrFASupp;
public string gStrFYQH;
public string gStrFPos;
public string gStrFStar;
public string gStrFSave;
public string gStrFAddress;
public string gStrFLblColor;
public string gStrFIsCheckList;
}
}
#region 加载字段规则
private bool m_GetRule()
{
string strSQL = "";
DataTable dtGet = null;
#if(DEBUG)
try
{
#endif
if (CommongIntTypeOrder == )
{
strSQL = "select AFNoAFNameAFLockAFCaptionAFType" +
"AFMustAFMinAFMaxAFDefaultAFDatern" +
"AFDBAFAllowAFDisallowAFSBAFBigAFSmallAFInputMethod" +
"AFCHKAFRelationAFDescAFSecondrn" +
"AFQCAFExceptionAFASuppAFYQHAFPosAFStarAFSave"+
"AFAddressAFLblColorAFIsCheckList from P_Field_Rule A rn" +
"INNER JOIN P_Field_Initial B ON AFNo=BFNo rn" +
"where AFormType= AND BFSection= AND " +
"(BFRegion= OR BFRegion=) ORDER BY AFOrder";
}
else
{
strSQL = "select AFNoAFNameAFLockAFCaptionAFType"+
"AFMustAFMinAFMaxAFDefaultAFDatern" +
"AFDBAFAllowAFDisallowAFSBAFBigAFSmall"+
"AFInputMethodAFCHKAFRelationAFDescAFSecondrn" +
"AFQCAFExceptionAFASuppAFYQHAFPosAFStar"+
"AFSaveAFAddressAFLblColorAFIsCheckList "+
"from P_Field_Rule A rn" +
"INNER JOIN P_Field_Initial B ON AFNo=BFNo rn" +
"where AFormType=" + CommongIntFormTypeToString() +
" AND BFSection= AND (BFRegion=" + CommongIntRegionToString() +
" OR BFRegion=) ORDER BY AFOrder";
}
dtGet = DBGetDataTableBySQL(strSQL);
if (dtGetRowsCount <= )
{
CommonShowMessage("字段规则表没有数据请马上联系软件工程师!" MessageBoxIconError);
return false;
}
//获得类信息为下面的反射调用做准备
Type oType = TypeGetType("CCB_DonetClassFolderFieldRuleInfo");
//生成类对象数组和数据库记录个数是一致的
mMainFieldRule = new FieldRuleInfo[dtGetRowsCount];
for (int i = ; i < dtGetRowsCount; i++)
{
//这里使用反射动态为FieldRuleInfo字段赋值数据
mMainFieldRule[i] = new FieldRuleInfo();
for (int j = ; j < dtGetColumnsCount; j++)
{
//这里直接获取类的字段名称然后把数据库里对应字段的值赋值给它
FieldInfo fieldInfo = oTypeGetField("gStr" + dtGetColumns[j]ColumnName
BindingFlagsPublic | BindingFlagsNonPublic | BindingFlagsInstance
| BindingFlagsStatic);
fieldInfoSetValue(mMainFieldRule[i] dtGetRows[i][j]ToString());
}
}
return true;
#if(DEBUG)
}
catch (Exception ex)
{
return false;
MyLogWriteErrLog("frmDEm_GetRule" exMessage);
}
finally
{
dtGet = null;
}
#endif
}
#endregion