如何在网格视图中将负数放在括号中

时间:2012-12-05 20:26:04

标签: c# asp.net sql

  

可能重复:
  How can I stop the time from displaying in a GridView when displaying a date?

我在名为“总计”的列中有负数的网格视图,我喜欢将所有负数放在括号中。

e.g。

Total
76  
(-66)
646  
(-76)  
(-10)  
(-6) 
16  
676

我正在使用带有C#的ASP.NET,我应该怎么做。

或者我可以在SQL Query中执行此操作;正在通过sql数据源填充网格视图。

3 个答案:

答案 0 :(得分:1)

看看这个简单的例子。我正在使用Gridview:

C#

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        List<int> x = new List<int>() { 76, -66, 646, -76, -10, -6, 16, 676 };
        this.GridView1.DataSource = x;
        this.GridView1.DataBind();
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (Convert.ToInt32(e.Row.Cells[0].Text) < 0)
            {
                e.Row.Cells[0].Text = "(" + e.Row.Cells[0].Text + ")";
            }
        }

    }
}

输出:

Item
76
(-66)
646
(-76)
(-10)
(-6)
16
676
祝你好运

编辑:我不会修改SQL的outpupt以使其仅适用于此。

答案 1 :(得分:1)

我会做类似于Hanlet Escano的事情,但不是解析,我会像这样对待数据对象:

Default.aspx的

<asp:GridView ID="gvGrid" runat="server" AutoGenerateColumns="false" OnRowDataBound="gvGrid_RowDataBound">
  <Columns>
    <asp:TemplateField>
      <ItemTemplate>
        <asp:Literal ID="litData" runat="server" />
      </ItemTemplate>
    </asp:TemplateField>
  </Columns>
</asp:GridView>

Default.aspx.cs

protected void Page_Load(object sender,EventArgs e)       {         if(!IsPostBack)         {           //生成数据           var data = new List(){76,-66,646,-76,-10,-6,16,676};

      gvGrid.DataSource = data;
      gvGrid.DataBind();
    }
  }

  protected void gvGrid_RowDataBound(object sender, GridViewRowEventArgs e)
  {
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
      //Strongly Type Controls
      var litData = (Literal)e.Row.FindControl("litData");

      //Strongly Type Data
      var data = (int)e.Row.DataItem;

      //Display Data
      if (data < 0)
      {
        litData.Text = "[" + data.ToString() + "]";
      }
      else
      {
        litData.Text = data.ToString();
      }
    }
  }

这有几个好处,数据已经以其原生形式(int)存储,它只是在一个对象变量中。

其次,如果将来您需要处理具有更复杂数据对象(Person / Business / Foo / Bar对象)的多个列,则可以使用相同的技术。

答案 2 :(得分:0)

使用gridview的onRowDataBound事件并根据需要更新单元格,添加括号和东西:)

检查出来:

http://www.dotnetfunda.com/forums/thread9403-get-the-particular-value-in-gridview-using-rowdatabound-in-csharpnet.aspx