Domanda

I have the following code in an aspx page

<asp:DataList ID="MissionaryDataList" runat="server" DataKeyField="MissionaryID" DataSourceID="MissionaryDataSource" BorderStyle="Solid" BorderWidth="2px" CellPadding="0" CellSpacing="6" GridLines="Vertical" HorizontalAlign="Center" RepeatColumns="2" Width="100%">            
   <ItemTemplate>
      <asp:HyperLink ID="NameHyperLink" style="text-decoration:none" runat="server" NavigateUrl='<%# "~/Missionaries/Missionary.aspx?MissionaryID=" + Eval("MissionaryID") %>'  Text='<%# Eval("LastName") + ", " + Eval("FirstName") + (String.IsNullOrWhiteSpace((String)(Eval("SpouseFirstName"))) ? "" : (" & " + Eval("SpouseFirstName")))  %>' ></asp:HyperLink>
      <asp:Label ID="ApproveDateLabel" runat="server" Visible="false" Text='<%# Eval("ApproveDate") %>' />                    
   </ItemTemplate>
   <SeparatorStyle BorderColor="Black" BorderStyle="Solid" BorderWidth="2px" />
</asp:DataList>

The line that I am condcerned with is

<asp:HyperLink ID="NameHyperLink" style="text-decoration:none"
  runat="server" NavigateUrl='<%# "~/Missionaries/Missionary.aspx?MissionaryID=" +
  Eval("MissionaryID") %>'  Text='<%# Eval("LastName") + ", " + Eval("FirstName") +
  (String.IsNullOrWhiteSpace((String)(Eval("SpouseFirstName"))) ? "" :
  (" & " + Eval("SpouseFirstName")))  %>' >
</asp:HyperLink>'

The line works fine except when the "SpouseFirstName" is null. So what I want to do is move this to code behind so that I can test for null and not try to convert to a string. I think the code would be much better that way. Anyway, I am not exactly sure how to do this in this particular instance. I know how to use code behind, but since I am dealing with an SqlDataSource, I am not sure how to get the data in code behind for each item in the list. Any help with this would be greatly appreciated.

È stato utile?

Soluzione

You need to use DataList.ItemDataBound event to set the values for Hyperlink. Check out details about ItemDataBound at the below Url:

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.datalist.itemdatabound(v=vs.110).aspx

Your code will look like below:

  void Item_Bound(Object sender, DataListItemEventArgs e)
  {
     if (e.Item.ItemType == ListItemType.Item || 
         e.Item.ItemType == ListItemType.AlternatingItem)
     {

        // You can check for null here using e.Item.DataItem

        Hyperlink NameHyperLink = (HyperLink)e.Item.FindControl("NameHyperLink");

        NamedHyperLink.NavigateUrl = //Your code goes here..
     }

  }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top