2009-03-14 20 views
2

私はDataTableに、ACount,BCountおよびDCountの3つのフィールドを含んでいます。 ACount < 0の場合は、GridViewのいずれかの列に「S」を表示する必要があります。 ACount > 0の場合、その列に(ラベル内に)「D」を表示する必要があります。 BCountDCountと同じことです。 RowDataBound関数でこの条件付きチェックを行うにはどうすればよいですか?GridViewのRowDataBound関数

+0

.NET Frameworkのどのバージョンを使用していますか、どのコントロールを使用しようとしていますか、DataGridView? –

答えて

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の文字を配置したい場所を私はわからないんだけど、あなたはあなたのニーズを満たすためにrejigすることができるはずです。

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 += "..."; 
     } 
    } 
} 
関連する問題