RowDataBound function of GridView

后端 未结 2 1275
别跟我提以往
别跟我提以往 2020-12-12 01:15

I have a DataTable that contains 3 fields: ACount, BCount and DCount. If ACount < 0 then I need to displa

相关标签:
2条回答
  • 2020-12-12 01:29

    This has worked for me.... I must be misunderstanding something so I had to replace angled brackets with [ or ] for the ASP so just be aware of that.

     [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 += "...";
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-12 01:43

    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.

    0 讨论(0)
提交回复
热议问题