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

Create LinkButton in RadGrid dynamically without Item Template tags in aspx page(Using code behind file)

24 Answers 1090 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Alexis
Top achievements
Rank 1
Alexis asked on 17 Sep 2010, 07:48 AM
Hi,
         I have a problem to add LinkButton in Radgrid. i'm using DataTable as a source for RadGrid.The First Column of Datatable must come as Link Button on RadGrid. but the column of Datatable will not be static(if the DataTable has 5 columns in one scenario then the DataTable can has 50 columns in another scenario). It can change. so i cant use Item template  on RadGrid for this problem.

My Requirement is,

1. The First column of DataTable data will bind to Grid as LinkButton.
2. I need to add some event handler for that LinkButton.
 
  Plz send me some sample code for this. I need it urgently....

Thanks in advance.
Alexis

24 Answers, 1 is accepted

Sort by
0
Accepted
Princy
Top achievements
Rank 2
answered on 17 Sep 2010, 11:49 AM
Hello Alexis,

Here is one sample code to achieve this. Find the name of first column in DataTable and then create a GridButtonColumn dynamically with DataTextField as the field name of column in DataTable. Then in PreRender event hide the first AutoGenerated column of RadGrid.
 
C#:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dataTable = new DataTable();
            dataTable.TableName = "Users";
            DataColumn colString = new DataColumn("UserID");
            colString.DataType = System.Type.GetType("System.String");
            dataTable.Columns.Add(colString);
            DataColumn colString1 = new DataColumn("status");
            colString1.DataType = System.Type.GetType("System.Boolean");
            string colName= dataTable.Columns[0].ColumnName; // getting the name of first column in DataTable
            dataTable.Columns.Add(colString1);
            dataTable.Rows.Add(new object[] { "1", false });
            dataTable.Rows.Add(new object[] { "2", false });
            this.RadGrid1.DataSource = dataTable;
            // creating a GridButtonColumn
            GridButtonColumn btncol = new GridButtonColumn();
            btncol.ButtonType = GridButtonColumnType.LinkButton; // setting ButtonType as LinkButton
            btncol.DataTextField = colName; // setting DataTextField to first column in DataTable
            this.RadGrid1.MasterTableView.Columns.Add(btncol);
         }
    }
 
// hiding the first AutoGeneratedColumn column
 protected void RadGrid1_PreRender(object sender, EventArgs e)
    {
        if (RadGrid1.MasterTableView.RenderColumns.Length > 3)
        {
            RadGrid1.MasterTableView.RenderColumns[3].Display = false;
        
    }

Hope this helps,
Princy.
0
Alexis
Top achievements
Rank 1
answered on 20 Sep 2010, 08:35 AM

<!—I’m not using the Item Template due to this Grid is dynamically has so many columns-->

<telerik:RadGrid ID="MainGrid2" runat="server" GridLines="Both" Skin="Outlook">

<ClientSettings>

<Scrolling AllowScroll="True" UseStaticHeaders="false" aveScrollPosition="true FrozenColumnsCount="0" />                                                                  

  </ClientSettings>

 </telerik:RadGrid>

                                                                   

MainGrid2.DataSource = dT;//datasource is DataTable

string colName = dT.Columns[0].ColumnName;//getting the first column name

GridButtonColumn btncol = new GridButtonColumn();

btncol.ButtonType = GridButtonColumnType.LinkButton;

btncol.DataTextField = colName;

this.MainGrid2.MasterTableView.Columns.Add(btncol);// in the output,a new column is added in the grid at the firstPlace.

MainGrid2.DataBind();

I attached one image in which i clearly mentioned my query... 

  DataTable dT = HtmlTableParser.ParseTable(pvt);
                string colName = dT.Columns[0].ColumnName;
                GridButtonColumn btncol = new GridButtonColumn();
                btncol.ButtonType = GridButtonColumnType.LinkButton;
                btncol.DataTextField = colName; 
                this.MainGrid2.MasterTableView.Columns.Add(btncol);
                MainGrid2.DataSource = dT;
                MainGrid2.DataBind();


0
Princy
Top achievements
Rank 2
answered on 20 Sep 2010, 11:47 AM
Hello Alexis,

Make sure that you have added the code in PreRender event to hide the first column in DataTable. Also check whether you have used the correct the index of column to hide.

Otherwise you can try the following approach to hide the column in DataTable, where headervalue is columnuniquename.

C#:
protected void RadGrid1_PreRender(object sender, EventArgs e)
    {
       RadGrid1.MasterTableView.GetColumnSafe("HeaderValue").Display = false; // hide the column in DataTable using its  field name
    }

Thanks,
Princy.
0
Alexis
Top achievements
Rank 1
answered on 20 Sep 2010, 01:15 PM
Thank u so much Princy...

              Now that coding is working fine... then i need to add Event Hander to all that Link buttons which are binded to that Gird by using C# coding(not in aspx page)... plz help me on this....

Event Name is : OnClick()
Event Hander is like : Header_Click()

I need the Answer urgently... Plz help me on this...

thanks
Alexis
0
Accepted
Princy
Top achievements
Rank 2
answered on 21 Sep 2010, 06:11 AM
Hello Alexis,

A better option to execute some server side code when clicking the LinkButton would be adding a CommandName to GridButtonColumn. Then in ItemCommand event check with the CommandName, that you set.

Otherwise if you want to attach a click event to LinkButton, then the following code will be useful.

C#:
 GridButtonColumn btncol = new GridButtonColumn();
 btncol.ButtonType = GridButtonColumnType.LinkButton;
 btncol.DataTextField = colName;
 btncol.UniqueName = "NewButton"; // adding UniqueName

protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
   {
       if (e.Item is GridDataItem)
       {
           GridDataItem item = (GridDataItem)e.Item;
           LinkButton linkBtn = (LinkButton)item["NewButton"].Controls[0];
           linkBtn.Click += new EventHandler(Header_Click); // adding click event to LinkButton
       }
   }
   protected void Header_Click(object sender, EventArgs e)
   {
        
   }

Thanks,
Princy.
0
Alexis
Top achievements
Rank 1
answered on 21 Sep 2010, 08:22 AM
Thanks for Your Great Help Princy....

Again i need ur hand to help me. i want to apply one style sheet for that Linkbutton which are inside in the Grid(First Column). Because Initially the link button is looks in Blue color. then after i click it, it'll become as Pink or someother color. 

my requirement is
1) It needs to be in same color(specially in Black Color). so how can i use this Stylesheet for Link button dynamically?
Style Sheet Coding
.PivotGrid
{
text-decoration:none;
  color:#000;
  font-size:12px;
}

2) I need to add Tool Tip for that Link button which are in Grid first column. how can i use the Tool Tip property... Plz Help me on this...



(Need Answer Urgently),
Thanks,
Alexis.
0
Accepted
Princy
Top achievements
Rank 2
answered on 22 Sep 2010, 05:47 AM
Hello Alexis,

Try the following code snippet to assign CssClass and ToopTip dynamically.

C#:
protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
    {
        if (e.Item is GridDataItem)
        {
            GridDataItem item = (GridDataItem)e.Item;
            LinkButton linkBtn = (LinkButton)item["NewButton"].Controls[0];
            linkBtn.ToolTip ="new tooltip"; //setting ToolTip
            linkBtn.CssClass = "PivotGrid"; // assigning CSSClass
        }
    }

Thanks,
Princy.
0
Alexis
Top achievements
Rank 1
answered on 22 Sep 2010, 11:07 AM
Hi Princy,
                  As of now ur coding is working fine for me.... now i need ur help for someother work.... 
My Req is : 
1). I’m placing cursor on Amelia(u can see in that attachment), I want to show the toop tip with that name. but its showing New Tool Tip. 

How can I get what I’m looking for this implementation. Can u help me on this Princy?


2).Is it possible to show the Rad Grid header in some other way? 

Alexis

Princy

Smith

Michel

 Age

Salary

Age

Salary

Age

Salary

Age

Salary

25

5000USD

26

5000USD

35

6000USD

24

4000USD


I want to show the Rad Grid Header with 2 headers... Main Header, and sub header with each main header... also i need this to be done by dynamically... We get this header as DataRow from Data Table. but we are loop throughing to display this format on header, but we cant get this format on Rad Grid... Can u plz help us regarding this....

3) How can i assign Fore color to Rad Grid Headers alternate columns in programmatically?
 
We need Solution urgently... Plz Help us as soon as possible....
Thanks in Advance,
 Alexis


0
Accepted
Princy
Top achievements
Rank 2
answered on 23 Sep 2010, 10:19 AM
Hello Alexis,

1) Try the following code in ItemDataBound event to set Tooltip with that cell value.

C#:
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
   {
       if (e.Item is GridDataItem)
       {
           GridDataItem item = (GridDataItem)e.Item;
           LinkButton linkBtn = (LinkButton)item["NewButton"].Controls[0];
           linkBtn.ToolTip = linkBtn.Text;
       }
   }

2)Please go through the following link which discusses how to set multiple headers at run time.
Adding Multiple Header Rows at Runtime in RadGrid

3) The following code shows how to set alternative font colors for RadGrid headers

C#:
protected void RadGrid1_PreRender(object sender, EventArgs e)
    {
        int i=0;
        foreach (GridColumn col in RadGrid1.MasterTableView.AutoGeneratedColumns)
        {
            if(i%2==0)
               RadGrid1.MasterTableView.AutoGeneratedColumns[i].HeaderStyle.ForeColor = System.Drawing.Color.Blue;
            i++;
        }
    }

Thanks,
Princy.
0
Alexis
Top achievements
Rank 1
answered on 23 Sep 2010, 10:41 AM
Hi Princy,
Thanks for ur fabulous reply... I've a doubt on Multiple Row as Header to Radgrid at Runtime.... I'm getting the below content as string at runtime. but i cant use the HeaderTemplate tag for radgrid... 
     <TABLE id="Table1" cellSpacing="1" cellPadding="1" width="300"border="1">
        <TR>
         
<TD colspan="2" align="center"><b>Address</b></TD>
        
</TR>
        
<TR>
         
<TD width="50%"><b>City</b></TD>
         
<TD width="50%"><b>Postal code</b></TD>
        
</TR>
       
</TABLE>
1) Is it possible to assign this table to Rad Grid HeaderTemplate at Runtime?

2) Is it possible to Assign the Sorting options to RadGrid Headers(For City,  and for Postal Code)?

or

3) How to assign the AllowSorting property to all the columns in RadGrid which are binded with DataTable. Plz keep in mind that I'm not using Item Template... ????



 Plz Help me on this.... I need the solution Urgently.... 
 
Thanks in advance...
Alexis
0
Iana Tsolova
Telerik team
answered on 27 Sep 2010, 09:42 AM
Hello Alexis,

In order to use the preceding code for the header template, I suggest that you define it in custom class implementing the ITemplate interface. Then you use it, you can define the grid dynamically on Page_Init as explained in this article.
Then to enable to sorting for the headers, you can use LinkButtons instead of simple text. Set the CommandName to sort, and handle the sort command in the ItemCommand event.

All the best,
Iana
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
0
Alexis
Top achievements
Rank 1
answered on 27 Sep 2010, 12:05 PM
Hi Lana,
              Thanks for ur reply...   I dont understand clearly about the sorting options which u explained in previous response.. I need some more sample codes for get knowledge on this sorting....  (I dont use ItemTemplate in my coding, I'm directly bounding the data from DataTable to RadGrid as Princy helped me in this Forum).

we need solution urgently... Plz help us on this regard....


Thanks in Advance
Alexis
0
Iana Tsolova
Telerik team
answered on 28 Sep 2010, 11:15 AM
Hello Alexis,

I does not matter how you create the controls, declaratively or dynamically. In both cases you need to set the same properties for them. Find more about implementing sorting for GridTemplateColumns in the below articles:

http://www.telerik.com/help/aspnet-ajax/grdsortingforhyperlinktemplatecolumns.html
http://www.telerik.com/help/aspnet-ajax/grdapplycustomsortcriteria.html

Best wishes,
Iana
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
0
Jittu
Top achievements
Rank 1
answered on 24 Sep 2012, 03:28 PM
Hi,

I have created a link button in the Databound event for RadGrid but I am unable to write the Onclick event for the Link Button. The requirement is, if the cell value is empty I need to provide a Add link and when clicked opens a pop to add.
Can you please help me on this.

protected void RadGrid1_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
        {
 if (e.Item is GridDataItem)
            {
                GridDataItem item = (GridDataItem)e.Item;
                if (item["FieldName"].Text == "&nbsp;")        
                {
                    LinkButton MyLinkButton = new LinkButton();
                    MyLinkButton.Text = "Add";
                     item["FieldName"].Controls.Add(MyLinkButton);
                        item["FieldName"].ForeColor = System.Drawing.Color.Red;
}
}
}
0
Shinu
Top achievements
Rank 2
answered on 25 Sep 2012, 07:28 AM
Hi,

Try attaching the event in ItemCreated event as shown below.
C#:
protected void RadGrid1_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
 if (e.Item is GridDataItem)
 {
    GridDataItem item = (GridDataItem)e.Item;
    if (item["FieldName"].Text == "&nbsp;")       
    {
       LinkButton MyLinkButton = new LinkButton();
       MyLinkButton.Text = "Add";
       item["FieldName"].Controls.Add(MyLinkButton);
       item["FieldName"].ForeColor = System.Drawing.Color.Red;
       MyLinkButton.Click += new EventHandler(MyLinkButton_Click);
     }
 }
}
void  MyLinkButton_Click(object sender, EventArgs e)
{
}

Thanks,
Shinu.
0
Jittu
Top achievements
Rank 1
answered on 25 Sep 2012, 12:57 PM
Hi Shinu,

Thanks for the reply .I have tried doing that but its not working. It doesn't even add the Link button.

Rajini
0
Shinu
Top achievements
Rank 2
answered on 26 Sep 2012, 04:24 AM
Hi,

In general the proper place for adding controls to the grid items is in ItemCreated. But in the case of adding controls to the cells of GridBoundColumn,you cannot use ItemCreated only, but a combination of ItemCreated and ItemDataBound. This is due to the fact that the control created in ItemCreated will be erased when data-binding this control. Also, if you create the control in ItemDataBound when the controls are created from ViewState, the grid will not raise ItemDataBound, and the control will not be created and would not raise postback events. The solution for such cases is to create the control in ItemDataBound and recreate this control if needed on ItemCreated for subsequent postbacks. Here is the sample code.
C#:
protected void RadGrid1_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
 if (e.Item is GridDataItem)
 {
    GridDataItem item = (GridDataItem)e.Item;
    if (item["FieldName"].Text == " ")      
    {
       LinkButton MyLinkButton = new LinkButton();
       MyLinkButton.Text = "Add";
       item["FieldName"].Controls.Add(MyLinkButton);
       item["FieldName"].ForeColor = System.Drawing.Color.Red;
       MyLinkButton.Click += new EventHandler(MyLinkButton_Click);
     }
 }
}
void  MyLinkButton_Click(object sender, EventArgs e)
{
}
protected void RadGrid1_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
 if (e.Item is GridDataItem)
 {
    GridDataItem item = (GridDataItem)e.Item;
    if (item["FieldName"].Text == " ")      
    {
       LinkButton MyLinkButton = new LinkButton();
       MyLinkButton.Text = "Add";
       item["FieldName"].Controls.Add(MyLinkButton);
       item["FieldName"].ForeColor = System.Drawing.Color.Red;
    }
 }
}

Thanks,
Shinu.
0
Jittu
Top achievements
Rank 1
answered on 27 Sep 2012, 12:16 AM
Hi Shinu,

It dint work out . When I click on the Add Link Button it does a post back and removes the Add link button itself. It does not do a click event.Please help me on this.

Thanks,
Rajini
0
Shinu
Top achievements
Rank 2
answered on 27 Sep 2012, 06:25 AM
Hi,

Please try the following code snippet as a work around for this issue.

C#:
public static ArrayList IndexArray = new ArrayList();
protected void RadGrid1_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
    if (e.Item is GridDataItem)
    {
        GridDataItem item = (GridDataItem)e.Item;
        LinkButton MyLinkButton = new LinkButton();
        MyLinkButton.Text = "Add";
        MyLinkButton.ID = "ID";
          
        if (item["FieldName"].Text == "&nbsp;")
        {
                 
            IndexArray.Add(item.GetDataKeyValue("DataKeyName").ToString()); //storing the DataKeyValue of the row whose cell value is empty in an ArrayList
            item["FieldName"].Controls.Add(MyLinkButton);          
            item["FieldName"].ForeColor = System.Drawing.Color.Red;              
        
    }
}
void MyLinkButton_Click(object sender, EventArgs e)
{
    //your code
}  
protected void RadGrid1_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
    if (e.Item is GridDataItem)
    {
        GridDataItem item = (GridDataItem)e.Item;
        LinkButton MyLinkButton = new LinkButton();
        MyLinkButton.Text = "Add";
        MyLinkButton.ID = "ID";
        if (item["FieldName"].Text == "&nbsp;")
        {          
            item["FieldName"].Controls.Add(MyLinkButton);
            item["FieldName"].ForeColor = System.Drawing.Color.Red;
        }
        foreach (string id  in IndexArray)
        {
            string datakey = item.GetDataKeyValue("DataKeyName").ToString();
            if (datakey == id)
            {
                item["FieldName"].Controls.Add(MyLinkButton);
                item["FieldName"].ForeColor = System.Drawing.Color.Red;
                MyLinkButton.Click += new EventHandler(MyLinkButton_Click); //attaching click events for the cell with empty value
            }              
        }
    }
}

Thanks,
Shinu.
0
Jittu
Top achievements
Rank 1
answered on 27 Sep 2012, 06:36 AM
Hi Shinu,

Thanks for your reply .It works perfectly fine.
Thank you so much.

THanks,
Rajini
0
arun
Top achievements
Rank 1
answered on 15 Oct 2013, 05:20 PM
Shinu,
  I tried to implement your code, The columns show up fine in red but they are not clickable, Can you tell me what  am I missing.


    
public static ArrayList IndexArray = new ArrayList();   
 
      void GridCommon_ItemDataBound(object sender, GridItemEventArgs e)
      {
          if (e.Item is GridDataItem)
          {
              GridDataItem item = (GridDataItem)e.Item;
              LinkButton link = new LinkButton();
              link.Text = "Add";
              link.ID = "LinkID";
 
              if (item["PortfolioName"].Text == " ")
              {
                  IndexArray.Add(item.GetDataKeyValue("ID").ToString());
                  item["PortfolioName"].Controls.Add(link);
                  item["PortfolioName"].ForeColor = System.Drawing.Color.Red;
              }
 
          }
      }
 
      protected void PortfolioLink_Click(object sender, EventArgs e)
      {
          
      }
 
      void GridCommon_ItemCreated(object sender, GridItemEventArgs e)
      {
          if (e.Item is GridDataItem)
          {
              GridDataItem item = (GridDataItem)e.Item;
              LinkButton link = new LinkButton();
              link.Text = "Add";
              link.ID = "LinkID";
              if (item["PortfolioName"].Text == " ")
              {
                  item["PortfolioName"].Controls.Add(link);
                  item["PortfolioName"].ForeColor = System.Drawing.Color.Red;
              }
              foreach (string id in IndexArray)
              {
                  string datakey = item.GetDataKeyValue("ID").ToString();
                  if (datakey == id)
                  {
                      item["PortfolioName"].Controls.Add(link);
                      item["PortfolioName"].ForeColor = System.Drawing.Color.Red;
                      link.Click += new EventHandler(PortfolioLink_Click);
                  }
              }
          }
 
          }
0
Kostadin
Telerik team
answered on 18 Oct 2013, 08:23 AM
Hello Arun,

I have already answered your support ticket, I would ask you to continue our conversation there. I am providing the answer here if somebody else facing a similar issue as yours.

"I assume that is too late in page live cycle to attache an event handler of the button on one of those events (ItemDataBound and ItemCreated). A suitable solution is to create the link button on item load event."

Regards,
Kostadin
Telerik
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to the blog feed now.
0
Aanchal
Top achievements
Rank 1
answered on 19 Oct 2016, 07:28 PM

Hello, 

I am getting the following exception

"An exception of type 'System.ArgumentOutOfRangeException' occurred in System.Web.dll but was not handled in user code"

while using "LinkButton linkBtn = (LinkButton)item["NewButton"].Controls[0];"

Please help me.

0
Kostadin
Telerik team
answered on 24 Oct 2016, 12:22 PM
Hi Aanchal,

Are you using a Template Column in your case. If you do then you need to use FindControl method and pass the control ID as an argument. I would recommend you to check out the following help article which elaborates more on this matter.

Regards,
Kostadin
Telerik by Progress
Check out the new UI for ASP.NET Core, the most complete UI suite for ASP.NET Core development on the market, with 60+ tried-and-tested widgets, based on Kendo UI.
Tags
Grid
Asked by
Alexis
Top achievements
Rank 1
Answers by
Princy
Top achievements
Rank 2
Alexis
Top achievements
Rank 1
Iana Tsolova
Telerik team
Jittu
Top achievements
Rank 1
Shinu
Top achievements
Rank 2
arun
Top achievements
Rank 1
Kostadin
Telerik team
Aanchal
Top achievements
Rank 1
Share this question
or