Reputation: 4319
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?
Upvotes: 2
Views: 23638
Reputation: 119806
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.
Upvotes: 6
Reputation: 31
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 += "...";
}
}
}
Upvotes: 2