Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
511 views
in Technique[技术] by (71.8m points)

asp.net - RowDataBound function of GridView

I have a DataTable that contains 3 fields: ACount, BCount and DCount. If ACount < 0 then I need to display 'S' in one of the columns of the GridView. If ACount > 0 then I have to display 'D' in that column(in label). Same thing with BCount and DCount. How can I do this conditional check in the RowDataBound function?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The GridView OnRowDataBound event is your friend:

<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";
}

I'm not sure where you want the 'S' and 'D characters rendered, but you should be able to rejig to meet your needs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...