ASP.NET 2.0 GridView裡加了一個BoundField,資料型別是日期,我打算把DataFormatString設成{0:yyyy-MM-dd HH:mm:ss}讓它顯示得更整齊一點,但網頁上ASP.NET並沒有套用我指定的格式。如果我火大連{0:...}都不加,而把它調成"SHIT"之類的發洩性字眼,GridView倒是乖乖地拉出一大堆狗屎... orz

試了好久,最後查到網路上的相關文章,說將HtmlEncode屬性設為false即可解決DataFormatString設定無效的問題,並視之為BUG。但我最後追到MS關於BoundField.DataFormatString的官方Reference,裡面有一段Note:

When the HtmlEncode property is true, the value of the field is HTML encoded to its string representation before the formatting string is applied. For some objects, such as dates, you might want to control how the object is displayed with a formatting string. In those cases, you must set the HtmlEncode property to false.

套句MS愛用的說法,It's ** BY DESIGN **, not a bug.  沒耐心好好先看完Reference的人就要中招囉!

PS: 雖然官方參考書中就有說明,我覺得應該在Property Window下方顯示DataFormatString Description時就加註這段警語,以造福我等個性急躁、不耐查書的火爆浪子。算了算,繞這一圈耗了近半小時,我寶貴的青春哪~~~


Comments

# by huge

您好,在網路上看darkthread的文章實在惠我良多,不知道dt兄是否曉得如何動態去設定每一個BoundField的DataFormatString呢?目前小弟遇到某些特殊情況需要將DataFormatString進行設定的動作,不過在許多event及GridView的元件裡,都沒有找到相關的方法,先行謝過 mail : huge.huang@gmail.com

# by huge

dt兄您好,剛剛因為系統錯誤,打的文章就此付之一炬 ~_~ 主要想請教您關於如何動態設定GridView BoundField裡的DataFormatString。這部份困擾小弟許久,不過始終找不到在GridView的什麼event或是class下可以進行DataFormatString的設定 : (

# by Jeffrey

我不很是確定你要做的事,如果是程式跑起來後才要設定DataFormatString,可以將GridView的Column轉型成BoundField就可以設定了。如下例: BoundField bf = GridView1.Columns[0] as BoundField; bf.DataFormatString = "{0:yyyyMMdd}";

# by sam

不小心發現 在vs2008中 這個問題以經不存在了 不管true or false 日期都可以正常顯示也

# by Cycer

我也中獎了~ 因為我寫的程式不能在Server上正常顯示 經測試後發現 我是用 .Net framework 2.0 SP1 而其它人是用.Net framework 2.0 所以SP1有修正這個問題 不用再加上HtmlEncode

Post a comment