简体   繁体   English

如何在C#中修改数据表中的数据

[英]How to modify data within datatable in C#

I'm using Visual Studio 2008 (Asp.net (c#)) and SQl Server 2005 I have a datatable ("dtReportList") generated from database query and then I show the datatable by a gridview. 我正在使用Visual Studio 2008(Asp.net(c#))和SQl Server 2005,我有一个通过数据库查询生成的数据表(“ dtReportList”),然后通过gridview显示该数据表。
dtReportList = GetReportList(UserId); dtReportList = GetReportList(UserId); //get data from database //从数据库获取数据
GridView1.DataSource = dtReportList; GridView1.DataSource = dtReportList;
GridView1.DataBind(); GridView1.DataBind();

The output data of datatable will be:: datatable的输出数据将是:

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

I want to modify the DataTable before to assign it to the Grid's DataSource. 我想先修改DataTable,然后再将其分配给Grid的DataSource。 I want to modify the ReportName data of each row. 我想修改每一行的ReportName数据。

I cannot modifed the GetReportList method because is heavily used, so my only chance is to modify the DataTable before I will use it. 我不能修改GetReportList方法,因为该方法被大量使用,所以我唯一的机会是在使用DataTable之前先对其进行修改。

Is it possible to do it? 有可能做到吗? How can I do it? 我该怎么做?

I was thinking to do something like this? 我在想做这样的事情?

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();  

Thanks again for your help. 再次感谢你的帮助。

your code will work normally , what is the problem? 您的代码将正常工作,这是什么问题? the other choice is to write extension method and use it when needed, something like this 另一个选择是编写扩展方法并在需要时使用它,就像这样

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM