开发者

How do I convert a BoundField to a HyperLinkField?

开发者 https://www.devze.com 2023-03-29 14:20 出处:网络
I have a GridView (gv) bound to a dataset (ds). Columns[1] is bound to a field in ds named orderFilename; Columns[6] is a date field.开发者_C百科

I have a GridView (gv) bound to a dataset (ds). Columns[1] is bound to a field in ds named orderFilename; Columns[6] is a date field.

开发者_C百科

If Columns[6] is null, I want Columns[1] to appear as text; if Columns[6] is not null, I want Columns[1] to appear as a hyperlink, with a url ~/directory/ + orderFilename.

I have found a couple possible solutions on the Web but none seem to do what I want. Any help would be appreciated.


I prefer to stay away from BoundFields specifically because the next guy needs to always seem to convert them to template fields anyways to do customizations. I would recommend the following:

Use a template field with a Literal control for your column 1:

<asp:TemplateField HeaderText="File">
    <ItemTemplate>
        <asp:Literal ID="ltFilename" runat="server" 
            OnDataBinding="ltFilename_DataBinding" />
   </ItemTemplate>
</asp:TemplateField>

Then implement the OnDataBinding for the columns control:

protected void ltFilename_DataBinding(object sender, System.EventArgs e)
{
    Literal lt = (Literal)(sender);
    if (Eval("yourColumn6Field") == DBNull.Value)
    {
        // just show a text filename
        lt.Text = Eval("orderFilename").ToString();
    }
    else
    {
        // produce the link
        lt.Text = string.Format("<a href='{0}'>{1}</a>",
             ResolveUrl("~/directory/" + Eval("orderFilename").ToString()),
             Eval("orderFilename").ToString());
    }
}

The advantage to this is you have localized the logic directly to the control. You can easily swap it out and change it around without affecting other parts of the grid accidently.


Let's say, you have added a hyperlink control in column[1], If the column[6] is not null then you can set the NavigateURL property and set the URL. In this case, it will look like a hyperlink and if column[6] is null, then you don't need to set the URL, as it will behave like text.


Use a template column, and put two panels inside of it. One panel containing the link, and the other containing the text. Try something like this:

<asp:TemplateField>
    <ItemTemplate>
        <asp:Panel ID="pnlLink" runat="server" Visible='<%#Eval("SomeColumn") != null%>'>
             <asp:HyperLink ... ></asp:HyperLink>
        </asp:Panel>
        <asp:Panel ID="pnlLink" runat="server" Visible='<%#Eval("SomeColumn") = null%>'>
             <%#Eval("SomeColumn")%>
        </asp:Panel>
    </ItemTemplate>
</asp:TemplateField>

The other option, as @Muhammad Akhtar suggested, is to use a hyperlink regardless, and only set the URL when the DataField for Column[6] is not null.

0

精彩评论

暂无评论...
验证码 换一张
取 消