【问题标题】:RowDataBound function of GridViewGridView的RowDataBound函数
【发布时间】:2009-03-14 04:58:52
【问题描述】:

我有一个 DataTable,其中包含 3 个字段:ACountBCountDCount。如果ACount < 0,那么我需要在GridView 的列之一中显示“S”。如果ACount > 0 则我必须在该列中显示“D”(在标签中)。与BCountDCount 相同。如何在RowDataBound 函数中进行这种条件检查?

【问题讨论】:

  • 你使用的是什么版本的 .NET 框架,你想使用什么控件,DataGridView?

标签: asp.net vb.net


【解决方案1】:

GridView OnRowDataBound 事件是你的朋友:

<asp:gridview
  id="myGrid" 
  onrowdatabound="MyGrid_RowDataBound" 
  runat="server">

  <columns>
    <asp:boundfield headertext="ACount" datafield="ACount"  />
    <asp:boundfield headertext="BCount" datafield="BCount" />
    <asp:boundfield headertext="DCount" datafield="DCount" />
    <asp:templatefield headertext="Status">
      <itemtemplate>
        <asp:label id="aCount" runat="server" />
        <asp:label id="bCount" runat="server" />
        <asp:label id="dCount" runat="server" />
      </itemtemplate>
    </asp:templatefield>
  </columns>
</asp:gridview>

// Put this in your code behind or <script runat="server"> block
protected void MyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
  if(e.Row.RowType != DataControlRowType.DataRow)
  {
    return;
  }

  Label a = (Label)e.Row.FindControl("aCount");
  Label b = (Label)e.Row.FindControl("bCount");
  Label d = (Label)e.Row.FindControl("dCount");

  int ac = (int) ((DataRowView) e.Row.DataItem)["ACount"];
  int bc = (int) ((DataRowView) e.Row.DataItem)["BCount"];
  int dc = (int) ((DataRowView) e.Row.DataItem)["DCount"];

  a.Text = ac < 0 ? "S" : "D";
  b.Text = bc < 0 ? "S" : "D";
  d.Text = dc < 0 ? "S" : "D";
}

我不确定您希望在哪里渲染“S”和“D”字符,但您应该能够重新调整以满足您的需求。

【讨论】:

    【解决方案2】:

    这对我有用....我一定是误解了一些东西,所以我不得不用 [ 或 ] 替换 ASP 的尖括号,所以请注意这一点。

     [asp:TemplateField runat="server" HeaderText="Header"]
     [ItemTemplate]
     [asp:Label ID="theLabel" runat="server" Text='[%# Eval("DataSource").ToString() 
      %]'][/asp:Label]
     [/ItemTemplate]
     [/asp:TemplateField]
    
    
     protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
     {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label newLabel = (Label)e.Row.FindControl("theLabel");
    
            if (newLabel.Text.Length > 20) //20 is cutoff length
            {
                newLabel.Text = lbl.Text.Substring(0, 20);
    
                newLabel.Text += "...";
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-24
      • 2010-10-03
      • 2014-04-06
      • 1970-01-01
      相关资源
      最近更新 更多