Friday, August 13, 2010

Hiding GridEditCommandColumn and CommandItemDisplay

It is not necessary to disable a gridEditCommandColumn in the prerender or databind event of the radgrid or datagrid.

To hide the GridEditCommandColumn:

wgdDetails.Columns.Item(1).Visible = False


To hide the CommandItem (Add)


wgdDetails.MasterTableView.IsItemInserted = False
wgdDetails.MasterTableView.CommandItemDisplay = Telerik.Web.UI.GridCommandItemDisplay.None

Tuesday, August 3, 2010

Filter DataTable

Method to filter datatable. Returns a dataset with two datatables (0ne for the filtered data and another one to show any error message defined in the caller method or event)

1 Protected Function FilterDataTable(ByVal strFilterString As String, ByVal dtMainTable As Data.DataTable, ByVal strMessage As String) As Data.DataSet
2 Dim ResultData As New
DataSet
3 Dim dtMessage As New
Data.DataTable
4 Dim DataTableClon As New
Data.DataTable
5 Dim drClon As
System.Data.DataRow()
6 Dim dsDataFiltered As New
Data.DataSet
7 Try

8
ResultData.Tables.Add(dtMainTable)
9 DataTableClon = ResultData.Tables(0
).Copy
10
DataTableClon.Rows.Clear()
11 drClon = ResultData.Tables(0
).Select(strFilterString)
12 For Each dr In
drClon
13
DataTableClon.ImportRow(dr)
14 Next

15

16 dtMessage.TableName = "Header"
17 dtMessage.Columns.Add("ErrorMessage", GetType
(System.String))
18
dsDataFiltered.Tables.Add(DataTableClon)
19
dsDataFiltered.Tables.Add(dtMessage)
20 Dim newMessageRow As DataRow = dsDataFiltered.Tables("Header"
).NewRow()
21 newMessageRow("ErrorMessage") =
strMessage
22 dsDataFiltered.Tables("Header"
).Rows.Add(newMessageRow)
23

24 Catch ex As Exception
25 Call ManageError(strGlobalUser, strAppName, strModName, "FilterDataTable"
, intGlobalMain, Err, strGlobalPathError, ApplicationType.Web)
26 Finally

27 FilterDataTable =
dsDataFiltered
28 End Try

29 End Function

Export to a formatted excel file as an attachment (safe mode)

If you want to export a datatable into an excel file keeping each columns place in an excel file and you want also to be asked where you want your excel file to be saved. Then you should use the method I have bellow.

If you are also one of those programmers who had this:
Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80070005., then, you should also use this code instead of the one you are currently trying to make work.

I've tried before and it worked fine locally. However, once I deployed it didn't work at all. I tried to find out how to solve that issue and even though I did everything suggested on the net it never worked. May be the reason is because Microsoft doesn't support server side automation at office. You can read more about that
here

The method:

1 Public Sub ExportToSpreadsheet(ByVal tblTable As Data.DataTable, ByVal strName As String)
2 Try

3 Dim context As HttpContext =
HttpContext.Current
4 Dim grid As
System.Web.UI.WebControls.DataGrid
5 grid = New
System.Web.UI.WebControls.DataGrid
6 grid.HeaderStyle.Font.Bold = True

7 grid.DataSource =
tblTable
8 grid.DataMember =
tblTable.TableName
9
grid.DataBind()
10

11 context.Response.Clear()
12

13 Dim sw As StringWriter
14 sw = New
StringWriter()
15

16 Dim hw As HtmlTextWriter
17 hw = New
HtmlTextWriter(sw)
18

19 grid.RenderControl(hw)
20
context.Response.Write(sw.ToString)
21 context.Response.AppendHeader("content-disposition", "attachment; filename=" & strName & ".xls"
)
22 context.Response.ContentType = "application/excel"

23 context.Response.Charset = String
.Empty
24
context.Response.Flush()
25
context.Response.End()
26 Catch ex1 As
System.Threading.ThreadAbortException
27 Exit Sub

28 Catch ex As
Exception
29 Call ManageError("ExportToSpreadsheet"
, Err)
30 End Try

31

32 End Sub



Important Considerations:
1.ManageError is a method I use to manage errors, so that you can replace for a simple exit sub or another customized method you use to manage errors.

2. Make sure you will hava an exception type System.Threading.ThreadAbortException in your caller method since that exception will be catched there too.
Apparently the context.response.end automatically runs System.Threading.ThreadAbortException and the only way of avoiding it is catching it. I tried what Microsoft suggest. However, it shows my filter screen page instead of the datatable data.

3. If you don't really need to ask the user where to save your excel file you can simply use the code suggested in this page and forget about that exception.

Tuesday, July 13, 2010

ToolTip - RadToolTip

RadTooltip is used as a tooltip to show aditional information that can be formatted in any way you need and, most importantly doesn't disappear after some seconds as the standard tooltip, so it is the user who decides when he/she doesn't want to see it anymore by clicking in a close button.
RadTooltip belongs to the Telerik controls family, so you will need to have it installed.


Quick example - How to use it

1. On the MouseOver event of the txtSUMSGDesc textbox, show a customized tooltip with a textarea inside of it.

The HTML code for the textboxes:


1 <td>
2 <asp:TextBox ID="txtSUMSG" runat="server" CssClass="textbox_disabled2" ReadOnly="False" MaxLength="5" width="33px" ></asp:TextBox>

3 <asp:TextBox ID="txtSUMSGDesc" CssClass="textbox_disabled2" runat="server" Width="180px" AutoPostBack="true"></asp:TextBox>

4 </td>



the HTML code for the RadToolTip

1 <telerik:RadToolTip runat="server" ID="RadToolTip1" Position="TopRight" HideEvent="ManualClose"
2 ShowEvent="OnMouseOver" Width="350px" RelativeTo="Element"

3 TargetControlID="txtSUMSGDesc" OnClientBeforeShow="CheckIfShow">

4 <table width="100%">

5 <tr>

6 <td>

7 <asp:TextBox ID="txtMessageDesc" runat="server" TextMode="MultiLine"

8 Width="300px" CssClass="MessageText"></asp:TextBox>

9 </td>

10 </tr>

11 </table>

12 </telerik:RadToolTip>


The JavaScript functions needed to show the RadToolTip (only when there is information in the textbox)

1 function HideTooltip() {
2 var tooltip =
Telerik.Web.UI.RadToolTip.getCurrent();
3 if
(tooltip) tooltip.hide();
4
}
5

6 function ShowTooltip() {
7 window.setTimeout(function
() {
8 var tooltip = $find("RadToolTip1"
);
9 //API: show the tooltip

10
tooltip.show();
11 }, 10
);
12
}
13

14 function CheckIfShow(sender, args) {
15 var Elem = document.getElementById("<%=txtSUMSGDesc.ClientID%>"
);
16 //check if summary is visible

17 if (Elem.value == ""
) {
18 //API: if there are no errors, do not show the tooltip

19 args.set_cancel(true
);
20
}
21 }

Wednesday, July 7, 2010

Formatting textbox : RadNumericTextBox

If we need to format a textbox, so that we don't need to validate the input and if you can use telerik controls. You should use RadNumericTextBox control.


Before you need something like this in order to validate a number with maximum 4 decimals.


1 <asp:TextBox ID="txtTaxRate" runat="server" CssClass="textbox_num_enabled2" Width="50px" MaxLength="7" text='<%#DataBinder.Eval(Container, "DataItem.TaxRate") %>'></asp:TextBox>
2 <asp:RegularExpressionValidator ID="revTaxRate" runat="server"

3 ErrorMessage="RegularExpressionValidator" CssClass="error2"

4 ControlToValidate="txtTaxRate" ValidationExpression="^\d{0,2}(\.\d{1,4})?$"></asp:RegularExpressionValidator>

5

6

Now, you just need a RadNumeric Textbox like this:

1 <telerik:RadNumericTextBox ID="txtTaxRate" runat="server" DataType="System.Int64" MaxLength="9"
2 MaxValue="99.9999" MinValue="0" Skin="" CssClass="textbox_num_enabled2" EnableEmbeddedSkins="False"

3 Width="80px" text='<%#DataBinder.Eval(Container, "DataItem.TaxRate") %>
'>
4 <NumberFormat DecimalDigits="4" />

5 </telerik:RadNumericTextBox>

6

7

Datagrid column's formatting

Formatting a datagrid or radgrid column is really easy. We just need to verify the following:

1. Source Datatype to apply the format.
2. The format itself.

To clarify this:
Let's say we need to format a numeric field "Qty", so that instead of having 12 value, it shows 12.00, then, We need to ensure ourselves that "Qty" datatype is decimal or numeric in the case we are planning to use the {0:F4} format. Otherwise, it will always show 12.

Ways of formatting a radgrid or datagrid column in the aspx page:
1. Formatting with String.Format.
2. Formatting with Databinder.Eval

Even though, both can do exactly the same thing. The theory said (I couldn't verify this) that the String.Format method is faster than Databinder.Eval; However, some programmers said that the difference is just miliseconds and the code is a little bit more complicated so that is worthless.
Anyways, I will develop here the second method: Formatting with Databinder.Eval.

When using a BoundColumn:


1 <telerik:GridBoundColumn DataField="TaxRate" HeaderText="Tax Rate" UniqueName="TaxRate"
2 DataFormatString="{0:F4}" HtmlEncode="false">

3 <HeaderStyle Font-Names="Arial" HorizontalAlign="Right" Width="35px" />

4 <ItemStyle HorizontalAlign="Right" Wrap="True" />

5 </telerik:GridBoundColumn>



When Using a TemplateColumn:


1 <telerik:GridTemplateColumn HeaderText="Tax Rate" UniqueName="TaxRate" Visible="True">
2 <HeaderStyle Font-Names="Arial" HorizontalAlign="Right" Width="35px" Wrap="True" />

3 <ItemStyle HorizontalAlign="Right" Wrap="False" Font-Names="Arial" />

4 <ItemTemplate>

5 <asp:Label ID="lblTaxRate" runat="server" CssClass="label2" Width="35px" Text='<%# DataBinder.Eval (Container, "DataItem.TaxRate", "{0:F4}") %>'></asp:Label>

6 </ItemTemplate>

7 </telerik:GridTemplateColumn>



Formatting with String Format:


1 <%# String.Format("{0:c}",
2 ((System.Data.Common.DbDataRecord)Container.DataItem)["TaxRate"]) %>

3



Format Expressions:


1. This will display a text Price: followed by the numeric text in currency format

Format String: Price: {0:C}

NOTE : THE ABOVE MENTIONED FORMAT IS USING A ZERO IT IS NOT THE ALPHABET O

Applied to numeric and decimal data types.

The currency format is according to the culture info set in the web config file.


2. Integers are displayed in a zero-padded field four characters wide.

Format String : {0:D4}

Applied to integer datatype only.


3. To show two decimal places followed by "%"

Format String : {0:N2}%

Applied to integer datatype only.


4. To round the numbers to one decimal place and are zero padded for numbers less than three digits.

Format String : {0:000.0}

Applied to numeric and decimal datatype only.


5. Long Date format

Format String: {0:D}

Applied to date and datetime datatype only.

( the above formatting is as set in the web config)


6. Short Date format

Format String : {0:d}

Applied to date and datetime datatype only.

( the above formatting is as set in the web config)



6. Numeric Date format

Format String : {0:yy-MM-dd}

Applied to date and datetime datatype only.


Reorted Issues:

When the formatting doesn't work, verify the datatype and in the case of BoundColumns, try by setting: HtmlEncode = false.

Wednesday, June 23, 2010

Adding a Root Node to RadTreeView

How to?
1. Create a node (Root Node) from zero.

2. Add the nodes of our existing treeview to the new node.

Example:
(rtvFrom is my radtreeview)

1 Dim node As New RadTreeNode("Root Menu")
2 node.Nodes.AddRange(rtvFrom.Nodes.Cast(Of
RadTreeNode)())
3
rtvFrom.Nodes.Add(node)
4 rtvFrom.ExpandAllNodes()

RadTreview conected to DB example

It is very easy to work with treeviews and DB. The table structure is one of the most important things to take into consideration (It must be a table that has recursivity). Let's see a small example.

Description:
This treeview will show the available menu options for an application. Normally it varies depending on the environment:DEV(1), TEST(2), PRODUCTION(3). However, for this small example we are just sending 1 (Dev environment) hardcoded. You could use a combobox and send its value.

1) The table:
1 CREATE TABLE [dbo].[Metal_Menu](
2 [ME_SEQ] [uniqueidentifier] ROWGUIDCOL NOT NULL CONSTRAINT [DF_Metal_Menu_ME_SEQ] DEFAULT (newid
()),
3 [ME_PARENT] [uniqueidentifier] NULL
,
4 [ME_DESC] [varchar](100) NULL
,
5 [ME_URL] [varchar](500) NULL
,
6 [ME_PAGE] [varchar](100) NULL
,
7 [ME_TYPE] [int] NULL
,
8 [Active] [bit] NULL CONSTRAINT [DF_Metal_Menu_Active] DEFAULT ((1
)),
9 [CreatedBY] [varchar](255) NULL CONSTRAINT [DF_Metal_Menu_CreatedBY] DEFAULT ('web\iuser'
),
10 [CreatedDate] [datetime] NULL CONSTRAINT [DF_Metal_Menu_CreatedDate] DEFAULT (getdate
()),
11 [ModifBy] [varchar](255) NULL CONSTRAINT [DF_Metal_Menu_ModifBy] DEFAULT ('web\iuser'
),
12 [ModifDate] [datetime] NULL CONSTRAINT [DF_Metal_Menu_ModifDate] DEFAULT (getdate
()),
13 CONSTRAINT [PK_Metal_Menu] PRIMARY KEY CLUSTERED

14
(
15 [ME_SEQ] ASC

16 )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

17 ) ON [PRIMARY]



2. The HTML portion of the RADTREEVIEW:

1 <telerik:RadTreeView ID="rtvFrom" runat="server" EnableDragAndDrop="True" OnNodeDrop="RadTreeView1_HandleDrop"
2 OnClientNodeDropping="onNodeDropping" OnClientNodeDragging="onNodeDragging" MultipleSelect="true" EnableDragAndDropBetweenNodes="true" CheckBoxes="false">

3 <DataBindings>

4 <telerik:RadTreeNodeBinding Expanded="True" AllowDrop="false"/>

5 </DataBindings>

6 </telerik:RadTreeView>



3. The code behind (VB.Net) for this radtreeview:


1 rtvFrom.Nodes.Clear()
2 rtvFrom.DataTextField = "SYME_DESC"

3 rtvFrom.DataFieldID = "SYME_SEQ"

4 rtvFrom.DataValueField = "SYME_SEQ"

5 rtvFrom.DataFieldParentID = "SYME_PARENT"

6 ViewState.Add("TreeFrom", GetMenuTreeSync(1
, strUser))
7 rtvFrom.DataSource = CType(ViewState("TreeFrom"
), Data.DataSet)
8 rtvFrom.DataBind()



4. As you can see, up to his point. I am using a method "GetMenuTreeSync" to retrieve the information from the database. The method actually calls a stored procedure to get the information, but it could just execute a SQL sentence like this:

select * from ME_menu WHERE Active = 1 order by me_parent

Comments:
In this example I used a Viewstate object to store the dataset returned from the query, however you can use a simple local variable of dataset or datatable type.

Monday, June 21, 2010

RadScriptManager strange error : method get_EnableCdn ...

The error:

method get_EnableCdn in type system.web.ui.scriptmanager from assembly system.web.extensions, version=3.5.0.0, culture=neutral PublicKeyToken=31bf3856ad364e35' does not have an implementation.

The solution:

1. Delete this line from the pages you have it:


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


2. Verify this section in your web config:

1 <runtime>
2 <assemblyBinding appliesTo="v2.0.50727" xmlns="urn:schemas-microsoft-com:asm.v1">

3 <dependentAssembly>

4 <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>

5 <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>

6 </dependentAssembly>

7 <dependentAssembly>

8 <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>

9 <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>

10 </dependentAssembly>

11 </assemblyBinding>

12 </runtime>



Very important: Make sure you use the: appiesTo in the following line:

1 <assemblyBinding appliesTo="v2.0.50727" xmlns="urn:schemas-microsoft-com:asm.v1">
2

3. If the error message remains or in the case you were not able to see your telerik controls in design mode (you have a very big an strange error instead of it), you could also try:
- Make sure you have Telerik.Web.UI.dll, Telerik.Web.Design.dll and Telerik.Web.UI.xml in your bin folder.

4. Verify that you have only one reference to System.Web.Extensions in your project (whether you have it in your bin folder or in your GAC)

More Info:


http://www.telerik.com/community/forums/aspnet-ajax/general-discussions/236690-error-rendering-control.aspx

http://forums.asp.net/p/1497738/3661536.aspx

Thursday, June 17, 2010

Is it possible to change RadDatePicker language?


Yes, It is possible. We just need to put this line of code in the Page_Load event.

1 radDateFrom.Calendar.CultureInfo = New System.Globalization.CultureInfo(strLang)

radDateFrom = your radDatePicker control.
strLang = Your Selected Language

See a Complete small example

The Client code:

1 <form id="form1" runat="server">
2 <asp:ScriptManager ID="ScriptManager1" runat="server" />

3 <div>

4 <asp:DropDownList ID="ddl1" runat="server" AutoPostBack="True">

5 <asp:ListItem Text="en-US" />

6 <asp:ListItem Text="bg-BG" />

7 <asp:ListItem Text="es-ES" />

8 </asp:DropDownList>

9 <telerik:RadDateTimePicker ID="RadDateTimePicker1" runat="server" meta:resourcekey="RadDateTimePicker1Resource1">

10 <Calendar AutoPostBack="false" RangeMinDate="01/01/2009" RangeMaxDate="12/12/2009"

11 EnableViewSelector="true" MultiViewColumns="2" MultiViewRows="2" EnableNavigation="true"

12 meta:resourcekey="RadCalendar1Resource1" />

13 </telerik:RadDateTimePicker>

14 </div>

15 </form>




The code behind:





1 Partial Class Pages_RadExample
2 Inherits
System.Web.UI.Page
3

4
5 Protected Overrides Sub InitializeCulture()
6 Dim selectedLanguage As String = "en-US"

7 If Request.Form("ddl1") IsNot Nothing Then

8 selectedLanguage = Request.Form("ddl1"
)
9 End If

10 System.Threading.Thread.CurrentThread.CurrentCulture = New
System.Globalization.CultureInfo(selectedLanguage)
11 System.Threading.Thread.CurrentThread.CurrentUICulture = New
System.Globalization.CultureInfo(selectedLanguage)
12 MyBase
.InitializeCulture()
13 End Sub

14

15 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
16 Dim selectedLanguage As String = "en-US"

17 If Request.Form("ddl1") IsNot Nothing Then

18 selectedLanguage = Request.Form("ddl1"
)
19 End If

20 RadDateTimePicker1.Calendar.CultureInfo = New
System.Globalization.CultureInfo(selectedLanguage)
21 End Sub

22 End Class

Wednesday, June 16, 2010

Edit button visible per row in DataGrid

This is an issue that we always need to do. However, sometimes we are not sure about where to do the coding and how.

The event:
Grid_ItemDatabound

How to - Example:

1 Protected Sub wgdLots_ItemDataBound(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridItemEventArgs) Handles wgdLots.ItemDataBound
2 Dim txtQtyPlannedGrid As
Telerik.Web.UI.RadNumericTextBox
3 Dim txtQtyPickGrid As
TextBox
4 Try

5 If e.Item.ItemType = GridItemType.EditItem Then

6 txtQtyPlannedGrid = CType(e.Item.FindControl("txtQtyPlannedGrid"
), Telerik.Web.UI.RadNumericTextBox)
7 txtQtyPickGrid = CType(e.Item.FindControl("txtQtyPickGrid"
), TextBox)
8 If Not txtQtyPickGrid Is Nothing Then

9 strPallet = e.Item.Cells(1
).Text
10 If strPallet = "" Or strPallet = "&nbsp;" Then

11 txtQtyPickGrid.Enabled = False

12 End If

13 End If

14 Else

15 If CDbl(txtQtyPlanned.Text) = 0 Then

16 e.Item.Cells(12).Visible = False

17 End If

18 End If

19

20 Catch ex As Exception
21 Call ManageError(strGlobalUser, strAppName, strModName, "wgdLots_ItemDataBound"
, intGlobalMain, Err, strGlobalPathError, ApplicationType.Web)
22 End Try

23

24 End Sub