【问题标题】:How to modify data within datatable in C#如何在C#中修改数据表中的数据
【发布时间】:2026-02-13 08:45:02
【问题描述】:

我正在使用 Visual Studio 2008 (Asp.net (c#)) 和 SQl Server 2005 我有一个从数据库查询生成的数据表(“dtReportList”),然后我通过 gridview 显示数据表。
dtReportList = GetReportList(UserId); //从数据库中获取数据
GridView1.DataSource = dtReportList;
GridView1.DataBind();

datatable的输出数据为::

ReportId    ReportName      CreatedDate
1           DummyReport1    21/08/2009
2           DummyReport2    21/08/2009
3           DummyReport4    21/08/2009

我想修改 DataTable 之前将其分配给 Grid 的 DataSource。 我想修改每一行的ReportName数据。

我无法修改 GetReportList 方法,因为它被大量使用,所以我唯一的机会是在使用之前修改 DataTable。

有可能吗? 我该怎么做?

我正在考虑做这样的事情?

dtReportList = GetReportList(UserId); //get data from database  
foreach(DataRow report in dtReportList.Rows)  
{  
    Guid reportId = new Guid(report["ReportId"].ToString());  
    string reportTitle = GetReportTitle(conn, reportId, UserId,
        GetReportLanguage(reportId));  
    report["ReportName"] = reportTitle;  
}  
GridView1.DataSource = dtReportList;  
GridView1.DataBind();  

再次感谢您的帮助。

【问题讨论】:

    标签: c# datatable


    【解决方案1】:

    您的代码将正常工作,有什么问题?另一种选择是写extension method并在需要时使用它,像这样

    public static class ReportsExtensions
    {
    
        public static GetChangedList(this ReportsTable tbl)
        {
            foreach(DataRow report in tbl)  
            {  
                 Guid reportId = new Guid(report["ReportId"].ToString());  
                 string reportTitle = GetReportTitle(conn, reportId, UserId, GetReportLanguage(reportId));  
                 report["ReportName"] = reportTitle;  
            }  
        }
    }
    GridView1.DataSource = dtReportList.GetChangedList();  
    GridView1.DataBind();
    

    【讨论】:

    • 谢谢。我没有得到在 DataTable 中所做的更改(也许我没有正确编译代码)。我更喜欢你的代码,因为如果需要,我可以在任何地方使用它。