close
這個小問題著實也費了番功夫
一開始很天真的以為只要是繫結欄位都只要用
GridView.Rows(Index).Cell(Index).Text 就可以取得
無奈如果你的欄位是一個ButtonField或是HyperLinkField他只會回傳給你一個空字串
 
原是啥呢...因為這兩種欄位他還是有自己的Text屬性
但是如我們要依照資料庫篩選的資料來顯示 就會去設定 DataTextField 屬性為對應的欄位名稱
 
如果同時設定Text跟DataTextField那Text屬性會無效
但是我沒有去測試這樣是否就會取到Text的值 ~ 反正我們要的是變動的值 ~
 
那要怎麼取得DataTextField上的文字呢
這個問題的資料查起來還真的不多
有一部分的解答是錯誤的 後來找的一份正確的
 
解決辦法就是取值前要先行別轉換(而且要做正確的轉換)
 
錯誤的資料如下:
C# 語法 
string Mystr1 = ((HyperLink)row[RIndex].Cells[CIndex].Controls[0]).Text;
string Mystr2 = ((Button)row[RIndex].Cells[CIndex].Controls[0]).Text
VB 語法
string Mystr1 = CType(GridView1.Rows(RIndex).Cells(CIndex).Controls(0), HyperLink).Text
string Mystr2 = CType(GridView1.Rows(RIndex).Cells(CIndex).Controls(0), Button).Text
 
正確語法如下
C#語法
string Mystr1 = ((HyperLink)row[RIndex].Cells[CIndeex].Controls[0]).Text;
string Mystr2 = ((LinkButton)row[RIndex].Cells[CIndex].Controls[0]).Text
VB 語法
string Mystr1 = CType(GridView1.Rows(RIndex).Cells(CIndex).Controls(0), HyperLink).Text
string Mystr2 = CType(GridView1.Rows(RIndex).Cells(CIndex).Controls(0), LinkButton).Text
 
HyperLinkField轉換型別為HyperLink沒有問題
但是ButtonField的部分 則是轉換成LinkButton而不是Button
 
ps補充
依照 網友 啤 的方法測試了一下
 
發現
要做哪一種型別轉換
得看ButtonField中的ButtonType
如果是Button那原本 我已為錯誤的語法是可行的 網友啤 的語法也是ok的
但是寫此篇文章當時跟開始接觸ASP.net 所以 不知道ButtonField的ButtonType可以改
而預設ButtonType是Link 可以改成 Image 跟 Button
所以要識 所選擇的 ButtonType而決定要轉換成哪種型別
arrow
arrow
    全站熱搜

    ADOLPH 發表在 痞客邦 留言(1) 人氣()