Adding Link Column to ASP.NET GridView

patrick picture patrick · Dec 5, 2009 · Viewed 76k times · Source

I want to output a list of news headlines that are clickable. So far I can get it to print out a list of headlines because I dragged and dropped the NewsHeadline table in designer view in VS 2010. How do you think I should the make the list elements clickable? I looked for a URL attribute but I did not see it. Do I need to wrap in a < a href ?

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
        DataSourceID="SqlDataSource1" 
        EmptyDataText="There are no data records to display.">
        <Columns>
            <asp:BoundField DataField="NewsHeadline" HeaderText="NewsHeadline" 
                SortExpression="NewsHeadline" />
        </Columns>
    </asp:GridView>

  <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:ConnectionString1 %>" 
        ProviderName="<%$ ConnectionStrings:ConnectionString1.ProviderName %>" 
        SelectCommand="SELECT [NewsHeadline] FROM [NewsTable]"></asp:SqlDataSource>
   </form>

Answer

RSolberg picture RSolberg · Dec 5, 2009

You need to change the column type from a BoundColumn to a Hyperlink column.

   <asp:hyperlinkfield headertext="NewsHeadline"
      datatextfield="NewsHeadline"
      datanavigateurlfield="NewsURL" 
      datanavigateurlformatstring="http://{0}" />

In addition to making this change, you'll need to make sure that you are selecting the URL or something you can use to create the link to the news article. In the example above, I'm assuming the URL is something you can grab from your SQL source. If it is an ID, simply type out the rest of the url like this... "~/MyNewsPage.aspx?NewsID={0}"...