如何从数据表中提取值以在C#中列出

时间:2019-03-18 14:35:27

标签: c# sql-server

我有一个称为PurchaseInvoiceForm的采购发票表格。我有一个DataGridView,还使用了一个列表来存储项目,所以我成功地将数据保存到了数据库中。但是,每当我想将数据加载回表单时,一切都很好,除非我无法从DataTable中提取数据并加载回PurchaseInvoiceCart那是一个列表。代码在这里。

    foreach (DataTable row in dtPurchaseInvoice)
        {
            PurchaseInvoice i = new PurchaseInvoice();
            i.PurchaseInvoiceNo =Convert.ToInt32(row["PurchaseInvoiceNo"]);              
        }

3 个答案:

答案 0 :(得分:1)

foreach (DataRow row in dtPurchaseInvoice.Rows)
    {
        PurchaseInvoice i = new PurchaseInvoice();
        i.PurchaseInvoiceNo =Convert.ToInt32(row["PurchaseInvoiceNo"]);              
    }

答案 1 :(得分:1)

要从数据表中提取数据,请使用.Field<T>()中的System.Data.DataSetExtensions扩展方法。请参阅文档DataRow.Field

您需要创建类型为PurchaseInvoice的列表,并遍历DataRow集合table.Rows

请参见以下示例:

// create a list for your invoices
List<PurchaseInvoice> invoices = new List<PurchaseInvoice>();

foreach (DataRow row in dtPurchaseInvoice.Rows)
{   //                                   ^ Rows
    // create invoice
    PurchaseInvoice invoice = new PurchaseInvoice();

    // get an int
    invoice.PurchaseInvoiceNo = row.Field<int>("PurchaseInvoiceNo"); 

    // get a string
    invoice.CustomerName = row.Field<string>("CustomerName");

    // get a DateTime
    invoice.PurchaseDate = row.Field<DateTime>("PurchaseDate");

    // get a double
    invoice.PurchaseValue = row.Field<double>("PurchaseValue");

    // add invoice to list     
    invoices.Add(invoice);
}

使用.Field<T>()扩展名意味着您无需将对象转换/转换为正确的类型-该扩展名将为您处理。

它也适用于可为空的字段:

DateTime? date = row.Field<DateTime?>("PurchaseDate");

答案 2 :(得分:0)

您可以通过这种方式完成。

List<PurchaseInvoice> objPurchaseInvoiceList = new  List<PurchaseInvoice>();
foreach (DataTable row in dtPurchaseInvoice)
{
    objPurchaseInvoiceList.add(new  PurchaseInvoice{ PurchaseInvoiceNo=Convert.ToInt32(row["PurchaseInvoiceNo"])});                  
}