Sunday, February 21, 2010

Telerik Controls

How to Start Using Telerik Control
-----------------------------------

1. Install RadControlS_dev.msi, and Add References of below in path C:/Programfiles/Telerik/.....

1. Telerik.Web.UI.dll
2. Telerik.Web.UI.xml


2. In Web.config

1. Add below under httpHandlers tag in the Web.config

< add path="Telerik.Web.UI.WebResource.axd" verb="*" type="Telerik.Web.UI.WebResource, Telerik.Web.UI" validate="false"/>



2. Add below in assemblies tag in the Web.config

< add assembly="Telerik.Web.Design, Version=2009.3.1103.35, Culture=neutral, PublicKeyToken=121FAE78165BA3D4" />


Database Connection
--------------------

SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS; AttachDbFilename=|DataDirectory|\Testdb1.mdf;user

Instance=True;Integrated Security=True;");



3. In UI (.aspx page)
---------------------

1. Add Telerik Script Manager before using talerik Control in .aspx page

< telerik:RadScriptManager ID="RadScriptManager1" runat="server" >
< /telerik:RadScriptManager >

2. Add below, after Page Tag (in .aspx page)

<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>


4. Start to use Telerik Controls



======================================
1. Telerik radGrid
======================================

# 1. simple
------------
// (in .aspx page)

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

// In Code Behand
// namespaces
using System.Data;
using System.Data.SqlClient;
using Telerik.Web.UI;

// con is sqlconnection object,
con.Open();
SqlCommand cmd = new SqlCommand("select * from EMP_Tab1", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
RadGrid1.DataSource = dr;
RadGrid1.DataBind();
}


OR


con.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("select * from EMP_Tab1", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
RadGrid1.DataSource = ds;
RadGrid1.DataBind();
Session["data"] = ds;
con.Close();



# 2.1 complex with radGrid and Edit mode = "InPlace"
----------------------------------------------
// (in .aspx page)

< telerik:RadGrid ID="RadGrid1" runat="server" AllowPaging = "true" PageSize="5" AllowSorting="true"
AllowFilteringByColumn ="true" AutoGenerateColumns = "false" OnUpdateCommand="GV_UpdateCmd"
OnNeedDataSource="GridView1_NeedDs" >
< MasterTableView DataKeyNames="EMPid" EditFormSettings-EditColumn-ButtonType="LinkButton"
EditFormSettings-EditColumn-AutoPostBackOnFilter="false" EditMode="InPlace" >
< Columns >
< telerik:GridBoundColumn UniqueName="EmpID" Visible="false" DataField="EmpID" DataType="System.Int32"

HeaderText="Emp ID" >
< /telerik:GridBoundColumn >
< telerik:GridBoundColumn UniqueName="EmpName" DataField="EmpName" DataType = "System.String" HeaderText="Emp Name" >
</telerik:GridBoundColumn >
<telerik:GridBoundColumn UniqueName="EmpDesignation" DataField="empDesgination" DataType="System.String"

HeaderText="Designation" >
</telerik:GridBoundColumn >
< telerik:GridBoundColumn UniqueName="EmpDept" DataField="empDept" DataType="System.String" HeaderText="Department" >
< /telerik:GridBoundColumn >
< telerik:GridEditCommandColumn UniqueName="EditEmp" EditText="Edit" >
< /telerik:GridEditCommandColumn >
< /Columns >
< /MasterTableView >
< /telerik:RadGrid >




// In Code behand

// Namespaces
using System.Data;
using System.Data.SqlClient;
using Telerik.Web.UI;


// method to bind radGrid control
public void Bind_radGrid()
{
con.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("select * from EMP_Tab1", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
RadGrid1.DataSource = ds;
RadGrid1.DataBind();
Session["data"] = ds;
con.Close();

}

// NeedDataSource Event store temporary data source
protected void GridView1_NeedDs(object sender, GridNeedDataSourceEventArgs e)
{
RadGrid1.DataSource = Session["data"];
}


// UpdateCommand Event for Edit data within radGrid (Edit mode = "InPlace")
protected void GV_UpdateCmd(object sender, GridCommandEventArgs e)
{
string strEmpID = String.Empty;
string strEmpName = String.Empty;
string strDesc = String.Empty;
string strDept = String.Empty;
GridEditableItem item = (GridEditableItem)e.Item;

foreach (object obj in item["EmpID"].Controls)
{
if (obj.GetType().Equals(new TextBox().GetType()))
{
strEmpID = ((TextBox)obj).Text;
}
}

foreach (object obj in item["EmpName"].Controls)
{
if (obj.GetType().Equals(new TextBox().GetType()))
{
strEmpName = ((TextBox)obj).Text;
}
}

foreach (object obj in item["EmpDesignation"].Controls)
{
if (obj.GetType().Equals(new TextBox().GetType()))
{
strDesc = ((TextBox)obj).Text;
}
}

foreach (object obj in item["EmpDept"].Controls)
{
if (obj.GetType().Equals(new TextBox().GetType()))
{
strDept = ((TextBox)obj).Text;
}
}
con.Open();
string strQuery = "Update EMP_Tab1 set empName='" + strEmpName + "',EmpDesgination='" + strDesc +

"',EmpDept='" + strDept + "' where empId='" + strEmpID + "'";
SqlCommand cmdUpdate = new SqlCommand(strQuery, con);
cmdUpdate.ExecuteNonQuery();
con.Close();
Bind_radGrid();

}





# 2.2 complex with radGrid and Edit mode = "EditForms"
-------------------------------------------------------

// Changes in the UI and UpdateCommand Event
/// In UI radGrid Property set EditMode="EditForms"
/// In UI every GridBoundColumn set EditFormColumnIndex="0" or "1"
/// In UI add < EditFormSettings ColumnNumber="2" /> within < MasterTableView >
/// In Code Behand UpdateCommand Event change 'GridEditableItem' to GridEditFormItem

// In UI


< telerik:RadGrid ID="RadGrid1" runat="server" AllowPaging = "true" PageSize="5" AllowSorting="true"
AllowFilteringByColumn ="true" AutoGenerateColumns = "false" OnUpdateCommand="GV_UpdateCmd"
OnNeedDataSource="GridView1_NeedDs" >
< MasterTableView DataKeyNames="EMPid" EditFormSettings-EditColumn-ButtonType="LinkButton"
EditFormSettings-EditColumn-AutoPostBackOnFilter="false" EditMode="EditForms" >
< Columns >
< telerik:GridBoundColumn UniqueName="EmpID" Visible="false" EditFormColumnIndex="0" DataField="EmpID"

DataType="System.Int32" HeaderText="Emp ID" >
< /telerik:GridBoundColumn >
< telerik:GridBoundColumn UniqueName="EmpName" DataField="EmpName" EditFormColumnIndex="0" DataType = "System.String"

HeaderText="Emp Name" >
< /telerik:GridBoundColumn >
< telerik:GridBoundColumn UniqueName="EmpDesignation" DataField="empDesgination" EditFormColumnIndex="1"

DataType="System.String" HeaderText="Designation" >
< /telerik:GridBoundColumn >
< telerik:GridBoundColumn UniqueName="EmpDept" DataField="empDept" EditFormColumnIndex="1" DataType="System.String"

HeaderText="Department" >
< /telerik:GridBoundColumn >
< telerik:GridEditCommandColumn UniqueName="EditEmp" EditText="Edit" >
< /telerik:GridEditCommandColumn >
< /Columns >
< EditFormSettings ColumnNumber="2" / >
< /MasterTableView >

< /telerik:RadGrid >




// In Code behand

// NameSpaces
using System.Data;
using System.Data.SqlClient;
using Telerik.Web.UI;


// Bind radGrid Control
public void Bind_radGrid()
{
con.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("select * from EMP_Tab1", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
RadGrid1.DataSource = ds;
RadGrid1.DataBind();
Session["data"] = ds;
con.Close();

}

// NeedDataSource Event for Temporary Stored DataSource
protected void GridView1_NeedDs(object sender, GridNeedDataSourceEventArgs e)
{
RadGrid1.DataSource = Session["data"];
}

// Update Command Event for Edit data in radGrid (Edit mode = "EditForms")
protected void GV_UpdateCmd(object sender, GridCommandEventArgs e)
{
string strEmpID = String.Empty;
string strEmpName = String.Empty;
string strDesc = String.Empty;
string strDept = String.Empty;
//GridEditableItem item = (GridEditableItem)e.Item;
GridEditFormItem item = (GridEditFormItem)e.Item;
foreach (object obj in item["EmpID"].Controls)
{
if (obj.GetType().Equals(new TextBox().GetType()))
{
strEmpID = ((TextBox)obj).Text;
}
}

foreach (object obj in item["EmpName"].Controls)
{
if (obj.GetType().Equals(new TextBox().GetType()))
{
strEmpName = ((TextBox)obj).Text;
}
}

foreach (object obj in item["EmpDesignation"].Controls)
{
if (obj.GetType().Equals(new TextBox().GetType()))
{
strDesc = ((TextBox)obj).Text;
}
}

foreach (object obj in item["EmpDept"].Controls)
{
if (obj.GetType().Equals(new TextBox().GetType()))
{
strDept = ((TextBox)obj).Text;
}
}
con.Open();
string strQuery = "Update EMP_Tab1 set empName='" + strEmpName + "',EmpDesgination='" + strDesc +

"',EmpDept='" + strDept + "' where empId='" + strEmpID + "'";
SqlCommand cmdUpdate = new SqlCommand(strQuery, con);
cmdUpdate.ExecuteNonQuery();
con.Close();
Bind_radGrid();

}



# 2.3 In .ASPX page improve Edit view (EditFormSettings) & Add (ExpandCollapseColumn) with radGrid & Edit mode = "EditForms"
-------------------------------------------------------------------------------------------------------------------------

< EditFormSettings ColumnNumber="2" EditColumn-FooterStyle-Font-Bold="true" CaptionFormatString="Edit details for Subject ID

: {0}"
CaptionDataField="SubjectID" >
< FormTableItemStyle Wrap="False"< > /FormTableItemStyle >
< FormCaptionStyle CssClass="EditFormHeader"> < /FormCaptionStyle >
< FormMainTableStyle GridLines="None" CellSpacing="0" CellPadding="3" Width="100%" / >
< FormTableStyle GridLines="Horizontal" CellSpacing="0" CellPadding="2" Height="110px"
Width="100%" / >
< FormTableAlternatingItemStyle Wrap="False"> < /FormTableAlternatingItemStyle >
< FormStyle Width="100%" BackColor="#eef2ea" > < /FormStyle >
< EditColumn UpdateText="Update" UniqueName="EditCommandColumn1" CancelText="Cancel" >
< /EditColumn >
< FormTableButtonRowStyle HorizontalAlign="Left" > < /FormTableButtonRowStyle >
< /EditFormSettings >
< ExpandCollapseColumn ButtonType="ImageButton" Visible="False" UniqueName="ExpandColumn" >
< HeaderStyle Width="19px" / >
< /ExpandCollapseColumn >





# 3.1 In .ASPX Page (radGrid with Edit mode = "InPlace" and In Edit mode add and bind radCombo within radGrid
----------------------------------------------------------------------------------

// In UI radGrid property add Event ( OnItemDataBound="radGrid_ItemDataBound" )
// In UI add GridTempleteColumn, and under EditItemTemplate with RadComboBox

< telerik:GridTemplateColumn HeaderText="ID" Visible="false" EditFormColumnIndex="0" >

< EditItemTemplate >
< telerik:RadComboBox runat="server" ID="Id" Width="156px" EmptyMessage="--Select--" >
< /telerik:RadComboBox >
< /telerik:GridTemplateColumn >

// In Code Behand add event

protected void radGrid_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{

if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{

GridEditableItem editForm = (GridEditableItem)e.Item;
RadComboBox radcombo = (RadComboBox)editForm.FindControl("Id");
radcombo.DataSource = sssss;
radcombo.DataTextField = ssss.Columns[0].ToString();
radcombo.DataValueField = ssss.Columns[0].ToString();
radcombo.DataBind();
}

}



# 3.2 In .ASPX Page (radGrid with Edit mode = "EditForms" and In Edit mode add and bind radCombo within radGrid
----------------------------------------------------------------------------------

// In .ASPX page radGrid property add Event ( OnItemDataBound="radGrid_ItemDataBound" )
// In .ASPX page add GridTempleteColumn, and under EditItemTemplate with RadComboBox

< telerik:GridTemplateColumn HeaderText="ID" Visible="false" EditFormColumnIndex="0" >

< EditItemTemplate >
< telerik:RadComboBox runat="server" ID="Id" Width="156px" EmptyMessage="--Select--" >
< /telerik:RadComboBox >
< /telerik:GridTemplateColumn >

// In Code Behand add event

protected void radGrid_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{

if (e.Item is GridEditFormItem && e.Item.IsInEditMode)
{
GridEditFormItem editForm = (GridEditFormItem)e.Item;
RadComboBox cmbShortId = (RadComboBox)editForm.FindControl("ShortId");
Label lblShortName = (Label)editForm.FindControl("lblShortid");
String strlblShortName = lblShortName.Text;
cmbShortId.DataSource = null;
cmbShortId.DataBind();
if (ViewState["ShortID"] != null)
{
cmbShortId.Items.Insert(0, new RadComboBoxItem("-Select-", "0"));
//if(cmbShortId.DataSource == null)
cmbShortId.DataSource = ViewState["ShortID"];
cmbShortId.DataTextField = "ShortName";
cmbShortId.DataValueField = "ShortId";
if (strlblShortName != String.Empty)
cmbShortId.SelectedValue = strlblShortName;
cmbShortId.DataBind();
}
}

}


# 4. In .ASPX Page with radGrid get selected row key Value
-----------------------------------------------------

// Suppose in Employee table EMPID is Unique key value
// get select row EMPID.

1. IN .ASPX Page


/// take GridTemplateColumn under ItemTemplate under LABEL WITH Bind Text as empid
< MasterTableView >
< Columns >
< telerik:GridTemplateColumn HeaderText="Emp ID" Visible="false" EditFormColumnIndex="0" >
< ItemTemplate >
< asp:Label ID="lblEMPId" Text='<% #DataBinder.Eval(Container.DataItem, "empId") %>'

runat="server" > </asp:Label >
< /ItemTemplate >
< /telerik:GridTemplateColumn >
</Columns >
< /MasterTableView >

2. IN Code Behand in Required Event add below code

int getEmpid;
GridItemCollection gvSelectedItms = gvEmp.SelectedItems;
foreach (GridItem RowItem in gvSelectedItms)
{
lblTemp = (Label)RowItem.FindControl("lblEmp_Id");
getEmpid = Convert.ToInt32(lblTemp.Text);
}




# 5. In Telerik Grid Selected Grid Row Bind Values in Other Control like (Textbox etc)
----------------------------------------------------------------------------------

// Select the Row of the Grid
// Click the Edit Button than selected Row Display values in Other controls like Textbox etc.

// In UI

< telerik:RadGrid .......... >

< ClientSettings EnableRowHoverStyle="true" >
< Selecting AllowRowSelect="true" / >
< /ClientSettings >

..............

< /RadGrid >

// in Code Behand any button Click Event

GridItemCollection gvSelectedItms = gvEmp.SelectedItems;
if (gvEmp.SelectedItems.Count > 0 && gvEmp.SelectedItems.Count < 2)
{
foreach (GridItem RowItem in gvSelectedItms)
{

if (RowItem.Cells[3].Text.ToString() != " ")
txtEmpName.Text = RowItem.Cells[3].Text.ToString();
if (RowItem.Cells[4].Text.ToString() != " ")
txtEmpShortName.Text = RowItem.Cells[4].Text.ToString();
if (RowItem.Cells[5].Text.ToString() != " ")
txtDescription.Text = RowItem.Cells[5].ToolTip.ToString();
if (RowItem.Cells[9].Text.ToString() != " ")
radComboShortId.FindItemByText(RowItem.Cells[9].Text.ToString()).Selected = true;
}
}



# 6. radGrid Page Size Set in Web.Config
----------------------------------------

// In UI

PageSize=" < %$appSettings:GridPageSize % > "

// In Web.Config

< add key="GridPageSize" value="10"/ >



=========================
# 1. Telerik radComboBox
=========================

1. sample
------

// in UI

< telerik:RadComboBox ID="RadComboBox1" runat="server" / >


// In Code Behand

con.Open();
SqlCommand cmd = new SqlCommand("select EmpID,EmpName from EMP_Tab1", con);
SqlDataReader dr1 = cmd.ExecuteReader();
while (dr1.Read())
{
RadComboBox1.DataSource = dr1;
RadComboBox1.DataTextField = "EmpName";
RadComboBox1.DataValueField = "EmpID";
RadComboBox1.DataBind();
}
con.Close();



2. Reflect Selected Item In the radComboBox
-----------------------------------------
// Example, select 5th Item in radComboBox
radComboEmpId.FindItemByText(RowItem.Cells[4].Text.ToString()).Selected = true;




----------------------------------------------------------------
Telerik Grid - How to select multiple row select in the grid to avoid check boxes
-----------------------------------------------------------------


First Define the following Client events and properties for the Telerik Grid:
< telerik:RadGrid ID="gvRegistrationSearch" >
< ClientSettings EnableRowHoverStyle="true" >
< Selecting AllowRowSelect="true" / >
< ClientEvents OnRowClick="RowClick" OnRowDeselecting="RowDeselecting" OnRowSelecting="RowSelecting" OnRowDblClick="" / >
< /ClientSettings >
< PagerStyle Mode="NextPrevAndNumeric" AlwaysVisible="true" / >

The Javascript functions are listed below:

var clickedItemIndex;
var deselected;
var selected;

function RowClick(sender, args) //Attach to the OnRowClick client event
{
var master = $find('< %= gvRegistrationSearch.ClientID % > ').get_masterTableView();
var index = args.get_itemIndexHierarchical();
master.get_dataItems()[index].set_selected(!master.get_dataItems()[index].get_selected());
clickedItemIndex = index;

if (master.get_dataItems()[index].get_selected())
selected = true;
else
selected = false;
}

function RowDeselecting(sender, args) //Attach to the OnRowDeselecting client event
{
if (clickedItemIndex != args.get_itemIndexHierarchical())
args.set_cancel(true);
else if (selected)
deselected = false;
else
deselected = true;
}

function RowSelecting(sender, args) //Attach to the OnRowSelecting client event
{
if (clickedItemIndex == args.get_itemIndexHierarchical() && deselected)
args.set_cancel(true);
else
deselected = false;
}

To Access the Values form the code behind use the below code example as reference.



Int32 countSelectedItems = gvRegistrationSearch.SelectedIndexes.Count;
GridItemCollection gvSelectedItms = gvRegistrationSearch.SelectedItems;
StringBuilder RegistrationNOCollection = new StringBuilder();
if (gvSelectedItms.Count > 0)
{
foreach (GridItem RowItem in gvSelectedItms)
{
String tempRegNo=RowItem.Cells[3].Text.ToString();
if(!String.IsNullOrEmpty(tempRegNo))
RegistrationNOCollection.Append(tempRegNo + ",");
}
}
else
{
Response.Write("< script > alert('Please select at least one item to Delete!')< /script > ");
return;
}

Pending Point: IE enables only single selection at the moment.
Reference Links:
http://demos.telerik.com/aspnet-ajax/grid/examples/client/selecting/defaultcs.aspx
http://www.telerik.com/community/forums/aspnet-ajax/grid/row-selection-question.aspx

===========================


Please use the below method to implement multi row select functionality for the Telerik grid.

< telerik:RadGrid ID="RadGrid1" DataSourceID="SqlDataSource1" AllowMultiRowSelection="true"
runat="server" AllowSorting="True" GridLines="None" >
< ClientSettings EnableRowHoverStyle="true" >
< Selecting AllowRowSelect="True" / >
< /ClientSettings >
< /telerik:RadGrid >

No Javascript event binding required required

Imp: Please provide a label control below the grid that displays the below message.

Note: Use Ctrl + left mouse click to de select a selected row.

For references please use the below article.

http://demos.telerik.com/aspnet-ajax/grid/examples/client/selecting/defaultcs.aspx
--

===========================



Please add One more content place holder ["cphBreadCrumbLink"] to all your pages which all using "TrustMaster" master page.

Add BreadCrumb Link to Content Place holder "cphBreadCrumLink".

Add all your page action Tool bar within content place holder "cphPageMenu"

For any further clarification feel free to ask me..


Start with Telerik Control

Teleric Controls
================


// Register Assembly (page level)
---------------------

< %@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" % >



// ScriptManager (Form Level)

< telerik:RadScriptManager runat="server" ID="RadScriptManager1" / >



// Web.config

< compilation debug="true" >
< assemblies >
< add assembly="Telerik.Web.Design, Version=2009.3.1103.35, Culture=neutral, PublicKeyToken=121FAE78165BA3D4"/ >
< add assembly="Telerik.Web.Design, Version=2009.3.1103.20, Culture=neutral, PublicKeyToken=121FAE78165BA3D4"/ >
< /assemblies >
< /compilation >




< httpHandlers >

< add path="Telerik.Web.UI.WebResource.axd" verb="*" type="Telerik.Web.UI.WebResource, Telerik.Web.UI" validate="false"/ >

< /httpHandlers >










Grid Binding
-------------
SubjectBDto objSubjectBDTo = new SubjectBDto();

gvSubject.DataSource = null;
gvSubject.DataBind();

AdministrationService.AdministrationServiceClient objAdministrationServiceClient = new AdministrationService.AdministrationServiceClient();
DataTable dsSubject = objAdministrationServiceClient.GetSubjectList(); // objSubjectBDTo.SubjectList(); // new Vatsalya.BusinessComponent.Administration.Lookup.SubjectBC().GetSubjectList();
if(dsSubject != null)
if (dsSubject.Rows.Count > 0)
{
gvSubject.DataSource = dsSubject;
gvSubject.DataBind();
Session["data"] = dsSubject;
}










------------------------------------------------------------------------Two Telerik DateTimePicker controls with in RadGrid edit mode DateTimePicker Image Visiablity
------------------------------------------------------------------------

In UI
--------

< telerik:RadGrid
ID="RadGrid1"
runat="server"
EnableEmbeddedSkins="false"
Skin="Custom"
GridLines="Both"
Width="500px"
AutoGenerateColumns="false"
DataSourceID="XmlDataSource1"
>
< MasterTableView >
< Columns >
< telerik:GridEditCommandColumn / >
< telerik:GridDateTimeColumn ColumnEditorID="GridDateTimeColumnEditor1" DataField="datetime" HeaderText="Date/Time" PickerType="DateTimePicker" / >
< /Columns >
< /MasterTableView >
< /telerik:RadGrid >

< h2 > Using RadGrid ItemCreated< /h2 >

< telerik:RadGrid
ID="RadGrid2"
runat="server"
EnableEmbeddedSkins="false"
Skin="Custom"
GridLines="Both"
Width="500px"
AutoGenerateColumns="false"
DataSourceID="XmlDataSource1"
OnItemCreated="RadGrid2_ItemCreated"
>
< MasterTableView >
< Columns >
< telerik:GridEditCommandColumn / >
< telerik:GridDateTimeColumn DataField="datetime" HeaderText="Date/Time" PickerType="DateTimePicker" / >
< /Columns >
< /MasterTableView >
< /telerik:RadGrid >

< asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/datasource.xml" / >


In Code Behand
--------------


if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{
RadDateTimePicker picker = ((e.Item as GridEditableItem)["datetime"].Controls[0]) as RadDateTimePicker;
picker.ImagesPath = "~/picker_images/";
}




--------------------------------------------------------
Accessing Row Data In Telerik RadGrid (Server Side)
--------------------------------------------------------

Hi There, Ive no problems using Javascript to read the rows of a telerik radgrid component im using however I can seem to find anyway to access the row data server side when a postback occurs. Ive spent ages looking for solution but no luck. Any pointers would be greatly appreciated.


Answers
------


You might want to look at the DataKeyValues property of the OwnerTableView object, which will let you access a collection of values that represent the fields in a given row. I use it during the EditCommand event handler, since a user of my site is directed to an edit page if they click on the link to edit a row in the grid, and I need to pass along certain info about the given row in the query string.

If this turns out to be what you need, you'll also need to define which fields should be made available through this property. To do that, look at the MasterTableView.DataKeyNames property in the property sheet for the grid. You basically specify a comma-delimited list of field names.




-------------------------------
Empty Check validation
----------------------------------

Radalert (Teleric control)


function validate()
{
if (document.getElementById('< %=txtSubjectId.ClientID % > ').value == "") {
radalert('Please Enter BusinessRole Name');
return false;
} else if (document.getElementById('< %=txtSubjectName.ClientID % > ').value == "") {
radalert('Please Select Application Role Number');
return false;
} else if (document.getElementById('< %=txtSubShortName.ClientID % > ').value == "") {
radalert('Please Select Application Role Number');
return false;
}
else {
return true;
}
}



In Button
---------
OnClientClick="return validate();"






-------------------------------------------------------------------------------
Set default value of telerik:GridDropDownColumn inside of telerik:RadGrid
--------------------------------------------------------------------------



I have a telerik:RadGrid that is bound to a SQL Data Source. One of the columns is for "Location" which is really a look up value in another table.

< telerik:GridDropDownColumn
DataField="d_location_id"
DataSourceID="dsLocation"
UniqueName="d_location_id"
DataType="System.Int32"
ListValueField="d_location_id"
ListTextField="Abbreviation"
HeaderText="Location" >
< /telerik:GridDropDownColumn >
My list of locations is stored in an ObjectDataSource, which is bound to a static DataTable and sorted alphabetically for me already. What I would like to do is be able to set the default option for this dropdown.

For example, suppose I have the following locations:

1 Home
2 Work
3 Parents
4 Car
I would like to have Parents be my default value.

----------------------

Not sure if it is the best or most straightforward way or not, but it does work.

protected void gridMyInfo_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
if (e.Item.IsInEditMode && e.Item.ItemIndex < 0)
{
GridEditableItem editedItem = e.Item as GridEditableItem;
GridEditManager editMan = editedItem.EditManager;

GridDropDownListColumnEditor editor = editMan.GetColumnEditor("d_location_id") as GridDropDownListColumnEditor;
editor.ComboBoxControl.SelectedIndex = editor.ComboBoxControl.Items.FindItemIndexByText("Parents");
}
}


-------------------------------------------------------------------------------
In edit mode RadCombobox in RadGrd. Popup telerik:RadGrid
--------------------------------------------------------------------------

In .ASPX
-----------

< telerik:GridTemplateColumn HeaderText="BusinessRole ID" Visible="false" EditFormColumnIndex="0" >
< ItemTemplate >
< asp:Label ID="lblBusinessRole_ID" Text='< % #DataBinder.Eval(Container.DataItem, "BusinessRoleId") % > '
runat="server" > < /asp:Label >
< /ItemTemplate >

< /telerik:GridTemplateColumn >



In code behand
------------------

protected void gvBusinessRole_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
AdministrationService.AdministrationServiceClient objAdministrationServiceClient = new AdministrationService.AdministrationServiceClient();

if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{
GridEditableItem editForm = (GridEditableItem)e.Item;
RadComboBox radcombo = (RadComboBox)editForm.FindControl("ApplicationRoleId");
radcombo.DataSource = objAdministrationServiceClient.GetApplicationRoleIdList();
radcombo.DataTextField = objAdministrationServiceClient.GetApplicationRoleIdList().Columns[0].ToString();
radcombo.DataValueField = objAdministrationServiceClient.GetApplicationRoleIdList().Columns[0].ToString();
radcombo.DataBind();

}

}


Selected values update to Database
-----------------------------------

protected void gvBusinessRole_UpdateCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
{

GridEditableItem editForm = (GridEditableItem)e.Item;
RadComboBox radcombo = (RadComboBox)editForm.FindControl("ApplicationRoleId");

strApplicationRoleId = radcombo.SelectedValue.ToString();

objBusinessRoleBDto.ApplicationRoleId = Convert.ToInt32(strApplicationRoleId);

// Call the service to update the values
AdministrationService.AdministrationServiceClient objAdministrationServiceClient = new AdministrationService.AdministrationServiceClient();
objAdministrationServiceClient.UpdateBusinessRole(objBusinessRoleBDto);

Bind_gvBusinessRoles();



RadGrid Popup
--------------

// Method for Grid Popup
public void Bind_gvBusinessRoles()
{
BusinessRoleBDto objBusinessRoleBDTo = new BusinessRoleBDto();

gvBusinessRole.DataSource = null;
gvBusinessRole.DataBind();


// Calling service to Grid Popup operation.
AdministrationService.AdministrationServiceClient objAdministrationServiceClient = new AdministrationService.AdministrationServiceClient();
DataTable dsBusinessRole = objAdministrationServiceClient.GetBusinessRoleList();

if (dsBusinessRole != null)
if (dsBusinessRole.Rows.Count > 0)
{
gvBusinessRole.DataSource = dsBusinessRole;
gvBusinessRole.DataBind();
Session["data"] = dsBusinessRole;
}

}




-------------------------------------------------------------------------------
How to calculate RadGrid cell value on Client side? telerik:RadGrid
--------------------------------------------------------------------------

Each cell contains NumericTextBox. Is it possible to calculate one cell based on other cells in the same row (on client side).


ASPX:

< Columns >
< rad:GridTemplateColumn UniqueName="Price" HeaderText="Price" >
< EditItemTemplate >
< radI:RadNumericTextBox ID="txtPrice" runat="server" >
< /radI:RadNumericTextBox >
< /EditItemTemplate >
< /rad:GridTemplateColumn >
< rad:GridTemplateColumn UniqueName="Quantity" HeaderText=" Number of Items" >
< EditItemTemplate >
< radI:RadNumericTextBox ID="txtQuantity" runat="server" >
< /radI:RadNumericTextBox >
< /EditItemTemplate >
< /rad:GridTemplateColumn >
< rad:GridTemplateColumn UniqueName="TotalAmount" HeaderText="Total" >
< EditItemTemplate >
< radI:RadNumericTextBox ID="txtTotalAmount" runat="server" >
< /radI:RadNumericTextBox >
< /EditItemTemplate >
< /rad:GridTemplateColumn >
< /Columns >



C#

protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{

if (e.Item is GridDataItem && e.Item.IsInEditMode)
{
GridDataItem item = (GridDataItem)e.Item;
RadNumericTextBox txtPrice= item.FindControl("txtPrice") as RadNumericTextBox; // Get the textbox for column Price
RadNumericTextBox txtQuantity= item.FindControl("txtQuantity") as RadNumericTextBox; // Get the textbox for column Quantity
RadNumericTextBox txtTotalAmount= item.FindControl("txtTotalAmount") as RadNumericTextBox; // Get the textbox for column "TotalAmount", if it is template as shown in aspx

txtPrice.Attributes.Add("onFocusout", "return calculate('" + txtPrice.ClientID + "','" + txtQuantity.ClientID + "','" + txtTotalAmount.ClientID + "')");
txtQuantity.Attributes.Add("onFocusout", "return calculate('" + txtPrice.ClientID + "','" + txtQuantity.ClientID + "','" + txtTotalAmount.ClientID + "')");
txtTotalAmount.Attributes.Add("onfocus", "return calculate('" + txtPrice.ClientID + "','" + txtQuantity.ClientID + "','" + txtTotalAmount.ClientID + "')");
}
}


JavaScript:

< script type="text/javascript" >
function calculate(price, quantity, totalAmount)
{
var text1 = $find(price); //I used Asp.net Ajax find method
var text2 = $find(quantity);
var text3 = $find(totalAmount);
var total = text1.GetValue() * text2.GetValue();
text3.SetValue(total);
}
< /script >




-------------------------------------------------------------------------------
how to set wcf credentials when Telerik radgrid consumes the wcf service?
--------------------------------------------------------------------------


have a wcf service that requires client credentials so I can set this via code like this :

wcf.ClientCredentials.UserName.UserName = "user"; wcf.ClientCredentials.UserName.Password = "password";




OK if you need to get data from another server, it looks like you need to create your own server-side class as an ObjectDataSource on the server to be the client for your WCF service, because the browser's cross-domain restrictions will prevent the RadGrid from making client-side requests to both servers.

Your ObjectDataSource does the work of making the WCF requests.

Here's the Telerik RadGrid docs for how to use an ObjectDataSource: http://demos.telerik.com/aspnet-ajax/controls/examples/integration/aspajaxgridapplication/defaultcs.aspx?product=grid

...and here's Microsoft's docs on ObjectDataSource: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.objectdatasource.aspx






-------------------------------------------------------------------------------
Changing how a telerik radgrid marks a row as “modified”
--------------------------------------------------------------------------

am working with the Telerik Winforms Radgrid version 2009.2.9.701 in visual studio 2008 (C#) and I've come across and issue I can't seem to find a solution for.

When the radgrid is populated and the user changes a cell within a row, the row is not flagged as "modified" until the user actually clicks onto another location on the datagrid. If the user modifies any values in a row and immediately clicks the "Save" button on my winform, the row is not flagged as having been modified and is not showing up in my list of modified rows.

I am using the following code to gather the modified rows ...

DataTable modifiedRows = dataTable.GetChanges(DataRowState.Modified);
My question is as follows: Is there a way to mark a row as "Modified" when the user changes a value in ANY cell in the row, without the user having to click off of the row before clicking the save button. I can't seem to find the flag that marks a data row as "Modified".


1 Answer
---------

This might be a bit of a work around but can you make the Save button move the focus off the grid when clicked? This may cause the grid row to be marked Modified.

private void SaveButton_Click(object sender, EventArgs e)
{
SaveButton.Focus();
// Do work to save the grid's modified rows
}





-------------------------------------------------------------------------------
Telerik RadGrid Add/Edit Row Performance Issue
--------------------------------------------------------------------------

*Are you duplicating the bind behaviour in the gridPhone_NeedDataSource event, your ItemUpdated, Deleted and Inserted events, and the native Rad Grid binding behviour (by using a asp:SqlDataSource control)?* It would be useful to see your code-behind to see if you are or not.

How many records do you have in the grid? I find if I have a large number of items in the Grid and have some of the advanced features turned on (I've noticed you've got row selecting enabled) the grid grinds to a halt.





--------------------------------------------------------
Accessing Row Data In Telerik RadGrid (Server Side)
--------------------------------------------------------

Hi There, Ive no problems using Javascript to read the rows of a telerik radgrid component im using however I can seem to find anyway to access the row data server side when a postback occurs. Ive spent ages looking for solution but no luck. Any pointers would be greatly appreciated.


Answers
------


You might want to look at the DataKeyValues property of the OwnerTableView object, which will let you access a collection of values that represent the fields in a given row. I use it during the EditCommand event handler, since a user of my site is directed to an edit page if they click on the link to edit a row in the grid, and I need to pass along certain info about the given row in the query string.

If this turns out to be what you need, you'll also need to define which fields should be made available through this property. To do that, look at the MasterTableView.DataKeyNames property in the property sheet for the grid. You basically specify a comma-delimited list of field names.


--------------------------------------------------------
// Alert message in Code behand using Teleric RadAlert
--------------------------------------------------------

String radalertscript = "function f(){radalert('Record updated successfully.', 330, 110,'ProjectName'); Sys.Application.remove_load(f);}; Sys.Application.add_load(f);";
//ScriptManager.RegisterClientScriptBlock(updatePanelId, updatePanelId.GetType(), "message", radalertscript, true);
Page.ClientScript.RegisterStartupScript(this.GetType(), "radalert", radalertscript);

2 comments:

  1. Hi,If your purpose is to design a web page that is a profile type web page that will be used primarily as an informational web page for friends and family then the best Web Design Cochin is something that allows you to customize the text and layout of the web page. Thanks..........

    ReplyDelete