Hi,
I have a radgrid and it is a bound column. I have tried to set the format using DataFormatString = "{0:NNN-NNN-NNNN}" but I keep getting 9999999999 as the output. I would like 999-999-9999
I read somewhere that the column had to be a number in order to format it the way I want it. There has to be an easy way to format this?
thanks,
Will
I have a radgrid and it is a bound column. I have tried to set the format using DataFormatString = "{0:NNN-NNN-NNNN}" but I keep getting 9999999999 as the output. I would like 999-999-9999
I read somewhere that the column had to be a number in order to format it the way I want it. There has to be an easy way to format this?
thanks,
Will
8 Answers, 1 is accepted
0

Gimmik
Top achievements
Rank 1
answered on 26 May 2011, 09:58 PM
Hi Will,
Have you tried setting the column type as a GridNumericColumn? That might fix your problem.
Hope that helps!
-Gimmik
Have you tried setting the column type as a GridNumericColumn? That might fix your problem.
<
telerik:GridNumericColumn
DataField
=
"Freight"
HeaderText
=
"GridNumericColumn"
UniqueName
=
"Freight"
>
</
telerik:GridNumericColumn
>
Hope that helps!
-Gimmik
0

Will
Top achievements
Rank 1
answered on 26 May 2011, 11:58 PM
Unfortunately that didnt work.
0

siddhartha
Top achievements
Rank 1
answered on 27 May 2011, 02:01 AM
Try using the MaskedColumn in the RadGrid property column layout.. !!!
0

Princy
Top achievements
Rank 2
answered on 27 May 2011, 05:19 AM
Hello Will,
Try setting the DataFormatString as shown below.
aspx:
Thanks,
Princy.
Try setting the DataFormatString as shown below.
aspx:
<
telerik:GridBoundColumn
DataField
=
"ContactNo1"
HeaderText
=
"ContactNo1"
UniqueName
=
"ContactNo1"
DataFormatString
=
"{0:###-###-####}"
>
</
telerik:GridBoundColumn
>
Thanks,
Princy.
0

Will
Top achievements
Rank 1
answered on 27 May 2011, 06:02 PM
I tried them and it didnt work either. I think the maskedColumn is for editing only. I'm trying to display the data. I've even set the datatype="System.Int64" for the grid column types. Still showed the data as 9999999999 instead of 999-999-9999.
0
Hello Will,
DataFormatString
Kind regards,
Tsvetina
the Telerik team
DataFormatString
=
"{0:###-###-####}"
along with DataType="System.Int32" worked on my side. Is it possible that you send us your grid code and any steps needed to reproduce the problem that you are encountering?Kind regards,
Tsvetina
the Telerik team
Browse the vast support resources we have to jump start your development with RadControls for ASP.NET AJAX. See how to integrate our AJAX controls seamlessly in SharePoint 2007/2010 visiting our common SharePoint portal.
0

Will
Top achievements
Rank 1
answered on 01 Jun 2011, 06:02 PM
hi,
Here is my attach file. rename to .zip to use.
thanks,
Will
using System;
using System.Data.OleDb ;
using System.Data;
using System.Drawing;
using Telerik.Web.UI;
using BCStats.Utilities;
using System.ComponentModel;
using Telerik.Cms.Web.UI;
using System.Web .UI .WebControls ;
namespace Website.UserControls.General
{
public partial class BCStatsContact : CacheSubstitutionUserControl //System.Web.UI.UserControl
{
#region Sitefinity Properties
/// <summary>
/// Initialize variables just in case there is not set
/// </summary>
private String _CSVDirectory = "/Data/contacts/";
private String _CSVFile = "BCStatsContactList.csv";
private String _ColumnSortName = "Name";
private Int32 _PageSize = 55;
private String _GroupByName = "";
/// <summary>
/// Name of csv file to display in grid
/// </summary>
[Category("Grid Properties")]
[Description("Name of csv file to load")]
public String CSVFile
{
get { return _CSVFile; }
set { _CSVFile = value; }
}
/// <summary>
/// Directory of csv file to load
/// </summary>
[Category("Grid Properties")]
[Description("Directory of csv file to load")]
public String CSVDirectory
{
get { return _CSVDirectory; }
set { _CSVDirectory = value; }
}
/// <summary>
/// Column Name to sort on
/// </summary>
[Category("Grid Properties")]
[Description("Sort grid by ColumnName")]
public String ColumnSortName
{
get { return _ColumnSortName; }
set { _ColumnSortName = value; }
}
/// <summary>
/// Sort direction of column name in Ascending or Descending order
/// </summary>
[Category("Grid Properties")]
[Description("Sort Direction")]
public SortOrderType SortOrder { get; set;}
public enum SortOrderType {Ascending,Descending}
/// <summary>
/// Number of records to display per page of the radgrid
/// </summary>
[Category("Grid Properties")]
[Description("Number of records to display per page")]
public Int32 RecordsToDisplay
{
get { return _PageSize; }
set { _PageSize = value; }
}
/// <summary>
/// Number of records to display per page of the radgrid
/// </summary>
[Category("Grid Properties")]
[Description("Group Records to column name")]
public String GroupByColumnName
{
get { return _GroupByName; }
set { _GroupByName = value; }
}
#endregion
#region Cache Substitution settings
/// <summary>
/// Gets the page mode that is used for the cache substitution
/// </summary>
public override SubstitutionPageMode PageMode
{
get { return SubstitutionPageMode.Full; }
}
#endregion
protected void Page_Load(object sender, EventArgs e)
{
DataSet tmp = new DataSet();
if (!IsPostBack) { LoadGrid(); }
}
/// <summary>
/// Get the data from csv file to load into the grid and set sort column name of grid
/// </summary>
protected void LoadGrid()
{
try
{
//get the data from csv file
DataSet csvsource = readCsv(CSVFile, CSVDirectory);
//check to see if there is any data to set the grid to
if (csvsource != null)
{
//set the datasource of grid
RadGrid1.DataSource = csvsource;
//check to see if there is a sortname and if the columnName exists in RadGrid
if (ColumnSortName != "") // && RadGrid2.Columns.Contains(ColumnSortName))
{
//set column sort order
RadGrid1.MasterTableView.SortExpressions.AddSortExpression(GetSortColumnOrder(ColumnSortName));
//disable all column sorting capability
RadGrid1.AllowSorting = false;
}
// cannot set a to less than 10 per page
if (RecordsToDisplay <= 10)
{
RadGrid1.PageSize = 10;
}
else
{
RadGrid1.PageSize = RecordsToDisplay;
}
if (_GroupByName != "")
{
GridGroupByExpression expression = new GridGroupByExpression();
GridGroupByField gridGroupByField = new GridGroupByField();
//Group by display header data
gridGroupByField.FieldName = "Dept";
gridGroupByField.HeaderText = string.Empty;
gridGroupByField.FieldAlias = "<b>";
gridGroupByField.HeaderValueSeparator = " ";
expression.SelectFields.Add(gridGroupByField);
//GroupByFields values (group data) column to sort by (ie DeptSort)
gridGroupByField = new GridGroupByField();
gridGroupByField.FieldName = "DeptSort";
gridGroupByField.HeaderText = string.Empty;
expression.GroupByFields.Add(gridGroupByField);
RadGrid1.MasterTableView.GroupByExpressions.Add(expression);
//sort order
GridSortExpression expression1 = new GridSortExpression();
expression1.FieldName = "TitleSort";
expression1.SortOrder = GridSortOrder.Ascending;
RadGrid1.MasterTableView.SortExpressions.AddSortExpression(expression1);
}
//set grid to values
RadGrid1.DataBind();
//RadGrid1.MasterTableView.Columns.FindByUniqueName("Email").Visible = false;
RadGrid1.ClientSettings.Resizing.AllowColumnResize = true;
}
}
catch (Exception e)
{
//error message to display
ErrorHandler.HandleError("Error Loading Grid data: " + e.Message + "\n\n" + Environment.StackTrace);
}
}
protected void RadGrid1_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
//set the datasource of grid
RadGrid1.DataSource = readCsv(CSVFile, CSVDirectory);
}
protected void RadGrid1_SortCommand(object source, GridSortCommandEventArgs e)
{
if (e.CommandArgument == "DeptSort,TitleSort")
{
//Request a data from the datasource reflecting the needed sorting
RadGrid1.DataSource = readCsv(CSVFile, CSVDirectory);
//Rebind the grid
e.Item.OwnerTableView.Rebind();
// RadGrid1.Rebind();
}
}
protected void RadGrid1_ColumnCreated(object sender, GridColumnCreatedEventArgs e)
{
if (e.Column is GridGroupSplitterColumn)
{
e.Column.HeaderStyle.Width = Unit.Pixel(1);
e.Column.HeaderStyle.Font.Size = FontUnit.Point(1);
e.Column.ItemStyle.Width = Unit.Pixel(1);
e.Column.ItemStyle.Font.Size = FontUnit.Point(1);
e.Column.Resizable = false;
}
if ((e.Column.UniqueName == "Email") || (e.Column.UniqueName == "Dept")) // || (e.Column.UniqueName == "DeptSort") || (e.Column.UniqueName == "TitleSort"))
{
e.Column.Visible = false;
}
//if (e.Column.UniqueName == "Title")
//{
// e.Column.HeaderStyle.Width = 200;
//}
}
/// <summary>
/// function: GetSortColumnOrder
/// Determines what column to sort the grid to display the data
/// </summary>
/// <returns>column to sort and order to sort</returns>
protected GridSortExpression GetSortColumnOrder(string ColName )
{
GridSortExpression sortCol = new GridSortExpression { FieldName = ColName };
switch (SortOrder)
{
case SortOrderType.Ascending :
sortCol.SortOrder = GridSortOrder.Ascending;
break ;
case SortOrderType .Descending :
sortCol.SortOrder = GridSortOrder.Descending;
break;
default:
sortCol.SortOrder = GridSortOrder.None;
break;
}
return sortCol ;
}
protected void RadGrid1_PageIndexChanged(object sender, GridPageChangedEventArgs e)
{
LoadGrid();
}
protected void ChangeGroupHeaderColour(object sender, GridItemEventArgs e)
{
if (e.Item is GridGroupHeaderItem)
{
GridGroupHeaderItem item = e.Item as GridGroupHeaderItem;
//if (item.GroupIndex.Split('_').Length == 4)
//{
e.Item.BackColor = Color.LightGray ;
//}
//else{
// e.Item.BackColor = Color.Coral;
//}
}
}
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
//if (e.Item is GridDataItem)
//{
// GridDataItem dbitem = (GridDataItem)e.Item;
// if (dbitem["Phone"].Text.Length == 10)
// {
// //format the phone number
// dbitem["Phone"].Text = String.Format("{0:###-###-####}", Convert.ToInt64(dbitem["Phone"].Text));
// }
//if (dbitem["Name"].Text != "")
//{
// GridHyperLinkColumn hyplnk = new GridHyperLinkColumn();
// hyplnk.DataTextField = "Name";
// hyplnk.DataNavigateUrlFields.SetValue("Email",0);
// hyplnk.DataNavigateUrlFormatString = "mailto:{0}";
//}
// }
ChangeGroupHeaderColour(sender, e);
}
protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
{
if (e.Item is GridCommandItem)
{
e.Item.FindControl("InitInsertButton").Visible = false;
e.Item.FindControl("AddNewRecordButton").Visible = false;
e.Item.FindControl("RefreshButton").Visible = false;
}
if (e.Item is GridGroupHeaderItem)
{
(e.Item as GridGroupHeaderItem).Cells[0].Controls.Clear();
}
}
//public void ConfigureExport()
//{
// RadGrid2.ExportSettings.ExportOnlyData = true; // CheckBox1.Checked;
// RadGrid2.ExportSettings.IgnorePaging = true;
// //RadGrid1.ExportSettings.OpenInNewWindow = CheckBox3.Checked;
//}
//protected void RadGrid2_PreRender(object sender, EventArgs e)
//{
// GridColumn gridCol = RadGrid2.MasterTableView.GetColumn("Name");
// gridCol.HeaderStyle.Width = Unit.Percentage(100); // Unit.Pixel(100);
//}
/// <summary>
/// reads a csv file into a dataset from a certain location
/// </summary>
/// <param name="fileName">csv filename to load</param>
/// <param name="filePath">path to csv filename</param>
/// <returns>dataset of csv file</returns>
public DataSet readCsv(string fileName, string filePath)
{
try
{
string tmppath = Server.MapPath(filePath );
string strPath = @tmppath; //"C:\Data\Projects\websiteCMS\Website\Data\pophouse\";
string ConnectionString =
string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};
Extended Properties=""text;HDR=Yes;FMT=Delimited"";", strPath);
string CommandText = string.Format(@"SELECT * FROM [{0}]",fileName, ConnectionString);
DataSet CSVDataSet = new DataSet();
OleDbConnection CSVConnection = new OleDbConnection(ConnectionString);
OleDbDataAdapter CSVAdapter = new OleDbDataAdapter(CommandText, CSVConnection);
CSVConnection.Open();
CSVAdapter.Fill(CSVDataSet, fileName);
CSVConnection.Close();
//RadGrid2.PagerStyle.Mode = GridPagerMode.NextPrev;
//GridColumn gridCol = RadGrid2.MasterTableView.GetColumn("Name");
//gridCol.HeaderStyle.Width = Unit.Pixel(300); // Unit.Pixel(100);
return CSVDataSet;
}
catch (Exception ex)
{
//lblerror.Text = ex.Message;
LitError.Text = Messenger.GetHtmlMessage(Messenger.MessageType.Error, "Error with csv file");
ErrorHandler.HandleError("Error loading csv file: " + ex.InnerException + "\n\n" + Environment.StackTrace);
//throw ex;
return null;
}
}
}
}
Here is my attach file. rename to .zip to use.
thanks,
Will
using
System;
using
System.Data.OleDb ;
using
System.Data;
using
System.Drawing;
using
Telerik.Web.UI;
using
BCStats.Utilities;
using
System.ComponentModel;
using
Telerik.Cms.Web.UI;
using
System.Web .UI .WebControls ;
namespace
Website.UserControls.General
{
public
partial
class
BCStatsContact : CacheSubstitutionUserControl
//System.Web.UI.UserControl
{
#region Sitefinity Properties
/// <summary>
/// Initialize variables just in case there is not set
/// </summary>
private
String _CSVDirectory =
"/Data/contacts/"
;
private
String _CSVFile =
"BCStatsContactList.csv"
;
private
String _ColumnSortName =
"Name"
;
private
Int32 _PageSize = 55;
private
String _GroupByName =
""
;
/// <summary>
/// Name of csv file to display in grid
/// </summary>
[Category(
"Grid Properties"
)]
[Description(
"Name of csv file to load"
)]
public
String CSVFile
{
get
{
return
_CSVFile; }
set
{ _CSVFile = value; }
}
/// <summary>
/// Directory of csv file to load
/// </summary>
[Category(
"Grid Properties"
)]
[Description(
"Directory of csv file to load"
)]
public
String CSVDirectory
{
get
{
return
_CSVDirectory; }
set
{ _CSVDirectory = value; }
}
/// <summary>
/// Column Name to sort on
/// </summary>
[Category(
"Grid Properties"
)]
[Description(
"Sort grid by ColumnName"
)]
public
String ColumnSortName
{
get
{
return
_ColumnSortName; }
set
{ _ColumnSortName = value; }
}
/// <summary>
/// Sort direction of column name in Ascending or Descending order
/// </summary>
[Category(
"Grid Properties"
)]
[Description(
"Sort Direction"
)]
public
SortOrderType SortOrder {
get
;
set
;}
public
enum
SortOrderType {Ascending,Descending}
/// <summary>
/// Number of records to display per page of the radgrid
/// </summary>
[Category(
"Grid Properties"
)]
[Description(
"Number of records to display per page"
)]
public
Int32 RecordsToDisplay
{
get
{
return
_PageSize; }
set
{ _PageSize = value; }
}
/// <summary>
/// Number of records to display per page of the radgrid
/// </summary>
[Category(
"Grid Properties"
)]
[Description(
"Group Records to column name"
)]
public
String GroupByColumnName
{
get
{
return
_GroupByName; }
set
{ _GroupByName = value; }
}
#endregion
#region Cache Substitution settings
/// <summary>
/// Gets the page mode that is used for the cache substitution
/// </summary>
public
override
SubstitutionPageMode PageMode
{
get
{
return
SubstitutionPageMode.Full; }
}
#endregion
protected
void
Page_Load(
object
sender, EventArgs e)
{
DataSet tmp =
new
DataSet();
if
(!IsPostBack) { LoadGrid(); }
}
/// <summary>
/// Get the data from csv file to load into the grid and set sort column name of grid
/// </summary>
protected
void
LoadGrid()
{
try
{
//get the data from csv file
DataSet csvsource = readCsv(CSVFile, CSVDirectory);
//check to see if there is any data to set the grid to
if
(csvsource !=
null
)
{
//set the datasource of grid
RadGrid1.DataSource = csvsource;
//check to see if there is a sortname and if the columnName exists in RadGrid
if
(ColumnSortName !=
""
)
// && RadGrid2.Columns.Contains(ColumnSortName))
{
//set column sort order
RadGrid1.MasterTableView.SortExpressions.AddSortExpression(GetSortColumnOrder(ColumnSortName));
//disable all column sorting capability
RadGrid1.AllowSorting =
false
;
}
// cannot set a to less than 10 per page
if
(RecordsToDisplay <= 10)
{
RadGrid1.PageSize = 10;
}
else
{
RadGrid1.PageSize = RecordsToDisplay;
}
if
(_GroupByName !=
""
)
{
GridGroupByExpression expression =
new
GridGroupByExpression();
GridGroupByField gridGroupByField =
new
GridGroupByField();
//Group by display header data
gridGroupByField.FieldName =
"Dept"
;
gridGroupByField.HeaderText =
string
.Empty;
gridGroupByField.FieldAlias =
"<b>"
;
gridGroupByField.HeaderValueSeparator =
" "
;
expression.SelectFields.Add(gridGroupByField);
//GroupByFields values (group data) column to sort by (ie DeptSort)
gridGroupByField =
new
GridGroupByField();
gridGroupByField.FieldName =
"DeptSort"
;
gridGroupByField.HeaderText =
string
.Empty;
expression.GroupByFields.Add(gridGroupByField);
RadGrid1.MasterTableView.GroupByExpressions.Add(expression);
//sort order
GridSortExpression expression1 =
new
GridSortExpression();
expression1.FieldName =
"TitleSort"
;
expression1.SortOrder = GridSortOrder.Ascending;
RadGrid1.MasterTableView.SortExpressions.AddSortExpression(expression1);
}
//set grid to values
RadGrid1.DataBind();
//RadGrid1.MasterTableView.Columns.FindByUniqueName("Email").Visible = false;
RadGrid1.ClientSettings.Resizing.AllowColumnResize =
true
;
}
}
catch
(Exception e)
{
//error message to display
ErrorHandler.HandleError(
"Error Loading Grid data: "
+ e.Message +
"\n\n"
+ Environment.StackTrace);
}
}
protected
void
RadGrid1_NeedDataSource(
object
source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
//set the datasource of grid
RadGrid1.DataSource = readCsv(CSVFile, CSVDirectory);
}
protected
void
RadGrid1_SortCommand(
object
source, GridSortCommandEventArgs e)
{
if
(e.CommandArgument ==
"DeptSort,TitleSort"
)
{
//Request a data from the datasource reflecting the needed sorting
RadGrid1.DataSource = readCsv(CSVFile, CSVDirectory);
//Rebind the grid
e.Item.OwnerTableView.Rebind();
// RadGrid1.Rebind();
}
}
protected
void
RadGrid1_ColumnCreated(
object
sender, GridColumnCreatedEventArgs e)
{
if
(e.Column
is
GridGroupSplitterColumn)
{
e.Column.HeaderStyle.Width = Unit.Pixel(1);
e.Column.HeaderStyle.Font.Size = FontUnit.Point(1);
e.Column.ItemStyle.Width = Unit.Pixel(1);
e.Column.ItemStyle.Font.Size = FontUnit.Point(1);
e.Column.Resizable =
false
;
}
if
((e.Column.UniqueName ==
"Email"
) || (e.Column.UniqueName ==
"Dept"
))
// || (e.Column.UniqueName == "DeptSort") || (e.Column.UniqueName == "TitleSort"))
{
e.Column.Visible =
false
;
}
//if (e.Column.UniqueName == "Title")
//{
// e.Column.HeaderStyle.Width = 200;
//}
}
/// <summary>
/// function: GetSortColumnOrder
/// Determines what column to sort the grid to display the data
/// </summary>
/// <returns>column to sort and order to sort</returns>
protected
GridSortExpression GetSortColumnOrder(
string
ColName )
{
GridSortExpression sortCol =
new
GridSortExpression { FieldName = ColName };
switch
(SortOrder)
{
case
SortOrderType.Ascending :
sortCol.SortOrder = GridSortOrder.Ascending;
break
;
case
SortOrderType .Descending :
sortCol.SortOrder = GridSortOrder.Descending;
break
;
default
:
sortCol.SortOrder = GridSortOrder.None;
break
;
}
return
sortCol ;
}
protected
void
RadGrid1_PageIndexChanged(
object
sender, GridPageChangedEventArgs e)
{
LoadGrid();
}
protected
void
ChangeGroupHeaderColour(
object
sender, GridItemEventArgs e)
{
if
(e.Item
is
GridGroupHeaderItem)
{
GridGroupHeaderItem item = e.Item
as
GridGroupHeaderItem;
//if (item.GroupIndex.Split('_').Length == 4)
//{
e.Item.BackColor = Color.LightGray ;
//}
//else{
// e.Item.BackColor = Color.Coral;
//}
}
}
protected
void
RadGrid1_ItemDataBound(
object
sender, GridItemEventArgs e)
{
//if (e.Item is GridDataItem)
//{
// GridDataItem dbitem = (GridDataItem)e.Item;
// if (dbitem["Phone"].Text.Length == 10)
// {
// //format the phone number
// dbitem["Phone"].Text = String.Format("{0:###-###-####}", Convert.ToInt64(dbitem["Phone"].Text));
// }
//if (dbitem["Name"].Text != "")
//{
// GridHyperLinkColumn hyplnk = new GridHyperLinkColumn();
// hyplnk.DataTextField = "Name";
// hyplnk.DataNavigateUrlFields.SetValue("Email",0);
// hyplnk.DataNavigateUrlFormatString = "mailto:{0}";
//}
// }
ChangeGroupHeaderColour(sender, e);
}
protected
void
RadGrid1_ItemCreated(
object
sender, GridItemEventArgs e)
{
if
(e.Item
is
GridCommandItem)
{
e.Item.FindControl(
"InitInsertButton"
).Visible =
false
;
e.Item.FindControl(
"AddNewRecordButton"
).Visible =
false
;
e.Item.FindControl(
"RefreshButton"
).Visible =
false
;
}
if
(e.Item
is
GridGroupHeaderItem)
{
(e.Item
as
GridGroupHeaderItem).Cells[0].Controls.Clear();
}
}
//public void ConfigureExport()
//{
// RadGrid2.ExportSettings.ExportOnlyData = true; // CheckBox1.Checked;
// RadGrid2.ExportSettings.IgnorePaging = true;
// //RadGrid1.ExportSettings.OpenInNewWindow = CheckBox3.Checked;
//}
//protected void RadGrid2_PreRender(object sender, EventArgs e)
//{
// GridColumn gridCol = RadGrid2.MasterTableView.GetColumn("Name");
// gridCol.HeaderStyle.Width = Unit.Percentage(100); // Unit.Pixel(100);
//}
/// <summary>
/// reads a csv file into a dataset from a certain location
/// </summary>
/// <param name="fileName">csv filename to load</param>
/// <param name="filePath">path to csv filename</param>
/// <returns>dataset of csv file</returns>
public
DataSet readCsv(
string
fileName,
string
filePath)
{
try
{
string
tmppath = Server.MapPath(filePath );
string
strPath = @tmppath;
//"C:\Data\Projects\websiteCMS\Website\Data\pophouse\";
string
ConnectionString =
string
.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};
Extended Properties=
""
text;HDR=Yes;FMT=Delimited
""
;", strPath);
string
CommandText =
string
.Format(@
"SELECT * FROM [{0}]"
,fileName, ConnectionString);
DataSet CSVDataSet =
new
DataSet();
OleDbConnection CSVConnection =
new
OleDbConnection(ConnectionString);
OleDbDataAdapter CSVAdapter =
new
OleDbDataAdapter(CommandText, CSVConnection);
CSVConnection.Open();
CSVAdapter.Fill(CSVDataSet, fileName);
CSVConnection.Close();
//RadGrid2.PagerStyle.Mode = GridPagerMode.NextPrev;
//GridColumn gridCol = RadGrid2.MasterTableView.GetColumn("Name");
//gridCol.HeaderStyle.Width = Unit.Pixel(300); // Unit.Pixel(100);
return
CSVDataSet;
}
catch
(Exception ex)
{
//lblerror.Text = ex.Message;
LitError.Text = Messenger.GetHtmlMessage(Messenger.MessageType.Error,
"Error with csv file"
);
ErrorHandler.HandleError(
"Error loading csv file: "
+ ex.InnerException +
"\n\n"
+ Environment.StackTrace);
//throw ex;
return
null
;
}
}
}
}
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Contacts.ascx.cs" Inherits="Website.UserControls.General.BCStatsContact" %>
<
script
type
=
"text/javascript"
>
function onRequestStart(sender, args)
{
if (args.get_eventTarget().indexOf("ExportToExcelButton") >= 0 ||
args.get_eventTarget().indexOf("ExportToWordButton") >= 0 ||
args.get_eventTarget().indexOf("ExportToCsvButton") >= 0)
{
args.set_enableAjax(false);
}
}
</
script
>
<
style
type
=
"text/css"
>
.RadGrid1 .rgGroupCol
{
padding-left: 0 ;
padding-right: 0 ;
}
</
style
>
<
asp:Literal
ID
=
"LitError"
runat
=
"server"
></
asp:Literal
>
<
telerik:RadAjaxManager
ID
=
"RadAjaxManager1"
runat
=
"server"
>
<
ClientEvents
OnRequestStart
=
"onRequestStart"
/>
<
AjaxSettings
>
<
telerik:AjaxSetting
AjaxControlID
=
"RadGrid1"
>
<
UpdatedControls
>
<
telerik:AjaxUpdatedControl
ControlID
=
"RadGrid1"
/>
</
UpdatedControls
>
</
telerik:AjaxSetting
>
</
AjaxSettings
>
</
telerik:RadAjaxManager
>
<
telerik:RadGrid
ID
=
"RadGrid1"
AllowSorting
=
"True"
CssClass
=
"RadGrid1"
HeaderStyle-CssClass
=
"RadGrid1"
OnNeedDataSource
=
"RadGrid1_NeedDataSource"
AllowPaging
=
"true"
runat
=
"server"
GridLines
=
"None"
Width
=
"95%"
BorderStyle
=
"None"
HeaderStyle-BorderStyle
=
"None"
CommandItemStyle-BorderStyle
=
"None"
OnPageIndexChanged
=
"RadGrid1_PageIndexChanged"
OnItemCreated
=
"RadGrid1_ItemCreated"
OnColumnCreated
=
"RadGrid1_ColumnCreated"
OnItemDataBound
=
"RadGrid1_ItemDataBound"
PagerStyle-Mode
=
"NextPrev"
>
<
ExportSettings
HideStructureColumns
=
"true"
/>
<
MasterTableView
Width
=
"100%"
CommandItemDisplay
=
"Top"
CommandItemSettings-RefreshText
=
""
BorderStyle
=
"None"
CommandItemStyle-BorderStyle
=
"None"
AutoGenerateColumns
=
"false"
>
<
Columns
>
<
telerik:GridNumericColumn
NumericType
=
"Number"
DataFormatString
=
"{0:###-###-####}"
DataType
=
"System.Int32"
UniqueName
=
"Phone"
DataField
=
"Phone"
HeaderText
=
"Phone"
></
telerik:GridNumericColumn
>
<
telerik:GridHyperLinkColumn
DataTextField
=
"Name"
HeaderText
=
"Name"
DataNavigateUrlFields
=
"Email"
DataNavigateUrlFormatString
=
"mailto:{0}"
></
telerik:GridHyperLinkColumn
>
<
telerik:GridBoundColumn
DataField
=
"Title"
HeaderText
=
"Title"
HeaderStyle-Width
=
"40%"
></
telerik:GridBoundColumn
>
<
telerik:GridBoundColumn
DataField
=
"TitleSort"
HeaderText
=
"TitleSort"
AllowSorting
=
"true"
Visible
=
"false"
></
telerik:GridBoundColumn
>
<
telerik:GridBoundColumn
DataField
=
"DeptSort"
HeaderText
=
"DeptSort"
AllowSorting
=
"true"
Visible
=
"false"
></
telerik:GridBoundColumn
>
</
Columns
>
<
CommandItemSettings
ShowExportToWordButton
=
"false"
ShowExportToExcelButton
=
"false"
ShowExportToCsvButton
=
"false"
/>
</
MasterTableView
>
</
telerik:RadGrid
>
using System;
using System.Data.OleDb ;
using System.Data;
using System.Drawing;
using Telerik.Web.UI;
using BCStats.Utilities;
using System.ComponentModel;
using Telerik.Cms.Web.UI;
using System.Web .UI .WebControls ;
namespace Website.UserControls.General
{
public partial class BCStatsContact : CacheSubstitutionUserControl //System.Web.UI.UserControl
{
#region Sitefinity Properties
/// <summary>
/// Initialize variables just in case there is not set
/// </summary>
private String _CSVDirectory = "/Data/contacts/";
private String _CSVFile = "BCStatsContactList.csv";
private String _ColumnSortName = "Name";
private Int32 _PageSize = 55;
private String _GroupByName = "";
/// <summary>
/// Name of csv file to display in grid
/// </summary>
[Category("Grid Properties")]
[Description("Name of csv file to load")]
public String CSVFile
{
get { return _CSVFile; }
set { _CSVFile = value; }
}
/// <summary>
/// Directory of csv file to load
/// </summary>
[Category("Grid Properties")]
[Description("Directory of csv file to load")]
public String CSVDirectory
{
get { return _CSVDirectory; }
set { _CSVDirectory = value; }
}
/// <summary>
/// Column Name to sort on
/// </summary>
[Category("Grid Properties")]
[Description("Sort grid by ColumnName")]
public String ColumnSortName
{
get { return _ColumnSortName; }
set { _ColumnSortName = value; }
}
/// <summary>
/// Sort direction of column name in Ascending or Descending order
/// </summary>
[Category("Grid Properties")]
[Description("Sort Direction")]
public SortOrderType SortOrder { get; set;}
public enum SortOrderType {Ascending,Descending}
/// <summary>
/// Number of records to display per page of the radgrid
/// </summary>
[Category("Grid Properties")]
[Description("Number of records to display per page")]
public Int32 RecordsToDisplay
{
get { return _PageSize; }
set { _PageSize = value; }
}
/// <summary>
/// Number of records to display per page of the radgrid
/// </summary>
[Category("Grid Properties")]
[Description("Group Records to column name")]
public String GroupByColumnName
{
get { return _GroupByName; }
set { _GroupByName = value; }
}
#endregion
#region Cache Substitution settings
/// <summary>
/// Gets the page mode that is used for the cache substitution
/// </summary>
public override SubstitutionPageMode PageMode
{
get { return SubstitutionPageMode.Full; }
}
#endregion
protected void Page_Load(object sender, EventArgs e)
{
DataSet tmp = new DataSet();
if (!IsPostBack) { LoadGrid(); }
}
/// <summary>
/// Get the data from csv file to load into the grid and set sort column name of grid
/// </summary>
protected void LoadGrid()
{
try
{
//get the data from csv file
DataSet csvsource = readCsv(CSVFile, CSVDirectory);
//check to see if there is any data to set the grid to
if (csvsource != null)
{
//set the datasource of grid
RadGrid1.DataSource = csvsource;
//check to see if there is a sortname and if the columnName exists in RadGrid
if (ColumnSortName != "") // && RadGrid2.Columns.Contains(ColumnSortName))
{
//set column sort order
RadGrid1.MasterTableView.SortExpressions.AddSortExpression(GetSortColumnOrder(ColumnSortName));
//disable all column sorting capability
RadGrid1.AllowSorting = false;
}
// cannot set a to less than 10 per page
if (RecordsToDisplay <= 10)
{
RadGrid1.PageSize = 10;
}
else
{
RadGrid1.PageSize = RecordsToDisplay;
}
if (_GroupByName != "")
{
GridGroupByExpression expression = new GridGroupByExpression();
GridGroupByField gridGroupByField = new GridGroupByField();
//Group by display header data
gridGroupByField.FieldName = "Dept";
gridGroupByField.HeaderText = string.Empty;
gridGroupByField.FieldAlias = "<b>";
gridGroupByField.HeaderValueSeparator = " ";
expression.SelectFields.Add(gridGroupByField);
//GroupByFields values (group data) column to sort by (ie DeptSort)
gridGroupByField = new GridGroupByField();
gridGroupByField.FieldName = "DeptSort";
gridGroupByField.HeaderText = string.Empty;
expression.GroupByFields.Add(gridGroupByField);
RadGrid1.MasterTableView.GroupByExpressions.Add(expression);
//sort order
GridSortExpression expression1 = new GridSortExpression();
expression1.FieldName = "TitleSort";
expression1.SortOrder = GridSortOrder.Ascending;
RadGrid1.MasterTableView.SortExpressions.AddSortExpression(expression1);
}
//set grid to values
RadGrid1.DataBind();
//RadGrid1.MasterTableView.Columns.FindByUniqueName("Email").Visible = false;
RadGrid1.ClientSettings.Resizing.AllowColumnResize = true;
}
}
catch (Exception e)
{
//error message to display
ErrorHandler.HandleError("Error Loading Grid data: " + e.Message + "\n\n" + Environment.StackTrace);
}
}
protected void RadGrid1_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
//set the datasource of grid
RadGrid1.DataSource = readCsv(CSVFile, CSVDirectory);
}
protected void RadGrid1_SortCommand(object source, GridSortCommandEventArgs e)
{
if (e.CommandArgument == "DeptSort,TitleSort")
{
//Request a data from the datasource reflecting the needed sorting
RadGrid1.DataSource = readCsv(CSVFile, CSVDirectory);
//Rebind the grid
e.Item.OwnerTableView.Rebind();
// RadGrid1.Rebind();
}
}
protected void RadGrid1_ColumnCreated(object sender, GridColumnCreatedEventArgs e)
{
if (e.Column is GridGroupSplitterColumn)
{
e.Column.HeaderStyle.Width = Unit.Pixel(1);
e.Column.HeaderStyle.Font.Size = FontUnit.Point(1);
e.Column.ItemStyle.Width = Unit.Pixel(1);
e.Column.ItemStyle.Font.Size = FontUnit.Point(1);
e.Column.Resizable = false;
}
if ((e.Column.UniqueName == "Email") || (e.Column.UniqueName == "Dept")) // || (e.Column.UniqueName == "DeptSort") || (e.Column.UniqueName == "TitleSort"))
{
e.Column.Visible = false;
}
//if (e.Column.UniqueName == "Title")
//{
// e.Column.HeaderStyle.Width = 200;
//}
}
/// <summary>
/// function: GetSortColumnOrder
/// Determines what column to sort the grid to display the data
/// </summary>
/// <returns>column to sort and order to sort</returns>
protected GridSortExpression GetSortColumnOrder(string ColName )
{
GridSortExpression sortCol = new GridSortExpression { FieldName = ColName };
switch (SortOrder)
{
case SortOrderType.Ascending :
sortCol.SortOrder = GridSortOrder.Ascending;
break ;
case SortOrderType .Descending :
sortCol.SortOrder = GridSortOrder.Descending;
break;
default:
sortCol.SortOrder = GridSortOrder.None;
break;
}
return sortCol ;
}
protected void RadGrid1_PageIndexChanged(object sender, GridPageChangedEventArgs e)
{
LoadGrid();
}
protected void ChangeGroupHeaderColour(object sender, GridItemEventArgs e)
{
if (e.Item is GridGroupHeaderItem)
{
GridGroupHeaderItem item = e.Item as GridGroupHeaderItem;
//if (item.GroupIndex.Split('_').Length == 4)
//{
e.Item.BackColor = Color.LightGray ;
//}
//else{
// e.Item.BackColor = Color.Coral;
//}
}
}
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
//if (e.Item is GridDataItem)
//{
// GridDataItem dbitem = (GridDataItem)e.Item;
// if (dbitem["Phone"].Text.Length == 10)
// {
// //format the phone number
// dbitem["Phone"].Text = String.Format("{0:###-###-####}", Convert.ToInt64(dbitem["Phone"].Text));
// }
//if (dbitem["Name"].Text != "")
//{
// GridHyperLinkColumn hyplnk = new GridHyperLinkColumn();
// hyplnk.DataTextField = "Name";
// hyplnk.DataNavigateUrlFields.SetValue("Email",0);
// hyplnk.DataNavigateUrlFormatString = "mailto:{0}";
//}
// }
ChangeGroupHeaderColour(sender, e);
}
protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
{
if (e.Item is GridCommandItem)
{
e.Item.FindControl("InitInsertButton").Visible = false;
e.Item.FindControl("AddNewRecordButton").Visible = false;
e.Item.FindControl("RefreshButton").Visible = false;
}
if (e.Item is GridGroupHeaderItem)
{
(e.Item as GridGroupHeaderItem).Cells[0].Controls.Clear();
}
}
//public void ConfigureExport()
//{
// RadGrid2.ExportSettings.ExportOnlyData = true; // CheckBox1.Checked;
// RadGrid2.ExportSettings.IgnorePaging = true;
// //RadGrid1.ExportSettings.OpenInNewWindow = CheckBox3.Checked;
//}
//protected void RadGrid2_PreRender(object sender, EventArgs e)
//{
// GridColumn gridCol = RadGrid2.MasterTableView.GetColumn("Name");
// gridCol.HeaderStyle.Width = Unit.Percentage(100); // Unit.Pixel(100);
//}
/// <summary>
/// reads a csv file into a dataset from a certain location
/// </summary>
/// <param name="fileName">csv filename to load</param>
/// <param name="filePath">path to csv filename</param>
/// <returns>dataset of csv file</returns>
public DataSet readCsv(string fileName, string filePath)
{
try
{
string tmppath = Server.MapPath(filePath );
string strPath = @tmppath; //"C:\Data\Projects\websiteCMS\Website\Data\pophouse\";
string ConnectionString =
string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};
Extended Properties=""text;HDR=Yes;FMT=Delimited"";", strPath);
string CommandText = string.Format(@"SELECT * FROM [{0}]",fileName, ConnectionString);
DataSet CSVDataSet = new DataSet();
OleDbConnection CSVConnection = new OleDbConnection(ConnectionString);
OleDbDataAdapter CSVAdapter = new OleDbDataAdapter(CommandText, CSVConnection);
CSVConnection.Open();
CSVAdapter.Fill(CSVDataSet, fileName);
CSVConnection.Close();
//RadGrid2.PagerStyle.Mode = GridPagerMode.NextPrev;
//GridColumn gridCol = RadGrid2.MasterTableView.GetColumn("Name");
//gridCol.HeaderStyle.Width = Unit.Pixel(300); // Unit.Pixel(100);
return CSVDataSet;
}
catch (Exception ex)
{
//lblerror.Text = ex.Message;
LitError.Text = Messenger.GetHtmlMessage(Messenger.MessageType.Error, "Error with csv file");
ErrorHandler.HandleError("Error loading csv file: " + ex.InnerException + "\n\n" + Environment.StackTrace);
//throw ex;
return null;
}
}
}
}
0

Gimmik
Top achievements
Rank 1
answered on 01 Jun 2011, 08:45 PM
Hi Will,
You might be better off submitting a support ticket to Telerik. Then you can zip your whole solution and submit it for support.
-Gimmik
You might be better off submitting a support ticket to Telerik. Then you can zip your whole solution and submit it for support.
-Gimmik