GridView的RowDataBound函数

use*_*348 2 vb.net asp.net

我有一个DataTable包含3个领域:ACount,BCountDCount.如果ACount < 0那时我需要在其中一列中显示"S" GridView.如果ACount > 0那时我必须在该列中显示"D"(在标签中).同样的事情BCountDCount.我怎样才能在RowDataBound函数中进行这种条件检查?

Kev*_*Kev 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";
}
Run Code Online (Sandbox Code Playgroud)

我不确定你想要'S'和'D字符呈现的位置,但你应该能够重新调整以满足你的需求.