2009-03-14 7 views
2

J'ai un DataTable qui contient 3 champs: ACount, BCount et DCount. Si ACount < 0 alors j'ai besoin d'afficher 'S' dans l'une des colonnes du GridView. Si ACount > 0 alors je dois afficher 'D' dans cette colonne (dans l'étiquette). Même chose avec BCount et DCount. Comment puis-je effectuer cette vérification conditionnelle dans la fonction RowDataBound?Fonction RowDataBound de GridView

+0

Quelle version de .NET framework utilisez-vous et quel contrôle essayez-vous d'utiliser, DataGridView? –

Répondre

5

L'événement GridView OnRowDataBound est votre ami:

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

Je ne sais pas où vous voulez que le « S » et « D caractères rendus, mais vous devriez être en mesure de remanier pour répondre à vos besoins.

2

Cela a fonctionné pour moi .... Je dois être malentendu quelque chose alors j'ai dû remplacer les supports angulaires avec [ou] pour l'ASP donc juste être conscient de cela.

[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 += "..."; 
     } 
    } 
}