Showing posts with label Telerik. Show all posts
Showing posts with label Telerik. Show all posts

Wednesday, August 24, 2016

Telerik and Webforms: Trimming Paste on a RadComboBox

I had an issue with being able to trim incoming text into a radcombobox.  The code below is really simple but it took me a bit to figure out.  I'm stuck not using the latest release of Telerik's ASP.Net webform controls so maybe there is a different way to do this with later versions, but this worked for me.


I'm plugging into the RadComboBox's OnClientItemsRequesting by setting it to "MyItemsRequesting"

  function MyItemsRequesting(s, e) {  
     var txt = e.get_text();  
     if (txt != txt.trim()) {  
      e.set_cancel(true);  
      var d = document.getElementById("mymasternamepageifany" + "_mydropdownid_Input");  
      if (d != null) d.value = txt.trim();  
      s.requestItems(txt.trim(), false);  
     }  
   /* more code */  
  }  



Tuesday, May 27, 2014

Fixing Telerik's RadToolTip After Latest Releases Broke It

Scenario


Ok, so I had the following scenario.  I was using a Telerik Radgrid with a gridtemplate column that displayed user comments.  Often the comments were long so I would truncate the comment text that would be displayed, and then I add a RadToolTip with the target of the comment label in the grid that on hover would display the full comment text in a tool tip.  But then something happened...the latest changes broke the tool tip so that if I did anything on the grid like sort, update a row, whatever often the comment tool tip would become blank.  I read that it has something to do with how the radtooltip now stores it's content in the viewstate...well that was the excuse, but IMHO it is broke as it worked before and it doesn't work now.

The Fix


Step 1) Add a RadToolTipManager to your page, outside of your update pannels.  Here is an example


   <telerik:RadToolTipManager ID="RadToolTipManager1" runat="server" OnAjaxUpdate="RadToolTipManager1_AjaxUpdate"  
    RelativeTo="Element" Position="TopLeft" Width="450" ManualClose="True" ShowDelay="600"  
    Title="Comments">  
   </telerik:RadToolTipManager>  

Notice there is an OnAjaxUpdate method.  You will have to add that in your code behind, but let's worry about that in a second.

Step 2: Add a or update an existing RadGrid ItemDataBound event so we can add a tool tip on to each comment field.


 if ( e.Item.OwnerTableView.Name == "MasterTableName" && ( e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem ) )  
    {  
     Control cntl = e.Item.FindControl ( "mylabelintemplatecontrolidwithtruncatedtext" );  
     if ( cntl != null )  
     {  
      if ( this.RadToolTipManager1 != null )  
      {  
       this.RadToolTipManager1.TargetControls.Add ( cntl.ClientID, true );  
      }  
     }  
    }  

Note: I'm doing the e.Item.OwnerTableView.Name check because I'm using a grid with detail tables. If you don't have any detail tables you can skip that part of the check.  You might also add in a check to make sure the Radgrid is in read only mode, I didn't but I might go back and do that just to make it more efficient.

Step 3) Add your RadToolTipManager Ajax update method.


   protected void RadToolTipManager1_AjaxUpdate ( object sender, Telerik.Web.UI.ToolTipUpdateEventArgs e )  
   {  
    for ( int i = 0 ; i < MyGridView.Items.Count ; i++ )  
    {  
     if ( MyGridView.Items[ i ].OwnerTableView.Name == "MasterTableName" && ( MyGridView.Items[ i ].ItemType == GridItemType.Item || MyGridView.Items[ i ].ItemType == GridItemType.AlternatingItem ) )  
     {  
      /* unfortunately only get client ID back on ajax method, so we have to loop to find matching client ID */  
      Control cntl = MyGridView.Items[ i ].FindControl ( "mylabelintemplatecontrolidwithtruncatedtext" );  
      if ( cntl != null && cntl.ClientID == e.TargetControlID )  
      {  
       /* get row ID number */  
       int myID = Convert.ToInt32(MyGridView.Items[ i ].GetDataKeyValue ( "myID" ));  
        /* now get full comment text out of the database */  
        var rv = ( from myrow in ( (DataView)MyDataSet.Select ( DataSourceSelectArguments.Empty ) ).ToTable ().AsEnumerable ()  
              where ( myrow.Field<int> ( "myID" ) == myID )  
              select myrow ).FirstOrDefault ();  
       Label lblInsideToolTip = new Label ();  
       lblInsideToolTip.Text = rv[ "mycommenttextfield" ].ToString ();  
       e.UpdatePanel.ContentTemplateContainer.Controls.Add ( lblInsideToolTip );  
      }  
     }  
    }  
   }  

Ok, a few comments on Step 3.  I could only get the ClientID of the target control from the Telerik.Web.UI.ToolTipUpdateEventArgs object, so I had to loop through all of my RadGrid items and then try match client ID's of the column I was looking for.  Kind of a bummer. I elected to grab the comment text from the Dataset itself.  There are other ways of doing this.  Also this is just demo code, you might want to add this in a big try catch or at least check for more nulls.

Conclusion


This seems to work.  I can sort, edit, insert rows and now the comment field's tool tip is always current.  I hope this code helps. Also be sure to add the using System.Linq at the top of the page in your code behind if it isn't there.


Tuesday, March 25, 2014

Telerik UI Designer Fix for Asp.Net Ajax

Having trouble with Telerik UI in design mode (btw, I don't usually even look at web form pages in design mode anymore, but some still do).  If you get some weird stuff happening, this might be your fix.

Go to whatever visual studio version you are using and open the visual studio command prompt in admin mode (right click the shortcut, run as administrator...the command prompt might be named something slightly different depending on what version of VS you are using).

Then copy / paste this into the command prompt (changing this slightly for whatever version of the .net framework telerik version your have installed, if you have multiple versions installed do this for each one). Also note depending on what version of the Telerik controls you have installed, you might have to change the "UI for ASP.Net...." path to whatever path your telerik bin lies in.


 gacutil /i "C:\Program Files (x86)\Telerik\UI for ASP.NET AJAX Q1 2014\Bin40\Telerik.Web.Design.dll  

I hope this helps someone, credit goes to my boss for finding this.

Wednesday, February 26, 2014

Web Forms: Getting the Bound DataRow Values of a Grid Row While in Read Only Mode

OK, I had a Telerik gridview, and I wanted to add a right click event on the rows that would pop a window.  I also wanted to pass some of the data elements on the row clicked in the URL string of the popup window.

On the MasterTableView I had the Primary Key ID in the DataKeyNames property, so I could get the primary key ID from the clicked row using this technique-

http://www.telerik.com/forums/how-to-create-dynamic-context-menu-in-hierarchy-grid

But what about the rest of the data?  I could try to get at the data in it's label form on the grid row, but what I really wanted was the underlying data that was bound to the grid.  After tweaking a using a little bit if Linq, I came up with this-


  protected void GridContextMenu_ItemClick ( object sender, RadMenuEventArgs e )  
   {  
    try  
    {  
     string radGridClickedRowIndex = Request.Form[ "radGridClickedRowIndex" ]; //hidden form field  
     int RowIndex = -1;  
     RowIndex = Convert.ToInt32 ( radGridClickedRowIndex );  
     GridDataItem gridRow = GridView.Items[ RowIndex ] as GridDataItem;  
     int ID = Convert.ToInt32(gridRow.GetDataKeyValue ( "ID" ).ToString ());  
     var rv = ( from myrow in ((DataView)GRIDDataSet.Select ( DataSourceSelectArguments.Empty )).ToTable().AsEnumerable ()  
           where ( myrow.Field<int> ( "ID" ) == ID )  
           select myrow ).FirstOrDefault ();  
      ...  

And then you can access items in the bound data row like this

string myvalue = rv["column_name"].ToString();


Some of you will not get what I'm talking about.  But to a certain group of people I hope this is useful. Remember to include the System.Linq namespaces at the top of the code behind page.

Tuesday, July 05, 2011

Using A ValidationSummary Control's ShowMessageBox (kinda) with Telerik Controls in Medium Trust

 I guess there is an issue with Validation Summaries and Telerik Controls.  If your site is running under Medium trust, you can't use the ShowMessageBox and instead you have to use the ShowSummary method.  I noticed this through off the styling of some of my controls once the error summary was rendered so I came up with a work around. Note be careful where you call this code else you will get an error, this worked for me using the FormView_ItemCommand.


ValidationSummary vs =
(ValidationSummary)MyFormView.Row.FindControl ( "myvalidationsummaryname" );
if ( vs != null )
{
  string sErr = vs.HeaderText  + "\\n";
  for ( int i = 0 ; i < this.Validators.Count ; i++ )
  {
    if ( !this.Validators[ i ].IsValid )
      sErr += "* " + this.Validators[ i ].ErrorMessage + "\\n";
  }
  myRadAjaxManager.ResponseScripts.Add ("alert('" + sErr + "');" );
}

That should get you going.

Tuesday, June 28, 2011

Populating a Telerik RadListBox with JSON on the Client Side

Ok, this is the poor man's way to do this. I'm actually not calling a web service to pull my jSON string back from the server, but rather a RadScriptManager, but this will get you going.

My approach. Note it assumed that you have a Telerik RadAjaxScriptManager on your page (or master page that you will need to access).

Step 1 Include the Following Namespace in Page Code Behind Class

using System.Web.Script.Serialization;

Step 2 Create a Class Object to be Serialized in the Page Code Behind Class

[Serializable]
public class itm
{
   public string val { get; set; }
   public string txt { get; set; }
}

Step 3 Create a Serialization Method in the Page Code Behind Class

public string ToJSON ( object obj )
{
  JavaScriptSerializer serializer = new JavaScriptSerializer ();
  return serializer.Serialize ( obj );
}

Step 4 Create a Method in the Page Code Behind Class That Will Take Data, Populate a list of itms,Serialize that list into a jSON string, then call the RadAjaxManager's ResponseScripts.Add method to pass the jSON string to the client side.

A few notes here. One you could use AJAX to make a call to a web service to accomplish the same thing, for my example was just doing a basic test so I didn't bother. Also note that you will need to call this method somewhere (on a databind of a form view, Page_Load, whatever, inorder for the method to do anything). Note I'm doing a very lazy and inefficient way to get my data out of the database, I actually defined a sql datasource on my aspx page, and then reference it in the code behind. You probably will want to get your data another way...

void JSONListBoxItems ( hsRadListBox lst, SqlDataSource ds, string txt, string val )
  {
  lst.Items.Clear ();
  List<itm> itms = new List<itm> ();
  if ( lst == null || ds == null || string.IsNullOrEmpty ( txt ) || string.IsNullOrEmpty ( val ) )
  {
   ;
  }
  else
  {
    DataView view = (DataView)ds.Select ( DataSourceSelectArguments.Empty );
    if ( view != null && view.ToTable () != null )
    {
      DataTable table = view.ToTable ();
      for ( int i = 0 ; i< table.Rows.Count ; i++ )
      {
       itm t = new itm ();
       t.txt = table.Rows[ i ][ txt ].ToString ();
       t.val = table.Rows[ i ][ val ].ToString ();
       itms.Add ( t );
      }
    }
   }
   myRadAjaxManager.ResponseScripts.Add ("POPRadListBX('" + lst.ClientID.ToString () + "'," + ToJSON ( itms ) + ");" );
 }

Step 5, Add the Following Javascript on the ASPX page.

function POPRadListBX(tid, js) {
        var lst = $find(tid);
        if (lst != null) {
          var zzz = lst.get_items();
          lst.trackChanges();
          for (var i = 0; i < js.length; i++) {
            var item = new Telerik.Web.UI.RadListBoxItem();
            item.set_text(js[i].txt);
            item.set_value(js[i].val);
            zzz.add(item);
          }
          lst.commitChanges();
        }
      }


Done. If I have time I'll circle back and make a downloadable example.

Wednesday, May 11, 2011

Passing Client Side Dates to Server Side Vars With Telerik Rad Controls

Ok, sometimes you need to pass a client side datetime value from a Raddatetimepicker up to the server side for use. Sometimes with localization this can get kind of tricky, but Telerik introduced a new method to make this somewhat less painless.

in javascript
var dt = $telerik.findDatePicker("controlID", null);
  var dtValue = dt.get_selectedDate().format("yyyy/MM/dd");


This method will put your datetime value in a format that is SQL server friendly. Happy coding.

Monday, July 20, 2009

Not Digging Telerik

[Update] Someone from Telerik contacted me willing to help us out with our issue. That says a lot for Telerik and restores a good chunk of my faith in their controls and their support.

I like Telerik. They have produced some very cool controls to use with ASP.Net. Unfortunately the 2009 Q1 release broke all our controls at work. We normally inherit off of the Telerik controls and add some additional functionality. Whatever changes happened under the hood makes the Q1 + releases useless to us.

My job is to figure out a solution. So far no luck. Telerik says they don't support inheritance issues. Wish we would have known that earlier, or at least known to expect that existing working code will not be guaranteed to work in the future as is.

Sucks. Use this as a warning against becoming too dependant on 3rd party controls, as you can and will get burned.

Friday, October 10, 2008

Radgrid Column Name Changing

At work I ran into a scenario where we couldn't use our customized Radgrid which handles localization behind the scenes. So I had to use the standard Telerik Radgrid. Here is a link to how to deal with columns-

http://www.telerik.com/help/aspnet/grid/grdusingcolumns.html

For some reason changing the header text as suggested in the example for me didn't work. I need to change the header text names at runtime due to the headers need to be translated into the viewing clients language. But in fooling around I found a neat trick that did work. It might not be too efficient, but it got what I wanted to get done done.

My Radgrid was bound to a sqldatasource. So I added a new selected event handler on the Page.Init like so-


protected void Page_Init (object sender, EventArgs e)
{
myDataSet.Selected +=
new SqlDataSourceStatusEventHandler (myDataSet_Selected);
}
void myDataSet_Selected (object sender, SqlDataSourceStatusEventArgs e)
{
foreach (GridColumn column in myGridView.Columns)
{
if (column.UniqueName == "some name" )
{
(column
as GridBoundColumn ).HeaderText =
"whatever the translated text is";
break;
}
}
}


It works! Hope this helps someone.

Tuesday, May 20, 2008

Telerik RadComboBox Auto Complete Example

Ok, I found a few blog post and some documentation from Telerik on how to create a web service to populate a RadComboBox. None of the examples where complete, so here is a very basic example to get you going.

First, in design mode drag a RadScriptManager to your page. Switch to design mode, and click on the smart tag. Add the whatever it is called to your web config. Then drag a RadComboBox to your page. Then add the the Javascript so you have something that looks like below. Some of the code is obscured by the right side bar, just select the code and copy paste into a text viewer and it should all be there. I need to find sometime to either find a new blogging platform or widen out my blog a bit.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Telerik_Error._Default" %>
<%
@ Register assembly="Telerik.Web.UI" namespace="Telerik.Web.UI" tagprefix="telerik" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<
html xmlns="http://www.w3.org/1999/xhtml" >
<
head runat="server">
<title>Untitled Page</title>
</
head>
<
body>
<form id="form1" runat="server">
<div>
<script type="text/javascript">
function OnClientItemsRequesting(sender, eventArgs)
{
var context = eventArgs.get_context();
context[
"FilterString"] = eventArgs.get_text();
context[
"test"] = "2";
}
</script>

<telerik:RadScriptManager ID="RadScriptManager1" Runat="server">
</telerik:RadScriptManager>
<telerik:RadComboBox runat="server" ID="RadComboBox1" Width="300px"
EnableLoadOnDemand="true"
OnClientItemsRequesting="OnClientItemsRequesting">
<WebServiceSettings Method="GetProducts" Path="Test.asmx" />
</telerik:RadComboBox>
</div>
</form>
</
body>
</
html>


Ok, half way done. Now create the webservice. I called mine GetProducts. In order for it to work you have to use the RadComboItemData object as well as Generic list. Here is a sample webservice.

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using Telerik.Web.UI;
using System.Collections.Generic;

namespace Telerik_Error
{
/// <summary>
/// Summary description for Test
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(
false)]
// To allow this Web Service to be called from script,
//using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class Test : System.Web.Services.WebService
{

[WebMethod(EnableSession=
true)]
public RadComboBoxItemData[] GetProducts(object context)
{
IDictionary<string, object> contextDictionary = (IDictionary<string, object>)context;
List<RadComboBoxItemData> result = new List<RadComboBoxItemData>();
for (int i = 0; i <= 5; i++)
{
RadComboBoxItemData itemData =
new RadComboBoxItemData();
itemData.Text = contextDictionary[
"test"].ToString() +
contextDictionary[
"FilterString"].ToString() + i.ToString();
itemData.Value =
"value" + i;
result.Add(itemData);
}
return result.ToArray();
}

}
}


This came from a sample project that I was working on called Telerik_Error, thus the weird namespace reference. You can ignore that. Also not that in the javascript you can add additional variables to the context object, like I did with the variable test. Hope this code helps. The next step would be to include data. You should be able to pull in a datatable from a database and loop through it add items once you get the base webservice up and running.

Wednesday, May 07, 2008

Telerik RadComboBox in a RadGrid

Ok, this post is only a half post, as for now I will leave out a lot of details. I use Telerik's control suite for ASP.Net (www.telerik.com) at work. I spent about four hours yesterday trying to get a RadComboBox's selected value to bind to a column in the Grid's dataset when in edit mode (so I could get two way databinding on the grid so it will handle the update/delete/insert automatically as long as you setup the appropriate procs and params in your SQL datasource).

Without including all the details I couldn't get things to work until I bound the RadComboBox to a column that initially had the value of ''in the dataset . Then, in the item data bound event I set the value the RadComboBox to the value it should be.

So in my stored proc I had to return two columns like this, mycolumn (which I set in the select to ''), and then mycolumn_real_value which in the stored proc is the value that should be the value for mycolmn. The RadComboBox's selectedvalue is bound to mycolumn like selectedvalue='<%# Bind("mycolumn") %>'. Then in the item data bound event for the Grid I cast the e.Item as a GridItem, then do a findcontrol to find the RadComboBox, then set the text of that RadComboBox to the value of mycolumn_real_value. Also you can't give the RadComboBox a DataSourceID. I ended up building a function that pulls a new DataView out of a DataSource, then loops through that view's rows and add's new items to the RadComboBox.

I'm sure there is another way, but I couldn't get anything else to work, including the downloaded Telerik examples.

I'll post actual code for this at one point, and to 99% of you who read this it will sound like a bunch of nonsense(like most of my post), but to those of you like me who have been pulling their hair out to get two way databinding to work on a RadComboBox in a RadGrid the above will put you on the right path.