Question

Inside a ListView Control's <ItemTemplate> I'm using a LinkButton. When the List populates it has a set of LinkButtons. The link button text's are generated from a column in the records retrieved using a data source.

When I click on a LinkButton, I need it's text to be captured into either a hidden field or view state during the post back, so that it will be displayed in a Label or TextBox when page post back happens.

But it does not happen on first page post back. Instead, I have to click on the LinkButton twice for two post backs for the value to be displayed in Label/TextBox.

How can I get it done in the first post back ?

I have tried the same without the ListView, using just a LinkButton as below, and get the same outcome.

protected void LinkButton_Click(object sender, EventArgs e)
{
    LinkButton selectedButton = (LinkButton)sender;
    HiddenField1.Value = selectedButton.Text;
    ViewState["LinkButtonText"] = selectedButton.Text;
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(HiddenField1.Value))
    {
        Label1.Text = HiddenField1.Value;
    }
    TextBox1.Text = HiddenField1.Value;

    if (ViewState["LinkButtonText"] != null)
    {
        if (!string.IsNullOrEmpty(ViewState["LinkButtonText"].ToString()))
        {
            ViewStateTextBox.Text = ViewState["LinkButtonText"].ToString();
        }
    }
}
Was it helpful?

Solution

Well, It happens since the sequence of the server side method execution. The page load before hand, then the control click methods, in that order. Instead of updating hidden field like that now using a client side JavaScript function OnClientClick of the LinkButton control, which updates the hidden field.

OTHER TIPS

In short, you use it everytime you need to execute something ONLY on first load.

The classic usage of Page.IsPostBack is data binding / control initialization.

if(!Page.IsPostBack)
{
   //Control Initialization
   //Databinding
}

Things that are persisted on ViewState and ControlState don't need to be recreated on every postback so you check for this condition in order to avoid executing unnecessary code.

Another classic usage is getting and processing Querystring parameters. You don't need to do that on postback.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top