Ronaldinho Learn Coding
Ronaldinho Learn Coding

Reputation: 13824

Gridview: Change link button text base on value of cell in same row

Below is gridview that I want it to be, ID, Name and Status are Label, Action is LinkButton

ID ------------- Name ------------- Status ------------- Action

1 -------------- Name1 ------------ Active ------------ Disable

2 -------------- Name2 ------------ In-active --------- Enable

3 -------------- Name3 ------------ Active ------------ Disable

How can I set the LinkButton Text to "Disable" or "Enable" depend on value (text) of Status (which is always either Active or In-active)?

My link button is as below, how can change the text 'Do you want to proceed' to 'Do you want to Disable' or 'Do you want to Enable' base on the logic above

<asp:LinkButton ID="lbtAction" runat="server"
               CommandArgument='<%# Eval("ID")%>'
               OnClientClick="return confirm('Do you want to proceed?')"
               OnClick="DoAction"></asp:LinkButton>

Upvotes: 1

Views: 7534

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460228

Use RowDataBound and place your logic there:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        LinkButton lbtAction = (LinkButton) e.Row.FindControl("lbtAction");
        Label lblStatus = (Label) e.Row.FindControl("lblStatus");
        bool active = lblStatus.Text == "Active";
        lbtAction.Text = active ? "Disable" : "Enable";
        string onClientClick  = string.Format("return confirm('Do you want to {0}?')",
                                               active ? "Disable" : "Enable");
        lbtAction.OnClientClick = onClientClick;
    }
}

Upvotes: 3

Rahul
Rahul

Reputation: 77896

Use Gridview RowDataBound event to achieve the same. Like below (not exact code but you can start with alike)

void RowDataBound(object sender, GridViewRowEventArgs e)
{
 if(e.Row.RowType == DataControlRowType.DataRow)
    {
        if(((Label)e.Row.FindControl("Status")).Text == "Active")
{
  //disable
}
else
{
//enable
}
}
}

Upvotes: 1

Related Questions