user4522610
user4522610

Reputation:

call javascript from server side on link button telerik

I am new to telerik and javascript. I have a link button. On button click I have two conditions from server side. according to that I need to call javascript.

Aspx Code:

<asp:LinkButton ID="TestLinkButton" runat="server" OnClick="Test_Click" 
SkinID="SmallCommandItemTemplateLinkButton">Test</asp:LinkButton>                                                           

Server Side Code:

protected void Test_Click(object sender, EventArgs e)
{
    if (a == 0)
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(), "scriptsKey", "<script type=\"text/JavaScript\" language=\"javascript\">ShowAlert();</script>");
    }
    else
    {
        TestLinkButton.Attributes["onclick"] = String.Format("return ShowEditForm('{0}')", test);
    }
}

Here it is not able to find TestLinkButton. If I am using GridItemEventArgs in button click arguments, Then it is giving error as No Overload for'testLinkButton_click' matches delegate'System.Eventhandler'.

Upvotes: 0

Views: 599

Answers (2)

VDWWD
VDWWD

Reputation: 35524

I may be wrong, but I think you are looking for a way to attach the javascript onclick to the LinkButton in a GridView. You seem to be doing it on a server OnClick of the LinkButton, but that will take a roundtrip to the server (PostBack).

You can do the same in the OnItemDataBound event of the GridView. You need to add the OnItemDataBound to the GridView.

<telerik:RadGrid ID="RadGrid1" runat="server" OnItemDataBound="RadGrid1_ItemDataBound" >

Code behind

protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
    //check if the item is a GridDataItem
    if (e.Item is GridDataItem)
    {
        //if 'a' needs to come from the dataset that is bound to the gridview, you can do this
        GridDataItem item = (GridDataItem)e.Item;
        string a = Convert.ToInt32(item["ID"].Text);

        //or another grid value
        string b = item["name"].Text;

        //find the linkbutton with findcontrol and cast it back to one
        LinkButton linkbutton= e.Item.FindControl("TestLinkButton") as LinkButton;

        if (a == 0)
        {
            //attach the OnClientClick click function
            linkbutton.OnClientClick = string.Format("ShowDeleteForm('{0}'); return false;", test2);
        }
        else
        {
            //attach the OnClientClick click function
            linkbutton.OnClientClick = string.Format("ShowEditForm('{0}'); return false;", test);
        }
    }
}

Upvotes: 0

Martin Parenteau
Martin Parenteau

Reputation: 73731

The LinkButton can be retrieved from the sender argument of the Test_Click event handler, and the Javascript code can be attached to its OnClientClick property:

LinkButton lnkButton = sender as LinkButton;
lnkButton.OnClientClick = String.Format("return ShowEditForm('{0}')", test);

Upvotes: 1

Related Questions