Fred
Fred

Reputation: 4076

ASP.Net, Datagrid: render column differently based upon value?

I've looked and looked and I'm not seeing the answer to this.

I have a datetime value that's getting bound to a datagrid. I want to display the column as either the datetime, or if said datetime is null, an asp:button for the users to click.

I can't seem to find specific information on how to do it. My initial approach was <% if blah blah then %>, but I can't seem to get at the dataitem in that manner. I've also looked at events, but nothing is jumping out at me as being the solution (I'm sure I'm wrong, I'm just not seeing it).

Any suggestions?

Upvotes: 0

Views: 583

Answers (2)

dotnetN00b
dotnetN00b

Reputation: 5131

You should use Gridview if you are using ASP.NET 3.5 or higher. Using a templatefield column, add a button and label. In the rowdatabound event, you should show only the button or the label, using the Visible property, depending on whether there's a date or not.

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460208

Assuming that you actually mean GridView instead of DataGrid, otherwise it would work similarly(ItemDataBound etc.).

You could use a TemplateField with a Label and a Button and switch visibility of both controls in RowDataBound:

protected void Grid_RowDataBound(Object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        var row = ((DataRowView)e.Row.DataItem).Row;
        DateTime? date = row.Field<DateTime?>("DateColumn");
        var lblDate = (Label)e.Row.FindControl("LblDate");
        var btnDate = (Button)e.Row.FindControl("BtnDate");
        lblDate.Visible = date.HasValue;
        btnDate.Visible = !date.HasValue;
        if (date.HasValue) lblDate.Text = date.ToString();
    }
}

aspx:

<asp:GridView ID="GridView1" AutoGenerateColumns="false" OnRowDataBound="Grid_RowDataBound" runat="server">
<Columns>
    <asp:TemplateField HeaderText="DateColumn">
        <ItemTemplate>
            <asp:Label ID="LblDate" runat="server"></asp:Label>
            <asp:Button ID="BtnDate" Text="click me" runat="server"  />
        </ItemTemplate>
    </asp:TemplateField>
</Columns>
</asp:GridView>

Upvotes: 1

Related Questions