Domanda

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

È stato utile?

Soluzione

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

Altri suggerimenti

First of all, use string.Format to format a url string

hplPostIt.NavigateUrl = string.Format("https://www.mysite.com/Fruit/Apples.aspx?Season={0}&Color_Date={1}&num={2}", SeasonLabel.Text, TypeLabel.Text, SeasonLabel.Text);

Second You don't need FindControl to access to hplPostIt, if it located directly on Page. See "youpagename.aspx.design.cs" to find control declaration

Third Probably null reference exception thrown by one of text control (SeasonLabel, TypeLabel)

Have you tried running it in the formview databound event rather than page load?

Something like:

<asp:FormView ID="FormView1" runat="server" OnDataBound="FormView1_DataBound" ...>

and in the code behind

protected void FormView1_DataBound(object sender, EventArgs e)
{
Label Apple = FormView1.FindControl("Apple") as Label;
HyperLink hplPostIt = FormView1.FindControl("hplPostIt") as HyperLink; 
// etc.
}

As a workaround

<asp:HyperLink ID="hplPostIt" runat="server" NavigateUrl='<%# getLink(Eval("Apple")) >' />

Then

protected string getLink(object obj)
{
string fruit = obj.ToString();
// if else with fruit string.
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top