【问题标题】:Change DataTable Column Value更改 DataTable 列值
【发布时间】:2011-07-16 12:31:02
【问题描述】:

我有一个这样的数据表:

Attribute          Percentage      ReferenceAmount        TaxAmount
------------       ------------     ----------------      -----------
  Sales              5.00             5000                  250
  VAT                2.00             250                   5
  Discount            0                 0                   100

我想用一个 GridView 绑定这个 DataTable。 但是在 GridView 中,我不想显示 0。我只想将该单元格留空,而不是零。如果包含零,我不想显示任何其他内容。 如何在 DataTable 中替换 EmptyString 而不是零?

【问题讨论】:

    标签: c# asp.net gridview datatable


    【解决方案1】:

    我回答问题晚了,我知道答案已被接受。但在接受的答案中,您是在数据绑定之后迭代行,然后设置值。

    在 DataBinding 时替换值会更好。它将克服 gridview 行迭代的额外开销。

    您可以使用 GridView 的RowDataBound 事件。这是完整的代码..

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        System.Data.DataRow dr = ((System.Data.DataRowView)e.Row.DataItem).Row;
    
        if (dr["Percentage"].ToString() == "0")
        {
            ((Label)e.Row.FindControl("lblPercentage")).Text = "";
            //this is template field
            //OR---If you don't use template field you  can do like..--
            e.Row.Cells[1].Text  = "";
        }      
    }
    }
    

    【讨论】:

      【解决方案2】:

      以下 GridView DataBound 方法将遍历 GridView 中的每个单元格,并将“0”替换为空字符串:

              protected void GridView1_DataBound(object sender, EventArgs e)
              {
                  foreach (GridViewRow row in GridView1.Rows)
                  {
                      for (int i = 0; i < row.Cells.Count - 1; i++)
                      {
                          if (row.Cells[i].Text == "0")
                          {
                              row.Cells[i].Text = "";
                          }
                      }
                  }
              }
      

      【讨论】:

        【解决方案3】:

        您可以轻松地将名为 PercentageDescription 的属性添加为字符串

         public string PercentageDescription
         {
            return Percentage == 0 ? " " : Percentage.ToString();
         }
        

        【讨论】:

          猜你喜欢
          • 2016-06-01
          • 2011-04-13
          • 2018-11-29
          • 1970-01-01
          • 1970-01-01
          • 2018-11-15
          • 2011-04-15
          • 2019-02-28
          • 2011-11-02
          相关资源
          最近更新 更多