GridView的RowDataBound函数

时间:2009-03-14 04:58:53

标签: asp.net vb.net

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

2 个答案:

答案 0 :(得分:5)

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字符呈现的位置,但你应该能够重新调整以满足你的需求。

答案 1 :(得分: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 += "...";
        }
    }
}