我會盡可能地解釋我的情況。在c#中改變DataTable的方法?
我有一個DataTable包含幾個數據,稍後將生成一個報告。其中一列是DateTime類型。問題是當報告顯示日期時,它們以長格式「10/14/1996 12:00:00 AM」顯示,並且它們需要以格式 「DD-MMM-YYYY」顯示。
我已經嘗試了幾件事情,將dataTable中的值更改爲所需的格式。 我嘗試這樣做:
for (int i = 0; i < dt.Rows.Count; i++)
{
DateTime cellValueDateOfBirth=Convert.ToDateTime(dt.Rows[i][indexDateOfBirth]);
string formattedDateOfBirth = cellValueDateOfBirth.ToString("DD-MMM-YYYY");
dt.Rows[i].SetField(indexDateOfBirth, formattedDateOfBirth);
dt.Rows[i].ItemArray.SetValue(formattedDateOfBirth, indexDateOfBirth);
}
不工作,因爲當我調試,我看到的
string test = dt.Rows[i].ItemArray[indexDateOfBirth].ToString();
值未設置爲formattedDateOfBirth的值,如我所料。該報告仍然生成未格式化的日期。
我試了幾種方法來改變那個日期的值,但沒有成功。
我真的不關心所有的dateTime數據,所以我在想這是一個好主意(萬一不可能簡單地改變日期列的值)來創建一個包含所有數組的數組格式化的值,然後找到一種方法來刪除具有未格式化日期的列,並將其替換爲(使用格式化日期創建的新陣列)(如果可能,將其替換爲原始位置)。 我已經創建了該數組,但不知道如何用數組中的值替換列值。這是我到目前爲止有:
string[] FormattedDatesOfBirth = new string[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
DateTime cellValueDateOfBirth=Convert.ToDateTime(dt.Rows[i][indexDateOfBirth]);
string formattedDateOfBirth = cellValueDateOfBirth.ToString(EMR.HelperClasses.Core.chsDateFormat);
FormattedDatesOfBirth[i] = formattedDateOfBirth;
}
//then here I would create a column with the data in FormattedDatesOfBirth[]
一些其他的想法是讓DataTable的副本,但不能複製格式化列並添加相反,格式化值的數組。
你認爲這是可能的嗎?有沒有另一種方法來做到這一點?也許我試圖以錯誤的方式改變數值......
我真的不確定是否還有其他更好的解決方案,我會很樂意聽到您的所有建議,我對此沒有任何意見。任何幫助將不勝感激。
不會在DataTable中更改!報告格式! –
@MitchWheat我不知道如何:(這是一個DevExpress XtraReport。 –
閱讀文檔.... –