2012-10-05 27 views
3

我使用BoundFields實現了GridView(動態創建)。我想更改DataBound事件上的BoundField值。該值包含布爾值(True/False),我需要將它們更改爲「Active」/「Inactive」。如果這不是動態GridView,我會使用TemplateField,但是,由於我動態創建GridView,最簡單的方法是在BoundField中執行操作。在DataBound事件上更改GridView的BoundField值

但我不明白如何改變它。

這是正確的解僱我的DataBound事件:

protected void gr_RowDataBound(object sender, GridViewRowEventArgs e) 
    { 
     DataRowView drv = (DataRowView)e.Row.DataItem; 
     if (e.Row.RowType == DataControlRowType.DataRow) 
     { 
      if (drv["IsRegistered"] != DBNull.Value) 
      { 
       bool val = Convert.ToBoolean(drv["IsRegistered"]); 
       //???? HOW TO CHANGE PREVIOUS VALUE TO NEW VALUE (val) HERE? 
      } 
     } 
    } 
+0

這對我來說似乎並不那麼容易。我試圖在網上找到一些很好很容易的例子,但是不能。另外對於其他一些列,我需要調用其他方法來格式化數據。 – renathy

+0

我有一個類似的場景:許多使用綁定字段的Gridviews。默認情況下,bool值呈現「True」或「False」。我希望他們翻譯成德語,如「Ja」/「Nein」。看到我的答案... – Tillito

回答

6

隨着BoundFields不能使用FindControl找到一個TemplateField控制來設置它的Text屬性實例。相反,你設置Cell-Text

protected void gr_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    DataRowView drv = (DataRowView)e.Row.DataItem; 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     if (drv["IsRegistered"] != DBNull.Value) 
     { 
      bool val = Convert.ToBoolean(drv["IsRegistered"]); 
      // assuming that the field is in the third column 
      e.Row.Cells[2].Text = val ? "Active" : "Inactive"; 
     } 
    } 
} 

除此之外,你甚至可以在動態GridView使用TemplateFields

How to add TemplateField programmatically

+0

我也發佈了我的代碼,這也適用於你不知道哪些是bool字段的情況。 – Tillito

0

在我的情況,我甚至不知道該名稱或包含布爾值的列的索引。因此,我首先檢查單元格的值是「真」還是「假」,如果是,我記得它的索引。在此之後,我知道索引,如果沒有,我什麼都不做,如果我找到了,然後我重播它的價值。

這是我的工作代碼:

// Cache of indexes of bool fields 
private List<int> _boolFieldIndexes; 

private void gvList_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    //-- if I checked and there are no bool fields, do not do anything 
    if ((_boolFieldIndexes == null) || _boolFieldIndexes.Any()) 
    { 
     if (e.Row.RowType == DataControlRowType.DataRow) 
     { 
      //-- have I checked the indexes before? 
      if (_boolFieldIndexes == null) 
      { 
       _boolFieldIndexes = new List<int>(); 
       for (int i = 0; i < e.Row.Cells.Count; i++) 
       { 
        if ((e.Row.Cells[i].Text == "True") || (e.Row.Cells[i].Text == "False")) 
        { 
         // remember which column is a bool field 
         _boolFieldIndexes.Add(i); 
        } 
       } 
      } 
      //-- go through the bool columns: 
      foreach (int index in _boolFieldIndexes) 
      { 
       //-- replace its value: 
       e.Row.Cells[index].Text = e.Row.Cells[index].Text 
        .Replace("True", "Ja") 
        .Replace("False", "Nein"); 
      } 
     } 
    } 
} 

的好處是,這適用於任何的GridView。只需附加活動。