I am building one radgrid with dynamic column creation. i.e I am binding dynamic columns in code behind file. I have declared grid as follows.
<
telerik:RadGrid ID="radgrdClaimsAvailable" runat="server" Skin="Office2007" GridLines="None" AllowPaging="true" PageSize="10" AutoGenerateColumns="true">
<HeaderStyle BackColor="#E3EAF1"></HeaderStyle>
<ClientSettings EnablePostBackOnRowClick="true">
<Selecting AllowRowSelect="True"></Selecting>
</ClientSettings>
<MasterTableView PagerStyle-AlwaysVisible="true" PagerStyle-Mode="NextPrevNumericAndAdvanced" AllowPaging="true" AllowSorting="true">
</MasterTableView>
</telerik:RadGrid>
Now I want hide one column. How can I achieve this through code behind. When I put following line of code in Grid PreRender, ColumnCreated, Page Prerender Completed event events it is throughing exception like:
Code:
If
radgrdClaimsAvailable.Columns.Count > 2 Then
radgrdClaimsAvailable.Columns(1).Display =
False
radgrdClaimsAvailable.Columns(2).Display =
False
End If
Exception:
Failed accessing GridColumn by index. Please verify that you have specified the structure of RadGrid correctly.
Please Help me in Hiding the columns in CodeBehind for RadGrid.
Thanks in Advance,
Medac
13 Answers, 1 is accepted

I guess you want to hide autogeneratedcolumn from code behind. If so try the following code snippet.
VB:
Protected Sub RadGrid1_PreRender(ByVal sender As Object, ByVal e As EventArgs) |
If RadGrid1.MasterTableView.RenderColumns.Length > 2 Then |
RadGrid1.MasterTableView.RenderColumns(2).Display = False |
RadGrid1.MasterTableView.RenderColumns(3).Display = False |
End If |
End Sub |
-Shinu.

It is working fine thank you very much.....
One more help I need
How can we set the Formatting type for Autogenerated columns?
like
<
telerik:GridBoundColumn DataField="Dr. Billed" UniqueName="Dr. Billed" HeaderText="Dr. Billed"
DataFormatString="{0:c}">
I want to set DataFormattingString to {0:C} for Autogenerated column.......
How can i achieve the above....
Thanks in advance,
Medac

Give a try with following server code to apply DataStringFormat for AutoGenerateColumns.
C#:
protected void RadGrid1_ColumnCreated(object sender, GridColumnCreatedEventArgs e) |
{ |
if (e.Column.UniqueName == "Dr. Billed") |
{ |
GridBoundColumn CN = (GridBoundColumn)e.Column; |
CN.DataFormatString = "{0:c}"; |
} |
} |
Thanks,
Princy.

It is working fine.
I have a grid which contains 10 rows. Last row that is 10th row displays GrandTotal. Can I sort only 9 rows by leaving grand total row?
Note: I have autotogenerated columns in this grid.
I am sorting the grid as below.
Protected
Sub Page_PreRenderComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRenderComplete
Dim sortExpr As New GridSortExpression
sortExpr.FieldName =
"Totals"
sortExpr.SortOrder = GridSortOrder.Descending
radgrdClaimsAvailable.MasterTableView.SortExpressions.AddSortExpression(sortExpr)
radgrdClaimsAvailable.Rebind()
End Sub
From this code my grand total is getting displayed at the middle based Total value.
Can I sort only nine rows except last row?
Regards,
Medac
To insert additional sort expressions if needed, consider adding sort expression programmatically to the SortExpressions collection of RadGrid for ASP.NET AJAX. For further details please review this online example of the product:
Programmatic Sorting
Sincerely yours,
Pavlina
the Telerik team
Instantly find answers to your questions on the new Telerik Support Portal.
Check out the tips for optimizing your support resource searches.

Can I apply footer feature for AutogeneratedColumns radgrid?
I have visited http://demos.telerik.com/aspnet-ajax/grid/examples/groupby/groupfooter/defaultcs.aspx link where in I could find that it is possible to have footer by specifying the expression in GridBoundColumn.
So in my radgrid AugeneratedColumns = True and I am binding the grid dynamically. In my scnerio is it possible to have footer in my grid?
Thanks,
Medac

Set the aggregate property for the auto-generatedcolumn in the ColumnCreated event as shown below.
CS:
protected void RadGrid1_ColumnCreated(object sender, GridColumnCreatedEventArgs e) |
{ |
if (e.Column.UniqueName == "ColumnName") |
{ |
GridBoundColumn boundColumn = e.Column as GridBoundColumn; |
boundColumn.Aggregate = GridAggregateFunction.Sum; |
} |
} |
You may also go through the following forum link which discusses a similar requirement.
Grouping Aggregation - Dynamic Columns
Shinu

I have implemented the code which you have given in Column Created event for specifying the aggeregate function but for me it is giving error
Protected
Sub radgrdClaimsAvailable_ColumnCreated(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridColumnCreatedEventArgs) Handles radgrdClaimsAvailable.ColumnCreated
Dim iSubCount As Short
Dim gridBoundcolumn As New GridBoundColumn
If radgrdClaimsAvailable.MasterTableView.RenderColumns.Length > 0 Then
For iSubCount = 4 To radgrdClaimsAvailable.MasterTableView.RenderColumns.Length - 1
gridBoundcolumn = radgrdClaimsAvailable.MasterTableView.RenderColumns(iSubCount)
gridBoundcolumn.Aggregate = GridAggregateFunction.Sum
Next
End If
End Sub
It is giving following error for the below line
For iSubCount = 4 To radgrdClaimsAvailable.MasterTableView.RenderColumns.Length - 1
An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll
I have not added if (e.Column.UniqueName == "ColumnName") this line becuase i dnt know the column name
Help me in this......
Regards,
Medac

I am done with all the functionalities of my autogenerated columns grid.
Now Huge Performance hit !!!!!!!!!!!!
It is taking saveral mintues to load the grid only. Hardly 10 rows are there with 10 columns.
I have written following events for the grid and page....
can you please suggest me some tips so that i can implement the same to improve the performance...
radgrd1_DataBound - Here I am setting the tooltip for the grid
radgrd1_ItemCommand - Getting the value (id value) from the selected row.
radgrd1_NeedDataSource - Getting the Datatable from viewstate and again assigning it to grid for paging and sorting.
Page_PrerenderCompleted - In this event I am setting the Column Type for the Dynamic generated columns, Addinf aggregate functionality to the autogenerated columns, Addind sort expression for the column and rebinding the grid.
Give some tips to improve the performance of the grid loading.
Regards,
Medac
To optimize the RadGrid performance and your page overall performance, please refer to the resources pointed below:
http://www.telerik.com/help/aspnet-ajax/gridoverview.html (Chapter 'Performance tips and tricks')
http://www.telerik.com/products/aspnet-ajax/resources/top-performance.aspx
They can help you reduce the loading time.
Kind regards,
Pavlina
the Telerik team
Instantly find answers to your questions on the new Telerik Support Portal.
Check out the tips for optimizing your support resource searches.

Grid:
<telerik:RadGrid runat="server" ID="RadGrid1" OnNeedDataSource="RadGrid1_NeedDataSource" OnDataBound="RadGrid1_DataBound" AllowPaging="True" AllowSorting="True" Visible="False"> |
<MasterTableView> |
<RowIndicatorColumn> |
<HeaderStyle Width="20px" /> |
</RowIndicatorColumn> |
<ExpandCollapseColumn> |
<HeaderStyle Width="20px" /> |
</ExpandCollapseColumn> |
</MasterTableView> |
</telerik:RadGrid> |
Code behind:
using System; |
using System.Data; |
using System.Data.Common; |
using System.Data.SqlClient; |
using System.Configuration; |
using System.Collections; |
using System.Web; |
using System.Web.Security; |
using System.Web.UI; |
using System.Web.UI.WebControls; |
using System.Web.UI.WebControls.WebParts; |
using System.Web.UI.HtmlControls; |
using System.Web.Configuration; |
using Telerik.Web.UI; |
public partial class SearchCustomers : System.Web.UI.Page |
{ |
public static string strConn = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; |
protected void Page_Load(object sender, EventArgs e) |
{ |
if (!IsPostBack) |
{ |
} |
} |
protected void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e) |
{ |
using (SqlConnection sqlConn = new SqlConnection(strConn)) |
{ |
sqlConn.Open(); |
SqlCommand sqlCmd; |
sqlCmd = new SqlCommand("sp_GetCustomerList", sqlConn); |
sqlCmd.CommandType = CommandType.StoredProcedure; |
//ADD PARAMETERS |
//several input parameters... |
SqlDataAdapter daConsultationResident = new SqlDataAdapter(sqlCmd); |
DataTable dtConsultationResident = new DataTable(); |
daConsultationResident.Fill(dtConsultationResident); |
((RadGrid)source).DataSource = dtConsultationResident; |
//following line throws out of range exception |
//RadGrid1.Columns.FindByUniqueName("ID").Visible = false; |
sqlCmd.Dispose(); |
sqlConn.Close(); |
} |
} |
} |
protected void RadGrid1_DataBound(object sender, EventArgs e) |
{ |
} |
protected void RadGrid1_ColumnCreated(object sender, GridColumnCreatedEventArgs e) |
{ |
//this module never executes |
if (e.Column.UniqueName == "ID") |
{ |
GridBoundColumn CN = (GridBoundColumn)e.Column; |
CN.DataFormatString = "{0:c}"; |
} |
} |
protected void btnSearch_Click(object sender, EventArgs e) |
{ |
RadGrid1.Rebind(); |
RadGrid1.Visible = true; |
} |
} |
To achieve your goal you could handle on PreRender event of the grid, traverse the Columns collection to locate the column of interest, and alter its properties. You must then rebind the grid by calling its Rebind() method to reflect the changes:
More info is available in this link:
http://www.telerik.com/help/aspnet-ajax/grdusingcolumns.html (at the bottom of the page)
All the best,
Pavlina
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.

We are providing the code for necessary consideration.
<%@ Page Language="C#" MasterPageFile="~/Presentationlayer/MasterAdmin.master" AutoEventWireup="true" CodeFile="T_Other_AgentwiseCaseStatement.aspx.cs" Inherits="Presentationlayer_TAgentwiseCaseStatement" Title="Agentwise Case Statement" %>
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<%@ Register Src="MS_Control/MultipleSelection.ascx" TagName="MultipleSelection" TagPrefix="uc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div>
<script type="text/javascript">
function pageLoad() {
var grid = $find('<%=RadGrid1.ClientID %>');
var columns = grid.get_masterTableView().get_columns();
for (var i = 0; i < columns.length; i++) {
columns[i].resizeToFit();
}
}
</script>
</div>
<div>
<telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="True"
AllowSorting="true" AllowPaging="True" PageSize="50" Skin="Sunset"
ShowFooter="True" AllowFilteringByColumn="true" ShowGroupPanel="true"
onneeddatasource="RadGrid1_NeedDataSource" OnColumnCreated ="RadGrid1_ColumnCreated" > <%--OnColumnCreated ="RadGrid1_ColumnCreated --%>
<HeaderContextMenu CssClass="GridContextMenu GridContextMenu_Sunset"></HeaderContextMenu>
<ExportSettings HideStructureColumns="true" IgnorePaging="true" OpenInNewWindow="true" ExportOnlyData="true" />
<MasterTableView CommandItemDisplay="Top" ShowGroupFooter="true" GroupLoadMode="Client" TableLayout="Fixed" Width="100%">
<CommandItemSettings ShowExportToWordButton="true" ShowExportToExcelButton="true"
ShowExportToCsvButton="true" ShowExportToPdfButton="true" ShowAddNewRecordButton="false" />
<RowIndicatorColumn FilterControlAltText="Filter RowIndicator column"></RowIndicatorColumn>
<ExpandCollapseColumn FilterControlAltText="Filter ExpandColumn column"></ExpandCollapseColumn>
<EditFormSettings>
<EditColumn FilterControlAltText="Filter EditCommandColumn column"></EditColumn>
</EditFormSettings>
</MasterTableView>
<ClientSettings Selecting-AllowRowSelect="true" AllowKeyboardNavigation="true" EnablePostBackOnRowClick="true" EnableRowHoverStyle="true" AllowGroupExpandCollapse="true" ReorderColumnsOnClient="True" AllowDragToGroup="true" AllowColumnsReorder="True">
<Selecting AllowRowSelect="True"></Selecting>
<Scrolling AllowScroll="false" UseStaticHeaders="true" />
<Resizing AllowColumnResize="true" EnableRealTimeResize="true" AllowResizeToFit="true" />
</ClientSettings>
<FilterMenu EnableImageSprites="False"></FilterMenu>
</telerik:RadGrid>
</div>
<div>
<telerik:RadDock ID="RadDock1" runat="server" Width="380px" Left="10" Top="125"
Title="Search Companion" DefaultCommands="ExpandCollapse">
<ContentTemplate>
<table>
<tr>
<td>
<table width="90%">
<tr>
<td> From</td>
<td>
<telerik:RadDatePicker ID="rdpFrom" runat="server" Width="100" Culture="(Default)">
<Calendar UseRowHeadersAsSelectors="False" UseColumnHeadersAsSelectors="False" ViewSelectorText="x" Skin="Outlook"></Calendar>
<DatePopupButton ImageUrl="" HoverImageUrl=""></DatePopupButton>
<DateInput DisplayDateFormat="dd/MM/yyyy" AutoPostBack="False"></DateInput>
</telerik:RadDatePicker>
</td>
<td> To</td>
<td>
<telerik:RadDatePicker ID="rdpTo" runat="server" Width="100" Culture="(Default)">
<Calendar UseRowHeadersAsSelectors="False" UseColumnHeadersAsSelectors="False" ViewSelectorText="x" Skin="Outlook"></Calendar>
<DatePopupButton ImageUrl="" HoverImageUrl=""></DatePopupButton>
<DateInput DisplayDateFormat="dd/MM/yyyy" AutoPostBack="False"></DateInput>
</telerik:RadDatePicker>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td style="z-index:2">
<asp:CheckBox ID="CheckBox1" runat="server" Text="All/Selective Agent" Checked="true"
AutoPostBack="true" oncheckedchanged="CheckBox1_CheckedChanged" />
<br />
<uc1:MultipleSelection ID="chkAgent" runat="server" width="400px" />
</td></tr>
<tr>
<td colspan="1">
<table width="50%">
<tr>
<td>
Print Company Name,Address & Report Heading :
</td>
<td>
<telerik:RadComboBox ID="ddlincldagentcase" runat="server" Width="60PX">
<Items>
<telerik:RadComboBoxItem Text="Yes" Value="Y" />
<telerik:RadComboBoxItem Selected="true" Text="No" Value="N" />
</Items>
</telerik:RadComboBox>
</td>
</tr>
</table>
</td>
</tr>
</tr>
<caption>
<br />
<br />
<tr>
<td>
<table width="75%">
<tr>
<td align="left">
<telerik:RadButton ID="rbtRpt" runat="server" onclick="rbtRpt_Click"
Text="Print">
</telerik:RadButton>
</td>
<td align="right">
<telerik:RadButton ID="rbtShow" runat="server" onclick="rbtShow_Click"
Text="Preview">
</telerik:RadButton>
</td>
</tr>
</table>
</td>
</tr>
</caption>
</tr>
</table>
</ContentTemplate>
</telerik:RadDock>
<%--<asp:SqlDataSource ID="SqlDataSource2" ProviderName="System.Data.SqlClient" SelectCommand="SELECT DISTINCT name as DOCTORNAME FROM doctor"
runat="server"></asp:SqlDataSource>--%>
</div>
</asp:Content>
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Web.Configuration;
using System.Data.SqlClient;
using System.Globalization;
using Telerik.Web.UI;
public partial class Presentationlayer_TAgentwiseCaseStatement : System.Web.UI.Page
{
string conn;
Binddata btd;
Misc1 misc;
string strfltr1;
public void conns()
{
conn = WebConfigurationManager.ConnectionStrings[Convert.ToString(Session["connstring"])].ConnectionString;
}
public void reset()
{
misc = new Misc1();
}
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToString(Session["connstring"]) == "" || Convert.ToString(Session["connstring"]) == null)
{
Response.Redirect("Userauthentication.aspx");
}
else
{
if (!IsPostBack)
{
btd = new Binddata();
ViewState["crdate"] = btd.getsrdate();
ViewState["fnstartdate"] = Convert.ToString(Session["fnstartdate"]);
ViewState["mode"] = "0";
string opdt = "01/04/" + Convert.ToString(ViewState["fnstartdate"]);
rdpFrom.SelectedDate = DateTime.Parse(ViewState["fnstartdate"].ToString(), CultureInfo.CreateSpecificCulture("en-CA")); ;
chkAgent.Visible = false;
rdpTo.SelectedDate = DateTime.Parse(ViewState["crdate"].ToString(), CultureInfo.CreateSpecificCulture("en-CA")); ;
//ViewState["ch"] = "1";
//bindgrid();
//RadGrid1.DataBind();
//RadDock1.Collapsed = true;
}
}
}
protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
if (Convert.ToString(ViewState["mode"]) == "1")
{
bindgrid();
}
}
private void bindgrid()
{
conns();
SqlConnection con = new SqlConnection(conn);
SqlCommand com;
try
{
//ViewState["cmpid"] = "1";
con.Open();
com = new SqlCommand("Usp_AgentwiseCasestmt", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@ComCode", "");
com.Parameters.AddWithValue("@FrmDt", DateTime.Parse(rdpFrom.SelectedDate.Value.ToString("yyyy/MM/dd"), CultureInfo.CreateSpecificCulture("en-CA")));
com.Parameters.AddWithValue("@ToDt", DateTime.Parse(rdpTo.SelectedDate.Value.ToString("yyyy/MM/dd"), CultureInfo.CreateSpecificCulture("en-CA")));
// com.Parameters.AddWithValue("@ch", Int32.Parse(Convert.ToString(ViewState["ch"])));
com.Parameters.AddWithValue("@strfltr", Convert.ToString(ViewState["strfltr"]));
// com.Parameters.AddWithValue("@Pending", ddlonlypending.SelectedValue);
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
da.Fill(dt);
RadGrid1.MasterTableView.Caption = "AgentWise CaseStatement " + rdpFrom.SelectedDate.Value.ToString("dd/MM/yyyy") + " To" + rdpTo.SelectedDate.Value.ToString("dd/MM/yyyy");
//int x = com.ExecuteNonQuery();
RadGrid1.DataSource = dt;
RadGrid1.DataBind();
}
catch (Exception ex)
{
}
finally
{
con.Close();
}
}
protected void RadGrid1_PreRender(object sender, System.EventArgs e)
{
/
}
protected void rbtShow_Click(object sender, EventArgs e)
{
ViewState["mode"] = "1";
if (chkAgent.sValue != "")
{
strfltr1 = " and AGENT.CODE IN(" + chkAgent.sValue + ") ";
}
else
{
strfltr1 = "";
}
ViewState["strfltr"] = strfltr1;
bindgrid();
RadGrid1.DataBind();
RadDock1.Collapsed = true;
}
protected void rbtRpt_Click(object sender, EventArgs e)
{
Response.Write("<script>window.open('T_Other_AgentwiseCaseStatement_rpt.aspx?cmp=" + Convert.ToString(ViewState["cmpid"]) + "&dtfrom=" + rdpFrom.SelectedDate.Value.ToString("dd/MM/yyyy") + "&dtto=" + rdpTo.SelectedDate.Value.ToString("dd/MM/yyyy") + "&strfltr=" + Convert.ToString(ViewState["strfilter"]) + "', '','left=0,height=900,width=1200,top=0,resizable=no,scrollbars=yes,toolbar=no,status=no,target=_blank,location=no');</script>");
}
protected void RadGrid1_ColumnCreated(object sender, GridColumnCreatedEventArgs e)
{
if (e.Column.ColumnType== "GridBoundColumn")
{
if (e.Column.UniqueName != "patient" && e.Column.UniqueName != "Agent" && e.Column.UniqueName != "casedt" && e.Column.UniqueName != "CaseNo")
{
e.Column.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
e.Column.HeaderStyle.HorizontalAlign = HorizontalAlign.Right;
}
if (e.Column.DataType == typeof(String))
{
e.Column.ItemStyle.HorizontalAlign = HorizontalAlign.Left;
e.Column.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
}
}
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox1.Checked == true)
{
chkAgent.Visible = false;
}
else
{
chkAgent.Visible = true;
bindagent();
}
}
public void bindagent()
{
conns();
SqlConnection con = new SqlConnection(conn);
SqlCommand com;
con.Open();
com = new SqlCommand("Select CODE, NAME from AGENT Order by Name", con);
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
da.Fill(dt);
chkAgent.CreateCheckBox(dt, "name", "code");
}
}