簡體   English   中英

如何在C#中修改數據表中的數據

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

我正在使用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();  

再次感謝你的幫助。

您的代碼將正常工作,這是什么問題? 另一個選擇是編寫擴展方法並在需要時使用它,就像這樣

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