请原谅我,因为我不确定我是否要问正确的方法。当字段名称为“ dynamic”且等于另一个变量时,我需要获取一个字段的值。
我尝试了这个: 这是我的using语句:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Interop.QBFC13;
using CtixQBIntegration.Session_Framework;
using CTixQBIntegration.ExtensionMethods;
using System.Data.OleDb;
using System.IO;
using CTixQBIntegration.Models;
using Newtonsoft.Json;
using System.Linq;
这是我的对象:
public class InvoiceMapping
{
public string ID { get; set; }
public string RefNumber { get; set;}
public string CustomerRef { get; set; }
public string PONumber { get; set; }
public string ItemRef { get; set; }
public string Description { get; set; }
public string Quantity { get; set; }
public string UnitOfMeasure { get; set; }
public string Rate { get; set; }
public string Total { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string Address3 { get; set; }
public string Address4 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
public string ServiceDate { get; set; }
public string TxnDate { get; set; }
public string Note { get; set; }
}
这是我的代码:
DataTable dt = originalDataSource;
DataTable cl = new DataTable();
Invoice invoice = new Invoice();
List<SourceList> invoiceFields = (from prop in invoice.GetType().GetProperties()
select new SourceList()
{
FieldName = prop.Name
}).ToList();
//Check if column names have already been converted
try
{
//Converts Excel Column Names to Quickbooks Column Names
foreach (var item in invoiceFields)
{
cl.Columns.Add(item.FieldName);
}
foreach(var field in invoiceFields)
{
DataRow destRow = cl.NewRow();
foreach(DataRow sourcerow in dt.Rows)
{
foreach(DataColumn col in dt.Columns)
{
string colName = col.ColumnName;
var mappingField = mapping.GetType().GetProperty(field.FieldName).GetValue(colName);
destRow[field.FieldName] = sourcerow[mappingField.ToString()];
}
}
}
dataGridView1.DataSource = null;
dataGridView1.DataSource = cl;
}
我需要从“映射”对象获取值,该对象的字段名称等于field.fieldName。
我讨厌添加太多代码,但它可能有助于某人理解问题。我将其缩短为仅显示前两个字段。这适用于所有“硬编码”的内容,如下所示,问题在于,我需要使它们全部动态化,以便它可以与任何数据源一起使用:
DataTable dt = originalDataSource;
DataTable cl = new DataTable();
cl.Columns.Add("RefNumber");
cl.Columns.Add("CustomerRef");
string refnumber = mapping.RefNumber;
string customerRef = mapping.CustomerRef;
//Check if column names have already been converted
try
{
//Converts Excel Column Names to Quickbooks Column Names
foreach (DataRow sourcerow in dt.Rows)
{
DataRow destRow = cl.NewRow();
foreach (DataColumn col in dt.Columns)
{
if (refnumber != "" && refnumber != null)
{
destRow["RefNumber"] = sourcerow[refnumber];
}
if (customerRef != "" && customerRef != null)
{
destRow["CustomerRef"] = sourcerow[customerRef];
}
}
cl.Rows.Add(destRow);
}
}
非常感谢您的协助。