This is a migrated thread and some comments may be shown as answers.

Dynamically created GridImageButton doesn fires Clicking-Events

5 Answers 368 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Marcel
Top achievements
Rank 1
Marcel asked on 19 Apr 2012, 08:25 AM
Hi everybody,
i have a RadGrid which I've added a GridImageColumn.
Sureley i want a reaction on Clicking the Imagebutton therefore but none of the Clicking-Event doesn't work.

I added directly by creating the GridImagebutton an OnClientClick-Method and a OnClick-Method.
I also tried to use the ItemCreated-Event of the Radgrid and adding the Click-Functionalty also there.

Anybody can help me?
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DefaultCS.aspx.cs" Inherits="TelerikNestedGrid.DefaultCS" %>
 
<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/tr/xhtml11/DTD/xhtml11.dtd">
<head id="Head1" runat="server">
    <!-- custom head section -->
    <!-- end of custom head section -->
</head>
<body class="BODY">
    <form runat="server" id="mainForm" method="post">
    <!-- content start -->
    <telerik:RadScriptManager ID="RadScriptManager1" runat="server" />
    <script language="javascript" type="text/javascript">
        function testAlert() {
            alert("hello");
        }
    </script>
    <br />
    <div style="width: 730px;">
        <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
        <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
        </telerik:RadAjaxManager>
        <br />
    </div>
    <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="testAlert()"/>
 
    <!-- content end -->
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using System.Data;
using System.IO;
using System.Data.Odbc;
 
namespace TelerikNestedGrid
{
    public partial class DefaultCS : System.Web.UI.Page
    {       
        private void DefineGridStructure()
        {
 
            RadGrid RadGrid1 = new RadGrid();
            RadGrid1.ID = "RadGrid1";
            RadGrid1.ItemCreated += new GridItemEventHandler(RadGrid1_ItemCreated);
             
            //Assignt the DataTable as Source
            RadGrid1.DataSource = GetTableFromCSV(@"D:\RadGridImport.csv"); ;
 
            //If only Bind the Data here, the ImageColumn will not appear.
            RadGrid1.DataBind();
 
            //Create and Add the new Column
            GridImageColumn col = new GridImageColumn();
            col.ImageUrl= "/images/stift_icon.gif";
            GridImageButton btn = new GridImageButton(col);
            btn.OnClientClick = "testAlert()";
            btn.Click += new ImageClickEventHandler(GridButton_Click);
            RadGrid1.Columns.Add(col);
 
 
            //If i first Bind and then Rebind() here, the ImageColumn is at the Beginning.
            RadGrid1.Rebind();
 
            this.PlaceHolder1.Controls.Add(RadGrid1);
        }
 
        public void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridDataItem)
            {
                //e.Item.Cells[0].Controls[0].GetType() -> type is usual button and not GridImageButton? Why that?
                TableCell t = e.Item.Cells[0];
                foreach (Control c in t.Controls)
                {
                    c.GetType();
                    //(c as ImageButton).OnClientClick = "testAlert()";
                    (c as Button).OnClientClick = "testAlert()";
                    (c as Button).Click += new EventHandler(GridButton_Click);
                    (c as Button).Attributes.Add("onclick", "GridButton_Click()");
 
                }
            }
        }
 
        public void GridButton_Click(object sender, EventArgs e)
        {
            Console.WriteLine();
        }
 
        protected void Page_Init(object source, System.EventArgs e)
        {
            DefineGridStructure();
        }
 
        protected void Page_Load(object sender, EventArgs e)
        {
 
        }
 
        private DataTable GetTableFromCSV(string path)
        {
            if (!File.Exists(path))
                throw new FileNotFoundException();
 
            FileInfo fileInfo = new FileInfo(path);
            DataTable dataTable = new DataTable();
            string connectionString = String.Format("Driver={{Microsoft Text Driver (*.txt; *.csv)}};Dbq={0};", fileInfo.DirectoryName);
            OdbcConnection connection = new OdbcConnection(connectionString);
            OdbcDataAdapter da = new OdbcDataAdapter(String.Format("select * from [{0}]", fileInfo.Name), connection);
            da.Fill(dataTable);
            return dataTable;
        }
    }
}

C

5 Answers, 1 is accepted

Sort by
0
Shinu
Top achievements
Rank 2
answered on 19 Apr 2012, 02:21 PM
Hi Marcel,

Please try the following approach to add a ButtonColumn dynamically and attach both client and server events respectively. Here is the sample code.
1)From client side:
JS:
<script type="text/javascript">
    function OnCommand(sender, args) {
        debugger;
        if (args.get_commandName() == "YourCommandName")
            alert("Fired");
    }
</script>
2)From server side:
C#:
RadGrid1.ClientSettings.ClientEvents.OnCommand = "OnCommand";//attaching the client event
GridButtonColumn col1 = new GridButtonColumn();
col1.HeaderText = "Text";
col1.ButtonType = GridButtonColumnType.ImageButton;
col1.ImageUrl = "~/Images/index.jpg";
col1.CommandName = "YourCommandName";
RadGrid1.MasterTableView.Columns.Add(col1);
 void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
if (e.CommandName == "YourCommandName")
{
}
}

Thanks,
Shinu.
0
Marcel
Top achievements
Rank 1
answered on 23 Apr 2012, 01:00 PM
Hi Shinu,
thanks for your response. Your example works quite good and the imagebuttons finally fires the client side JS-event.
Anyhow, there's one more thing i has to find out and one thing I didn't yet understand:

  1. How can I now figure out, in which row the button was pressed, so that i can access the values of it?
  2. If I add (in the .aspx) the OnItemCommand to the RadGrid with the Method for the Code behind, i always get an Exception that the Method could not be found but the Names surely match. Must i use the ItemCommand-Event in antoher way?

Greetings,
Marcel

0
Accepted
Shinu
Top achievements
Rank 2
answered on 24 Apr 2012, 07:06 AM
Hi Marcel,

1. You can get the Row index of the button you pressed using javascript. Please check the following code.

Javascript:
<script type="text/javascript">
    function OnCommand(sender,args) {
        if (args.get_commandName() == "YourCommandName") {
            alert(args.get_commandArgument());
        }   
    }
</script>

2. I might have confused you by giving the ItemCommand event along with the code for creating GridButtonColumn. I appologize for giving so. Actually I created the RadGrid programmatically, so i added the ItemCommand from code behind. Please check the code I tried.

C#:
protected void Page_Load(object sender, EventArgs e)
{
    RadGrid RadGrid1 = new RadGrid();
    RadGrid1.ID = "RadGrid1";
    RadGrid1.AutoGenerateColumns = false;
    RadGrid1.ItemCommand += new GridCommandEventHandler(RadGrid1_ItemCommand); //adding ItemCommand event 
    RadGrid1.ClientSettings.ClientEvents.OnCommand = "OnCommand";//creating client event
    /********ADDING IMAGE BUTTON HERE*********/
    GridButtonColumn col1 = new GridButtonColumn();
    col1.HeaderText = "Text";
    col1.ButtonType = GridButtonColumnType.ImageButton;
    col1.ImageUrl = "~/Images/index.jpg";
    col1.CommandName = "YourCommandName";
    RadGrid1.MasterTableView.Columns.Add(col1);
    RadGrid1.DataSourceID = "sqlDataSource2";
    this.form1.Controls.Add(RadGrid1);    
}
void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
    GridDataItem item = (GridDataItem)e.Item;
 
    if (e.CommandName == "YourCommandName")
    {
        int index = item.ItemIndex;// getting row index in server side
    }
}

OR
If you are not adding the ItemCommand event form code behind, you can add the event in ASPX as shown below.

ASPX:
<telerik:RadGrid ID="RadGrid1" runat="server" OnItemCommand="RadGrid1_ItemCommand"></telerik:RadGrid>


Thanks,
Shinu.
0
Marcel
Top achievements
Rank 1
answered on 24 Apr 2012, 10:10 AM
Hi Shinu,
thank you very much for your help. Everything works fine, now.
Btw, about the 2nd question of the OnItemCommand: I let Visual Studio autocreate the EventhandlerMethod and it didn't add the public modifier. Therfore, it couldn't find the it from the aspx. My bad.

Greetings,
Marcel
0
Shinu
Top achievements
Rank 2
answered on 25 Apr 2012, 05:18 AM
Hi Marcel,

Glad to know that it worked for you.If you are unable to attach event from ASPX then try adding the event from the server side in Page_Load as follows.

C#:
RadGrid1.ItemCommand += new GridCommandEventHandler(RadGrid1_ItemCommand);

Thanks,
Shinu.
Tags
Grid
Asked by
Marcel
Top achievements
Rank 1
Answers by
Shinu
Top achievements
Rank 2
Marcel
Top achievements
Rank 1
Share this question
or