Search code examples
c#asp.netformview

asp:Hyperlink returning null in Formview


I have a asp:Hyperlink set up in my applications' formview and a label

<br />
<b>Posting Site:</b>
<asp:Label ID="AppleLabel" runat="server" Text='<%# Bind("Apple") %>' />
<br />
<asp:HyperLink ID="hplPostIt" Text="Text" runat="server"/>

and in my Page_Load event I attempt to find the label and the hyperlink:

Label Apple = FormView1.FindControl("Apple") as Label;
HyperLink hplPostIt = FormView1.FindControl("hplPostIt") as HyperLink;

Then I try to use an if statement to change the NavigateURL property of the hyperlink based on the text of the label and Visual Studio complains that the object reference is not set. Here is my if else condition:

if (!Page.IsPostBack)
{
    lblRow.Text = Request.QueryString["num"];
    hplPostIt.Text = "Eat Now";

    if (Fruit.Text == "Fruit")
    {
       hplPostIt.NavigateUrl = 
              "https://www.mysite.com/Fruit/Apples.aspx?Season=" + 
              SeasonLabel.Text + "&Color_Date=" + TypeLabel.Text + 
              "&num=" + SeasonLabel.Text;
    }
    else
    {
       hplPostIt.NavigateUrl = 
              "Fruit/Apples.aspx?Season=" + SeasonLabel.Text + 
              "&Color_Date=" + TypeLabel.Text + "&num=" + SeasonLabel.Text;
    }
}

Edited I left out the Postback check

I have also tried using this in a protected void FormView1_DataBound(object sender, EventArgs e) with no luck


Solution

  • I made lot of assumptions and added some code to make a working example for you. In case you think I did not get you, please add some more information by commenting on my answer of editing your question!

    Assumptions

    • Class Fruit - representing your dataContainer - simplified it, to store a name
    • on Page_Load I bound some demo values
    • added a paging functionality to provide a working example

    Solution

    1. I used a customMethod(..) to bind on property NavigateUrl
    2. added string.Format(..) to concat your strings

    Still unclear

    • Where do SeasonLabel and TypeLabel come from?

    Markup

    <form id="form1" runat="server">
    <div>
      <asp:FormView ID="fvFruits" runat="server" AllowPaging="True"
       OnPageIndexChanging="fvFruits_PageIndexChanging">
            <ItemTemplate>
                <asp:Label ID="lblFruit" runat="server" Text='<%# Bind("Name") %>' />
                <asp:HyperLink ID="hplPostIt" Text="yourText" 
                 NavigateUrl='<%# customMethod(Eval("Name")) %>' runat="server"/>
            </ItemTemplate>
        </asp:FormView>
    </div>
    </form> 
    

    CodeBehind

    protected void Page_Load(object sender, EventArgs e)
    {
        // demo purposes to add some data
        if (!Page.IsPostBack)
            bindDemoData();
    }
    
    private void bindDemoData()
    {
        List<Fruit> fruits = new List<Fruit>();
        fruits.Add(new Fruit() { Name = "Apple" });
        fruits.Add(new Fruit() { Name = "Banana" });
        fruits.Add(new Fruit() { Name = "Orange" });
        fvFruits.DataSource = fruits;
        fvFruits.DataBind();
    }
    
    /// <summary>
    /// Custom method to check for a given parameter value, which will be given
    /// by the dataBinding within markup code.
    /// You might even pass more parameter values
    /// </summary>
    /// <param name="fruit">the name of the fruit</param>
    /// <returns>custom link for each given fruitName</returns>
    public string customMethod(object fruit)
    {
        if (fruit != null)
        {
            string fruitName = fruit.ToString();
            // insert custom binding here!
            string url = "https://www.mysite.com/Fruit/";
            if (fruitName == "Apple")
                url += "Apples.aspx";
            else if (fruitName == "Banana")
                url += "Banana.aspx";
            else if (fruitName == "Orange")
                url += "Orange.aspx";
            /*else
                url += "defaultFruit.aspx";;  // up to you*/
    
            // can't see where SeasonLabel and TypeLabel are defined??? please add a comment if I did get you wrong
            url += string.Format("?Season={0}&Color_Date={1}&num={2}", SeasonLabel.Text, TypeLabel.Text, SeasonLabel.Text);
    
            //uncomment this line and comment out the line above to get a working example
            //url += string.Format("?Season={0}&Color_Date={1}&num={2}", "a", "b", "c");
    
            return url;
        }
        return "https://www.mysite.com/error.aspx"; // probably - but up to you
    }
    protected void fvFruits_PageIndexChanging(object sender, FormViewPageEventArgs e)
    {
        fvFruits.PageIndex = e.NewPageIndex;
        bindDemoData();
    }
    
    // demo data container
    public class Fruit
    {
        public string Name { get; set; }
    }
    

    Result Pic

    result when testing this code