From 86a04dcbf59ccdb9366cecabc3ff3197dad80b56 Mon Sep 17 00:00:00 2001 From: Dinko Krastev Date: Mon, 6 Apr 2026 17:32:02 +0300 Subject: [PATCH 01/12] Create First Project to replace AIPrompt code snippet --- .github/workflows/build-code-snippets.yml | 102 +++++++++++++++ .gitignore | 8 +- controls/aiprompt/getting-started.md | 13 +- docs-builder.yml | 1 + .../Common/Common.csproj | 15 +++ .../Common/Form1.Designer.cs | 59 +++++++++ .../Common/Form1.cs | 26 ++++ .../Common/Form1.resx | 120 ++++++++++++++++++ .../Common/Program.cs | 17 +++ .../NuGet.config | 8 ++ .../Telerik.WinControls.UI.Snippets.slnx | 3 + 11 files changed, 360 insertions(+), 12 deletions(-) create mode 100644 .github/workflows/build-code-snippets.yml create mode 100644 snippets/Telerik.WinControls.UI.Snippets/Common/Common.csproj create mode 100644 snippets/Telerik.WinControls.UI.Snippets/Common/Form1.Designer.cs create mode 100644 snippets/Telerik.WinControls.UI.Snippets/Common/Form1.cs create mode 100644 snippets/Telerik.WinControls.UI.Snippets/Common/Form1.resx create mode 100644 snippets/Telerik.WinControls.UI.Snippets/Common/Program.cs create mode 100644 snippets/Telerik.WinControls.UI.Snippets/NuGet.config create mode 100644 snippets/Telerik.WinControls.UI.Snippets/Telerik.WinControls.UI.Snippets.slnx diff --git a/.github/workflows/build-code-snippets.yml b/.github/workflows/build-code-snippets.yml new file mode 100644 index 000000000..32c1c2663 --- /dev/null +++ b/.github/workflows/build-code-snippets.yml @@ -0,0 +1,102 @@ +name: Build WinForms Solutions + +on: + push: + paths: + - '**/*.md' + - 'snippets/**' + pull_request: + paths: + - '**/*.md' + - 'snippets/**' + workflow_dispatch: + +jobs: + build: + runs-on: windows-latest + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Detect snippet or folder changes + id: snippet_check + shell: pwsh + run: | + git fetch --no-tags --prune --depth=0 origin + # Determine comparison base (works for push + PR) + if ("${{ github.event_name }}" -eq "pull_request") { + $base = "${{ github.event.pull_request.base.sha }}" + } else { + $base = "${{ github.event.before }}" + } + Write-Host "Comparing against $base" + $changedFiles = git diff --name-only $base HEAD + if (-not $changedFiles) { + echo "should_build=false" >> $env:GITHUB_OUTPUT + exit 0 + } + $shouldBuild = $false + foreach ($file in $changedFiles) { + Write-Host "Changed: $file" + # CONDITION 1: + # Any change inside /snippets folder + if ($file -like "snippets/*") { + Write-Host "Change inside snippets folder detected." + $shouldBuild = $true + break + } + # CONDITION 2: + # .md file with snippet tag added/modified + if ($file -like "*.md") { + $diff = git diff $base HEAD -- $file + if ($diff -match "> $env:GITHUB_OUTPUT + - name: Setup .NET 10 + if: steps.snippet_check.outputs.should_build == 'true' + uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.x' + + - name: Add Telerik NuGet source + if: steps.snippet_check.outputs.should_build == 'true' + shell: pwsh + run: | + dotnet nuget add source "https://nuget.telerik.com/v3/index.json" --name "Telerik NuGet Server" --username "api-key" --password $env:TELERIK_API_KEY --store-password-in-clear-text + env: + TELERIK_API_KEY: ${{ secrets.TELERIK_API_KEY }} + + - name: Debug Telerik NuGet + if: steps.snippet_check.outputs.should_build == 'true' + shell: pwsh + run: | + Write-Host "TELERIK_API_KEY length: $($env:TELERIK_API_KEY.Length)" + dotnet nuget list source + - name: Restore & Build all solutions + if: steps.snippet_check.outputs.should_build == 'true' + shell: pwsh + run: | + # Find both .sln and .slnx files + $solutions = Get-ChildItem "./snippets" -Recurse -Include *.sln,*.slnx -File + if (-not $solutions) { + Write-Error "No solution files (.sln or .slnx) found!" + exit 1 + } + foreach ($sln in $solutions) { + Write-Host "" + Write-Host "==============================" + Write-Host "Building $($sln.FullName)" + Write-Host "==============================" + dotnet restore "$($sln.FullName)" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + dotnet build "$($sln.FullName)" ` + --configuration Release ` + --no-restore + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + } \ No newline at end of file diff --git a/.gitignore b/.gitignore index 1bced3123..d4081dcc4 100644 --- a/.gitignore +++ b/.gitignore @@ -77,4 +77,10 @@ SlugLog.log start-docs.sh start-docs.sh watch.sh -watch.sh +watch.sh +.suo +.baml +**/bin/ +**/obj/ +**/.vs/ +**.csproj.user diff --git a/controls/aiprompt/getting-started.md b/controls/aiprompt/getting-started.md index 979f774be..d506d1b9d 100644 --- a/controls/aiprompt/getting-started.md +++ b/controls/aiprompt/getting-started.md @@ -46,17 +46,8 @@ Follow the steps: You can create a new __AIPromptOutputItem__ instance and fill it with returned response from the AI model. Then, you can populate the __OutputItems__ collection of RadAIPrompt. This will create a new AIPromptOutputVisualItem in the Output view where you can interact with the response. ````C# -private void RadAIPrompt1_PromptRequest(object sender, Telerik.WinControls.UI.AIPrompt.PromptRequestEventArgs e) -{ - AIPromptOutputItem responseAIPromptOutputItemModel = new AIPromptOutputItem() - { - Title = "Response from your AI model", - InputText = e.InputText, - ResponseText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", // Here you can set the string value returned from your AI model - }; - - this.radAIPrompt1.OutputItems.Add(responseAIPromptOutputItemModel); -} + + ```` ````VB.NET diff --git a/docs-builder.yml b/docs-builder.yml index 47fa888c5..fff6cd220 100644 --- a/docs-builder.yml +++ b/docs-builder.yml @@ -16,6 +16,7 @@ img-max-width: 100% center-images: false table-layout: fixed enable-tabbed-code-blocks: true +external-snippets-path: ./snippets pdf-cover-png-path: ./images/pdf-cover.png gitLastCommitDateEnabled: true search-provider: nuclia diff --git a/snippets/Telerik.WinControls.UI.Snippets/Common/Common.csproj b/snippets/Telerik.WinControls.UI.Snippets/Common/Common.csproj new file mode 100644 index 000000000..742751b32 --- /dev/null +++ b/snippets/Telerik.WinControls.UI.Snippets/Common/Common.csproj @@ -0,0 +1,15 @@ + + + + WinExe + net10.0-windows + enable + true + enable + + + + + + + \ No newline at end of file diff --git a/snippets/Telerik.WinControls.UI.Snippets/Common/Form1.Designer.cs b/snippets/Telerik.WinControls.UI.Snippets/Common/Form1.Designer.cs new file mode 100644 index 000000000..6a9c6409b --- /dev/null +++ b/snippets/Telerik.WinControls.UI.Snippets/Common/Form1.Designer.cs @@ -0,0 +1,59 @@ +namespace Common +{ + partial class Form1 + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + radaiPrompt1 = new Telerik.WinControls.UI.RadAIPrompt(); + ((System.ComponentModel.ISupportInitialize)radaiPrompt1).BeginInit(); + SuspendLayout(); + // + // radaiPrompt1 + // + radaiPrompt1.Location = new Point(13, 13); + radaiPrompt1.Margin = new Padding(4, 4, 4, 4); + radaiPrompt1.Name = "radaiPrompt1"; + radaiPrompt1.Size = new Size(500, 450); + radaiPrompt1.TabIndex = 0; + // + // Form1 + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(904, 588); + Controls.Add(radaiPrompt1); + Name = "Form1"; + Text = "Form1"; + ((System.ComponentModel.ISupportInitialize)radaiPrompt1).EndInit(); + ResumeLayout(false); + } + + #endregion + + private Telerik.WinControls.UI.RadAIPrompt radaiPrompt1; + } +} diff --git a/snippets/Telerik.WinControls.UI.Snippets/Common/Form1.cs b/snippets/Telerik.WinControls.UI.Snippets/Common/Form1.cs new file mode 100644 index 000000000..406a64290 --- /dev/null +++ b/snippets/Telerik.WinControls.UI.Snippets/Common/Form1.cs @@ -0,0 +1,26 @@ +using Telerik.WinControls.UI.AIPrompt; + +namespace Common +{ + public partial class Form1 : Form + { + public Form1() + { + InitializeComponent(); + } + + // >> aiprompt-getting-started-promptrequest + private void RadAIPrompt1_PromptRequest(object sender, Telerik.WinControls.UI.AIPrompt.PromptRequestEventArgs e) + { + AIPromptOutputItem responseAIPromptOutputItemModel = new AIPromptOutputItem() + { + Title = "Response from your AI model", + InputText = e.InputText, + ResponseText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", // Here you can set the string value returned from your AI model + }; + + this.radaiPrompt1.OutputItems.Add(responseAIPromptOutputItemModel); + } + // << aiprompt-getting-started-promptrequest + } +} diff --git a/snippets/Telerik.WinControls.UI.Snippets/Common/Form1.resx b/snippets/Telerik.WinControls.UI.Snippets/Common/Form1.resx new file mode 100644 index 000000000..8b2ff64a1 --- /dev/null +++ b/snippets/Telerik.WinControls.UI.Snippets/Common/Form1.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/snippets/Telerik.WinControls.UI.Snippets/Common/Program.cs b/snippets/Telerik.WinControls.UI.Snippets/Common/Program.cs new file mode 100644 index 000000000..225f67593 --- /dev/null +++ b/snippets/Telerik.WinControls.UI.Snippets/Common/Program.cs @@ -0,0 +1,17 @@ +namespace Common +{ + internal static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + // To customize application configuration such as set high DPI settings or default font, + // see https://aka.ms/applicationconfiguration. + ApplicationConfiguration.Initialize(); + Application.Run(new Form1()); + } + } +} \ No newline at end of file diff --git a/snippets/Telerik.WinControls.UI.Snippets/NuGet.config b/snippets/Telerik.WinControls.UI.Snippets/NuGet.config new file mode 100644 index 000000000..a8f279a55 --- /dev/null +++ b/snippets/Telerik.WinControls.UI.Snippets/NuGet.config @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/snippets/Telerik.WinControls.UI.Snippets/Telerik.WinControls.UI.Snippets.slnx b/snippets/Telerik.WinControls.UI.Snippets/Telerik.WinControls.UI.Snippets.slnx new file mode 100644 index 000000000..fe93bce8c --- /dev/null +++ b/snippets/Telerik.WinControls.UI.Snippets/Telerik.WinControls.UI.Snippets.slnx @@ -0,0 +1,3 @@ + + + From a0f0f3f3f027e51662974d61e8c6258df7decf95 Mon Sep 17 00:00:00 2001 From: Dinko Krastev Date: Wed, 8 Apr 2026 15:41:46 +0300 Subject: [PATCH 02/12] Update C# and add VB --- controls/aiprompt/getting-started.md | 15 +-- .../Common.VB/ApplicationEvents.vb | 29 +++++ .../Common.VB/Common.VB.vbproj | 42 ++++++ .../Common.VB/Common.VB.vbproj.user | 8 ++ .../Common.VB/Form1.Designer.vb | 51 ++++++++ .../Common.VB/Form1.resx | 120 ++++++++++++++++++ .../Common.VB/Form1.vb | 16 +++ .../My Project/Application.Designer.vb | 34 +++++ .../Common.VB/My Project/Application.myapp | 10 ++ .../Common/{Common.csproj => CommonC#.csproj} | 0 .../Telerik.WinControls.UI.Snippets.slnx | 3 +- 11 files changed, 313 insertions(+), 15 deletions(-) create mode 100644 snippets/Telerik.WinControls.UI.Snippets/Common.VB/ApplicationEvents.vb create mode 100644 snippets/Telerik.WinControls.UI.Snippets/Common.VB/Common.VB.vbproj create mode 100644 snippets/Telerik.WinControls.UI.Snippets/Common.VB/Common.VB.vbproj.user create mode 100644 snippets/Telerik.WinControls.UI.Snippets/Common.VB/Form1.Designer.vb create mode 100644 snippets/Telerik.WinControls.UI.Snippets/Common.VB/Form1.resx create mode 100644 snippets/Telerik.WinControls.UI.Snippets/Common.VB/Form1.vb create mode 100644 snippets/Telerik.WinControls.UI.Snippets/Common.VB/My Project/Application.Designer.vb create mode 100644 snippets/Telerik.WinControls.UI.Snippets/Common.VB/My Project/Application.myapp rename snippets/Telerik.WinControls.UI.Snippets/Common/{Common.csproj => CommonC#.csproj} (100%) diff --git a/controls/aiprompt/getting-started.md b/controls/aiprompt/getting-started.md index d506d1b9d..31a984598 100644 --- a/controls/aiprompt/getting-started.md +++ b/controls/aiprompt/getting-started.md @@ -45,22 +45,9 @@ Follow the steps: You can create a new __AIPromptOutputItem__ instance and fill it with returned response from the AI model. Then, you can populate the __OutputItems__ collection of RadAIPrompt. This will create a new AIPromptOutputVisualItem in the Output view where you can interact with the response. -````C# - -```` -````VB.NET -Private Sub RadAIPrompt1_PromptRequest(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.AIPrompt.PromptRequestEventArgs) - Dim responseAIPromptOutputItemModel As AIPromptOutputItem = New AIPromptOutputItem() With { - .Title = "Response from your AI model", - .InputText = e.InputText, - .ResponseText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." - } - Me.radAIPrompt1.OutputItems.Add(responseAIPromptOutputItemModel) -End Sub - -```` + ## User Interaction diff --git a/snippets/Telerik.WinControls.UI.Snippets/Common.VB/ApplicationEvents.vb b/snippets/Telerik.WinControls.UI.Snippets/Common.VB/ApplicationEvents.vb new file mode 100644 index 000000000..d28316024 --- /dev/null +++ b/snippets/Telerik.WinControls.UI.Snippets/Common.VB/ApplicationEvents.vb @@ -0,0 +1,29 @@ +Imports Microsoft.VisualBasic.ApplicationServices + +Namespace My + ' The following events are available for MyApplication: + ' Startup: Raised when the application starts, before the startup form is created. + ' Shutdown: Raised after all application forms are closed. This event is not raised if the application terminates abnormally. + ' UnhandledException: Raised if the application encounters an unhandled exception. + ' StartupNextInstance: Raised when launching a single-instance application and the application is already active. + ' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected. + + ' **NEW** ApplyApplicationDefaults: Raised when the application queries default values to be set for the application. + + ' Example: + ' Private Sub MyApplication_ApplyApplicationDefaults(sender As Object, e As ApplyApplicationDefaultsEventArgs) Handles Me.ApplyApplicationDefaults + ' + ' ' Setting the application-wide default Font: + ' e.Font = New Font(FontFamily.GenericSansSerif, 12, FontStyle.Regular) + ' + ' ' Setting the HighDpiMode for the Application: + ' e.HighDpiMode = HighDpiMode.PerMonitorV2 + ' + ' ' If a splash dialog is used, this sets the minimum display time: + ' e.MinimumSplashScreenDisplayTime = 4000 + ' End Sub + + Partial Friend Class MyApplication + + End Class +End Namespace diff --git a/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Common.VB.vbproj b/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Common.VB.vbproj new file mode 100644 index 000000000..fe44d9fbd --- /dev/null +++ b/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Common.VB.vbproj @@ -0,0 +1,42 @@ + + + + WinExe + net10.0-windows + Sub Main + true + WindowsForms + + + + + + + + + + + + + + + ..\..\..\..\..\..\.nuget\packages\ui.for.winforms.common\2026.1.210\lib\net9.0-windows\Telerik.WinControls.UI.dll + + + + + + True + True + Application.myapp + + + + + + MyApplicationCodeGenerator + Application.Designer.vb + + + + \ No newline at end of file diff --git a/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Common.VB.vbproj.user b/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Common.VB.vbproj.user new file mode 100644 index 000000000..370ab9918 --- /dev/null +++ b/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Common.VB.vbproj.user @@ -0,0 +1,8 @@ + + + + + Form + + + diff --git a/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Form1.Designer.vb b/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Form1.Designer.vb new file mode 100644 index 000000000..de4f84419 --- /dev/null +++ b/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Form1.Designer.vb @@ -0,0 +1,51 @@ + +Partial Class Form1 + Inherits System.Windows.Forms.Form + + 'Form overrides dispose to clean up the component list. + + Protected Overrides Sub Dispose(disposing As Boolean) + Try + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + Finally + MyBase.Dispose(disposing) + End Try + End Sub + + 'Required by the Windows Form Designer + Private components As System.ComponentModel.IContainer + + 'NOTE: The following procedure is required by the Windows Form Designer + 'It can be modified using the Windows Form Designer. + 'Do not modify it using the code editor. + + Private Sub InitializeComponent() + RadaiPrompt1 = New Telerik.WinControls.UI.RadAIPrompt() + CType(RadaiPrompt1, ComponentModel.ISupportInitialize).BeginInit() + SuspendLayout() + ' + ' RadaiPrompt1 + ' + RadaiPrompt1.Location = New Point(18, 14) + RadaiPrompt1.Margin = New Padding(4, 4, 4, 4) + RadaiPrompt1.Name = "RadaiPrompt1" + RadaiPrompt1.Size = New Size(500, 450) + RadaiPrompt1.TabIndex = 0 + ' + ' Form1 + ' + AutoScaleDimensions = New SizeF(8F, 20F) + AutoScaleMode = AutoScaleMode.Font + ClientSize = New Size(800, 450) + Controls.Add(RadaiPrompt1) + Name = "Form1" + Text = "Form1" + CType(RadaiPrompt1, ComponentModel.ISupportInitialize).EndInit() + ResumeLayout(False) + End Sub + + Friend WithEvents RadaiPrompt1 As Telerik.WinControls.UI.RadAIPrompt + +End Class diff --git a/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Form1.resx b/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Form1.resx new file mode 100644 index 000000000..8b2ff64a1 --- /dev/null +++ b/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Form1.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Form1.vb b/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Form1.vb new file mode 100644 index 000000000..13761973b --- /dev/null +++ b/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Form1.vb @@ -0,0 +1,16 @@ +Imports Telerik.WinControls.UI.AIPrompt + +Public Class Form1 + + '// >> aiprompt-getting-started-promptrequest-vb + Private Sub RadAIPrompt1_PromptRequest(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.AIPrompt.PromptRequestEventArgs) + Dim responseAIPromptOutputItemModel As AIPrompt OutputItem = New AIPromptOutputItem() With { + .Title = "Response from your AI model", + .InputText = e.InputText, + .ResponseText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." + } + Me.RadaiPrompt1.OutputItems.Add(responseAIPromptOutputItemModel) + End Sub + '// << aiprompt-getting-started-promptrequest-vb + +End Class diff --git a/snippets/Telerik.WinControls.UI.Snippets/Common.VB/My Project/Application.Designer.vb b/snippets/Telerik.WinControls.UI.Snippets/Common.VB/My Project/Application.Designer.vb new file mode 100644 index 000000000..1ca0d2252 --- /dev/null +++ b/snippets/Telerik.WinControls.UI.Snippets/Common.VB/My Project/Application.Designer.vb @@ -0,0 +1,34 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:4.0.30319.42000 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Namespace My + + 'NOTE: This file is auto-generated; do not modify it directly. To make changes, + ' or if you encounter build errors in this file, go to the Project Designer + ' (go to Project Properties or double-click the My Project node in + ' Solution Explorer), and make changes on the Application tab. + ' + Partial Friend Class MyApplication + + + Public Sub New() + MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows) + Me.IsSingleInstance = False + Me.EnableVisualStyles = True + Me.SaveMySettingsOnExit = True + Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses + End Sub + + + Protected Overrides Sub OnCreateMainForm() + Me.MainForm = Form1 + End Sub + End Class +End Namespace diff --git a/snippets/Telerik.WinControls.UI.Snippets/Common.VB/My Project/Application.myapp b/snippets/Telerik.WinControls.UI.Snippets/Common.VB/My Project/Application.myapp new file mode 100644 index 000000000..0f12f3238 --- /dev/null +++ b/snippets/Telerik.WinControls.UI.Snippets/Common.VB/My Project/Application.myapp @@ -0,0 +1,10 @@ + + + true + Form1 + false + 0 + true + 0 + true + \ No newline at end of file diff --git a/snippets/Telerik.WinControls.UI.Snippets/Common/Common.csproj b/snippets/Telerik.WinControls.UI.Snippets/Common/CommonC#.csproj similarity index 100% rename from snippets/Telerik.WinControls.UI.Snippets/Common/Common.csproj rename to snippets/Telerik.WinControls.UI.Snippets/Common/CommonC#.csproj diff --git a/snippets/Telerik.WinControls.UI.Snippets/Telerik.WinControls.UI.Snippets.slnx b/snippets/Telerik.WinControls.UI.Snippets/Telerik.WinControls.UI.Snippets.slnx index fe93bce8c..e09c120fa 100644 --- a/snippets/Telerik.WinControls.UI.Snippets/Telerik.WinControls.UI.Snippets.slnx +++ b/snippets/Telerik.WinControls.UI.Snippets/Telerik.WinControls.UI.Snippets.slnx @@ -1,3 +1,4 @@ - + + From 1e8e77f2975064f1108cc06b09a36b1ff4904e9c Mon Sep 17 00:00:00 2001 From: Dinko Krastev Date: Tue, 14 Apr 2026 16:58:10 +0300 Subject: [PATCH 03/12] Fix error --- .../Common.VB/Form1.vb | 2 +- .../My Project/Application.Designer.vb | 53 +++++++++++-------- 2 files changed, 33 insertions(+), 22 deletions(-) diff --git a/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Form1.vb b/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Form1.vb index 13761973b..a02486ad2 100644 --- a/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Form1.vb +++ b/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Form1.vb @@ -4,7 +4,7 @@ Public Class Form1 '// >> aiprompt-getting-started-promptrequest-vb Private Sub RadAIPrompt1_PromptRequest(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.AIPrompt.PromptRequestEventArgs) - Dim responseAIPromptOutputItemModel As AIPrompt OutputItem = New AIPromptOutputItem() With { + Dim responseAIPromptOutputItemModel As AIPromptOutputItem = New AIPromptOutputItem() With { .Title = "Response from your AI model", .InputText = e.InputText, .ResponseText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." diff --git a/snippets/Telerik.WinControls.UI.Snippets/Common.VB/My Project/Application.Designer.vb b/snippets/Telerik.WinControls.UI.Snippets/Common.VB/My Project/Application.Designer.vb index 1ca0d2252..51defbf28 100644 --- a/snippets/Telerik.WinControls.UI.Snippets/Common.VB/My Project/Application.Designer.vb +++ b/snippets/Telerik.WinControls.UI.Snippets/Common.VB/My Project/Application.Designer.vb @@ -8,27 +8,38 @@ ' '------------------------------------------------------------------------------ -Namespace My - - 'NOTE: This file is auto-generated; do not modify it directly. To make changes, - ' or if you encounter build errors in this file, go to the Project Designer - ' (go to Project Properties or double-click the My Project node in - ' Solution Explorer), and make changes on the Application tab. - ' - Partial Friend Class MyApplication +Option Strict On +Option Explicit On - - Public Sub New() - MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows) - Me.IsSingleInstance = False - Me.EnableVisualStyles = True - Me.SaveMySettingsOnExit = True - Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses - End Sub - - Protected Overrides Sub OnCreateMainForm() - Me.MainForm = Form1 - End Sub - End Class +Namespace My + + 'NOTE: This file is auto-generated; do not modify it directly. To make changes, + ' or if you encounter build errors in this file, go to the Project Designer + ' (go to Project Properties or double-click the My Project node in + ' Solution Explorer), and make changes on the Application tab. + ' + Partial Friend Class MyApplication + + _ + Public Sub New() + MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows) + Me.IsSingleInstance = false + Me.EnableVisualStyles = true + Me.SaveMySettingsOnExit = true + Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses + Me.HighDpiMode = HighDpiMode.DpiUnaware + End Sub + + _ + Protected Overrides Sub OnCreateMainForm() + Me.MainForm = Global.Common.VB.Form1 + End Sub + + _ + Protected Overrides Function OnInitialize(ByVal commandLineArgs As System.Collections.ObjectModel.ReadOnlyCollection(Of String)) As Boolean + Me.MinimumSplashScreenDisplayTime = 0 + Return MyBase.OnInitialize(commandLineArgs) + End Function + End Class End Namespace From b46f70fca502e464d63d8b0868959c908141cba6 Mon Sep 17 00:00:00 2001 From: Dinko Krastev Date: Mon, 20 Apr 2026 16:50:44 +0300 Subject: [PATCH 04/12] Create PowerShell to download code snippets from Azure --- .github/scripts/download-snippets.ps1 | 95 ++++++++++++++ .github/workflows/build-code-snippets.yml | 99 ++------------- controls/aiprompt/getting-started.md | 21 +-- .../Common.VB/ApplicationEvents.vb | 29 ----- .../Common.VB/Common.VB.vbproj | 42 ------ .../Common.VB/Common.VB.vbproj.user | 8 -- .../Common.VB/Form1.Designer.vb | 51 -------- .../Common.VB/Form1.resx | 120 ------------------ .../Common.VB/Form1.vb | 16 --- .../My Project/Application.Designer.vb | 45 ------- .../Common.VB/My Project/Application.myapp | 10 -- .../Common/CommonC#.csproj | 15 --- .../Common/Form1.Designer.cs | 59 --------- .../Common/Form1.cs | 26 ---- .../Common/Form1.resx | 120 ------------------ .../Common/Program.cs | 17 --- .../NuGet.config | 8 -- .../Telerik.WinControls.UI.Snippets.slnx | 4 - 18 files changed, 106 insertions(+), 679 deletions(-) create mode 100644 .github/scripts/download-snippets.ps1 delete mode 100644 snippets/Telerik.WinControls.UI.Snippets/Common.VB/ApplicationEvents.vb delete mode 100644 snippets/Telerik.WinControls.UI.Snippets/Common.VB/Common.VB.vbproj delete mode 100644 snippets/Telerik.WinControls.UI.Snippets/Common.VB/Common.VB.vbproj.user delete mode 100644 snippets/Telerik.WinControls.UI.Snippets/Common.VB/Form1.Designer.vb delete mode 100644 snippets/Telerik.WinControls.UI.Snippets/Common.VB/Form1.resx delete mode 100644 snippets/Telerik.WinControls.UI.Snippets/Common.VB/Form1.vb delete mode 100644 snippets/Telerik.WinControls.UI.Snippets/Common.VB/My Project/Application.Designer.vb delete mode 100644 snippets/Telerik.WinControls.UI.Snippets/Common.VB/My Project/Application.myapp delete mode 100644 snippets/Telerik.WinControls.UI.Snippets/Common/CommonC#.csproj delete mode 100644 snippets/Telerik.WinControls.UI.Snippets/Common/Form1.Designer.cs delete mode 100644 snippets/Telerik.WinControls.UI.Snippets/Common/Form1.cs delete mode 100644 snippets/Telerik.WinControls.UI.Snippets/Common/Form1.resx delete mode 100644 snippets/Telerik.WinControls.UI.Snippets/Common/Program.cs delete mode 100644 snippets/Telerik.WinControls.UI.Snippets/NuGet.config delete mode 100644 snippets/Telerik.WinControls.UI.Snippets/Telerik.WinControls.UI.Snippets.slnx diff --git a/.github/scripts/download-snippets.ps1 b/.github/scripts/download-snippets.ps1 new file mode 100644 index 000000000..8840f178b --- /dev/null +++ b/.github/scripts/download-snippets.ps1 @@ -0,0 +1,95 @@ + +$MyPat = $(GITHUB_TOKEN) +$PipelineName = "WinForms_Documentation_Code_CI" +$Branch = "main" +$ArtifactName_CS = "SamplesCS" +$ArtifactName_VB = "SamplesVB" +$Company = "prgs-devtools" +$Project = "DevTools" + +# Build Auth header + +#$B64Pat = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes(":$MyPat")) +$B64Pat = [Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$MyPat")) +$h = @{"Authorization" = "Basic " + $B64Pat} + +# Get build definition id +Write-Output ("https://dev.azure.com/$($Company)/$($Project)/_apis/build/definitions?name=$($PipelineName)&api-version=7.0") + +$response = Invoke-WebRequest -Uri "https://dev.azure.com/$($Company)/$($Project)/_apis/build/definitions?name=$($PipelineName)&api-version=7.0" -Method Get -Headers $h -UseBasicParsing + +if (( $? -eq $false ) -or ( $response.StatusCode -ne 200 )) +{ + if ($response.StatusCode -ne 200) + { + Write-Output (":| Error: " + $response.StatusCode) >> $LogFile + exit 1 + } + $msg = $Error[0].Exception.Message + Write-Output ":| $(Get-Date) Error: $($msg)" >> $LogFile +} + +$response_json = ($response.Content | ConvertFrom-Json) +$DefinitionId = $response_json.value.id + +# Get latest build id for named branch + +$response = Invoke-WebRequest -Uri "https://dev.azure.com/$($Company)/$($Project)/_apis/build/latest/$($DefinitionId)?branchName=$($Branch)&api-version=7.0-preview" -Method 'GET' -Headers $h -UseBasicParsing +if (( $? -eq $false ) -or ( $response.StatusCode -ne 200 )) +{ + if ($response.StatusCode -ne 200) + { + Write-Output (":| Error: " + $response.StatusCode) >> $LogFile + exit 1 + } + $msg = $Error[0].Exception.Message + Write-Output ":| $(Get-Date) Error: $($msg)" >> $LogFile +} +$response_json = ($response.Content | ConvertFrom-Json) +$BuildId = $response_json.id + +# Get latest named artifact + +$response = Invoke-WebRequest -Uri "https://dev.azure.com/$($Company)/$($Project)/_apis/build/builds/$($BuildId)/artifacts?artifactName=$($ArtifactName_CS)&api-version=7.0" -Method 'GET' -Headers $h -UseBasicParsing +if (( $? -eq $false ) -or ( $response.StatusCode -ne 200 )) +{ + if ($response.StatusCode -ne 200) + { + Write-Output (":| Error: " + $response.StatusCode) >> $LogFile + exit 1 + } + $msg = $Error[0].Exception.Message + Write-Output ":| $(Get-Date) Error: $($msg)" >> $LogFile +} +$response_json = ($response.Content | ConvertFrom-Json) +$response_json.resource.downloadUrl + +# Download latest named artifact + +# Download CS files + +$Download_CS = "..\..\snippets\SamplesCS.zip" +$response = Invoke-WebRequest -Uri $response_json.resource.downloadUrl -Method 'GET' -Headers $h -UseBasicParsing -OutFile "$($Download_CS)" + +if ( $? -eq $false ) +{ + $msg = $Error[0].Exception.Message + Write-Output ":| $(Get-Date) Error: $($msg)" >> $LogFile + exit 1 +} + +# Download VB files + +$Download_VB = "..\..\snippets\SamplesVB.zip" +$response = Invoke-WebRequest -Uri $response_json.resource.downloadUrl -Method 'GET' -Headers $h -UseBasicParsing -OutFile "$($Download_VB)" + +if ( $? -eq $false ) +{ + $msg = $Error[0].Exception.Message + Write-Output ":| $(Get-Date) Error: $($msg)" >> $LogFile + exit 1 +} + + +Expand-Archive -Path $Download_CS -DestinationPath "..\..\snippets" -Force +Expand-Archive -Path $Download_VB -DestinationPath "..\..\snippets" -Force diff --git a/.github/workflows/build-code-snippets.yml b/.github/workflows/build-code-snippets.yml index 32c1c2663..374d80698 100644 --- a/.github/workflows/build-code-snippets.yml +++ b/.github/workflows/build-code-snippets.yml @@ -1,102 +1,19 @@ -name: Build WinForms Solutions +name: Documentation Build on: - push: - paths: - - '**/*.md' - - 'snippets/**' - pull_request: - paths: - - '**/*.md' - - 'snippets/**' - workflow_dispatch: + workflow_dispatch: # manual trigger + # or: push: { branches: [main] } jobs: - build: + download-snippets: runs-on: windows-latest - steps: - - name: Checkout + - name: Checkout repo uses: actions/checkout@v4 - - name: Detect snippet or folder changes - id: snippet_check + - name: Download and extract artifacts shell: pwsh - run: | - git fetch --no-tags --prune --depth=0 origin - # Determine comparison base (works for push + PR) - if ("${{ github.event_name }}" -eq "pull_request") { - $base = "${{ github.event.pull_request.base.sha }}" - } else { - $base = "${{ github.event.before }}" - } - Write-Host "Comparing against $base" - $changedFiles = git diff --name-only $base HEAD - if (-not $changedFiles) { - echo "should_build=false" >> $env:GITHUB_OUTPUT - exit 0 - } - $shouldBuild = $false - foreach ($file in $changedFiles) { - Write-Host "Changed: $file" - # CONDITION 1: - # Any change inside /snippets folder - if ($file -like "snippets/*") { - Write-Host "Change inside snippets folder detected." - $shouldBuild = $true - break - } - # CONDITION 2: - # .md file with snippet tag added/modified - if ($file -like "*.md") { - $diff = git diff $base HEAD -- $file - if ($diff -match "> $env:GITHUB_OUTPUT - - name: Setup .NET 10 - if: steps.snippet_check.outputs.should_build == 'true' - uses: actions/setup-dotnet@v4 - with: - dotnet-version: '10.0.x' - - - name: Add Telerik NuGet source - if: steps.snippet_check.outputs.should_build == 'true' - shell: pwsh - run: | - dotnet nuget add source "https://nuget.telerik.com/v3/index.json" --name "Telerik NuGet Server" --username "api-key" --password $env:TELERIK_API_KEY --store-password-in-clear-text env: - TELERIK_API_KEY: ${{ secrets.TELERIK_API_KEY }} - - - name: Debug Telerik NuGet - if: steps.snippet_check.outputs.should_build == 'true' - shell: pwsh - run: | - Write-Host "TELERIK_API_KEY length: $($env:TELERIK_API_KEY.Length)" - dotnet nuget list source - - name: Restore & Build all solutions - if: steps.snippet_check.outputs.should_build == 'true' - shell: pwsh + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | - # Find both .sln and .slnx files - $solutions = Get-ChildItem "./snippets" -Recurse -Include *.sln,*.slnx -File - if (-not $solutions) { - Write-Error "No solution files (.sln or .slnx) found!" - exit 1 - } - foreach ($sln in $solutions) { - Write-Host "" - Write-Host "==============================" - Write-Host "Building $($sln.FullName)" - Write-Host "==============================" - dotnet restore "$($sln.FullName)" - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - dotnet build "$($sln.FullName)" ` - --configuration Release ` - --no-restore - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - } \ No newline at end of file + .\.github\scripts\download-snippets.ps1 \ No newline at end of file diff --git a/controls/aiprompt/getting-started.md b/controls/aiprompt/getting-started.md index 31a984598..8d80e6b4a 100644 --- a/controls/aiprompt/getting-started.md +++ b/controls/aiprompt/getting-started.md @@ -8,6 +8,7 @@ published: True position: 3 --- + # Getting Started with WinForms AIPrompt This article shows how you can start using RadAIPrompt. The following result will be achieved at the end of this tutorial: @@ -18,11 +19,7 @@ This article shows how you can start using RadAIPrompt. The following result wil ## Adding Telerik Assemblies Using NuGet -To use `RadAIPrompt` when working with NuGet packages, install the `Telerik.UI.for.WinForms.AllControls` package. The [package target framework version may vary]({%slug winforms-available-nugets%}). - -Read more about NuGet installation in the [Install using NuGet Packages]({%slug winforms/nuget%}) article. ->tip With the 2025 Q1 release, the Telerik UI for WinForms has a new licensing mechanism. You can learn more about it [here]({%slug license-key%}). ## Adding Assembly References Manually @@ -33,7 +30,7 @@ When dragging and dropping a control from the Visual Studio (VS) Toolbox onto th * __Telerik.WinControls.UI__ * __TelerikCommon__ -The Telerik UI for WinForms assemblies can be install by using one of the available [installation approaches]({%slug winforms/installation-deployment-and-distribution/installing-on-your-computer%}). + ## Defining the RadAIPrompt @@ -46,7 +43,7 @@ Follow the steps: You can create a new __AIPromptOutputItem__ instance and fill it with returned response from the AI model. Then, you can populate the __OutputItems__ collection of RadAIPrompt. This will create a new AIPromptOutputVisualItem in the Output view where you can interact with the response. - + ## User Interaction @@ -73,16 +70,4 @@ End Sub ```` -## Telerik UI for WinForms Learning Resources -* [Telerik UI for WinForms AIPrompt Component](https://www.telerik.com/products/winforms/aiprompt.aspx) -* [Getting Started with Telerik UI for WinForms Components](https://docs.telerik.com/devtools/winforms/getting-started/first-steps) -* [Telerik UI for WinForms Setup](https://docs.telerik.com/devtools/winforms/installation-and-upgrades/installing-on-your-computer) -* [Telerik UI for WinForms Application Modernization](https://docs.telerik.com/devtools/winforms/winforms-converter/overview) -* [Telerik UI for WinForms Visual Studio Templates](https://docs.telerik.com/devtools/winforms/visual-studio-integration/visual-studio-templates) -* [Deploy Telerik UI for WinForms Applications](https://docs.telerik.com/devtools/winforms/deployment-and-distribution/application-deployment) -* [Telerik UI for WinForms Virtual Classroom(Training Courses for Registered Users)](https://learn.telerik.com/learn/course/external/view/elearning/17/telerik-ui-for-winforms) -* [Telerik UI for WinForms License Agreement)](https://www.telerik.com/purchase/license-agreement/winforms-dlw-s) - -## See Also -* [AIPrompt Button]({%slug aiprompt-prompt-button%}) diff --git a/snippets/Telerik.WinControls.UI.Snippets/Common.VB/ApplicationEvents.vb b/snippets/Telerik.WinControls.UI.Snippets/Common.VB/ApplicationEvents.vb deleted file mode 100644 index d28316024..000000000 --- a/snippets/Telerik.WinControls.UI.Snippets/Common.VB/ApplicationEvents.vb +++ /dev/null @@ -1,29 +0,0 @@ -Imports Microsoft.VisualBasic.ApplicationServices - -Namespace My - ' The following events are available for MyApplication: - ' Startup: Raised when the application starts, before the startup form is created. - ' Shutdown: Raised after all application forms are closed. This event is not raised if the application terminates abnormally. - ' UnhandledException: Raised if the application encounters an unhandled exception. - ' StartupNextInstance: Raised when launching a single-instance application and the application is already active. - ' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected. - - ' **NEW** ApplyApplicationDefaults: Raised when the application queries default values to be set for the application. - - ' Example: - ' Private Sub MyApplication_ApplyApplicationDefaults(sender As Object, e As ApplyApplicationDefaultsEventArgs) Handles Me.ApplyApplicationDefaults - ' - ' ' Setting the application-wide default Font: - ' e.Font = New Font(FontFamily.GenericSansSerif, 12, FontStyle.Regular) - ' - ' ' Setting the HighDpiMode for the Application: - ' e.HighDpiMode = HighDpiMode.PerMonitorV2 - ' - ' ' If a splash dialog is used, this sets the minimum display time: - ' e.MinimumSplashScreenDisplayTime = 4000 - ' End Sub - - Partial Friend Class MyApplication - - End Class -End Namespace diff --git a/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Common.VB.vbproj b/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Common.VB.vbproj deleted file mode 100644 index fe44d9fbd..000000000 --- a/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Common.VB.vbproj +++ /dev/null @@ -1,42 +0,0 @@ - - - - WinExe - net10.0-windows - Sub Main - true - WindowsForms - - - - - - - - - - - - - - - ..\..\..\..\..\..\.nuget\packages\ui.for.winforms.common\2026.1.210\lib\net9.0-windows\Telerik.WinControls.UI.dll - - - - - - True - True - Application.myapp - - - - - - MyApplicationCodeGenerator - Application.Designer.vb - - - - \ No newline at end of file diff --git a/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Common.VB.vbproj.user b/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Common.VB.vbproj.user deleted file mode 100644 index 370ab9918..000000000 --- a/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Common.VB.vbproj.user +++ /dev/null @@ -1,8 +0,0 @@ - - - - - Form - - - diff --git a/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Form1.Designer.vb b/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Form1.Designer.vb deleted file mode 100644 index de4f84419..000000000 --- a/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Form1.Designer.vb +++ /dev/null @@ -1,51 +0,0 @@ - -Partial Class Form1 - Inherits System.Windows.Forms.Form - - 'Form overrides dispose to clean up the component list. - - Protected Overrides Sub Dispose(disposing As Boolean) - Try - If disposing AndAlso components IsNot Nothing Then - components.Dispose() - End If - Finally - MyBase.Dispose(disposing) - End Try - End Sub - - 'Required by the Windows Form Designer - Private components As System.ComponentModel.IContainer - - 'NOTE: The following procedure is required by the Windows Form Designer - 'It can be modified using the Windows Form Designer. - 'Do not modify it using the code editor. - - Private Sub InitializeComponent() - RadaiPrompt1 = New Telerik.WinControls.UI.RadAIPrompt() - CType(RadaiPrompt1, ComponentModel.ISupportInitialize).BeginInit() - SuspendLayout() - ' - ' RadaiPrompt1 - ' - RadaiPrompt1.Location = New Point(18, 14) - RadaiPrompt1.Margin = New Padding(4, 4, 4, 4) - RadaiPrompt1.Name = "RadaiPrompt1" - RadaiPrompt1.Size = New Size(500, 450) - RadaiPrompt1.TabIndex = 0 - ' - ' Form1 - ' - AutoScaleDimensions = New SizeF(8F, 20F) - AutoScaleMode = AutoScaleMode.Font - ClientSize = New Size(800, 450) - Controls.Add(RadaiPrompt1) - Name = "Form1" - Text = "Form1" - CType(RadaiPrompt1, ComponentModel.ISupportInitialize).EndInit() - ResumeLayout(False) - End Sub - - Friend WithEvents RadaiPrompt1 As Telerik.WinControls.UI.RadAIPrompt - -End Class diff --git a/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Form1.resx b/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Form1.resx deleted file mode 100644 index 8b2ff64a1..000000000 --- a/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Form1.resx +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Form1.vb b/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Form1.vb deleted file mode 100644 index a02486ad2..000000000 --- a/snippets/Telerik.WinControls.UI.Snippets/Common.VB/Form1.vb +++ /dev/null @@ -1,16 +0,0 @@ -Imports Telerik.WinControls.UI.AIPrompt - -Public Class Form1 - - '// >> aiprompt-getting-started-promptrequest-vb - Private Sub RadAIPrompt1_PromptRequest(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.AIPrompt.PromptRequestEventArgs) - Dim responseAIPromptOutputItemModel As AIPromptOutputItem = New AIPromptOutputItem() With { - .Title = "Response from your AI model", - .InputText = e.InputText, - .ResponseText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." - } - Me.RadaiPrompt1.OutputItems.Add(responseAIPromptOutputItemModel) - End Sub - '// << aiprompt-getting-started-promptrequest-vb - -End Class diff --git a/snippets/Telerik.WinControls.UI.Snippets/Common.VB/My Project/Application.Designer.vb b/snippets/Telerik.WinControls.UI.Snippets/Common.VB/My Project/Application.Designer.vb deleted file mode 100644 index 51defbf28..000000000 --- a/snippets/Telerik.WinControls.UI.Snippets/Common.VB/My Project/Application.Designer.vb +++ /dev/null @@ -1,45 +0,0 @@ -'------------------------------------------------------------------------------ -' -' This code was generated by a tool. -' Runtime Version:4.0.30319.42000 -' -' Changes to this file may cause incorrect behavior and will be lost if -' the code is regenerated. -' -'------------------------------------------------------------------------------ - -Option Strict On -Option Explicit On - - -Namespace My - - 'NOTE: This file is auto-generated; do not modify it directly. To make changes, - ' or if you encounter build errors in this file, go to the Project Designer - ' (go to Project Properties or double-click the My Project node in - ' Solution Explorer), and make changes on the Application tab. - ' - Partial Friend Class MyApplication - - _ - Public Sub New() - MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows) - Me.IsSingleInstance = false - Me.EnableVisualStyles = true - Me.SaveMySettingsOnExit = true - Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses - Me.HighDpiMode = HighDpiMode.DpiUnaware - End Sub - - _ - Protected Overrides Sub OnCreateMainForm() - Me.MainForm = Global.Common.VB.Form1 - End Sub - - _ - Protected Overrides Function OnInitialize(ByVal commandLineArgs As System.Collections.ObjectModel.ReadOnlyCollection(Of String)) As Boolean - Me.MinimumSplashScreenDisplayTime = 0 - Return MyBase.OnInitialize(commandLineArgs) - End Function - End Class -End Namespace diff --git a/snippets/Telerik.WinControls.UI.Snippets/Common.VB/My Project/Application.myapp b/snippets/Telerik.WinControls.UI.Snippets/Common.VB/My Project/Application.myapp deleted file mode 100644 index 0f12f3238..000000000 --- a/snippets/Telerik.WinControls.UI.Snippets/Common.VB/My Project/Application.myapp +++ /dev/null @@ -1,10 +0,0 @@ - - - true - Form1 - false - 0 - true - 0 - true - \ No newline at end of file diff --git a/snippets/Telerik.WinControls.UI.Snippets/Common/CommonC#.csproj b/snippets/Telerik.WinControls.UI.Snippets/Common/CommonC#.csproj deleted file mode 100644 index 742751b32..000000000 --- a/snippets/Telerik.WinControls.UI.Snippets/Common/CommonC#.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - - WinExe - net10.0-windows - enable - true - enable - - - - - - - \ No newline at end of file diff --git a/snippets/Telerik.WinControls.UI.Snippets/Common/Form1.Designer.cs b/snippets/Telerik.WinControls.UI.Snippets/Common/Form1.Designer.cs deleted file mode 100644 index 6a9c6409b..000000000 --- a/snippets/Telerik.WinControls.UI.Snippets/Common/Form1.Designer.cs +++ /dev/null @@ -1,59 +0,0 @@ -namespace Common -{ - partial class Form1 - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - radaiPrompt1 = new Telerik.WinControls.UI.RadAIPrompt(); - ((System.ComponentModel.ISupportInitialize)radaiPrompt1).BeginInit(); - SuspendLayout(); - // - // radaiPrompt1 - // - radaiPrompt1.Location = new Point(13, 13); - radaiPrompt1.Margin = new Padding(4, 4, 4, 4); - radaiPrompt1.Name = "radaiPrompt1"; - radaiPrompt1.Size = new Size(500, 450); - radaiPrompt1.TabIndex = 0; - // - // Form1 - // - AutoScaleDimensions = new SizeF(8F, 20F); - AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(904, 588); - Controls.Add(radaiPrompt1); - Name = "Form1"; - Text = "Form1"; - ((System.ComponentModel.ISupportInitialize)radaiPrompt1).EndInit(); - ResumeLayout(false); - } - - #endregion - - private Telerik.WinControls.UI.RadAIPrompt radaiPrompt1; - } -} diff --git a/snippets/Telerik.WinControls.UI.Snippets/Common/Form1.cs b/snippets/Telerik.WinControls.UI.Snippets/Common/Form1.cs deleted file mode 100644 index 406a64290..000000000 --- a/snippets/Telerik.WinControls.UI.Snippets/Common/Form1.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Telerik.WinControls.UI.AIPrompt; - -namespace Common -{ - public partial class Form1 : Form - { - public Form1() - { - InitializeComponent(); - } - - // >> aiprompt-getting-started-promptrequest - private void RadAIPrompt1_PromptRequest(object sender, Telerik.WinControls.UI.AIPrompt.PromptRequestEventArgs e) - { - AIPromptOutputItem responseAIPromptOutputItemModel = new AIPromptOutputItem() - { - Title = "Response from your AI model", - InputText = e.InputText, - ResponseText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", // Here you can set the string value returned from your AI model - }; - - this.radaiPrompt1.OutputItems.Add(responseAIPromptOutputItemModel); - } - // << aiprompt-getting-started-promptrequest - } -} diff --git a/snippets/Telerik.WinControls.UI.Snippets/Common/Form1.resx b/snippets/Telerik.WinControls.UI.Snippets/Common/Form1.resx deleted file mode 100644 index 8b2ff64a1..000000000 --- a/snippets/Telerik.WinControls.UI.Snippets/Common/Form1.resx +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/snippets/Telerik.WinControls.UI.Snippets/Common/Program.cs b/snippets/Telerik.WinControls.UI.Snippets/Common/Program.cs deleted file mode 100644 index 225f67593..000000000 --- a/snippets/Telerik.WinControls.UI.Snippets/Common/Program.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace Common -{ - internal static class Program - { - /// - /// The main entry point for the application. - /// - [STAThread] - static void Main() - { - // To customize application configuration such as set high DPI settings or default font, - // see https://aka.ms/applicationconfiguration. - ApplicationConfiguration.Initialize(); - Application.Run(new Form1()); - } - } -} \ No newline at end of file diff --git a/snippets/Telerik.WinControls.UI.Snippets/NuGet.config b/snippets/Telerik.WinControls.UI.Snippets/NuGet.config deleted file mode 100644 index a8f279a55..000000000 --- a/snippets/Telerik.WinControls.UI.Snippets/NuGet.config +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/snippets/Telerik.WinControls.UI.Snippets/Telerik.WinControls.UI.Snippets.slnx b/snippets/Telerik.WinControls.UI.Snippets/Telerik.WinControls.UI.Snippets.slnx deleted file mode 100644 index e09c120fa..000000000 --- a/snippets/Telerik.WinControls.UI.Snippets/Telerik.WinControls.UI.Snippets.slnx +++ /dev/null @@ -1,4 +0,0 @@ - - - - From 760d32f4f66898dac57569ac58cba919369a0461 Mon Sep 17 00:00:00 2001 From: Dinko Krastev Date: Mon, 20 Apr 2026 16:53:10 +0300 Subject: [PATCH 05/12] Reset the AIPrompt Getting Started article --- controls/aiprompt/getting-started.md | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/controls/aiprompt/getting-started.md b/controls/aiprompt/getting-started.md index 8d80e6b4a..2338d0e23 100644 --- a/controls/aiprompt/getting-started.md +++ b/controls/aiprompt/getting-started.md @@ -8,7 +8,6 @@ published: True position: 3 --- - # Getting Started with WinForms AIPrompt This article shows how you can start using RadAIPrompt. The following result will be achieved at the end of this tutorial: @@ -19,7 +18,11 @@ This article shows how you can start using RadAIPrompt. The following result wil ## Adding Telerik Assemblies Using NuGet +To use `RadAIPrompt` when working with NuGet packages, install the `Telerik.UI.for.WinForms.AllControls` package. The [package target framework version may vary]({%slug winforms-available-nugets%}). + +Read more about NuGet installation in the [Install using NuGet Packages]({%slug winforms/nuget%}) article. +>tip With the 2025 Q1 release, the Telerik UI for WinForms has a new licensing mechanism. You can learn more about it [here]({%slug license-key%}). ## Adding Assembly References Manually @@ -30,7 +33,7 @@ When dragging and dropping a control from the Visual Studio (VS) Toolbox onto th * __Telerik.WinControls.UI__ * __TelerikCommon__ - +The Telerik UI for WinForms assemblies can be install by using one of the available [installation approaches]({%slug winforms/installation-deployment-and-distribution/installing-on-your-computer%}). ## Defining the RadAIPrompt @@ -42,7 +45,6 @@ Follow the steps: You can create a new __AIPromptOutputItem__ instance and fill it with returned response from the AI model. Then, you can populate the __OutputItems__ collection of RadAIPrompt. This will create a new AIPromptOutputVisualItem in the Output view where you can interact with the response. - @@ -70,4 +72,16 @@ End Sub ```` +## Telerik UI for WinForms Learning Resources +* [Telerik UI for WinForms AIPrompt Component](https://www.telerik.com/products/winforms/aiprompt.aspx) +* [Getting Started with Telerik UI for WinForms Components](https://docs.telerik.com/devtools/winforms/getting-started/first-steps) +* [Telerik UI for WinForms Setup](https://docs.telerik.com/devtools/winforms/installation-and-upgrades/installing-on-your-computer) +* [Telerik UI for WinForms Application Modernization](https://docs.telerik.com/devtools/winforms/winforms-converter/overview) +* [Telerik UI for WinForms Visual Studio Templates](https://docs.telerik.com/devtools/winforms/visual-studio-integration/visual-studio-templates) +* [Deploy Telerik UI for WinForms Applications](https://docs.telerik.com/devtools/winforms/deployment-and-distribution/application-deployment) +* [Telerik UI for WinForms Virtual Classroom(Training Courses for Registered Users)](https://learn.telerik.com/learn/course/external/view/elearning/17/telerik-ui-for-winforms) +* [Telerik UI for WinForms License Agreement)](https://www.telerik.com/purchase/license-agreement/winforms-dlw-s) + +## See Also +* [AIPrompt Button]({%slug aiprompt-prompt-button%}) From 1ed1cbec9128661d41d558cdaefe427af22b5791 Mon Sep 17 00:00:00 2001 From: Dinko Krastev Date: Mon, 20 Apr 2026 17:28:27 +0300 Subject: [PATCH 06/12] Add Test MD file --- snippets/test.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 snippets/test.md diff --git a/snippets/test.md b/snippets/test.md new file mode 100644 index 000000000..e69de29bb From 157c6364f5a4114d04470a8ebd4072411a88d337 Mon Sep 17 00:00:00 2001 From: Dinko Krastev Date: Tue, 21 Apr 2026 10:38:39 +0300 Subject: [PATCH 07/12] Modify the build-code-snippets file to run on the main branch --- .github/workflows/build-code-snippets.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build-code-snippets.yml b/.github/workflows/build-code-snippets.yml index 374d80698..b1539c58b 100644 --- a/.github/workflows/build-code-snippets.yml +++ b/.github/workflows/build-code-snippets.yml @@ -2,7 +2,8 @@ name: Documentation Build on: workflow_dispatch: # manual trigger - # or: push: { branches: [main] } + push: + branches: [main] jobs: download-snippets: From 12645d5eea4a6f3662706e7ac23d6abf9050bbf1 Mon Sep 17 00:00:00 2001 From: Dinko Krastev Date: Wed, 22 Apr 2026 10:05:40 +0300 Subject: [PATCH 08/12] Update PowerShell --- .github/workflows/build-code-snippets.yml | 2 +- docfx/metadata-config.json | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build-code-snippets.yml b/.github/workflows/build-code-snippets.yml index b1539c58b..8b2d1245a 100644 --- a/.github/workflows/build-code-snippets.yml +++ b/.github/workflows/build-code-snippets.yml @@ -3,7 +3,7 @@ name: Documentation Build on: workflow_dispatch: # manual trigger push: - branches: [main] + branches: [master] jobs: download-snippets: diff --git a/docfx/metadata-config.json b/docfx/metadata-config.json index 8bde2f596..04f5441ff 100644 --- a/docfx/metadata-config.json +++ b/docfx/metadata-config.json @@ -3,8 +3,7 @@ "src": [ { "files": [ - "src/**.dll", - "src/**.XML" + ] } ], From 7f81724d981360a0ebf958db1692e1495dcf7617 Mon Sep 17 00:00:00 2001 From: Dinko Krastev Date: Wed, 22 Apr 2026 10:20:44 +0300 Subject: [PATCH 09/12] Remote XML for testing --- docfx/metadata-config.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docfx/metadata-config.json b/docfx/metadata-config.json index 04f5441ff..813990d87 100644 --- a/docfx/metadata-config.json +++ b/docfx/metadata-config.json @@ -3,7 +3,7 @@ "src": [ { "files": [ - + "src/**.dll" ] } ], From ffb74d4e8ff7e67ca0a58d737de8c351b21fae37 Mon Sep 17 00:00:00 2001 From: Dinko Krastev Date: Fri, 24 Apr 2026 16:49:18 +0300 Subject: [PATCH 10/12] Reset changes --- .github/scripts/download-snippets.ps1 | 95 ----------------------- .github/workflows/build-code-snippets.yml | 20 ----- .gitignore | 8 +- docfx/metadata-config.json | 3 +- 4 files changed, 3 insertions(+), 123 deletions(-) delete mode 100644 .github/scripts/download-snippets.ps1 delete mode 100644 .github/workflows/build-code-snippets.yml diff --git a/.github/scripts/download-snippets.ps1 b/.github/scripts/download-snippets.ps1 deleted file mode 100644 index 8840f178b..000000000 --- a/.github/scripts/download-snippets.ps1 +++ /dev/null @@ -1,95 +0,0 @@ - -$MyPat = $(GITHUB_TOKEN) -$PipelineName = "WinForms_Documentation_Code_CI" -$Branch = "main" -$ArtifactName_CS = "SamplesCS" -$ArtifactName_VB = "SamplesVB" -$Company = "prgs-devtools" -$Project = "DevTools" - -# Build Auth header - -#$B64Pat = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes(":$MyPat")) -$B64Pat = [Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$MyPat")) -$h = @{"Authorization" = "Basic " + $B64Pat} - -# Get build definition id -Write-Output ("https://dev.azure.com/$($Company)/$($Project)/_apis/build/definitions?name=$($PipelineName)&api-version=7.0") - -$response = Invoke-WebRequest -Uri "https://dev.azure.com/$($Company)/$($Project)/_apis/build/definitions?name=$($PipelineName)&api-version=7.0" -Method Get -Headers $h -UseBasicParsing - -if (( $? -eq $false ) -or ( $response.StatusCode -ne 200 )) -{ - if ($response.StatusCode -ne 200) - { - Write-Output (":| Error: " + $response.StatusCode) >> $LogFile - exit 1 - } - $msg = $Error[0].Exception.Message - Write-Output ":| $(Get-Date) Error: $($msg)" >> $LogFile -} - -$response_json = ($response.Content | ConvertFrom-Json) -$DefinitionId = $response_json.value.id - -# Get latest build id for named branch - -$response = Invoke-WebRequest -Uri "https://dev.azure.com/$($Company)/$($Project)/_apis/build/latest/$($DefinitionId)?branchName=$($Branch)&api-version=7.0-preview" -Method 'GET' -Headers $h -UseBasicParsing -if (( $? -eq $false ) -or ( $response.StatusCode -ne 200 )) -{ - if ($response.StatusCode -ne 200) - { - Write-Output (":| Error: " + $response.StatusCode) >> $LogFile - exit 1 - } - $msg = $Error[0].Exception.Message - Write-Output ":| $(Get-Date) Error: $($msg)" >> $LogFile -} -$response_json = ($response.Content | ConvertFrom-Json) -$BuildId = $response_json.id - -# Get latest named artifact - -$response = Invoke-WebRequest -Uri "https://dev.azure.com/$($Company)/$($Project)/_apis/build/builds/$($BuildId)/artifacts?artifactName=$($ArtifactName_CS)&api-version=7.0" -Method 'GET' -Headers $h -UseBasicParsing -if (( $? -eq $false ) -or ( $response.StatusCode -ne 200 )) -{ - if ($response.StatusCode -ne 200) - { - Write-Output (":| Error: " + $response.StatusCode) >> $LogFile - exit 1 - } - $msg = $Error[0].Exception.Message - Write-Output ":| $(Get-Date) Error: $($msg)" >> $LogFile -} -$response_json = ($response.Content | ConvertFrom-Json) -$response_json.resource.downloadUrl - -# Download latest named artifact - -# Download CS files - -$Download_CS = "..\..\snippets\SamplesCS.zip" -$response = Invoke-WebRequest -Uri $response_json.resource.downloadUrl -Method 'GET' -Headers $h -UseBasicParsing -OutFile "$($Download_CS)" - -if ( $? -eq $false ) -{ - $msg = $Error[0].Exception.Message - Write-Output ":| $(Get-Date) Error: $($msg)" >> $LogFile - exit 1 -} - -# Download VB files - -$Download_VB = "..\..\snippets\SamplesVB.zip" -$response = Invoke-WebRequest -Uri $response_json.resource.downloadUrl -Method 'GET' -Headers $h -UseBasicParsing -OutFile "$($Download_VB)" - -if ( $? -eq $false ) -{ - $msg = $Error[0].Exception.Message - Write-Output ":| $(Get-Date) Error: $($msg)" >> $LogFile - exit 1 -} - - -Expand-Archive -Path $Download_CS -DestinationPath "..\..\snippets" -Force -Expand-Archive -Path $Download_VB -DestinationPath "..\..\snippets" -Force diff --git a/.github/workflows/build-code-snippets.yml b/.github/workflows/build-code-snippets.yml deleted file mode 100644 index 8b2d1245a..000000000 --- a/.github/workflows/build-code-snippets.yml +++ /dev/null @@ -1,20 +0,0 @@ -name: Documentation Build - -on: - workflow_dispatch: # manual trigger - push: - branches: [master] - -jobs: - download-snippets: - runs-on: windows-latest - steps: - - name: Checkout repo - uses: actions/checkout@v4 - - - name: Download and extract artifacts - shell: pwsh - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - .\.github\scripts\download-snippets.ps1 \ No newline at end of file diff --git a/.gitignore b/.gitignore index d4081dcc4..1bced3123 100644 --- a/.gitignore +++ b/.gitignore @@ -77,10 +77,4 @@ SlugLog.log start-docs.sh start-docs.sh watch.sh -watch.sh -.suo -.baml -**/bin/ -**/obj/ -**/.vs/ -**.csproj.user +watch.sh diff --git a/docfx/metadata-config.json b/docfx/metadata-config.json index 813990d87..8bde2f596 100644 --- a/docfx/metadata-config.json +++ b/docfx/metadata-config.json @@ -3,7 +3,8 @@ "src": [ { "files": [ - "src/**.dll" + "src/**.dll", + "src/**.XML" ] } ], From 857dd9194fe04be2d5f987e7d17ef44cc0115088 Mon Sep 17 00:00:00 2001 From: Dinko Krastev Date: Fri, 24 Apr 2026 16:51:01 +0300 Subject: [PATCH 11/12] Remove test file --- snippets/test.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 snippets/test.md diff --git a/snippets/test.md b/snippets/test.md deleted file mode 100644 index e69de29bb..000000000 From 05dda544b56dbae65fa44470a2526497c87914a3 Mon Sep 17 00:00:00 2001 From: Dinko Krastev Date: Thu, 7 May 2026 19:16:36 +0300 Subject: [PATCH 12/12] MD Files: Update All files and replace their code snippets with corresponding ID from the documentation code solution. --- controls/aiprompt/getting-started.md | 25 +- controls/aiprompt/views.md | 62 +- controls/barcodeview/barcode-reader.md | 33 +- .../2d-barcodes/PDF417/settings.md | 30 +- .../2d-barcodes/QRCode/settings.md | 32 +- .../2d-barcodes/SwissQRCode/overview.md | 80 +- .../2d-barcodes/datamatrix/settings.md | 23 +- .../barcodeview/how-to/export-to-image.md | 36 +- .../customizing-radbindingnavigator.md | 44 +- controls/bindingnavigator/getting-started.md | 28 +- controls/breadcrumb/data-binding.md | 22 +- controls/breadcrumb/getting-started.md | 146 +-- .../accessing-and-customizing-elements.md | 29 +- .../html-like-text-formatting.md | 13 +- controls/buttons/button/getting-started.md | 51 +- controls/buttons/button/tooltips.md | 31 +- .../accessing-and-customizing-elements.md | 19 +- .../checkbox/databinding-radcheckbox.md | 30 +- controls/buttons/checkbox/getting-started.md | 28 +- .../checkbox/handling-radcheckbox-states.md | 21 +- controls/buttons/checkbox/tooltips.md | 31 +- .../accessing-and-customizing-elements.md | 25 +- .../buttons/dropdownbutton/getting-started.md | 85 +- .../buttons/dropdownbutton/key-shortcuts.md | 33 +- controls/buttons/dropdownbutton/tooltips.md | 50 +- .../working-with-raddropdownbutton-items.md | 88 +- controls/buttons/mnemonics.md | 13 +- .../accessing-and-customizing-elements.md | 17 +- .../radiobutton/designing-radradiobutton-.md | 28 +- .../buttons/radiobutton/getting-started.md | 37 +- .../handling-radradiobutton-states.md | 43 +- controls/buttons/radiobutton/tooltips.md | 31 +- .../accessing-and-customizing-elements.md | 27 +- controls/buttons/repeatbutton/tooltips.md | 37 +- .../working-with-radrepeatbutton.md | 50 +- .../accessing-and-customizing-elements.md | 23 +- .../splitbutton/right-to-left-support.md | 13 +- controls/buttons/splitbutton/tooltips.md | 50 +- .../working-with-radsplitbutton-items.md | 126 +- .../accessing-and-customizing-elements.md | 27 +- .../buttons/togglebutton/getting-started.md | 24 +- .../handling-radtogglebutton-states.md | 51 +- controls/buttons/togglebutton/tooltips.md | 35 +- .../accessing-and-customizing-elements.md | 40 +- .../buttons/toggleswitch/getting-started.md | 20 +- controls/buttons/toggleswitch/tooltips.md | 35 +- controls/calculator/calculationbehavior.md | 90 +- controls/calculator/custom-functions.md | 137 +-- controls/calculator/getting-started.md | 24 +- .../formatting-items.md | 48 +- .../customizing-appearance/using-templates.md | 25 +- .../customizing-zoom-navigation.md | 46 +- .../features/column-and-row-headers.md | 33 +- controls/calendar/features/footer.md | 14 +- controls/calendar/features/multiview-mode.md | 25 +- .../calendar/features/repeating-events.md | 25 +- controls/calendar/features/selecting-dates.md | 39 +- controls/calendar/getting-started.md | 36 +- .../cultureinfo-and-regioninfo-basics.md | 13 +- .../localization/globalization-properties.md | 13 +- .../localization/localization-provider.md | 57 +- .../properties-that-can-be-localized.md | 125 +- .../localization/right-to-left-support.md | 13 +- controls/callout/getting-started.md | 62 +- controls/callout/key-features.md | 20 +- controls/callout/shapes.md | 212 +--- controls/cardview/custom-items.md | 177 +-- .../formatting-items.md | 98 +- .../visual-data-representation.md | 53 +- controls/cardview/editors/overview.md | 57 +- .../cardview/editors/switching-editors.md | 50 +- controls/cardview/features/filtering.md | 28 +- controls/cardview/features/grouping.md | 31 +- controls/cardview/features/sorting.md | 28 +- .../populating-with-data/binding-to-data.md | 191 +-- .../populating-with-data/unbound-mode.md | 103 +- .../customizing-appearance.md | 15 +- controls/carousel/data-binding.md | 165 +-- controls/carousel/getting-started.md | 55 +- .../using-radcarousel/carousel-items.md | 58 +- .../using-radcarousel/carousel-path.md | 58 +- controls/chartview/axes/axes.md | 92 +- controls/chartview/axes/axis-alignment.md | 99 +- controls/chartview/axes/categorical.md | 34 +- controls/chartview/axes/datetime.md | 76 +- controls/chartview/axes/inverse-axis.md | 108 +- controls/chartview/axes/linear.md | 49 +- controls/chartview/axes/logarithmic.md | 38 +- controls/chartview/axes/multiple-axes.md | 209 +--- controls/chartview/axes/plot-mode.md | 65 +- controls/chartview/axes/polar.md | 47 +- controls/chartview/axes/radial.md | 93 +- controls/chartview/axes/scale-breaks.md | 58 +- .../modifying-the-default-context-menu.md | 52 +- .../customization/custom-labels-text.md | 138 +-- .../customization/custom-rendering.md | 382 +----- .../customization/formatting-series-labels.md | 56 +- .../formatting-trackball-labels.md | 55 +- controls/chartview/customization/palettes.md | 68 +- .../annotations/free-figure-annotation.md | 82 +- .../features/annotations/grid-line.md | 146 +-- .../features/annotations/marked-zone.md | 132 +-- .../features/annotations/plot-band.md | 118 +- controls/chartview/features/chart-grid.md | 98 +- controls/chartview/features/drill-down.md | 412 +------ controls/chartview/features/export.md | 18 +- .../chartview/features/lasso-selection.md | 137 +-- controls/chartview/features/lasso-zoom.md | 87 +- controls/chartview/features/legend.md | 197 +--- .../chartview/features/scroll-and-zoom.md | 78 +- controls/chartview/features/selection.md | 126 +- controls/chartview/features/smart-labels.md | 156 +-- controls/chartview/features/title.md | 32 +- controls/chartview/features/tooltip.md | 130 +-- controls/chartview/features/trackball.md | 93 +- controls/chartview/null-values-support-.md | 30 +- .../binding-to-bindinglist.md | 148 +-- .../binding-to-datatable.md | 46 +- .../chartview/printing-support/printing.md | 120 +- controls/chartview/series-types/area.md | 39 +- controls/chartview/series-types/bar.md | 60 +- controls/chartview/series-types/bezier.md | 35 +- controls/chartview/series-types/bubble.md | 45 +- controls/chartview/series-types/donut.md | 66 +- controls/chartview/series-types/fastline.md | 34 +- controls/chartview/series-types/funnel.md | 35 +- controls/chartview/series-types/hlc.md | 27 +- .../indicators/custom-indicators.md | 492 +------- .../series-types/indicators/indicators.md | 150 +-- controls/chartview/series-types/line.md | 38 +- .../series-types/ohlc-and-candlestick.md | 54 +- controls/chartview/series-types/pie.md | 66 +- controls/chartview/series-types/polar.md | 149 +-- .../chartview/series-types/radar-column.md | 72 +- controls/chartview/series-types/radar.md | 168 +-- .../series-types/range-and-rangebar.md | 66 +- controls/chartview/series-types/scatter.md | 69 +- .../chartview/series-types/scatterarea.md | 58 +- .../chartview/series-types/scatterline.md | 64 +- controls/chartview/series-types/stepline.md | 35 +- controls/chartview/series-types/watterfall.md | 98 +- controls/chat/chat-items/cards.md | 159 +-- controls/chat/chat-items/messages.md | 229 +--- controls/chat/chat-items/overlays.md | 95 +- controls/chat/chat-items/suggested-actions.md | 41 +- controls/chat/chatelementfactory.md | 152 +-- .../accessing-and-customizing-elements.md | 148 +-- .../customizing-appearance/custom-items.md | 181 +-- .../customizing-appearance/custom-overlays.md | 122 +- controls/chat/getting-started.md | 51 +- controls/chat/how-to/scroll-to-item.md | 6 +- controls/chat/localization/localization.md | 76 +- controls/chat/toolbar.md | 56 +- controls/checkedlistbox/data-biniding.md | 148 +-- controls/checkedlistbox/getting-started.md | 305 +---- .../accessing-and-customizing-elements.md | 15 +- controls/clock/getting-started.md | 38 +- controls/clock/tooltips.md | 35 +- .../accessing-and-customizing-elements.md | 26 +- controls/commandbar/floating-strips.md | 105 +- controls/commandbar/getting-started.md | 34 +- .../customize-the-control-context-menu.md | 50 +- .../how-to/customize-the-overflow-button.md | 52 +- .../prevent-the-control-from-gaining-focus.md | 40 +- .../commandbar/localization/localization.md | 70 +- .../localization/right-to-left-support.md | 16 +- controls/commandbar/save-and-load-layout.md | 103 +- .../customizing-appearance.md | 56 +- controls/dataentry/getting-started.md | 236 +--- .../how-to/change-auto-generated-editor.md | 258 +---- ...e-the-editor-to-a-bound-raddropdownlist.md | 317 +---- .../how-to/handle-unsupported-values.md | 75 +- .../programmatically-arrange-items-.md | 205 +--- .../properties-events-and-attributes.md | 245 +--- controls/dataentry/validation.md | 296 +---- .../custom-display-names.md | 28 +- .../formatting-nodes.md | 175 +-- controls/datafilter/datafilter-dialog.md | 25 +- controls/datafilter/editing/custom-editors.md | 144 +-- controls/datafilter/editing/events.md | 115 +- controls/datafilter/getting-started.md | 29 +- .../datafilter/localization/localization.md | 187 +-- controls/datafilter/save-load-filters.md | 38 +- .../data-binding.md | 25 +- .../descriptor-items.md | 33 +- .../unbound-mode.md | 32 +- ...e-the-editor-to-a-bound-raddropdownlist.md | 300 +---- .../customizing-appearance.md | 28 +- controls/datalayout/getting-started.md | 200 +--- controls/datalayout/localization.md | 208 +--- .../properties-events-and-attributes.md | 76 +- controls/datalayout/save-load-layout.md | 63 +- controls/datalayout/validation.md | 272 +---- controls/desktopalert/button-items.md | 49 +- .../accessing-and-customizing-elements.md | 39 +- controls/desktopalert/gettingstarted.md | 31 +- controls/diagram/background-grid.md | 70 +- controls/diagram/custom-shapes.md | 77 +- .../data-binding/binding-to-custom-objects.md | 628 +--------- .../data-binding/data-binding-basics.md | 103 +- controls/diagram/diagram-factory.md | 196 +--- .../diagram-items/connections/cap-types.md | 188 +-- .../connections/connection-types.md | 162 +-- .../diagram-items/connections/connections.md | 73 +- .../diagram/diagram-items/containershapes.md | 76 +- controls/diagram/diagram-items/shapes.md | 129 +-- controls/diagram/diagram-tools/text-tool.md | 15 +- .../drag-and-drop-from-another-control.md | 301 +---- .../drag-and-drop/ole-drag-and-drop.md | 133 +-- controls/diagram/features/commands.md | 38 +- controls/diagram/features/export.md | 17 +- controls/diagram/features/grouping.md | 170 +-- controls/diagram/features/layout.md | 87 +- controls/diagram/features/pan-and-zoom.md | 125 +- controls/diagram/features/printing-support.md | 32 +- controls/diagram/features/routing.md | 191 +-- .../diagram/features/save-and-load-layout.md | 61 +- controls/diagram/features/undo-and-redo.md | 46 +- controls/diagram/information-adorner.md | 95 +- .../clipboard-operations.md | 27 +- .../diagram/items-manipulation/editing.md | 74 +- .../items-manipulation/removing-items.md | 34 +- .../diagram/items-manipulation/resizing.md | 49 +- .../diagram/items-manipulation/rotation.md | 41 +- .../diagram/items-manipulation/selection.md | 127 +- controls/diagram/items-manipulation/zorder.md | 212 +--- controls/diagram/localization.md | 122 +- controls/diagram/populating-with-data.md | 136 +-- controls/diagram/settings-pane.md | 77 +- .../dockingguidestemplate.md | 85 +- .../document-manager.md | 64 +- .../floating-windows.md | 15 +- .../using-the-commandmanager.md | 114 +- .../using-the-contextmenuservice.md | 66 +- .../using-the-dragdropservice.md | 108 +- .../using-the-redockservice.md | 32 +- ...docking-a-usercontrol-with-custom-event.md | 83 +- .../docking-singleton-forms.md | 106 +- .../get-a-hostwindow-by-its-content.md | 47 +- .../getting-started.md | 25 +- controls/dock/getting-started.md | 95 +- .../loading-and-saving-layouts.md | 57 +- ...l-saving-and-loading-layout-and-content.md | 148 +-- controls/dock/localization/localization.md | 202 +--- .../localization/right-to-left-support.md | 15 +- .../mdi-mode/automatic-mdi-form-handling.md | 91 +- .../object-model/accessing-dockwindows.md | 38 +- .../dock/object-model/alloweddockstates.md | 30 +- .../creating-a-raddock-at-runtime.md | 27 +- ...oolwindow-and-documentwindow-at-runtime.md | 243 +--- .../customizing-floating-windows.md | 112 +- .../customizing-tabstrip-items.md | 233 +--- ...-building-an-advanced-layout-at-runtime.md | 165 +-- .../dock/object-model/tabs-and-captions.md | 92 +- ...d-documentwindow-properties-and-methods.md | 15 +- .../checkeddropdownlist/autocompletemodes.md | 13 +- .../accessing-and-customizing-elements.md | 27 +- .../customizing-appearance/customization.md | 96 +- .../checkeddropdownlist/getting-started.md | 20 +- .../how-to/add-non-existing-items.md | 47 +- .../how-to/use-as-radgridview-editor.md | 138 +-- .../adding-items-programmatically.md | 32 +- .../populating-with-data/data-binding.md | 144 +-- .../dropdownlist/animation-effects.md | 17 +- .../dropdownlist/custom-items.md | 244 +--- .../accessing-and-customizing-elements.md | 16 +- .../formatting-items.md | 76 +- .../dropdownlist/dropdown-resizing.md | 183 +-- .../dropdownlist/dropdownstyle.md | 110 +- .../dropdownlist/features/auto-complete.md | 171 +-- .../dropdownlist/features/filtering.md | 59 +- .../dropdownlist/features/scrolling.md | 90 +- .../dropdownlist/features/selection.md | 47 +- .../dropdownlist/features/sorting.md | 81 +- .../dropdownlist/getting-started.md | 32 +- .../dropdownlist/item-sizing.md | 104 +- .../adding-items-programmatically.md | 33 +- .../populating-with-data/data-binding.md | 73 +- .../dropdownlist/right-to-left-support.md | 15 +- .../fontdropdownlist/add-custom-fonts.md | 14 +- .../accessing-and-customizing-elements.md | 29 +- .../formatting-items.md | 58 +- .../fontdropdownlist/getting-started.md | 51 +- .../fontdropdownlist/localization.md | 20 +- .../update-recently-used-fonts.md | 7 +- .../formatting-items.md | 140 +-- .../customizing-items-(visual-appearance).md | 117 +- .../listcontrol/data-representation.md | 60 +- .../drag-and-drop-in-bound-mode.md | 260 +---- .../listcontroldragdropservice.md | 212 +--- .../listcontrol/features.md | 140 +-- .../listcontrol/features/filtering.md | 88 +- .../listcontrol/features/searching.md | 24 +- .../listcontrol/features/selection.md | 28 +- .../listcontrol/features/sorting.md | 12 +- .../listcontrol/getting-started.md | 23 +- .../adding-items-programmatically.md | 78 +- .../populating-with-data/databinding.md | 74 +- .../listcontrol/visual-data-representation.md | 73 +- .../editors/autocompletebox/auto-complete.md | 80 +- .../caret-positioning-and-selection.md | 42 +- .../autocompletebox/creating-custom-blocks.md | 96 +- .../formatting-blocks.md | 31 +- .../autocompletebox/getting-started.md | 31 +- .../editors/autocompletebox/text-editing.md | 94 +- .../accessing-and-customizing-elements.md | 16 +- controls/editors/browseeditor/dialog-types.md | 89 +- .../editors/browseeditor/getting-started.md | 18 +- .../working-with-radbrowseeditor.md | 24 +- .../accessing-and-customizing-elements.md | 28 +- .../adding-items-programmatically.md | 157 +-- .../accessing-and-customizing-elements.md | 60 +- .../calculatordropdown/getting-started.md | 17 +- controls/editors/colorbox/getting-started.md | 20 +- .../editors/colorbox/properies-and-events.md | 24 +- .../how-to/set-null-or-empty-value.md | 42 +- .../dateonlypicker/properties-events.md | 111 +- .../datetimepicker/MaskDateTimeProvider.md | 15 +- .../customize-radcalendar-programmatically.md | 64 +- .../free-form-date-time-parsing.md | 20 +- .../how-to/set-null-or-empty-value.md | 42 +- .../how-to/tweak-increment-step.md | 109 +- .../cultureinfo-and-regioninfo-basics.md | 13 +- .../internationalization/date-formats.md | 15 +- .../internationalization.md | 54 +- .../datetimepicker/navigation-modes.md | 13 +- .../raddatetimepicker-properties.md | 162 +-- .../accessing-and-customizing-elements.md | 3 - .../editors/domainupdown/getting-started.md | 3 - .../adding-items-programmatically.md | 3 - .../populating-with-data/data-binding.md | 3 - .../accessing-and-customizing-elements.md | 3 - .../maskededitbox/date-and-time-masks.md | 17 +- .../editors/maskededitbox/localization.md | 60 +- .../editors/maskededitbox/standard-masks.md | 15 +- .../maskededitbox/textmaskformat-property.md | 34 +- .../editors/maskededitbox/timespan-masks.md | 3 - .../working-with-radmaskededitbox.md | 18 +- .../editors/popupeditor/customize-elements.md | 52 +- .../editors/popupeditor/getting-started.md | 39 +- .../handling-popup-keyboard-input.md | 27 +- .../properties-events-and-methods.md | 27 +- .../editors/spineditor/getting-started.md | 18 +- .../editors/spineditor/null-value-support.md | 105 +- .../textbox/adding-buttons-to-radtextbox.md | 123 +- controls/editors/textbox/getting-started.md | 5 - .../editors/textbox/programming-radtextbox.md | 15 +- .../editors/textboxcontrol/autocomplete.md | 84 +- .../caret-positioning-and-selection.md | 49 +- .../textboxcontrol/creating-custom-blocks.md | 218 +--- .../formatting-blocks.md | 42 +- .../editors/textboxcontrol/getting-started.md | 85 +- .../editors/textboxcontrol/localization.md | 3 - controls/editors/textboxcontrol/properties.md | 17 +- .../editors/textboxcontrol/text-editing.md | 101 +- .../customizing-programatically.md | 6 - .../customizing-programatically.md | 184 +-- .../timepicker/free-form-date-time-parsing.md | 21 +- controls/editors/timepicker/localization.md | 66 +- .../customizing-appearance.md | 67 +- .../editors/timespanpicker/format-string.md | 12 +- .../editors/timespanpicker/getting-started.md | 12 +- .../editors/timespanpicker/localization.md | 64 +- .../dialog-controls/radopenfiledialog.md | 170 +-- .../dialog-controls/radopenfolderdialog.md | 92 +- .../dialog-controls/radsavefiledialog.md | 69 +- .../file-dialogs/features/context-menu.md | 40 +- .../file-dialogs/features/editing-options.md | 76 +- controls/file-dialogs/getting-started.md | 81 +- .../filter-view-changing-default-editors.md | 341 +----- .../filter-view-getting-started.md | 18 +- .../filter-view/filter-view-localization.md | 75 +- controls/filter-view/unbound_mode.md | 231 +--- .../colordialog/custom-colors.md | 34 +- .../colordialog/getting-started.md | 24 +- .../colordialog/localizattion.md | 89 +- .../colordialog/properties-methods-events.md | 33 +- .../form/accessing-radform-elements.md | 78 +- .../form/detect-theme-change.md | 44 +- controls/forms-and-dialogs/form/mdi.md | 51 +- controls/forms-and-dialogs/form/themes.md | 16 +- .../messagebox/getting-started.md | 40 +- .../messagebox/localization.md | 127 +- .../messagebox/parameters.md | 59 +- ...ing-when-the-user-drags-the-radtitlebar.md | 31 +- .../radtitlebar/help-button.md | 50 +- .../accessing-and-customizing-elements.md | 17 +- .../shapedform/customizing-shapedform.md | 13 +- .../shapedform/getting-started.md | 15 +- .../statusstrip/adding-items.md | 58 +- .../statusstrip/gettingstarted.md | 90 +- .../customizing-appearance.md | 12 +- .../tabbedform/features/context-menu.md | 43 +- .../tabbedform/features/drag-and-drop.md | 30 +- .../tabbedform/features/navigation.md | 13 +- .../tabbedform/features/pinned-tabs.md | 24 +- .../tabbedform/features/quick-actions.md | 14 +- .../tabbedform/features/tab-settings.md | 30 +- .../tabbedform/features/titlebar-style.md | 12 +- .../tabbedform/localization.md | 58 +- .../adding-items-programmatically.md | 138 +-- .../toolbarform/customizing-appearance.md | 21 +- .../toolbarform/features/item-alignment.md | 74 +- .../toolbarform/features/wrap-mode.md | 23 +- .../context-menu/data-item-context-menu.md | 35 +- .../context-menu/modifying-context-menu.md | 29 +- controls/ganttview/custom-items/data-cells.md | 217 +--- controls/ganttview/custom-items/data-items.md | 271 +---- .../ganttview/custom-items/task-elements.md | 187 +-- .../editing/creating-custom-editor.md | 131 +-- .../ganttview/editing/customizing-editor.md | 119 +- .../ganttview/formatting/custom-painting.md | 98 +- .../graphicalview-item-formatting.md | 33 +- .../graphicalview-link-item-formatting.md | 69 +- .../formatting/textview-item-formatting.md | 76 +- .../formatting/timeline-item-formatting.md | 54 +- controls/ganttview/integration.md | 35 +- controls/ganttview/localization.md | 128 +-- .../printing-support/printing-events.md | 98 +- .../ganttview/timeline/custom-timeline.md | 254 +--- controls/ganttview/timeline/timeline-views.md | 135 +-- controls/ganttview/today-indicator.md | 27 +- controls/ganttview/tooltip.md | 68 +- .../working-with-data/adding-new-items.md | 25 +- .../working-with-data/binding-to-database.md | 15 +- .../working-with-data/data-binding-basics.md | 115 +- .../importing-xml-from-ms-project.md | 295 +---- .../working-with-data/link-type-converter.md | 92 +- .../populating-with-data-programmatically.md | 175 +-- .../gauges/bulletgraph/getting-started.md | 48 +- .../bulletgraph/save-and-load-layout.md | 22 +- .../gauges/lineargauge/getting-started.md | 87 +- .../lineargauge/properties-and-events.md | 27 +- .../lineargauge/save-and-load-layout.md | 17 +- .../gauges/radialgauge/getting-started.md | 394 +------ .../radialgauge/properties-and-events.md | 84 +- .../radialgauge/save-and-load-layout.md | 23 +- controls/gridview/features/caption.md | 38 +- .../conditional-custom-context-menus.md | 85 +- .../context-menus/custom-context-menus.md | 56 +- .../modifying-the-default-context-menu.md | 66 +- controls/gridview/features/copy-paste-cut.md | 121 +- .../radgridviewdragdropservice.md | 55 +- ...-reordering-in-self-reference-hierarchy.md | 206 +--- .../editors/customizing-editor-behavior.md | 27 +- .../editing/editors/data-validation.md | 40 +- .../editing/editors/default-editors.md | 114 +- .../editors/handling-editors'-events.md | 64 +- ...sers-to-add-items-to-dropdownlisteditor.md | 192 +--- ...editor-depending-on-the-cell-value-type.md | 98 +- .../editing/editors/using-custom-editors.md | 185 +-- .../customizing-radexpressioneditor.md | 118 +- .../expression-editor/end-user-support.md | 42 +- .../expression-editor/expression-syntax.md | 35 +- .../expression-editor/functions-reference.md | 76 +- .../editing/expression-editor/localization.md | 130 +-- .../delete-using-controls-api.md | 65 +- .../validation.md | 36 +- .../export-data-in-a-group-to-excel.md | 178 +-- .../features/exporting-data/export-to-csv.md | 111 +- .../export-to-excel-via-excelml-format.md | 203 +--- .../features/exporting-data/export-to-pdf.md | 540 +-------- ...der-and-footer-to-the-exported-document.md | 128 +-- ...colum-width-and-row-height-with-excelml.md | 63 +- .../features/exporting-data/html-export.md | 196 +--- .../features/exporting-data/spread-export.md | 307 +---- .../exporting-data/spreadstream-export.md | 160 +-- .../exporting-data/troubleshooting.md | 35 +- .../filtering/How-To/filter-on-enter.md | 59 +- .../features/filtering/basic-filtering.md | 75 +- .../filtering/custom-filter-dialog.md | 26 +- .../features/filtering/custom-filtering.md | 129 +-- .../gridview/features/filtering/events.md | 83 +- .../filtering/excel-like-filtering.md | 117 +- .../filterexpressionchanged-event.md | 20 +- .../features/filtering/filtering-row.md | 30 +- ...er-cell-into-edit-mode-programmatically.md | 15 +- ...rogrammatically-(composite-descriptors).md | 90 +- ...s-programmatically-(simple-descriptors).md | 85 +- .../features/grouping/basic-grouping.md | 48 +- .../features/grouping/custom-grouping.md | 149 +-- controls/gridview/features/grouping/events.md | 73 +- .../grouping/formatting-group-header-row.md | 67 +- .../features/grouping/group-aggregates.md | 51 +- .../features/grouping/groups-collection.md | 97 +- .../setting-groups-programmatically.md | 66 +- .../features/grouping/sorting-group-rows.md | 67 +- .../grouping/using-grouping-expressions.md | 64 +- controls/gridview/features/merged-cells.md | 131 +-- .../events-and-customization.md | 88 +- .../printing-support/gridprintstyle.md | 59 +- .../printing-hierarchical-grid.md | 23 +- .../printing-support/printing-support.md | 32 +- .../features/save-and-load-layout/advanced.md | 108 +- .../save-and-load-layout.md | 70 +- .../gridview/features/scrolling/events.md | 36 +- .../features/scrolling/scroll-modes.md | 98 +- .../scrolling/scrolling-programmatically.md | 47 +- .../features/selection/basic-selection.md | 76 +- .../features/selection/multiple-selection.md | 34 +- ...lecting-rows-and-cells-programmatically.md | 136 +-- .../features/sorting/basic-sorting.md | 94 +- .../features/sorting/custom-sorting.md | 213 +--- controls/gridview/features/sorting/events.md | 76 +- .../setting-sorting-programmatically.md | 67 +- .../features/sorting/sorting-expressions.md | 31 +- controls/gridview/features/virtual-mode.md | 61 +- .../creating-hierarchical-grids.md | 23 +- .../logical-vs.-visual-grid-structure.md | 59 +- .../fundamentals/ui-virtualization.md | 61 +- ...ding-to-hierarchical-data-automatically.md | 62 +- ...g-to-hierarchical-data-programmatically.md | 426 +------ ...ting-hierarchy-using-an-xml-data-source.md | 46 +- .../hierarchy-of-one-to-many-relations.md | 110 +- .../how-to/accessing-child-templates.md | 17 +- ...tting-only-to-cells-in-a-child-template.md | 56 +- .../how-to/expanding-all-rows.md | 39 +- ...sen-parent-row-in-hierarchy-radgridview.md | 61 +- .../how-to/resizing-child-gridviewinfo.md | 22 +- .../load-on-demand-hierarchy.md | 139 +-- ...ad-on-demand-self-referencing-hierarchy.md | 270 +---- .../object-relational-hierarchy-mode.md | 97 +- .../self-referencing-hierarchy.md | 326 +----- .../gridview/localization/localization.md | 662 +---------- .../localization/right-to-left-support.md | 15 +- .../populating-with-data/bind-to-xml.md | 18 +- .../binding-to-a-collection-of-interfaces.md | 184 +-- .../binding-to-array-and-arraylist.md | 149 +-- .../binding-to-bindinglist.md | 117 +- .../binding-to-datareader.md | 27 +- ...framework-using-database-first-approach.md | 80 +- .../binding-to-generic-lists.md | 108 +- .../binding-to-observablecollection.md | 183 +-- .../binding-to-sub-objects.md | 165 +-- ...reflecting-custom-object-changes-in-rgv.md | 422 +------ ...tips-when-binding-to-custom-collections.md | 31 +- ...utorial-binding-to-datatable-or-dataset.md | 27 +- .../populating-with-data/unbound-mode.md | 254 +--- .../updating-the-database-with-ado.net.md | 211 +--- .../alternating-row-color.md | 30 +- .../html-like-text-formatting.md | 27 +- .../gridview/styling-and-appearance/images.md | 44 +- .../view-definitions/column-groups-view.md | 73 +- .../gridview/view-definitions/html-view.md | 104 +- .../gridview/view-definitions/overview.md | 15 +- .../accessing-and-setting-the-currentcell.md | 30 +- .../visual-elements/cells/accessing-cells.md | 62 +- .../cells/conditional-formatting-cells.md | 59 +- .../cells/creating-custom-cells.md | 555 +-------- .../cells/formating-examples/child-tabs.md | 99 +- .../cells/formating-examples/command-cell.md | 47 +- .../cells/formating-examples/group-rows.md | 41 +- .../cells/formating-examples/row-numbers.md | 51 +- .../formating-examples/style-property.md | 54 +- .../visual-elements/cells/formatting-cells.md | 207 +--- .../visual-elements/cells/gridviewcellinfo.md | 30 +- .../visual-elements/cells/iterating-cells.md | 32 +- .../cells/painting-and-drawing-in-cells.md | 40 +- .../visual-elements/cells/tooltips.md | 52 +- ...accessing-and-iterating-through-columns.md | 117 +- .../columns/calculated-column-expressions.md | 23 +- .../column-types/gridviewbrowsecolumn.md | 33 +- .../column-types/gridviewcalculatorcolumn.md | 33 +- .../column-types/gridviewcheckboxcolumn.md | 104 +- .../column-types/gridviewcolorcolumn.md | 31 +- .../column-types/gridviewcomboboxcolumn.md | 395 +------ .../column-types/gridviewcommandcolumn.md | 55 +- .../column-types/gridviewdatetimecolumn.md | 130 +-- .../column-types/gridviewdecimalcolumn.md | 112 +- .../column-types/gridviewhyperlinkcolumn.md | 115 +- .../column-types/gridviewimagecolumn.md | 64 +- .../column-types/gridviewmaskboxcolumn.md | 33 +- .../gridviewmulticomboboxcolumn.md | 71 +- .../column-types/gridviewratingcolumn.md | 27 +- .../column-types/gridviewselectcolumn.md | 63 +- .../column-types/gridviewsparklinecolumn.md | 13 - .../column-types/gridviewtextboxcolumn.md | 43 +- .../column-types/gridviewtimespancolumn.md | 51 +- .../visual-elements/columns/columns-events.md | 26 +- .../columns/converting-data-types.md | 324 +----- .../columns/data-formatting.md | 39 +- .../columns/generating-columns.md | 155 +-- .../columns/pinning-and-unpinning-columns.md | 37 +- .../columns/reordering-columns.md | 32 +- .../resizing-columns-programatically.md | 45 +- .../columns/working-with-columnchooser.md | 84 +- .../rows/adding-and-inserting-rows.md | 82 +- .../rows/conditional-formatting-rows.md | 22 +- .../rows/creating-custom-rows.md | 175 +-- .../visual-elements/rows/drag-and-drop.md | 627 +--------- .../visual-elements/rows/formatting-rows.md | 84 +- .../visual-elements/rows/gridviewrowinfo.md | 23 +- .../rows/how-to/autosize-entire-row.md | 132 +-- .../visual-elements/rows/iterating-rows.md | 162 +-- .../gridview/visual-elements/rows/new-row.md | 258 +---- .../visual-elements/rows/painting-rows.md | 60 +- .../visual-elements/rows/pinned-rows.md | 52 +- .../visual-elements/rows/removing-rows.md | 60 +- .../rows/reordering-system-rows.md | 21 +- .../visual-elements/rows/resizing-rows.md | 24 - .../visual-elements/rows/row-behaviors.md | 255 +---- .../visual-elements/rows/rows-vs-childrows.md | 177 +-- .../visual-elements/rows/search-row.md | 63 +- .../rows/selected-rows-and-current-row.md | 45 +- .../visual-elements/rows/summary-rows.md | 231 +--- .../visual-elements/rows/tag-property.md | 73 +- controls/heatmap/colorizers.md | 471 +------- controls/heatmap/custom-painting.md | 279 +---- controls/heatmap/definition-types.md | 201 +--- controls/heatmap/getting-started.md | 93 +- controls/heatmap/legend.md | 41 +- .../populating-with-data/data-binding.md | 323 +----- .../populating-with-data/unbound-mode.md | 276 +---- controls/heatmap/selection.md | 36 +- controls/heatmap/tooltip-screentip.md | 40 +- controls/image-editor/features/adustments.md | 59 +- .../image-editor/features/canvas-resize.md | 15 +- controls/image-editor/features/crop.md | 16 +- controls/image-editor/features/drawing.md | 38 +- controls/image-editor/features/effects.md | 28 +- controls/image-editor/features/flip.md | 15 +- controls/image-editor/features/history.md | 20 +- controls/image-editor/features/resize.md | 15 +- controls/image-editor/features/rotate.md | 15 +- .../image-editor/features/round-corners.md | 15 +- controls/image-editor/localization.md | 325 +----- .../layoutcontrol/customizing-appearance.md | 114 +- controls/layoutcontrol/getting-started.md | 133 +-- controls/layoutcontrol/load-layout.md | 68 +- controls/layoutcontrol/localization.md | 164 +-- controls/listview/custom-items.md | 445 +------ .../accessing-and-customizing-elements.md | 15 +- .../formatting-items.md | 160 +-- ...addragdropservice-and-ole-drag-and-drop.md | 273 +---- .../drag-and-drop-from-another-control.md | 293 +---- .../drag-and-drop-in-bound-mode.md | 238 +--- .../drag-and-drop-using-raddragdropservice.md | 326 +----- controls/listview/editors/custom-editors.md | 136 +-- controls/listview/editors/default-editors.md | 51 +- controls/listview/editors/editors.md | 74 +- .../listview/export-data/spread-export.md | 185 +-- controls/listview/features/filtering.md | 81 +- controls/listview/features/grouping.md | 102 +- controls/listview/features/item-sizing.md | 51 +- controls/listview/features/selection.md | 27 +- controls/listview/features/sorting.md | 125 +- controls/listview/getting-started.md | 481 +------- controls/listview/keyboard-navigation-.md | 28 +- .../populating-with-data/data-binding.md | 295 +---- .../populating-with-data/unbound-mode.md | 90 +- controls/listview/using-checkboxes.md | 42 +- .../map/drag-and-drop/ole-drag-and-drop.md | 122 +- .../map/features/layers/clusterization.md | 105 +- controls/map/features/layers/colorization.md | 267 +---- controls/map/features/layers/overview.md | 110 +- controls/map/features/legend.md | 22 +- controls/map/features/minimap.md | 40 +- controls/map/features/navigation-controls.md | 13 +- controls/map/features/pan-and-zoom.md | 16 +- controls/map/features/scale-indicators.md | 30 +- .../map/file-readers/esri-shapefile-reader.md | 111 +- controls/map/file-readers/kml-reader.md | 41 +- .../map/file-readers/sql-geospatial-reader.md | 45 +- controls/map/getting-started.md | 29 +- .../how-to/adding-pins-and-drawing-regions.md | 140 +-- controls/map/localization.md | 84 +- controls/map/map-factory.md | 110 +- .../providers/azure-map/azuremapprovider.md | 4 - .../providers/bingmaps/bingrestmapprovider.md | 27 +- .../providers/bingmaps/elevation/bounds.md | 174 +-- .../map/providers/bingmaps/elevation/list.md | 95 +- .../providers/bingmaps/elevation/polyline.md | 219 +--- .../providers/bingmaps/elevation/sealevel.md | 90 +- controls/map/providers/bingmaps/route.md | 145 +-- controls/map/providers/bingmaps/search.md | 133 +-- .../map/providers/bingmaps/truck-route.md | 165 +-- controls/map/providers/cacheprovider.md | 30 +- controls/map/providers/localmapprovider.md | 26 +- .../map/providers/openstreetmapprovider.md | 74 +- controls/map/tooltips.md | 43 +- .../menus/application-menu/getting-started.md | 22 +- .../application-menu/populating-with-data.md | 89 +- .../contextmenu/add-context-menu-in-code.md | 17 +- controls/menus/contextmenu/context-menus.md | 42 +- controls/menus/menu/getting-started.md | 31 +- controls/menus/menu/menu-merge/menu-merge.md | 13 +- .../animation-effects.md | 81 +- .../menu-orientation.md | 132 +-- .../menu/usability/keyboard-navigation.md | 13 +- .../adding-and-removing-items.md | 133 +-- .../assign-shortcuts-to-menu-items.md | 57 +- .../multi-line-menu-item-text.md | 28 +- .../nesting-controls-in-menu-items.md | 217 +--- .../radmenuitem-events.md | 115 +- .../cancel-drop-down-closing.md | 28 +- .../drop-down-properties.md | 42 +- .../features/auto-complete.md | 26 +- .../multicolumncombobox/features/filtering.md | 59 +- .../multicolumncombobox/getting-started.md | 81 +- .../how-to/multiple-selection.md | 426 +------ .../populating-with-data/databinding.md | 78 +- .../populating-with-data/unbound-mode.md | 27 +- .../accessing-and-customizing-elements.md | 15 +- controls/navigationview/header-and-footer.md | 65 +- controls/navigationview/hierarchy-support.md | 76 +- controls/navigationview/ui-automation.md | 173 +-- .../features/balloon-notifications.md | 83 +- controls/notifyicon/features/contextmenu.md | 53 +- controls/notifyicon/features/popup.md | 101 +- controls/notifyicon/features/tooltip.md | 27 +- controls/notifyicon/getting-started.md | 50 +- controls/officenavigationbar/context-menu.md | 37 +- .../officenavigationbar/getting-started.md | 62 +- controls/officenavigationbar/localization.md | 105 +- .../officenavigationbar/options-dialog.md | 15 +- controls/officenavigationbar/peek-window.md | 45 +- controls/officenavigationbar/view-modes.md | 34 +- .../customizing-backstage-view.md | 93 +- .../customizing-the-explorerbarview.md | 56 +- ...add-contextMenu-to-radpageviewpage-tabs.md | 162 +-- controls/pageview/how-to/editing-page-tabs.md | 109 +- .../how-to/programatically-adding-pages.md | 47 +- .../subscribing-to-radpageviewpage-events.md | 42 +- .../pageview/localization/localization.md | 82 +- .../localization/right-to-left-support.md | 13 +- .../outlookview/using-the-overflow-grip.md | 42 +- .../outlookview/using-the-overflow-menu.md | 25 +- controls/pageview/peek-window.md | 45 +- .../customizing-the-selection-mode.md | 16 +- .../customizing-the-stack-position.md | 15 +- controls/pageview/stripview/fitting-items.md | 124 +- controls/pageview/stripview/new-item.md | 49 +- .../scrolling-and-overflow-(strip-buttons).md | 16 +- .../stripview/strip-element-properties.md | 15 +- .../collapsiblepanel/getting-started.md | 29 +- .../working-with-radcollapsiblepanel.md | 109 +- .../accessing-and-customizing-elements.md | 25 +- .../panels-and-labels/groupbox/mnemonics.md | 13 +- .../label/getting-started.md | 20 +- .../label/html-like-text-formatting.md | 13 +- .../panel/getting-started.md | 28 +- controls/panels-and-labels/separator.md | 49 +- controls/panorama/custom-tiles.md | 178 +-- .../accessing-and-customizing-elements.md | 31 +- .../panorama/drad-and-drop/drag-and-drop.md | 218 +--- controls/panorama/save-and-load-layout.md | 69 +- controls/panorama/scrolling.md | 101 +- controls/panorama/tiles.md | 173 +-- .../customize-pdf-rendering.md | 89 +- controls/pdfviewer/features/annotations.md | 175 +-- .../pdfviewer/features/digital-signature.md | 69 +- controls/pdfviewer/features/navigation.md | 57 +- .../pdfviewer/features/printing-support.md | 15 +- controls/pdfviewer/features/save-as.md | 12 +- .../pdfviewer/features/text/text-position.md | 20 +- .../pdfviewer/features/text/text-search.md | 30 +- .../pdfviewer/features/text/text-selection.md | 169 +-- controls/pdfviewer/features/thumbnails.md | 54 +- controls/pdfviewer/getting-started.md | 70 +- .../how-to/handle-rendering-events.md | 99 +- controls/pdfviewer/localization.md | 310 +---- controls/pdfviewer/rotation.md | 25 +- controls/pdfviewer/save-document.md | 28 +- controls/pdfviewer/ui/context-menu.md | 66 +- controls/pdfviewer/ui/document-modes.md | 26 +- controls/pdfviewer/ui/rotation.md | 13 +- controls/pdfviewer/ui/viewer-modes.md | 13 +- controls/picturebox/features/context-menu.md | 66 +- controls/picturebox/features/edit.md | 50 +- controls/picturebox/features/pan-and-zoom.md | 60 +- .../features/working-with-panels.md | 67 +- controls/picturebox/getting-started.md | 41 +- controls/picturebox/localization.md | 101 +- controls/pipspager/data-binding.md | 152 +-- controls/pipspager/getting-started.md | 53 +- .../pivotgrid/binding-with-radchartview.md | 119 +- controls/pivotgrid/calculated-fields.md | 86 +- controls/pivotgrid/calculated-items.md | 146 +-- controls/pivotgrid/context-menu.md | 99 +- controls/pivotgrid/custom-aggregation.md | 198 +--- .../formatting-appearance.md | 109 +- controls/pivotgrid/dialogs/custom-dialogs.md | 81 +- controls/pivotgrid/drilldown.md | 78 +- controls/pivotgrid/expand-behavior.md | 61 +- .../export-to-excel-via-excelml-format.md | 91 +- .../pivotgrid/exporting-data/export-to-pdf.md | 122 +- .../pivotgrid/exporting-data/spread-export.md | 148 +-- controls/pivotgrid/filtering/group-filters.md | 41 +- .../pivotgrid/filtering/report-filters.md | 65 +- controls/pivotgrid/iterating-cells.md | 62 +- controls/pivotgrid/layout-settings.md | 74 +- .../pivotgrid/localization/localization.md | 677 +---------- .../customizing-radpivotfieldlist.md | 197 +--- .../binding-to-icustomtypeprovider.md | 1019 +---------------- .../using-the-adomddataprovider.md | 68 +- .../using-the-datasource-property.md | 111 +- .../using-the-localsourcedataprovider.md | 135 +-- .../using-the-queryabledataprovider.md | 152 +-- .../using-the-xmladataprovider.md | 68 +- .../events-and-customization.md | 48 +- .../pivotgrid/printing-support/overview.md | 28 +- .../printing-support/pivotgridprintstyle.md | 96 +- .../save-and-load-layout/overview.md | 76 +- .../serialize-adomddataprovider.md | 302 +---- .../serialize-custom-aggregates.md | 313 +---- .../serialize-xmladdataprovider.md | 301 +---- controls/pivotgrid/sorting.md | 38 +- controls/propertygrid/attributes.md | 374 +----- controls/propertygrid/custom-items.md | 304 +---- .../customizing-appearance/customization.md | 63 +- .../editors/customizing-editor-behavior.md | 57 +- .../editors/handling-editors'-events.md | 126 +- .../editors/using-custom-editor.md | 132 +-- controls/propertygrid/editors/validation.md | 41 +- .../propertygrid/export-data/spread-export.md | 182 +-- .../propertygrid/features/custom-grouping.md | 68 +- controls/propertygrid/features/filtering.md | 15 +- controls/propertygrid/features/grouping.md | 32 +- controls/propertygrid/features/help-bar.md | 13 +- controls/propertygrid/features/sorting.md | 32 +- controls/propertygrid/features/toolbar.md | 66 +- controls/propertygrid/getting-started.md | 122 +- .../how-to/custom-keyboard-handling.md | 190 +-- controls/propertygrid/keyboard-navigation.md | 28 +- controls/propertygrid/localization.md | 79 +- .../binding-to-multiple-objects.md | 15 +- ...dpropertystore-adding-custom-properties.md | 54 +- controls/propertygrid/type-converters.md | 591 +--------- .../customizing-radrangeselector.md | 161 +-- controls/rangeselector/getting-started.md | 13 +- .../integration-with-radchartview.md | 132 +-- .../rangeselector/properties-and-events.md | 201 +--- .../ribbonbar/backstage-view/customization.md | 39 +- controls/ribbonbar/backstage-view/overview.md | 13 +- .../working-with-backstage-view.md | 30 +- .../adding-screen-tips.md | 64 +- .../creating-a-gallery.md | 141 +-- ...menu-quick-access-toolbar-and-shortcuts.md | 206 +--- .../customizing-the-start-menu.md | 13 +- controls/ribbonbar/getting-started.md | 52 +- .../set-radribbonbar-in-titlebar-mode.md | 15 +- .../ribbonbar/localization/localization.md | 34 +- .../localization/right-to-left-support.md | 13 +- .../adding-and-removing-groups-and-buttons.md | 101 +- ...-and-removing-tabs-and-ribbonbar-groups.md | 145 +-- .../customizing-the-application-menu.md | 145 +-- .../customizing-the-key-tips.md | 49 +- .../customizing-the-quick-access-menu.md | 31 +- .../managing-contextual-tab-groups.md | 77 +- .../customizing-simplified-layout.md | 32 +- .../simplified-mode/simplified-mode.md | 65 +- .../annotations/custom-annotations.md | 343 ++---- .../annotations/manipulating-annotations.md | 292 ++--- .../richtexteditor/document-elements/break.md | 119 +- .../document-elements/inline-image.md | 161 +-- .../document-elements/inlinieuicontainer.md | 132 +-- .../document-elements/paragraph.md | 206 ++-- .../document-elements/raddocument.md | 228 ++-- .../document-elements/section.md | 397 +++---- .../richtexteditor/document-elements/span.md | 194 ++-- .../richtexteditor/document-elements/table.md | 91 +- controls/richtexteditor/features/bookmarks.md | 132 +-- .../features/clipboard-support.md | 151 +-- .../richtexteditor/features/code-block.md | 67 +- controls/richtexteditor/features/commands.md | 67 +- controls/richtexteditor/features/comments.md | 40 +- .../content-controls/content-controls.md | 108 +- .../working-wirh-content-controls-ui.md | 52 +- .../working-with-content-controls.md | 124 +- .../richtexteditor/features/custom-fonts.md | 32 +- .../features/document-protection.md | 387 ++----- .../custom-fields.md | 465 +++----- .../document-variables.md | 134 +-- .../fields-and-document-variables/fields.md | 40 +- .../richtexteditor/features/format-painter.md | 34 +- .../features/headers-and-footers.md | 341 ++---- controls/richtexteditor/features/history.md | 71 +- controls/richtexteditor/features/hyperlink.md | 206 +--- .../richtexteditor/features/line-numbering.md | 20 +- .../insert-new-line-in-merge-field.md | 96 +- .../features/mail-merge/mail-merge.md | 181 +-- .../mentions/mentions-custom-provider.md | 461 +------- .../features/mentions/mentions-overview.md | 73 +- .../features/merge-documents/append.md | 25 +- .../features/merge-documents/merge.md | 19 +- .../merge-documents/raddocumentmerger.md | 13 +- .../richtexteditor/features/paste-options.md | 16 +- .../richtexteditor/features/positioning.md | 415 +++---- .../features/raddocumenteditor.md | 167 +-- .../features/read-only-ranges.md | 100 +- .../references/bibliographic-references.md | 99 +- .../captions-for-tables-and-figures.md | 34 +- .../features/references/cross-reference.md | 39 +- .../references/footnotes-and-endnotes.md | 284 ++--- .../features/repeat-table-header-row.md | 28 +- controls/richtexteditor/features/search.md | 128 +-- .../features/section-columns.md | 68 +- controls/richtexteditor/features/selection.md | 249 +--- .../richtexteditor/features/spellcheck.md | 131 +-- .../features/styles/list-styles.md | 83 +- .../features/styles/style-sheets.md | 64 +- .../richtexteditor/features/styles/styles.md | 502 ++++---- .../richtexteditor/features/track-changes.md | 75 +- controls/richtexteditor/features/watermark.md | 55 +- .../frequently-asked-questions.md | 337 ++---- .../getting-started/formatting-api.md | 204 ++-- .../getting-started/getting-started.md | 218 +--- .../use-as-rich-content-viewer.md | 14 +- ...ustomize-presentation-through-ui-layers.md | 171 +-- .../richtexteditor/how-to/drag-and-drop.md | 138 +-- .../how-to/repalce-default-dialogs.md | 142 +-- .../import-export/docx/docxformatprovider.md | 80 +- .../import-export/docx/settings.md | 84 +- .../import-export/html/htmlformatprovider.md | 200 ++-- .../import-export/html/settings.md | 298 ++--- .../import-export/pdf/pdfformatprovider.md | 27 +- .../import-export/pdf/settings.md | 134 +-- .../plain-text/txtformatprovider.md | 192 ++-- .../import-export/rtf/rtfformatprovider.md | 201 ++-- .../import-export/rtf/settings.md | 158 +-- .../import-export/xaml/settings.md | 210 ++-- .../import-export/xaml/xaml-verification.md | 22 +- .../import-export/xaml/xamlformatprovider.md | 45 +- controls/richtexteditor/keyboard-support.md | 221 ++-- controls/richtexteditor/localization.md | 110 +- controls/richtexteditor/printing.md | 17 +- .../richtexteditor/radrichtexteditorruler.md | 32 +- .../context-menu.md | 150 +-- .../editing-images.md | 43 +- .../how-to/custom-ribbon.md | 46 +- .../upgrading-to-radrichtexteditor.md | 79 +- ...creating-a-slide-viewer-with-radrotator.md | 95 +- .../appearance/formatting-appointments.md | 75 +- .../scheduler/appearance/formatting-cells.md | 146 +-- ...dify-size-of-rows-columns-and-resources.md | 65 +- ...tom-field-to-the-editappointment-dialog.md | 196 +--- .../adding-tooltips-to-appointments.md | 17 +- .../custom-appointment-element.md | 171 +-- .../recurrence-rule-walkthrough.md | 64 +- .../working-with-appointments.md | 71 +- .../working-with-recurring-appointments.md | 115 +- .../working-with-resources.md | 37 +- .../context-menu/customize-the-contextmenu.md | 66 +- .../binding-to-business-objects.md | 622 +--------- .../data-binding/binding-to-custom-fields.md | 235 +--- ...entityframework-and-telerik-data-access.md | 178 +-- .../data-binding/codeless-data-binding.md | 40 +- .../data-binding/data-binding-walkthrough.md | 249 +--- .../data-binding/scheduler-mapping.md | 394 ++----- ...ting-appointment-and-resource-relations.md | 93 +- .../data-binding/using-a-data-provider.md | 307 +---- .../data-binding/using-datasource-property.md | 70 +- .../data-binding/working-with-resources.md | 32 +- .../deleterecurringappointmentdialog.md | 120 +- .../dialogs/editappointmentdialog.md | 323 +----- .../scheduler/dialogs/editrecurrencedialog.md | 226 +--- ...addragdropservice-and-ole-drag-and-drop.md | 430 +------ .../drag-and-drop-from-another-control.md | 328 +----- .../drag-and-drop-using-raddragdropservice.md | 344 +----- .../end-user-functionality/copy-paste-cut.md | 32 +- .../editing-appointments-.md | 111 +- .../appointment-title-formatter.md | 97 +- .../scheduler/fundamentals/input-behavior.md | 74 +- .../scheduler-element-provider-.md | 142 +-- .../scheduler/fundamentals/scheduler-ruler.md | 132 +-- .../fundamentals/scheduler-selection.md | 71 +- controls/scheduler/holidays.md | 132 +-- .../loading-data-for-selected-day-only.md | 36 +- .../export-to-a-custom-file.md | 92 +- .../export-to-icalendar.md | 31 +- .../import-from-icalendar.md | 33 +- .../localization/localizing-dialog-strings.md | 50 +- .../localizing-scheduler-navigator.md | 102 +- .../localization/right-to-left-support.md | 13 +- .../localization/translating-strings.md | 650 +---------- .../print-support/events-and-customization.md | 127 +- .../print-support/print-support-overview.md | 28 +- .../print-support/schedulerprintstyles.md | 207 +--- .../scheduler/reminders/load-reminders.md | 78 +- .../reminders/localizing-reminder-strings.md | 188 +-- .../reminders/radschedulerreminder.md | 63 +- controls/scheduler/views/agenda-view.md | 62 +- .../views/common-visual-properties.md | 54 +- controls/scheduler/views/day-view.md | 267 +---- .../scheduler/views/grouping-by-resources.md | 314 +---- controls/scheduler/views/month-view.md | 243 +--- controls/scheduler/views/multiday-view.md | 46 +- .../views/scheduler-cell-containers.md | 162 +-- controls/scheduler/views/time-zones.md | 206 +--- controls/scheduler/views/timeline-view.md | 158 +-- controls/scheduler/views/views-walkthrough.md | 182 +-- controls/scheduler/views/week-view.md | 56 +- controls/scheduler/views/work-week-view.md | 44 +- .../scheduler/views/working-with-views.md | 64 +- .../assigning-global-radshortcuts.md | 12 +- .../shortcuts/getting-started-(radbuttons).md | 6 +- .../getting-started-(radmenuitems).md | 18 +- controls/slideview/animation.md | 25 +- controls/slideview/data-binding.md | 339 +----- controls/slideview/getting-started.md | 43 +- controls/slideview/infinite-scrolling.md | 14 +- controls/slideview/navigation-buttons.md | 21 +- controls/slideview/template-element.md | 41 +- controls/slideview/unbound-mode.md | 33 +- .../customizing-appearance/custom-painting.md | 47 +- controls/sparkline/export-to-image.md | 17 +- controls/sparkline/features/annotations.md | 87 +- controls/sparkline/features/indicators.md | 43 +- controls/sparkline/features/null-values.md | 63 +- controls/sparkline/getting-started.md | 71 +- .../populating-with-data/data-binding.md | 56 +- .../populating-with-data/unbound-mode.md | 48 +- controls/sparkline/printing-support.md | 17 +- controls/sparkline/series/sparkareaseries.md | 40 +- controls/sparkline/series/sparkbarseries.md | 38 +- controls/sparkline/series/sparklineseries.md | 40 +- .../sparkline/series/sparkscatterseries.md | 38 +- .../sparkline/series/sparkwinlossseries.md | 42 +- controls/sparkline/tooltips.md | 72 +- controls/spellchecker/dictionaries.md | 74 +- controls/spellchecker/getting-started.md | 32 +- controls/spellchecker/localization.md | 97 +- .../spellchecker/spell-check-as-you-type.md | 17 +- controls/spellchecker/spellchecking-modes.md | 26 +- .../spellchecker/spellchecking-radgridview.md | 55 +- .../splashscreens/flyout/getting-started.md | 15 +- .../overlay/customize-appearance.md | 8 +- .../splashscreens/overlay/getting-started.md | 12 +- .../overlay/how-to/custom-overlay-screen.md | 18 +- .../splashscreen/custom-splash.md | 14 +- .../splashscreen/getting-started.md | 6 +- ...-of-radsplitcontainers-programmatically.md | 80 +- .../building-advanced-layouts.md | 94 +- .../accessing-and-customizing-elements.md | 19 +- controls/splitcontainer/splitter-buttons.md | 54 +- controls/spreadsheet/events.md | 163 +-- controls/spreadsheet/features/context-menu.md | 41 +- .../spreadsheet/features/data-validation.md | 29 +- controls/spreadsheet/features/freeze-panes.md | 28 +- controls/spreadsheet/features/printing.md | 23 +- .../features/ui-working-with-selection.md | 206 +--- .../getting-started/getting-started.md | 24 +- .../how-to/customize-row-column-headers.md | 49 +- .../spreadsheet/how-to/customize-selection.md | 7 +- .../hide-row-column-headers-and-gridlines.md | 102 +- ...ting-number-of-visible-rows-and-columns.md | 13 +- controls/spreadsheet/import-export.md | 46 +- controls/spreadsheet/localization.md | 146 +-- controls/syntax-editor/commands.md | 14 +- controls/syntax-editor/features/caret.md | 54 +- controls/syntax-editor/features/fonts.md | 32 +- .../syntax-editor/features/intelliprompts.md | 57 +- .../features/keyboard-support.md | 25 +- controls/syntax-editor/features/layers.md | 174 +-- controls/syntax-editor/features/margins.md | 499 +------- controls/syntax-editor/features/palettes.md | 78 +- .../features/selection-drag-drop.md | 81 +- controls/syntax-editor/features/selection.md | 41 +- .../features/taggers/custom-language.md | 170 +-- .../features/taggers/custom-taggers.md | 115 +- .../features/taggers/folding-taggers.md | 125 +- .../features/taggers/overview.md | 23 +- controls/syntax-editor/features/word-wrap.md | 17 +- controls/syntax-editor/features/zooming.md | 53 +- controls/syntax-editor/getting-started.md | 41 +- controls/syntax-editor/localization.md | 29 +- .../properties-methods-events.md | 35 +- .../task-board-adding-task-cards.md | 53 +- .../task-board-adding-user-and-tasks.md | 71 +- .../task-board/task-board-getting-started.md | 95 +- .../task-board/task-board-sorting-tasks.md | 103 +- controls/task-board/task-board-tooltips.md | 59 +- .../task-dialog/task-dialog-element-types.md | 221 +--- .../task-dialog-getting-started.md | 141 +-- controls/task-dialog/task-dialog-icons.md | 51 +- controls/taskbar-button/features/jumplist.md | 70 +- controls/taskbar-button/features/progress.md | 36 +- .../features/thumbnail-buttons.md | 66 +- controls/taskbar-button/features/tooltips.md | 31 +- controls/taskbar-button/taskbar-manager.md | 38 +- ...ng-toast-notifications-programmatically.md | 105 +- .../toast-notification/getting-started.md | 44 +- .../handling-users-input.md | 60 +- .../accessing-and-customizing-elements.md | 25 +- .../progressbar/getting-started.md | 53 +- .../rating/customization.md | 142 +-- .../rating/getting-started.md | 58 +- .../rating/properties-and-events.md | 145 +-- .../accessing-and-customizing-elements.md | 19 +- .../scrollbar/getting-started.md | 61 +- .../custom-indicator.md | 187 +-- .../stepprogressbar/features/layout-mode.md | 209 +--- .../stepprogressbar/features/progress-mode.md | 181 +-- .../stepprogressbar/features/tooltip.md | 157 +-- .../stepprogressbar/getting-started.md | 67 +- .../accessing-and-customizing-elements.md | 29 +- .../customizing-appearance/customization.md | 96 +- .../trackbar/getting-started.md | 18 +- .../trackbar/modes.md | 89 +- .../trackbar/properties-events.md | 36 +- .../waitingbar/associated-control.md | 38 +- .../accessing-and-customizing-elements.md | 163 +-- .../waitingbar/getting-started.md | 139 +-- ...ing-waitingbar-with-a-background-worker.md | 174 +-- controls/treemap/colorizers.md | 91 +- controls/treemap/customizing-appearance.md | 130 +-- controls/treemap/data-binding.md | 20 +- controls/treemap/features/grouping.md | 22 +- controls/treemap/features/legend.md | 64 +- controls/treemap/features/tooltips.md | 73 +- controls/treemap/getting-started.md | 54 +- controls/treemap/layout-strategies.md | 57 +- controls/treemap/unbound-mode.md | 90 +- controls/treeview/breadcrumb.md | 25 +- .../context-menus/default-context-menu.md | 54 +- .../modifying-the-default-context-menu.md | 53 +- .../data-binding/binding-to-database-data.md | 24 +- .../binding-to-object-relational-data.md | 32 +- .../binding-to-self-referencing-data.md | 147 +-- .../data-binding/binding-to-xml-data.md | 28 +- .../data-binding/databinding-checkboxes.md | 265 +---- .../load-on-demand-with-crud-operations.md | 560 +-------- .../treeview/data-binding/load-on-demand.md | 63 +- .../data-binding/togglestateconverter.md | 313 +---- .../cancel-a-drag-and-drop-operation.md | 104 +- .../drag-and-drop-in-bound-mode.md | 425 +------ .../drag-and-drop/enabling-drag-and-drop.md | 77 +- .../modify-the-dragdropservice-behavior.md | 258 +---- controls/treeview/editing/custom-editors.md | 208 +--- controls/treeview/editing/editing-nodes.md | 25 +- .../treeview/export-data/spread-export.md | 169 +-- controls/treeview/getting-started.md | 38 +- .../how-to/assign-radscreentip-to-nodes.md | 52 +- .../keep-radtreeview-states-on-reset.md | 399 +------ .../treeview/localization/localization.md | 69 +- .../localization/right-to-left-support.md | 13 +- .../tree-lines-and-rows.md | 34 +- .../treeview/usability/keyboard-navigation.md | 26 +- .../adding-and-removing-nodes.md | 236 +--- .../bring-a-node-into-view.md | 93 +- .../working-with-nodes/custom-filtering.md | 62 +- .../working-with-nodes/custom-nodes.md | 348 +----- .../working-with-nodes/custom-sorting.md | 98 +- .../treeview/working-with-nodes/events.md | 28 +- .../working-with-nodes/filtering-nodes.md | 13 +- .../working-with-nodes/finding-nodes.md | 25 +- .../working-with-nodes/formatting-nodes.md | 77 +- .../working-with-nodes/reordering-nodes.md | 99 +- .../working-with-nodes/selecting-nodes.md | 98 +- .../working-with-nodes/sorting-nodes.md | 13 +- .../treeview/working-with-nodes/tooltips.md | 56 +- .../working-with-nodes/treenode-text-value.md | 27 +- .../working-with-nodes/using-checkboxes.md | 35 +- .../customizing-error-indication.md | 65 +- .../validation-provider/validation-rules.md | 246 +--- .../accessing-and-customizing-elements.md | 46 +- controls/virtual-keyboard/default-layouts.md | 29 +- controls/virtual-keyboard/localization.md | 189 +-- .../logical-keyboard-layout.md | 71 +- .../virtual-keyboard/save-and-load-layout.md | 65 +- .../virtual-keyboard/virtual-keyboard-form.md | 31 +- .../end-user-capabilities/resizing-rows.md | 14 +- .../virtualgrid/features/busy-indicators.md | 29 +- .../features/context-menu/context-menu.md | 33 +- .../context-menu/custom-context-menu.md | 195 +--- .../modifying-the-default-context-menu.md | 62 +- .../virtualgrid/features/copy-paste-cut.md | 61 +- .../editing/changing-default-editor.md | 34 +- .../editing/changing-editors-properties.md | 59 +- .../features/editing/data-validation.md | 42 +- .../virtualgrid/features/editing/editors.md | 24 +- .../features/editing/using-custom-editors.md | 180 +-- .../features/filtering/filtering.md | 272 +---- .../setting-filters-programmatically.md | 56 +- .../virtualgrid/features/input-behavior.md | 74 +- .../features/save-and-load-layout/advanced.md | 68 +- .../features/save-and-load-layout/overview.md | 74 +- controls/virtualgrid/features/scrolling.md | 43 +- .../features/selection/multi-select.md | 30 +- .../selection/selecting-progrmmatically.md | 31 +- .../features/selection/selection.md | 13 +- .../setting-sorting-programmatically.md | 31 +- .../virtualgrid/features/sorting/sorting.md | 295 +---- controls/virtualgrid/getting-started.md | 255 +---- .../hierarchical-data.md | 507 +------- controls/virtualgrid/how-to/summary-rows.md | 300 +---- .../virtualgrid/localization/localization.md | 221 +--- .../cells/creating-custom-cells.md | 251 +--- .../cells/formatting-data-cells.md | 48 +- .../cells/formatting-system-cells.md | 108 +- .../visual-elements/cells/tooltips.md | 56 +- .../visual-elements/columns/pining-columns.md | 29 +- .../resizing-columns-programmatically.md | 101 +- .../rows/alternating-row-colors.md | 15 +- .../rows/formatting-data-rows.md | 44 +- .../rows/formatting-system-rows.md | 73 +- .../visual-elements/rows/pinned-rows.md | 29 +- .../rows/resizing-rows-programmatically.md | 95 +- .../handle-add-delete-update-of-rows.md | 261 +---- .../virtualgrid-populating-with-data.md | 254 +--- controls/webcam/connect-to-camera-device.md | 25 +- controls/webcam/events.md | 46 +- controls/webcam/features/errors.md | 25 +- controls/webcam/features/media-information.md | 33 +- controls/webcam/features/recording-video.md | 47 +- controls/webcam/features/snapshots.md | 58 +- controls/webcam/getting-started.md | 105 +- .../webcam/how-to/mute-recording-audio.md | 22 +- .../webcam/how-to/save-snapshot-to-file.md | 34 +- controls/wizard/localization.md | 62 +- controls/wizard/modes.md | 43 +- controls/wizard/properties-methods-events.md | 40 +- controls/wizard/right-to-left-support.md | 17 +- 1213 files changed, 11083 insertions(+), 106405 deletions(-) diff --git a/controls/aiprompt/getting-started.md b/controls/aiprompt/getting-started.md index 2338d0e23..23c1ae169 100644 --- a/controls/aiprompt/getting-started.md +++ b/controls/aiprompt/getting-started.md @@ -48,29 +48,16 @@ You can create a new __AIPromptOutputItem__ instance and fill it with returned r + + ## User Interaction The __AIPromptOutputItem__ element gives the end user ability to interact with the response of the AI model. The end user can copy the response, generate again the response or vote for it. When the user use one of these interaction options, the __OutputItemAction__ event will be called. Thus allowing the developer to catch the moment of the user interaction and pass it to the AI model. -````C# -private void AIPrompt_OutputItemAction(object sender, OutputItemActionEventArgs e) -{ - if (e.OutputItem.Rating != 0) - { - MyAIService.UpVoteResponse(e.OutputItem.Rating); - } -} - -```` -````VB.NET - -Private Sub AIPrompt_OutputItemAction(ByVal sender As Object, ByVal e As OutputItemActionEventArgs) - If e.OutputItem.Rating <> 0 Then - MyAIService.UpVoteResponse(e.OutputItem.Rating) - End If -End Sub - -```` + + + + ## Telerik UI for WinForms Learning Resources * [Telerik UI for WinForms AIPrompt Component](https://www.telerik.com/products/winforms/aiprompt.aspx) diff --git a/controls/aiprompt/views.md b/controls/aiprompt/views.md index c7a26f927..45fa7193a 100644 --- a/controls/aiprompt/views.md +++ b/controls/aiprompt/views.md @@ -51,64 +51,10 @@ The following code snippet demonstrates how to add __RadAIPromptMoreActionsItem_ ![WinForms RadAIPrompt Views](images/aiprompt-views003.png) -````C# -RadAIPromptMoreActionsItem moreActionsItem = new RadAIPromptMoreActionsItem(); -AIPromptMoreActionsView actionsView = moreActionsItem.GetView() as AIPromptMoreActionsView; -actionsView.Padding = new Padding(16, 16, 16, 0); -StackLayoutElementLite panel = actionsView.Panel as StackLayoutElementLite; - -panel.Children.Add(this.CreateHeaderLabel("Translate")); -panel.Children.Add(this.CreateAction("German")); -panel.Children.Add(this.CreateAction("English")); -this.radAIPrompt1.Items.Add(moreActionsItem); - -private LightVisualElement CreateHeaderLabel(string text) -{ - return new LightVisualElement() - { - Margin = new Padding(-5, 12, 0, 0), - Font = new Font("Segoe UI Semibold", 10.5f), - Text = text - }; -} -private RadButtonElement CreateAction(string text) -{ - RadButtonElement actionButton = new RadButtonElement(text) - { - TextAlignment = ContentAlignment.MiddleLeft, - MinSize = new Size(120, 0) - }; - return actionButton; -} - -```` -````VB.NET - Dim moreActionsItem As RadAIPromptMoreActionsItem = New RadAIPromptMoreActionsItem() - Dim actionsView As AIPromptMoreActionsView = TryCast(moreActionsItem.GetView(), AIPromptMoreActionsView) - actionsView.Padding = New Padding(16, 16, 16, 0) - Dim panel As StackLayoutElementLite = TryCast(actionsView.Panel, StackLayoutElementLite) - panel.Children.Add(Me.CreateHeaderLabel("Translate")) - panel.Children.Add(Me.CreateAction("German")) - panel.Children.Add(Me.CreateAction("English")) - Me.radAIPrompt1.Items.Add(moreActionsItem) - - Private Function CreateHeaderLabel(ByVal text As String) As LightVisualElement - Return New LightVisualElement() With { - .Margin = New Padding(-5, 12, 0, 0), - .Font = New Font("Segoe UI Semibold", 10.5F), - .Text = text - } - End Function - - Private Function CreateAction(ByVal text As String) As RadButtonElement - Dim actionButton As RadButtonElement = New RadButtonElement(text) With { - .TextAlignment = ContentAlignment.MiddleLeft, - .MinSize = New Size(120, 0) - } - Return actionButton - End Function - -```` + + + + ## See Also diff --git a/controls/barcodeview/barcode-reader.md b/controls/barcodeview/barcode-reader.md index c6dfd838f..57b7a5dcf 100644 --- a/controls/barcodeview/barcode-reader.md +++ b/controls/barcodeview/barcode-reader.md @@ -27,35 +27,10 @@ The complete example is available in the Demo application >> BarcodeReader examp #### Decoding a barcode image -{{source=..\SamplesCS\BarcodeView\BarcodeViewGettingStarted.cs region=Decoder}} -{{source=..\SamplesVB\BarcodeView\BarcodeViewGettingStarted.vb region=Decoder}} - -````C# - -BarcodeType barcodeType = Telerik.WinControls.UI.Barcode.Reader.BarcodeType.Code93Extended; -Bitmap bitmap = new Bitmap(Properties.Resources.barcode_reader); -RadBarcodeReader reader = new Telerik.WinControls.UI.Barcode.RadBarcodeReader(); -var decodeResult = reader.Decode(bitmap, barcodeType); -if (decodeResult != null && decodeResult != DecodeResult.Empty) -{ - RadMessageBox.Show(decodeResult.Value); -} - -```` -````VB.NET - -Dim barcodeType As BarcodeType = Telerik.WinControls.UI.Barcode.Reader.BarcodeType.Code93Extended -Dim bitmap As Bitmap = New Bitmap(My.Resources.barcode_reader) -Dim reader As RadBarcodeReader = New Telerik.WinControls.UI.Barcode.RadBarcodeReader() -Dim decodeResult = reader.Decode(bitmap, barcodeType) - -If decodeResult IsNot Nothing AndAlso Not decodeResult.Equals(DecodeResult.Empty) Then - RadMessageBox.Show(decodeResult.Value) -End If - -```` - -{{endregion}} + + + + >caution When decoding a barcode image, the image should contain only the barcode itself, no additional text to be present in that image. diff --git a/controls/barcodeview/barcode-types/2d-barcodes/PDF417/settings.md b/controls/barcodeview/barcode-types/2d-barcodes/PDF417/settings.md index 89ddf962a..4af965103 100644 --- a/controls/barcodeview/barcode-types/2d-barcodes/PDF417/settings.md +++ b/controls/barcodeview/barcode-types/2d-barcodes/PDF417/settings.md @@ -44,31 +44,9 @@ One thing to keep in mind is that these properties are related to the data, whic #### Example -{{source=..\SamplesCS\BarcodeView\BarcodeViewGettingStarted.cs region=PdfBarcode}} -{{source=..\SamplesVB\BarcodeView\BarcodeViewGettingStarted.vb region=PdfBarcode}} - -````C# - -PDF417 encoder = new PDF417(); -encoder.Columns = 3; -encoder.Rows = 3; -encoder.EncodingMode = EncodingMode.Auto; -encoder.ECLevel = 2; -this.radBarcodeView1.Value = "123456Sofia"; -this.radBarcodeView1.Symbology = encoder; - -```` -````VB.NET - -Dim encoder As PDF417 = New PDF417() -encoder.Columns = 3 -encoder.Rows = 3 -encoder.EncodingMode = EncodingMode.Auto -encoder.ECLevel = 2 -Me.radBarcodeView1.Value = "123456Sofia" -Me.radBarcodeView1.Symbology = encoder - -```` -{{endregion}} + + + + diff --git a/controls/barcodeview/barcode-types/2d-barcodes/QRCode/settings.md b/controls/barcodeview/barcode-types/2d-barcodes/QRCode/settings.md index 9f655baf8..396e98a9a 100644 --- a/controls/barcodeview/barcode-types/2d-barcodes/QRCode/settings.md +++ b/controls/barcodeview/barcode-types/2d-barcodes/QRCode/settings.md @@ -42,34 +42,10 @@ Essentially, both the FNC1 property and the ApplicationIndicator data is applied #### Example -{{source=..\SamplesCS\BarcodeView\BarcodeViewGettingStarted.cs region=QRCode}} -{{source=..\SamplesVB\BarcodeView\BarcodeViewGettingStarted.vb region=QRCode}} - -````C# - -QRCode encoder = new QRCode(); -encoder.Version = 0; -encoder.ErrorCorrectionLevel = Telerik.WinControls.UI.Barcode.ErrorCorrectionLevel.M; -encoder.ECIMode = Telerik.WinControls.UI.Barcode.ECIMode.CP437; -encoder.CodeMode = Telerik.WinControls.UI.Barcode.CodeMode.Alphanumeric; -encoder.FNC1Mode = Telerik.WinControls.UI.Barcode.FNC1Mode.SecondPosition; -encoder.ApplicationIndicator = "00"; -this.radBarcodeView1.Symbology = encoder; - -```` -````VB.NET - -Dim encoder As QRCode = New QRCode() -encoder.Version = 0 -encoder.ErrorCorrectionLevel = Telerik.WinControls.UI.Barcode.ErrorCorrectionLevel.M -encoder.ECIMode = Telerik.WinControls.UI.Barcode.ECIMode.CP437 -encoder.CodeMode = Telerik.WinControls.UI.Barcode.CodeMode.Alphanumeric -encoder.FNC1Mode = Telerik.WinControls.UI.Barcode.FNC1Mode.SecondPosition -encoder.ApplicationIndicator = "00" -Me.radBarcodeView1.Symbology = encoder - -```` -{{endregion}} + + + + diff --git a/controls/barcodeview/barcode-types/2d-barcodes/SwissQRCode/overview.md b/controls/barcodeview/barcode-types/2d-barcodes/SwissQRCode/overview.md index 83ebbc3a6..b0a686bef 100644 --- a/controls/barcodeview/barcode-types/2d-barcodes/SwissQRCode/overview.md +++ b/controls/barcodeview/barcode-types/2d-barcodes/SwissQRCode/overview.md @@ -31,27 +31,10 @@ To generate a Swiss Barcode using Telerik UI for WinForms, you need to first set #### Example 1: Setting the SwissQRCode symbology -{{source=..\SamplesCS\BarcodeView\BarcodeViewGettingStarted.cs region=SetSwissQRCode}} -{{source=..\SamplesVB\BarcodeView\BarcodeViewGettingStarted.vb region=SetSwissQRCode}} + + -````C# - -SwissQRCode symbology = new SwissQRCode(); -symbology.Module = 4; -symbology.SizingMode = SizingMode.Manual; -this.radBarcodeView1.Symbology = symbology; - -```` -````VB.NET -Dim symbology As SwissQRCode = New SwissQRCode() -symbology.[Module] = 4 -symbology.SizingMode = SizingMode.Manual -Me.radBarcodeView1.Symbology = symbology - -```` - -{{endregion}} The Swiss QR code standard mandates that the input provided for the generation of the barcode is strictly formatted. Both, validating and generating this input, are complex processes and to facilitate them you can use the **SwissQRCodeValueStringBuilder** helper class. Its purpose is to hold the information needed for a **SwissQRCode** in a type-safe manner, to validate this information and to generate the input. Through its constructor, you need to set the following properties: @@ -74,71 +57,20 @@ The Swiss QR code standard mandates that the input provided for the generation o #### Example 2: Creating the SwissQRCodeValueStringBuilder -{{source=..\SamplesCS\BarcodeView\BarcodeViewGettingStarted.cs region=SwissQRCodeValueStringBuilder}} -{{source=..\SamplesVB\BarcodeView\BarcodeViewGettingStarted.vb region=SwissQRCodeValueStringBuilder}} - -````C# - -Telerik.Barcode.SwissQRCodeValueStringBuilder qrCodeValue = new Telerik.Barcode.SwissQRCodeValueStringBuilder( - new Telerik.Barcode.Iban("CH4431999123000889012", Telerik.Barcode.IbanType.QRIBAN), - Telerik.Barcode.SwissQRCodeCurrency.EUR, - new Telerik.Barcode.Contact("Max Muster & Söhne", - new Telerik.Barcode.StructuredAddress("CH", "8000", "Seldwyla", "Musterstrasse", "123")), - new Telerik.Barcode.Reference(Telerik.Barcode.ReferenceType.QRR, "210000000003139471430009017"), - new Telerik.Barcode.AdditionalInformation("Order from 15.03.2021", "//S1/10/1234/11/201021/30/102673386/32/7.7/40/0:30"), - new Telerik.Barcode.Contact("Simon Muster", new Telerik.Barcode.StructuredAddress("CH", "8000", "Seldwyla", "Musterstrasse", "1")), - (decimal)1949.75, - new Telerik.Barcode.AlternativeProcedure("Name AV1: UV;UltraPay005;12345", "Name AV2: XY;XYService;54321")); - -```` -````VB.NET - -Dim qrCodeValue As Telerik.Barcode.SwissQRCodeValueStringBuilder = New Telerik.Barcode.SwissQRCodeValueStringBuilder( - New Telerik.Barcode.Iban("CH4431999123000889012", Telerik.Barcode.IbanType.QRIBAN), - Telerik.Barcode.SwissQRCodeCurrency.EUR, - New Telerik.Barcode.Contact("Max Muster & Söhne", - New Telerik.Barcode.StructuredAddress("CH", "8000", "Seldwyla", "Musterstrasse", "123")), - New Telerik.Barcode.Reference(Telerik.Barcode.ReferenceType.QRR, "210000000003139471430009017"), - New Telerik.Barcode.AdditionalInformation("Order from 15.03.2021", "//S1/10/1234/11/201021/30/102673386/32/7.7/40/0:30"), - New Telerik.Barcode.Contact("Simon Muster", - New Telerik.Barcode.StructuredAddress("CH", "8000", "Seldwyla", "Musterstrasse", "1")), CDec(1949.75), - New Telerik.Barcode.AlternativeProcedure("Name AV1: UV;UltraPay005;12345", "Name AV2: XY;XYService;54321")) + + -```` - -{{endregion}} Once you've set up the **SwissQRCodeValueStringBuilder** you can call its **Validate** method which validates all its fields and the relations between them. The method returns a string which contains the accumulated errors. If there are no errors - **null** is returned. In this case, you can call the **BuildValue** method of the string builder which will build the string value to be provided to the **RadBarcodeView**. #### Example 3: Validate and build barcode value -{{source=..\SamplesCS\BarcodeView\BarcodeViewGettingStarted.cs region=ValidateSwissQR}} -{{source=..\SamplesVB\BarcodeView\BarcodeViewGettingStarted.vb region=ValidateSwissQR}} - -````C# - - string errors = qrCodeValue.Validate(); - -if (string.IsNullOrEmpty(errors)) -{ - this.radBarcodeView1.Value = qrCodeValue.BuildValue(); -} - - -```` -````VB.NET - -Dim errors As String = qrCodeValue.Validate() - -If String.IsNullOrEmpty(errors) Then - Me.radBarcodeView1.Value = qrCodeValue.BuildValue() -End If + + -```` -{{endregion}} Invoking the code from **Example 3** will generate the following result: diff --git a/controls/barcodeview/barcode-types/2d-barcodes/datamatrix/settings.md b/controls/barcodeview/barcode-types/2d-barcodes/datamatrix/settings.md index 7d0bfcb5d..488c55c0b 100644 --- a/controls/barcodeview/barcode-types/2d-barcodes/datamatrix/settings.md +++ b/controls/barcodeview/barcode-types/2d-barcodes/datamatrix/settings.md @@ -42,29 +42,10 @@ Determines character encoding used to encode the barcode contents. By default it ## Example -{{source=..\SamplesCS\Barcode\BarcodeSettings.cs region=DataMatrix}} -{{source=..\SamplesVB\Barcode\BarcodeSettings.vb region=DataMatrix}} + + -````C# -DataMatrix encoder = new DataMatrix(); -encoder.Encodation = Telerik.WinControls.UI.Barcode.Encodation.Ascii; -encoder.SymbolSize = Telerik.WinControls.UI.Barcode.SymbolSize.SquareAuto; -encoder.Encoding = Encoding.UTF8; -this.radBarcodeView1.Symbology = encoder; - - -```` -````VB.NET - -Dim encoder As DataMatrix = New DataMatrix() -encoder.Encodation = Telerik.WinControls.UI.Barcode.Encodation.Ascii -encoder.SymbolSize = Telerik.WinControls.UI.Barcode.SymbolSize.SquareAuto -encoder.Encoding = Encoding.UTF8 -Me.radBarcodeView1.Symbology = encoder - -```` -{{endregion}} # See Also diff --git a/controls/barcodeview/how-to/export-to-image.md b/controls/barcodeview/how-to/export-to-image.md index 1102d0735..3c0ebaf6b 100644 --- a/controls/barcodeview/how-to/export-to-image.md +++ b/controls/barcodeview/how-to/export-to-image.md @@ -28,38 +28,10 @@ You can export the **RadBarcodeView** content by using one of the following over #### Export to Image -{{source=..\SamplesCS\BarcodeView\BarcodeViewGettingStarted.cs region=ExportToImage}} -{{source=..\SamplesVB\BarcodeView\BarcodeViewGettingStarted.vb region=ExportToImage}} - -````C# - -using (SaveFileDialog saveFileDialog = new SaveFileDialog()) -{ - saveFileDialog.Filter = "Png (*.png)|*.png"; - saveFileDialog.FileName = "QRCode"; - if (saveFileDialog.ShowDialog() == DialogResult.OK) - { - Image img = radBarcodeView1.ExportToImage(); - img.Save(saveFileDialog.FileName, System.Drawing.Imaging.ImageFormat.Png); - } -} - -```` -````VB.NET - -Using saveFileDialog As SaveFileDialog = New SaveFileDialog() - saveFileDialog.Filter = "Png (*.png)|*.png" - saveFileDialog.FileName = "QRCode" - - If saveFileDialog.ShowDialog() = DialogResult.OK Then - Dim img As Image = radBarcodeView1.ExportToImage() - img.Save(saveFileDialog.FileName, System.Drawing.Imaging.ImageFormat.Png) - End If -End Using - -```` - -{{endregion}} + + + + >caption Figure 1: Exported Barcode diff --git a/controls/bindingnavigator/customizing-appearance/customizing-radbindingnavigator.md b/controls/bindingnavigator/customizing-appearance/customizing-radbindingnavigator.md index f231b7c2b..8f14946c7 100644 --- a/controls/bindingnavigator/customizing-appearance/customizing-radbindingnavigator.md +++ b/controls/bindingnavigator/customizing-appearance/customizing-radbindingnavigator.md @@ -25,20 +25,10 @@ You can access the control element by opening the [Element Hierarchy Editor]({%s The following snippet shows how you can access and change the properties of navigator buttons. -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadBindingNavigatorForm.cs region=changeButtonColor}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadBindingNavigatorForm.vb region=changeButtonColor}} -````C# -radBindingNavigator1.BindingNavigatorElement.NextButton.BackColor = ColorTranslator.FromHtml("#e83737"); -radBindingNavigator1.BindingNavigatorElement.NextButton.GradientStyle = Telerik.WinControls.GradientStyles.Solid; + + -```` -````VB.NET -radBindingNavigator1.BindingNavigatorElement.NextButton.BackColor = ColorTranslator.FromHtml("#e83737") -radBindingNavigator1.BindingNavigatorElement.NextButton.GradientStyle = Telerik.WinControls.GradientStyles.Solid - -```` - -{{endregion}} + >caption The NextButton background is changed: @@ -51,32 +41,10 @@ As of R2 2021 **RadBindingNavigator** can be customized to [use glyphs](https:// The following example shows how you can apply glyphs for the buttons: -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadBindingNavigatorForm.cs region=buttonGlyph}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadBindingNavigatorForm.vb region=buttonGlyph}} -````C# -radBindingNavigator1.BindingNavigatorElement.ButtonDisplayStyle = BindingNavigatorButtonDisplayStyle.Glyph; -radBindingNavigator1.BindingNavigatorElement.ButtonGlyphSize = 15; - -var font1 = ThemeResolutionService.GetCustomFont("TelerikWebUI"); -radBindingNavigator1.BindingNavigatorElement.AddNewButton.CustomFont = font1.Name; -radBindingNavigator1.BindingNavigatorElement.DeleteButton.CustomFont = font1.Name; -radBindingNavigator1.BindingNavigatorElement.AddNewButton.Text = "\ue817"; -radBindingNavigator1.BindingNavigatorElement.DeleteButton.Text = "\ue301"; - -```` -````VB.NET -radBindingNavigator1.BindingNavigatorElement.ButtonDisplayStyle = BindingNavigatorButtonDisplayStyle.Glyph -radBindingNavigator1.BindingNavigatorElement.ButtonGlyphSize = 15 - -Dim font1 = ThemeResolutionService.GetCustomFont("TelerikWebUI") -radBindingNavigator1.BindingNavigatorElement.AddNewButton.CustomFont = font1.Name -radBindingNavigator1.BindingNavigatorElement.DeleteButton.CustomFont = font1.Name -radBindingNavigator1.BindingNavigatorElement.AddNewButton.Text = "\ue817" -radBindingNavigator1.BindingNavigatorElement.DeleteButton.Text = "\ue301" - -```` + + -{{endregion}} + >caption The AddNewButton and DeleteButton are customized with custom glyphs: diff --git a/controls/bindingnavigator/getting-started.md b/controls/bindingnavigator/getting-started.md index ea3f1c076..955f39f32 100644 --- a/controls/bindingnavigator/getting-started.md +++ b/controls/bindingnavigator/getting-started.md @@ -38,30 +38,10 @@ The Telerik UI for WinForms assemblies can be install by using one of the availa 2\. Setup the `DataSource` property of the `BindingSource` and the `BindingSource` property of __RadBindingNaviagator__. -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadBindingNavigatorForm.cs region=radBindingNavigator1}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadBindingNavigatorForm.vb region=radBindingNavigator1}} - -````C# -this.bindingSource1.DataSource = new List() { 1, 2, 3, 4, 5, 6, 7, 8 }; -this.radBindingNavigator1.BindingSource = this.bindingSource1; - -```` -````VB.NET -Me.bindingSource1.DataSource = New List(Of Integer)() From { _ - 1, _ - 2, _ - 3, _ - 4, _ - 5, _ - 6, _ - 7, _ - 8 _ -} -Me.radBindingNavigator1.BindingSource = Me.bindingSource1 - -```` - -{{endregion}} + + + + 3\. Press __F5__ to run the project and you should see the following: diff --git a/controls/breadcrumb/data-binding.md b/controls/breadcrumb/data-binding.md index 2e310ba43..9edbc3d13 100644 --- a/controls/breadcrumb/data-binding.md +++ b/controls/breadcrumb/data-binding.md @@ -22,28 +22,10 @@ Since **RadBreadCrumb** internally uses a **RadTreeView**, you can use the [data ![WinForms RadBreadCrumb RadBreadCrumb Bound to the MusicCollection Database](images/breadcrumb-data-binding001.gif) + + -````C# -this.radBreadCrumb1.IsAutoCompleteEnabled = true; -this.radBreadCrumb1.DataSource = this.artistsBindingSource; -this.radBreadCrumb1.DisplayMember = "ArtistName"; -this.radBreadCrumb1.ValueMember = "ArtistID"; -this.radBreadCrumb1.RelationBindings.Add(new RelationBinding(this.albumsBindingSource, "AlbumName", "ArtistID", "ArtistID", "AlbumID")); -this.radBreadCrumb1.RelationBindings.Add(new RelationBinding(this.songsBindingSource, "SongName", "AlbumID", "AlbumID", "SongID")); - - -```` -````VB.NET - - Me.radBreadCrumb1.IsAutoCompleteEnabled = True - Me.radBreadCrumb1.DataSource = Me.artistsBindingSource - Me.radBreadCrumb1.DisplayMember = "ArtistName" - Me.radBreadCrumb1.ValueMember = "ArtistID" - Me.radBreadCrumb1.RelationBindings.Add(New RelationBinding(Me.albumsBindingSource, "AlbumName", "ArtistID", "ArtistID", "AlbumID")) - Me.radBreadCrumb1.RelationBindings.Add(New RelationBinding(Me.songsBindingSource, "SongName", "AlbumID", "AlbumID", "SongID")) - -```` ## See Also * [Getting Started]({%slug breadcrumb-getting-started%}) diff --git a/controls/breadcrumb/getting-started.md b/controls/breadcrumb/getting-started.md index ac75a0c9a..77a82a527 100644 --- a/controls/breadcrumb/getting-started.md +++ b/controls/breadcrumb/getting-started.md @@ -49,148 +49,10 @@ When you run the project and select a node in **RadTreeView**, the **RadBreadCru Similar to **RadTreeView**, **RadBreadCrumb** can also be bound to a collection of records. It is just necessary to set its **DataSource**, **DisplayMember**, **ChildMember** and **ParentMember** properties. In addition, enable the **IsAutoCompleteEnabled** property in order to get suggestions when the user types in the text box: -````C# - - public RadForm1() - { - InitializeComponent(); - - this.radBreadCrumb1.DisplayMember = "name"; - this.radBreadCrumb1.ParentMember = "pid"; - this.radBreadCrumb1.ChildMember = "id"; - this.radBreadCrumb1.DataSource = this.GetSampleData(); - - this.radBreadCrumb1.IsAutoCompleteEnabled = true; - } - - private DataTable GetSampleData() - { - DataTable dt = new DataTable(); - - DataColumn dc = new DataColumn(); - dc.ColumnName = "id"; - dc.DataType = typeof(int); - dt.Columns.Add(dc); - - DataColumn dc1 = new DataColumn(); - dc1.ColumnName = "name"; - dc1.DataType = typeof(string); - dt.Columns.Add(dc1); - - DataColumn dc2 = new DataColumn(); - dc2.ColumnName = "pid"; - dc2.DataType = typeof(int); - dt.Columns.Add(dc2); - - DataRow dr = dt.NewRow(); - dr[0] = 0; - dr[1] = "My Computer"; - dr[2] = DBNull.Value; - dt.Rows.Add(dr); - - dr = dt.NewRow(); - dr[0] = 1; - dr[1] = @"C:"; - dr[2] = 0; - dt.Rows.Add(dr); - - dr = dt.NewRow(); - dr[0] = 2; - dr[1] = @"D:"; - dr[2] = 0; - dt.Rows.Add(dr); - - dr = dt.NewRow(); - dr[0] = 3; - dr[1] = "Program Files"; - dr[2] = 1; - dt.Rows.Add(dr); - - dr = dt.NewRow(); - dr[0] = 4; - dr[1] = "Microsoft"; - dr[2] = 3; - dt.Rows.Add(dr); - - dr = dt.NewRow(); - dr[0] = 5; - dr[1] = "Telerik"; - dr[2] = 3; - dt.Rows.Add(dr); - - dr = dt.NewRow(); - dr[0] = 6; - dr[1] = "WINDOWS"; - dr[2] = 1; - dt.Rows.Add(dr); - - return dt; - } - -```` -````VB.NET - Public Sub New() - InitializeComponent() - Me.radBreadCrumb1.DisplayMember = "name" - Me.radBreadCrumb1.ParentMember = "pid" - Me.radBreadCrumb1.ChildMember = "id" - Me.radBreadCrumb1.DataSource = Me.GetSampleData() - Me.radBreadCrumb1.IsAutoCompleteEnabled = True - End Sub - - Private Function GetSampleData() As DataTable - Dim dt As DataTable = New DataTable() - Dim dc As DataColumn = New DataColumn() - dc.ColumnName = "id" - dc.DataType = GetType(Integer) - dt.Columns.Add(dc) - Dim dc1 As DataColumn = New DataColumn() - dc1.ColumnName = "name" - dc1.DataType = GetType(String) - dt.Columns.Add(dc1) - Dim dc2 As DataColumn = New DataColumn() - dc2.ColumnName = "pid" - dc2.DataType = GetType(Integer) - dt.Columns.Add(dc2) - Dim dr As DataRow = dt.NewRow() - dr(0) = 0 - dr(1) = "My Computer" - dr(2) = DBNull.Value - dt.Rows.Add(dr) - dr = dt.NewRow() - dr(0) = 1 - dr(1) = "C:" - dr(2) = 0 - dt.Rows.Add(dr) - dr = dt.NewRow() - dr(0) = 2 - dr(1) = "D:" - dr(2) = 0 - dt.Rows.Add(dr) - dr = dt.NewRow() - dr(0) = 3 - dr(1) = "Program Files" - dr(2) = 1 - dt.Rows.Add(dr) - dr = dt.NewRow() - dr(0) = 4 - dr(1) = "Microsoft" - dr(2) = 3 - dt.Rows.Add(dr) - dr = dt.NewRow() - dr(0) = 5 - dr(1) = "Telerik" - dr(2) = 3 - dt.Rows.Add(dr) - dr = dt.NewRow() - dr(0) = 6 - dr(1) = "WINDOWS" - dr(2) = 1 - dt.Rows.Add(dr) - Return dt - End Function - -```` + + + + >caption RadBreadCrumb used as a standalone control diff --git a/controls/buttons/button/customizing-appearance/accessing-and-customizing-elements.md b/controls/buttons/button/customizing-appearance/accessing-and-customizing-elements.md index 271fba55d..b288662ec 100644 --- a/controls/buttons/button/customizing-appearance/accessing-and-customizing-elements.md +++ b/controls/buttons/button/customizing-appearance/accessing-and-customizing-elements.md @@ -30,28 +30,7 @@ You can customize the nested elements at run time as well: #### Customize elements -{{source=..\SamplesCS\Buttons\Button.cs region=AccessingCustomizingElements}} -{{source=..\SamplesVB\Buttons\Button.vb region=AccessingCustomizingElements}} - -````C# -this.radButton1.ButtonElement.TextElement.ForeColor = Color.Red; -this.radButton1.ButtonElement.ButtonFillElement.BackColor = Color.Aqua; -this.radButton1.ButtonElement.BorderElement.BoxStyle = Telerik.WinControls.BorderBoxStyle.FourBorders; -this.radButton1.ButtonElement.BorderElement.TopColor = Color.Aqua; -this.radButton1.ButtonElement.BorderElement.BottomColor = Color.Aqua; -this.radButton1.ButtonElement.BorderElement.LeftColor = Color.Red; -this.radButton1.ButtonElement.BorderElement.RightColor = Color.Red; - -```` -````VB.NET -Me.radButton1.ButtonElement.TextElement.ForeColor = Color.Red -Me.radButton1.ButtonElement.ButtonFillElement.BackColor = Color.Aqua -Me.radButton1.ButtonElement.BorderElement.BoxStyle = Telerik.WinControls.BorderBoxStyle.FourBorders -Me.radButton1.ButtonElement.BorderElement.TopColor = Color.Aqua -Me.radButton1.ButtonElement.BorderElement.BottomColor = Color.Aqua -Me.radButton1.ButtonElement.BorderElement.LeftColor = Color.Red -Me.radButton1.ButtonElement.BorderElement.RightColor = Color.Red - -```` - -{{endregion}} + + + + diff --git a/controls/buttons/button/customizing-appearance/html-like-text-formatting.md b/controls/buttons/button/customizing-appearance/html-like-text-formatting.md index 69658e485..e16facd01 100644 --- a/controls/buttons/button/customizing-appearance/html-like-text-formatting.md +++ b/controls/buttons/button/customizing-appearance/html-like-text-formatting.md @@ -34,19 +34,10 @@ The following code snippet will produce the result shown in the screen-shot belo #### Setting HTML-like text -{{source=..\SamplesCS\Buttons\Button.cs region=htmltextrendering}} -{{source=..\SamplesVB\Buttons\Button.vb region=htmltextrendering}} + + -````C# -this.radButton1.Text = "This is RadLabel
Arial, Bold
Times, Italic Underline
Size = 9
Sample Text"; -```` -````VB.NET -Me.radButton1.Text = "This is RadLabel
Arial, Bold
Times, Italic Underline
Size = 9
Sample Text" - -```` - -{{endregion}} ![WinForms RadButtons Setting HTML-like Text ](images/buttons-button-html-like-text-formatting001.png) diff --git a/controls/buttons/button/getting-started.md b/controls/buttons/button/getting-started.md index cc3f6b78e..58bba07cd 100644 --- a/controls/buttons/button/getting-started.md +++ b/controls/buttons/button/getting-started.md @@ -48,48 +48,15 @@ To programmatically add a __RadButton__ to a form, create a new instance of a _ #### Adding a RadButton at runtime -{{source=..\SamplesCS\Buttons\Button.cs region=creatingbutton}} -{{source=..\SamplesVB\Buttons\Button.vb region=creatingbutton}} - -````C# -RadButton myNewRadButton = new RadButton(); -myNewRadButton.Text = "My New RadButton"; -myNewRadButton.Width = 150; -myNewRadButton.Height = 50; -this.Controls.Add(myNewRadButton); -myNewRadButton.Click+=myNewRadButton_Click; - -```` -````VB.NET -Dim myNewRadButton As New RadButton() -myNewRadButton.Text = "My New RadButton" -myNewRadButton.Width = 150 -myNewRadButton.Height = 50 -Me.Controls.Add(myNewRadButton) -AddHandler myNewRadButton.Click, AddressOf myNewRadButton_Click - -```` - -{{endregion}} - -{{source=..\SamplesCS\Buttons\Button.cs region=ButtonClick}} -{{source=..\SamplesVB\Buttons\Button.vb region=ButtonClick}} - -````C# -private void myNewRadButton_Click(object sender, EventArgs e) -{ - RadMessageBox.Show("Clicked"); -} - -```` -````VB.NET -Private Sub myNewRadButton_Click(sender As Object, e As EventArgs) - RadMessageBox.Show("Clicked") -End Sub - -```` - -{{endregion}} + + + + + + + + + ## Telerik UI for WinForms Learning Resources diff --git a/controls/buttons/button/tooltips.md b/controls/buttons/button/tooltips.md index 0fca745c8..852718092 100644 --- a/controls/buttons/button/tooltips.md +++ b/controls/buttons/button/tooltips.md @@ -15,42 +15,19 @@ There are two ways to assign tooltips to __RadButton__, namely setting the __Too #### Setting the ToolTipText property -{{source=..\SamplesCS\Buttons\Button.cs region=SetToolTipText}} -{{source=..\SamplesVB\Buttons\Button.vb region=SetToolTipText}} + + -````C# -this.radButton1.ButtonElement.ToolTipText = "I am a button"; -```` -````VB.NET -Me.radButton1.ButtonElement.ToolTipText = "I am a button" - -```` - -{{endregion}} ![WinForms RadButtons Setting ToolTipText](images/buttons-button-tooltips001.gif) #### Setting tool tips in the ToolTipTextNeeded event -{{source=..\SamplesCS\Buttons\Button.cs region=ToolTipTextNeeded}} -{{source=..\SamplesVB\Buttons\Button.vb region=ToolTipTextNeeded}} - -````C# -private void radButton1_ToolTipTextNeeded(object sender, Telerik.WinControls.ToolTipTextNeededEventArgs e) -{ - e.ToolTipText = "Click me"; -} - -```` -````VB.NET -Private Sub radButton1_ToolTipTextNeeded(sender As Object, e As Telerik.WinControls.ToolTipTextNeededEventArgs) - e.ToolTipText = "Click me" -End Sub + + -```` -{{endregion}} ![WinForms RadButtons Using ToolTipTextNeeded to Set ToolTipText](images/buttons-button-tooltips002.gif) diff --git a/controls/buttons/checkbox/customizing-appearance/accessing-and-customizing-elements.md b/controls/buttons/checkbox/customizing-appearance/accessing-and-customizing-elements.md index b257a461f..0ba45e16a 100644 --- a/controls/buttons/checkbox/customizing-appearance/accessing-and-customizing-elements.md +++ b/controls/buttons/checkbox/customizing-appearance/accessing-and-customizing-elements.md @@ -31,22 +31,7 @@ You can customize the nested elements at run time as well: #### Customize elements -{{source=..\SamplesCS\Buttons\CheckBox.cs region=AccessingCustomizingElements}} -{{source=..\SamplesVB\Buttons\CheckBox.vb region=AccessingCustomizingElements}} + + -````C# -this.radCheckBox1.ButtonElement.TextElement.ForeColor = Color.Blue; -this.radCheckBox1.ButtonElement.CheckMarkPrimitive.CheckElement.ForeColor = Color.Blue; -this.radCheckBox1.ButtonElement.CheckMarkPrimitive.Border.ForeColor = Color.Red; -this.radCheckBox1.ButtonElement.CheckMarkPrimitive.Border.BoxStyle = Telerik.WinControls.BorderBoxStyle.SingleBorder; -```` -````VB.NET -Me.radCheckBox1.ButtonElement.TextElement.ForeColor = Color.Blue -Me.radCheckBox1.ButtonElement.CheckMarkPrimitive.CheckElement.ForeColor = Color.Blue -Me.radCheckBox1.ButtonElement.CheckMarkPrimitive.Border.ForeColor = Color.Red -Me.radCheckBox1.ButtonElement.CheckMarkPrimitive.Border.BoxStyle = Telerik.WinControls.BorderBoxStyle.SingleBorder - -```` - -{{endregion}} diff --git a/controls/buttons/checkbox/databinding-radcheckbox.md b/controls/buttons/checkbox/databinding-radcheckbox.md index 52c302577..7ec71b685 100644 --- a/controls/buttons/checkbox/databinding-radcheckbox.md +++ b/controls/buttons/checkbox/databinding-radcheckbox.md @@ -26,32 +26,10 @@ Scroll down the property list and find the __IsChecked__ property. From the Bin You can also add __DataBindings__ to your control programmatically. The following code demonstrates binding the __IsChecked__ property to a column in a __DataTable__. -{{source=..\SamplesCS\Buttons\CheckBox.cs region=databinding}} -{{source=..\SamplesVB\Buttons\CheckBox.vb region=databinding}} - -````C# - -this.radCheckBox1.IsThreeState = false; -DataTable t = new DataTable(); -t.Columns.Add("A", typeof(bool)); -t.Rows.Add(true); -t.Rows.Add(false); -t.Rows.Add(true); -this.radCheckBox1.DataBindings.Add(new Binding("IsChecked", t, "A")); - -```` -````VB.NET -Me.radCheckBox1.IsThreeState = False -Dim t As New DataTable -t.Columns.Add("A", GetType(Boolean)) -t.Rows.Add(True) -t.Rows.Add(False) -t.Rows.Add(True) -Me.radCheckBox1.DataBindings.Add(New Binding("IsChecked", t, "A")) - -```` - -{{endregion}} + + + + diff --git a/controls/buttons/checkbox/getting-started.md b/controls/buttons/checkbox/getting-started.md index 4d95267c0..dd188e2f0 100644 --- a/controls/buttons/checkbox/getting-started.md +++ b/controls/buttons/checkbox/getting-started.md @@ -48,30 +48,10 @@ To programmatically add a __RadCheckBox__ to a form, create a new instance of a #### Adding a RadCheckBox at runtime -{{source=..\SamplesCS\Buttons\CheckBox.cs region=AddCheckBox}} -{{source=..\SamplesVB\Buttons\CheckBox.vb region=AddCheckBox}} - -````C# -public void AddCheckBox() -{ - RadCheckBox checkBox = new RadCheckBox(); - checkBox.ToggleState = Telerik.WinControls.Enumerations.ToggleState.On; - checkBox.Text = "Is active"; - this.Controls.Add(checkBox); -} - -```` -````VB.NET -Public Sub AddCheckBox() - Dim checkBox As New RadCheckBox() - checkBox.ToggleState = Telerik.WinControls.Enumerations.ToggleState.[On] - checkBox.Text = "Is active" - Me.Controls.Add(checkBox) -End Sub - -```` - -{{endregion}} + + + + ## See Also diff --git a/controls/buttons/checkbox/handling-radcheckbox-states.md b/controls/buttons/checkbox/handling-radcheckbox-states.md index 8869aa4e1..ff2e08c03 100644 --- a/controls/buttons/checkbox/handling-radcheckbox-states.md +++ b/controls/buttons/checkbox/handling-radcheckbox-states.md @@ -22,23 +22,10 @@ You can handle __ToggleStateChanged__ event of __RadCheckBox__ to take action wh You can also handle __ToggleStateChanging__ event. This event provides an opportunity to the toggle state change. The __StateChangingEventArgs__ passed as a parameter to the event handler have a __NewValue__ and __OldValue__ ToggleState members and a boolean __Cancel__ member. __NewValue__ holds the value of the __ToggleState__ that will be applied when the event is completed without being canceled. __OldValue__ holds the value of __ToggleState__ at the time the state change was initiated. __Canceled__ controls which value of __ToggleState__ is applied when the event completes. The default value is __false__ . Setting __Cancel__ to __true__ will prevent __ToggleStateChanged__ from firing and will leave the __ToggleState__ value as it was prior to the event. In the example below the __ToggleStateChanged__ event does not fire. -{{source=..\SamplesCS\Buttons\CheckBox.cs region=handlingToggleStateChanged}} -{{source=..\SamplesVB\Buttons\CheckBox.vb region=handlingToggleStateChanged}} -````C# -void radCheckBox1_ToggleStateChanged(object sender, StateChangedEventArgs args) -{ - MessageBox.Show(args.ToggleState.ToString()); -} - -```` -````VB.NET -Private Sub RadCheckBox1_ToggleStateChanged(ByVal sender As System.Object, ByVal args As Telerik.WinControls.UI.StateChangedEventArgs) - MessageBox.Show(args.ToggleState.ToString()) -End Sub - -```` - -{{endregion}} + + + + >note Due to the specifics of the [simple data binding](http://msdn.microsoft.com/en-us/library/system.windows.forms.binding(v=vs.110).aspx) we have introduced the __CheckStateChanging__ / __CheckStateChanged__ events together with the __CheckState__ property. These events and property provide the same functionality as the __ToggleStateChanged__, __ToggleStateChanging__ and the __ToggleState__ property, but give you the ability to simple data bind the control. diff --git a/controls/buttons/checkbox/tooltips.md b/controls/buttons/checkbox/tooltips.md index 1c04da7b7..1fc9af06b 100644 --- a/controls/buttons/checkbox/tooltips.md +++ b/controls/buttons/checkbox/tooltips.md @@ -14,42 +14,19 @@ There are two ways to assign tooltips to __RadCheckBox__, namely setting the __T #### Setting the ToolTipText property -{{source=..\SamplesCS\Buttons\CheckBox.cs region=SetToolTipText}} -{{source=..\SamplesVB\Buttons\CheckBox.vb region=SetToolTipText}} + + -````C# -this.radCheckBox1.ButtonElement.ToolTipText = "CheckBox tool tip"; -```` -````VB.NET -Me.radCheckBox1.ButtonElement.ToolTipText = "CheckBox tool tip" - -```` - -{{endregion}} ![WinForms RadCheckBox ToolTipText](images/buttons-checkbox-tooltips001.gif) #### Setting tool tips in the ToolTipTextNeeded event -{{source=..\SamplesCS\Buttons\CheckBox.cs region=ToolTipTextNeeded}} -{{source=..\SamplesVB\Buttons\CheckBox.vb region=ToolTipTextNeeded}} - -````C# -private void radCheckBox1_ToolTipTextNeeded(object sender, Telerik.WinControls.ToolTipTextNeededEventArgs e) -{ - e.ToolTipText = "I am a checkbox"; -} - -```` -````VB.NET -Private Sub radCheckBox1_ToolTipTextNeeded(sender As Object, e As Telerik.WinControls.ToolTipTextNeededEventArgs) - e.ToolTipText = "I am a checkbox" -End Sub + + -```` -{{endregion}} ![WinForms RadButtons ToolTipTextNeeded to set ToolTipText](images/buttons-checkbox-tooltips002.gif) diff --git a/controls/buttons/dropdownbutton/customizing-appearance/accessing-and-customizing-elements.md b/controls/buttons/dropdownbutton/customizing-appearance/accessing-and-customizing-elements.md index 90177b464..9838028b2 100644 --- a/controls/buttons/dropdownbutton/customizing-appearance/accessing-and-customizing-elements.md +++ b/controls/buttons/dropdownbutton/customizing-appearance/accessing-and-customizing-elements.md @@ -31,25 +31,8 @@ You can customize the nested elements at run time as well: #### Customize elements -{{source=..\SamplesCS\Buttons\DropDownButton.cs region=AccessingCustomizingElements}} -{{source=..\SamplesVB\Buttons\DropDownButton.vb region=AccessingCustomizingElements}} - -````C# -this.radDropDownButton1.DropDownButtonElement.ActionButton.ButtonFillElement.BackColor = Color.Red; -this.radDropDownButton1.DropDownButtonElement.ActionButton.ForeColor = Color.Yellow; -this.radDropDownButton1.DropDownButtonElement.ArrowButton.Fill.BackColor = Color.Yellow; -this.radDropDownButton1.DropDownButtonElement.ArrowButton.Border.BoxStyle = Telerik.WinControls.BorderBoxStyle.SingleBorder; -this.radDropDownButton1.DropDownButtonElement.ArrowButton.Border.ForeColor = Color.Black; - -```` -````VB.NET -Me.radDropDownButton1.DropDownButtonElement.ActionButton.ButtonFillElement.BackColor = Color.Red -Me.radDropDownButton1.DropDownButtonElement.ActionButton.ForeColor = Color.Yellow -Me.radDropDownButton1.DropDownButtonElement.ArrowButton.Fill.BackColor = Color.Yellow -Me.radDropDownButton1.DropDownButtonElement.ArrowButton.Border.BoxStyle = Telerik.WinControls.BorderBoxStyle.SingleBorder -Me.radDropDownButton1.DropDownButtonElement.ArrowButton.Border.ForeColor = Color.Black - -```` - -{{endregion}} + + + + diff --git a/controls/buttons/dropdownbutton/getting-started.md b/controls/buttons/dropdownbutton/getting-started.md index f44959a7d..a6de3cb35 100644 --- a/controls/buttons/dropdownbutton/getting-started.md +++ b/controls/buttons/dropdownbutton/getting-started.md @@ -47,35 +47,10 @@ To programmatically add a __RadDropDownButton__ to a form, create a new instanc #### Adding a RadButton at runtime -{{source=..\SamplesCS\Buttons\DropDownButton.cs region=CreatingButton}} -{{source=..\SamplesVB\Buttons\DropDownButton.vb region=CreatingButton}} - -````C# -RadDropDownButton radDropDownButton = new RadDropDownButton(); -radDropDownButton1.Text = "Fruits"; -RadMenuItem item1 = new RadMenuItem("Orange"); -radDropDownButton1.Items.Add(item1); -RadMenuItem item2 = new RadMenuItem("Lemon"); -radDropDownButton1.Items.Add(item2); -RadMenuItem item3 = new RadMenuItem("Banana"); -radDropDownButton1.Items.Add(item3); -this.Controls.Add(radDropDownButton); - -```` -````VB.NET -Dim radDropDownButton As New RadDropDownButton() -radDropDownButton1.Text = "Fruits" -Dim item1 As New RadMenuItem("Orange") -radDropDownButton1.Items.Add(item1) -Dim item2 As New RadMenuItem("Lemon") -radDropDownButton1.Items.Add(item2) -Dim item3 As New RadMenuItem("Banana") -radDropDownButton1.Items.Add(item3) -Me.Controls.Add(radDropDownButton) - -```` - -{{endregion}} + + + + ![WinForms RadButtons buttons-dropdownbutton-overview 001](images/buttons-dropdownbutton-overview001.png) @@ -83,53 +58,11 @@ Similarly, you can create item hierarchies in code by adding new __RadMenuItem__ #### Adding sub items -{{source=..\SamplesCS\Buttons\DropDownButton1.cs region=itemsHierarchy}} -{{source=..\SamplesVB\Buttons\DropDownButton1.vb region=itemsHierarchy}} - -````C# -using Telerik.WinControls.UI; -namespace RadDropDownButtonDemo -{ - public partial class Form1 : Form - { - private void Form1_Load(object sender, EventArgs e) - { - RadMenuItem mainItem = radDropDownButton1.Items[0] as RadMenuItem; - RadMenuItem mySubMenuItem = new RadMenuItem(); - mySubMenuItem.Text = "Submenu Item"; - mySubMenuItem.Click += new EventHandler(mySubMenuItem_Click); - mainItem.Items.Add(mySubMenuItem); - } - void mySubMenuItem_Click(object sender, EventArgs e) - { - MessageBox.Show((sender as RadMenuItem).Text + - " was clicked."); - } - } -} - -```` -````VB.NET -Imports System.Windows.Forms -Imports Telerik.WinControls.UI -Namespace RadDropDownButtonDemo - Public Class Form1 - Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) - Dim mainItem As RadMenuItem = TryCast(radDropDownButton1.Items(0), RadMenuItem) - Dim mySubMenuItem As New RadMenuItem() - mySubMenuItem.Text = "Submenu Item" - AddHandler mySubMenuItem.Click, AddressOf mySubMenuItem_Click - mainItem.Items.Add(mySubMenuItem) - End Sub - Sub mySubMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) - MessageBox.Show((TryCast(sender, RadMenuItem)).Text + " was clicked.") - End Sub - End Class -End Namespace - -```` - -{{endregion}} + + + + + ### Displaying Images with Items diff --git a/controls/buttons/dropdownbutton/key-shortcuts.md b/controls/buttons/dropdownbutton/key-shortcuts.md index 262de6c35..2a3c30533 100644 --- a/controls/buttons/dropdownbutton/key-shortcuts.md +++ b/controls/buttons/dropdownbutton/key-shortcuts.md @@ -15,35 +15,10 @@ Use the code below to open the drop-down menu using shortcuts(*Please refer to t #### Adding sub items -{{source=..\SamplesCS\Buttons\DropDownButton.cs region=keyShortcuts}} -{{source=..\SamplesVB\Buttons\DropDownButton.vb region=keyShortcuts}} - -````C# -public DropDownButton() -{ - InitializeComponent(); - this.radDropDownButton1.DropDownButtonElement.Shortcuts.Add(new RadShortcut(Keys.Control, Keys.N)); - this.radDropDownButton1.DropDownButtonElement.Click += new EventHandler(DropDownButtonElement_Click); -} -void DropDownButtonElement_Click(object sender, EventArgs e) -{ - this.radDropDownButton1.ShowDropDown(); -} - -```` -````VB.NET -Public Sub New() - InitializeComponent() - Me.radDropDownButton1.DropDownButtonElement.Shortcuts.Add(New RadShortcut(Keys.Control, Keys.B)) - AddHandler Me.radDropDownButton1.DropDownButtonElement.Click, AddressOf DropDownButtonElement_Click -End Sub -Sub DropDownButtonElement_Click(ByVal sender As Object, ByVal e As EventArgs) - Me.radDropDownButton1.ShowDropDown() -End Sub - -```` - -{{endregion}} + + + + diff --git a/controls/buttons/dropdownbutton/tooltips.md b/controls/buttons/dropdownbutton/tooltips.md index e72a5913a..f4b6e5c24 100644 --- a/controls/buttons/dropdownbutton/tooltips.md +++ b/controls/buttons/dropdownbutton/tooltips.md @@ -14,19 +14,10 @@ There are two ways to assign tooltips to __RadDropDownButton__, namely setting t #### Setting the ToolTipText property -{{source=..\SamplesCS\Buttons\DropDownButton.cs region=SetToolTipText}} -{{source=..\SamplesVB\Buttons\DropDownButton.vb region=SetToolTipText}} + + -````C# -this.radDropDownButton1.DropDownButtonElement.ToolTipText = "Click me"; -```` -````VB.NET -Me.radDropDownButton1.DropDownButtonElement.ToolTipText = "Click me" - -```` - -{{endregion}} >note In order to assign different tooltips for the action part and the arrow button, you must specify the __ToolTipText__ property of the DropDownButtonElement.__ActionButton__ or DropDownButtonElement.__ArrowButton__ element. @@ -34,39 +25,10 @@ Me.radDropDownButton1.DropDownButtonElement.ToolTipText = "Click me" #### Setting tool tips in the ToolTipTextNeeded event -{{source=..\SamplesCS\Buttons\DropDownButton.cs region=ToolTipTextNeeded}} -{{source=..\SamplesVB\Buttons\DropDownButton.vb region=ToolTipTextNeeded}} - -````C# -private void RadDropDownButton1_ToolTipTextNeeded(object sender, Telerik.WinControls.ToolTipTextNeededEventArgs e) -{ - ActionButtonElement actionButtonElement = sender as ActionButtonElement; - RadArrowButtonElement arrowButtonElement = sender as RadArrowButtonElement; - if (actionButtonElement!=null) - { - e.ToolTipText = "ActionButtonElement"; - } - else if (arrowButtonElement!=null) - { - e.ToolTipText = "RadArrowButtonElement"; - } -} - -```` -````VB.NET -Private Sub RadDropDownButton1_ToolTipTextNeeded(sender As Object, e As Telerik.WinControls.ToolTipTextNeededEventArgs) - Dim actionButtonElement As ActionButtonElement = TryCast(sender, ActionButtonElement) - Dim arrowButtonElement As RadArrowButtonElement = TryCast(sender, RadArrowButtonElement) - If actionButtonElement IsNot Nothing Then - e.ToolTipText = "ActionButtonElement" - ElseIf arrowButtonElement IsNot Nothing Then - e.ToolTipText = "RadArrowButtonElement" - End If -End Sub - -```` - -{{endregion}} + + + + ![WinForms RadButtons buttons-dropdownbutton-tooltips 002](images/buttons-dropdownbutton-tooltips002.gif) diff --git a/controls/buttons/dropdownbutton/working-with-raddropdownbutton-items.md b/controls/buttons/dropdownbutton/working-with-raddropdownbutton-items.md index 715b419f5..36a0f2457 100644 --- a/controls/buttons/dropdownbutton/working-with-raddropdownbutton-items.md +++ b/controls/buttons/dropdownbutton/working-with-raddropdownbutton-items.md @@ -40,90 +40,20 @@ You can also add __RadDropDownButton__ items in code at Run Time. The following #### Adding RadDropDownButton items -{{source=..\SamplesCS\Buttons\DropDownButton.cs region=creatingMenuItem}} -{{source=..\SamplesVB\Buttons\DropDownButton.vb region=creatingMenuItem}} - -````C# -void Form1_Load(object sender, EventArgs e) -{ - RadMenuItem myRadMenuItem = new RadMenuItem(); - myRadMenuItem.Text = "My New Item"; - radDropDownButton1.Items.Add(myRadMenuItem); - myRadMenuItem.Click += new EventHandler(myRadMenuItem_Click); -} -void myRadMenuItem_Click(object sender, EventArgs e) -{ - MessageBox.Show((sender as Telerik.WinControls.UI.RadMenuItem).Text + - " was clicked."); -} - -```` -````VB.NET -Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load - Dim myRadMenuItem As New RadMenuItem() - myRadMenuItem.Text = "My New Item" - radDropDownButton1.Items.Add(myRadMenuItem) - AddHandler myRadMenuItem.Click, AddressOf myRadMenuItem_Click -End Sub -Sub myRadMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) - MessageBox.Show((TryCast(sender, RadMenuItem)).Text + " was clicked.") -End Sub - -```` - -{{endregion}} + + + + Similarly, you can create item hierarchies in code by adding new __RadMenuItem__ objects to the __Items__ collection of your existing __RadMenuItem__. #### Adding sub items -{{source=..\SamplesCS\Buttons\DropDownButton1.cs region=itemsHierarchy}} -{{source=..\SamplesVB\Buttons\DropDownButton1.vb region=itemsHierarchy}} - -````C# -using Telerik.WinControls.UI; -namespace RadDropDownButtonDemo -{ - public partial class Form1 : Form - { - private void Form1_Load(object sender, EventArgs e) - { - RadMenuItem mainItem = radDropDownButton1.Items[0] as RadMenuItem; - RadMenuItem mySubMenuItem = new RadMenuItem(); - mySubMenuItem.Text = "Submenu Item"; - mySubMenuItem.Click += new EventHandler(mySubMenuItem_Click); - mainItem.Items.Add(mySubMenuItem); - } - void mySubMenuItem_Click(object sender, EventArgs e) - { - MessageBox.Show((sender as RadMenuItem).Text + - " was clicked."); - } - } -} - -```` -````VB.NET -Imports System.Windows.Forms -Imports Telerik.WinControls.UI -Namespace RadDropDownButtonDemo - Public Class Form1 - Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) - Dim mainItem As RadMenuItem = TryCast(radDropDownButton1.Items(0), RadMenuItem) - Dim mySubMenuItem As New RadMenuItem() - mySubMenuItem.Text = "Submenu Item" - AddHandler mySubMenuItem.Click, AddressOf mySubMenuItem_Click - mainItem.Items.Add(mySubMenuItem) - End Sub - Sub mySubMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) - MessageBox.Show((TryCast(sender, RadMenuItem)).Text + " was clicked.") - End Sub - End Class -End Namespace - -```` - -{{endregion}} + + + + + ## Displaying Images with Items diff --git a/controls/buttons/mnemonics.md b/controls/buttons/mnemonics.md index 94de1253a..c33269fed 100644 --- a/controls/buttons/mnemonics.md +++ b/controls/buttons/mnemonics.md @@ -15,19 +15,10 @@ __RadButton__, __RadCheckBox__, __RadRadioButton__, and __RadToggleButton__ supp All you need to do is to specify the character that will be used for a given control by placing the __&__ character before the desired symbol. The following example demonstrates how the __r__ key is used for radButton1 mnemonic: -{{source=..\SamplesCS\Buttons\Button.cs region=mnemonics}} -{{source=..\SamplesVB\Buttons\Button.vb region=mnemonics}} + + -````C# -this.radButton1.Text = "&radButton1"; -```` -````VB.NET -Me.radButton1.Text = "&radButton1" - -```` - -{{endregion}} ![WinForms RadButtons buttons-mnemonics](images/buttons-mnemonics001.png) diff --git a/controls/buttons/radiobutton/customizing-appearance/accessing-and-customizing-elements.md b/controls/buttons/radiobutton/customizing-appearance/accessing-and-customizing-elements.md index 314f6add7..c9d442edd 100644 --- a/controls/buttons/radiobutton/customizing-appearance/accessing-and-customizing-elements.md +++ b/controls/buttons/radiobutton/customizing-appearance/accessing-and-customizing-elements.md @@ -31,20 +31,7 @@ You can customize the nested elements at run time as well: #### Customize elements -{{source=..\SamplesCS\Buttons\RadioButton.cs region=AccessingCustomizingElements}} -{{source=..\SamplesVB\Buttons\RadioButton.vb region=AccessingCustomizingElements}} + + -````C# -this.radRadioButton1.ButtonElement.ForeColor = Color.Green; -this.radRadioButton1.ButtonElement.ShowBorder = true; -this.radRadioButton1.ButtonElement.BorderElement.ForeColor = Color.Black; -```` -````VB.NET -Me.radRadioButton1.ButtonElement.ForeColor = Color.Green -Me.radRadioButton1.ButtonElement.ShowBorder = True -Me.radRadioButton1.ButtonElement.BorderElement.ForeColor = Color.Black - -```` - -{{endregion}} diff --git a/controls/buttons/radiobutton/designing-radradiobutton-.md b/controls/buttons/radiobutton/designing-radradiobutton-.md index e9898ca38..875178670 100644 --- a/controls/buttons/radiobutton/designing-radradiobutton-.md +++ b/controls/buttons/radiobutton/designing-radradiobutton-.md @@ -31,21 +31,10 @@ Use the __TextImageRelation__ property to align the image with text. Note that t -{{source=..\SamplesCS\Buttons\RadioButtonDesigning.cs region=alignments}} -{{source=..\SamplesVB\Buttons\RadioButtonDesigning.vb region=alignments}} + + -````C# -this.radRadioButton10.RadioCheckAlignment = ContentAlignment.MiddleRight; -this.radRadioButton10.TextImageRelation = TextImageRelation.TextBeforeImage; -```` -````VB.NET -Me.radRadioButton10.RadioCheckAlignment = ContentAlignment.MiddleRight -Me.radRadioButton10.TextImageRelation = TextImageRelation.TextBeforeImage - -```` - -{{endregion}} ![WinForms RadButtons buttons-radiobutton-designing-radradiobutton 003](images/buttons-radiobutton-designing-radradiobutton003.png) @@ -57,19 +46,10 @@ To add multiple lines to radio button text in code use the newline "\n" characte #### Adding multiple lines -{{source=..\SamplesCS\Buttons\RadioButtonDesigning.cs region=settingText}} -{{source=..\SamplesVB\Buttons\RadioButtonDesigning.vb region=settingText}} - -````C# -radRadioButton1.Text = "One line" + System.Environment.NewLine + "Another line"; - -```` -````VB.NET -RadRadioButton1.Text = "One line" + System.Environment.NewLine + "Another line" + + -```` -{{endregion}} diff --git a/controls/buttons/radiobutton/getting-started.md b/controls/buttons/radiobutton/getting-started.md index 86bc69183..de8cc1bd9 100644 --- a/controls/buttons/radiobutton/getting-started.md +++ b/controls/buttons/radiobutton/getting-started.md @@ -48,25 +48,10 @@ To programmatically add a __RadRadioButton__ to a form, create a new instance o #### Adding RadRadioButton at run time -{{source=..\SamplesCS\Buttons\RadioButton.cs region=AddProgrammatically}} -{{source=..\SamplesVB\Buttons\RadioButton.vb region=AddProgrammatically}} + + -````C# -RadRadioButton radioButton = new RadRadioButton(); -radioButton.Text = "Medium size"; -radioButton.ToggleState = Telerik.WinControls.Enumerations.ToggleState.On; -this.Controls.Add(radioButton); -```` -````VB.NET -Dim radioButton As New RadRadioButton() -radioButton.Text = "Medium size" -radioButton.ToggleState = Telerik.WinControls.Enumerations.ToggleState.[On] -Me.Controls.Add(radioButton) - -```` - -{{endregion}} The following tutorial demonstrates creating two groups of radio buttons that act independently of one another. Choices are reflected in a label as they are selected. @@ -88,24 +73,10 @@ The following tutorial demonstrates creating two groups of radio buttons that ac #### Handling the ToggleStateChanged Event -{{source=..\SamplesCS\Buttons\RadioButton.cs region=handlingToggleStateChanged}} -{{source=..\SamplesVB\Buttons\RadioButton.vb region=handlingToggleStateChanged}} - -````C# -void radRadioButton1_ToggleStateChanged(object sender, StateChangedEventArgs args) -{ - lblStatus.Text = (sender as RadRadioButton).Text + " is selected"; -} - -```` -````VB.NET -Private Sub radRadioButton1_ToggleStateChanged(ByVal sender As Object, ByVal args As StateChangedEventArgs) - lblStatus.Text = (TryCast(sender, RadRadioButton)).Text + " is selected" -End Sub + + -```` -{{endregion}} 8\. Press __F5__ to run the application. Notice that selections made on radio buttons in the panel are independent of the radio button choices on the form. __RadRadioButton__ determines the radio groups by the control parent. All __RadRadioButtons__ sharing the same parent e.g. __RadGroupBox__, __RadPanel__ or a __Form__ will be part of one group. diff --git a/controls/buttons/radiobutton/handling-radradiobutton-states.md b/controls/buttons/radiobutton/handling-radradiobutton-states.md index 0fe6d01a7..f437c3ec5 100644 --- a/controls/buttons/radiobutton/handling-radradiobutton-states.md +++ b/controls/buttons/radiobutton/handling-radradiobutton-states.md @@ -21,54 +21,19 @@ You can handle the __ToggleStateChanged__ event of __RadRadioButton__ to take ac #### Handling ToggleStateChanged event -{{source=..\SamplesCS\Buttons\RadioButton.cs region=handlingToggleStateChangedWithArgs}} -{{source=..\SamplesVB\Buttons\RadioButton.vb region=handlingToggleStateChangedWithArgs}} + + -````C# -void radRadioButton2_ToggleStateChanged(object sender, StateChangedEventArgs args) -{ - MessageBox.Show(args.ToggleState.ToString()); -} -```` -````VB.NET -Private Sub radRadioButton2_ToggleStateChanged(ByVal sender As Object, ByVal args As StateChangedEventArgs) - MessageBox.Show(args.ToggleState.ToString()) -End Sub - -```` - -{{endregion}} You can also handle the __ToggleStateChanging__ event. This event provides an opportunity to cancel the toggle state change. The __StateChangingEventArgs__ passed as a parameter to the event handler have __NewValue__ and __OldValue__ ToggleState members and a Boolean __Cancel__ member. __NewValue__ holds the value of __ToggleState__ that will be applied when the event is completed without being canceled. __OldValue__ holds the value of __ToggleState__ at the time the state change was initiated. __Canceled__ controls which value of __ToggleState__ is applied when the event completes. The default value is __false__. Setting __Cancel__ to *true* will prevent the __ToggleStateChanged__ event from firing and will leave the __ToggleState__ value as it was prior to the event.  In the example below the __StateChangedEvent__ does not fire. #### Handling ToggleStateChanging event -{{source=..\SamplesCS\Buttons\RadioButton.cs region=StateChanging}} -{{source=..\SamplesVB\Buttons\RadioButton.vb region=StateChanging}} - -````C# -void radRadioButton3_ToggleStateChanging(object sender, StateChangingEventArgs args) -{ - args.Cancel = true; -} -void radRadioButton3_ToggleStateChanged(object sender, StateChangedEventArgs args) -{ - this.radRadioButton3.Text = args.ToggleState.ToString(); -} - -```` -````VB.NET -Private Sub radRadioButton3_ToggleStateChanging(ByVal sender As Object, ByVal args As StateChangingEventArgs) - args.Cancel = True -End Sub -Private Sub radRadioButton3_ToggleStateChanged(ByVal sender As Object, ByVal args As StateChangedEventArgs) - radRadioButton3.Text = args.ToggleState.ToString() -End Sub + + -```` -{{endregion}} >note Due to the specifics of the [simple data binding](http://msdn.microsoft.com/en-us/library/system.windows.forms.binding(v=vs.110).aspx) we have introduced the __CheckChanging__ / __CheckChanged__ events together with the __CheckState__ property. These events and property provide the same functionality as the __ToggleStateChanged__ , __ToggleStateChanging__ and the __ToggleState__ property, but give you the ability to simple data bind the control. > diff --git a/controls/buttons/radiobutton/tooltips.md b/controls/buttons/radiobutton/tooltips.md index 183c29e44..bf9723bde 100644 --- a/controls/buttons/radiobutton/tooltips.md +++ b/controls/buttons/radiobutton/tooltips.md @@ -14,43 +14,20 @@ There are two ways to assign tooltips to __RadRadioButton__, namely setting the #### Setting the ToolTipText property -{{source=..\SamplesCS\Buttons\RadioButton.cs region=SetToolTipText}} -{{source=..\SamplesVB\Buttons\RadioButton.vb region=SetToolTipText}} + + -````C# -this.radRadioButton1.ButtonElement.ToolTipText = "sample tooltip"; -```` -````VB.NET -Me.radRadioButton1.ButtonElement.ToolTipText = "sample tooltip" - -```` - -{{endregion}} ![WinForms RadRadioButton ToolTipText](images/buttons-radibutton-tooltips001.png) #### Setting tool tips in the ToolTipTextNeeded event -{{source=..\SamplesCS\Buttons\RadioButton.cs region=ToolTipTextNeeded}} -{{source=..\SamplesVB\Buttons\RadioButton.vb region=ToolTipTextNeeded}} - -````C# -private void RadRadioButton1_ToolTipTextNeeded(object sender, Telerik.WinControls.ToolTipTextNeededEventArgs e) -{ - e.ToolTipText = "Select a hot drink"; -} - -```` -````VB.NET -Private Sub RadRadioButton1_ToolTipTextNeeded(sender As Object, e As Telerik.WinControls.ToolTipTextNeededEventArgs) - e.ToolTipText = "Select a hot drink" -End Sub + + -```` -{{endregion}} ![WinForms RadRadioButton ToolTipTextNeeded](images/buttons-radibutton-tooltips002.png) diff --git a/controls/buttons/repeatbutton/customizing-appearance/accessing-and-customizing-elements.md b/controls/buttons/repeatbutton/customizing-appearance/accessing-and-customizing-elements.md index 72ee6588e..41aba3fef 100644 --- a/controls/buttons/repeatbutton/customizing-appearance/accessing-and-customizing-elements.md +++ b/controls/buttons/repeatbutton/customizing-appearance/accessing-and-customizing-elements.md @@ -32,28 +32,5 @@ You can customize the nested elements at run time as well: #### Customize elements -{{source=..\SamplesCS\Buttons\RepeatButton.cs region=AccessingCustomizingElements}} -{{source=..\SamplesVB\Buttons\RepeatButton.vb region=AccessingCustomizingElements}} - -````C# -this.radRepeatButton1.ButtonElement.TextElement.ForeColor = Color.Red; -this.radRepeatButton1.ButtonElement.ButtonFillElement.BackColor = Color.Aqua; -this.radRepeatButton1.ButtonElement.BorderElement.BoxStyle = Telerik.WinControls.BorderBoxStyle.FourBorders; -this.radRepeatButton1.ButtonElement.BorderElement.TopColor = Color.Aqua; -this.radRepeatButton1.ButtonElement.BorderElement.BottomColor = Color.Aqua; -this.radRepeatButton1.ButtonElement.BorderElement.LeftColor = Color.Red; -this.radRepeatButton1.ButtonElement.BorderElement.RightColor = Color.Red; - -```` -````VB.NET -Me.radRepeatButton1.ButtonElement.TextElement.ForeColor = Color.Red -Me.radRepeatButton1.ButtonElement.ButtonFillElement.BackColor = Color.Aqua -Me.radRepeatButton1.ButtonElement.BorderElement.BoxStyle = Telerik.WinControls.BorderBoxStyle.FourBorders -Me.radRepeatButton1.ButtonElement.BorderElement.TopColor = Color.Aqua -Me.radRepeatButton1.ButtonElement.BorderElement.BottomColor = Color.Aqua -Me.radRepeatButton1.ButtonElement.BorderElement.LeftColor = Color.Red -Me.radRepeatButton1.ButtonElement.BorderElement.RightColor = Color.Red - -```` - -{{endregion}} + + \ No newline at end of file diff --git a/controls/buttons/repeatbutton/tooltips.md b/controls/buttons/repeatbutton/tooltips.md index 826ac66b0..3a72af949 100644 --- a/controls/buttons/repeatbutton/tooltips.md +++ b/controls/buttons/repeatbutton/tooltips.md @@ -14,44 +14,15 @@ There are two ways to assign tooltips to __RadRepeatButton__, namely setting the #### Setting the ToolTipText property -{{source=..\SamplesCS\Buttons\RepeatButton.cs region=SetToolTipText}} -{{source=..\SamplesVB\Buttons\RepeatButton.vb region=SetToolTipText}} - -````C# -this.radRepeatButton1.ButtonElement.ToolTipText = "sample tooltip"; - -```` -````VB.NET - -Me.radRepeatButton1.ButtonElement.ToolTipText = "sample tooltip" - -```` - -{{endregion}} - + + ![WinForms RadRepeatButton ToolTipText](images/buttons-repeatbutton-tooltips001.png) #### Setting tool tips in the ToolTipTextNeeded event -{{source=..\SamplesCS\Buttons\RepeatButton.cs region=ToolTipTextNeeded}} -{{source=..\SamplesVB\Buttons\RepeatButton.vb region=ToolTipTextNeeded}} - -````C# -private void RadRepeatButton1_ToolTipTextNeeded(object sender, Telerik.WinControls.ToolTipTextNeededEventArgs e) -{ - e.ToolTipText = "Increase value"; -} - -```` -````VB.NET -Private Sub RadRepeatButton1_ToolTipTextNeeded(sender As Object, e As Telerik.WinControls.ToolTipTextNeededEventArgs) - e.ToolTipText = "Increase value" -End Sub - -```` - -{{endregion}} + + ![WinForms RadRepeatButton ToolTipTextNeeded](images/buttons-repeatbutton-tooltips002.png) diff --git a/controls/buttons/repeatbutton/working-with-radrepeatbutton.md b/controls/buttons/repeatbutton/working-with-radrepeatbutton.md index 2961a23e8..1c4ad5825 100644 --- a/controls/buttons/repeatbutton/working-with-radrepeatbutton.md +++ b/controls/buttons/repeatbutton/working-with-radrepeatbutton.md @@ -49,23 +49,8 @@ To programmatically add a __RadRepeatButton__ to a form, create a new instance #### Adding a RadButton at runtime -{{source=..\SamplesCS\Buttons\RepeatButton.cs region=creatingbutton}} -{{source=..\SamplesVB\Buttons\RepeatButton.vb region=creatingbutton}} - -````C# -RadRepeatButton repeatButton = new RadRepeatButton(); -repeatButton.Text = "Increase value"; -this.Controls.Add(repeatButton); - -```` -````VB.NET -Dim repeatButton As New RadRepeatButton() -repeatButton.Text = "Increase value" -Me.Controls.Add(repeatButton) - -```` - -{{endregion}} + + ### Working with RadRepeatButton @@ -76,35 +61,8 @@ To begin the repeat process, use the __ButtonClick__ event instead of __Click__ The following code illustrates the use of a __RadRepeatButton__ to manipulate a __ProgressBar__ control. At each interval the __ProgressBar__ value will increment. You do not need to write any additional code to handle the repeating event. As long as the mouse button is pressed down on the __RepeatButton__ control, the code in the __ButtonClick__ event handler will run at each interval. -{{source=..\SamplesCS\Buttons\RepeatButton.cs region=handlingClickEvent}} -{{source=..\SamplesVB\Buttons\RepeatButton.vb region=handlingClickEvent}} - -````C# -void radRepeatButton1_Click(object sender, EventArgs e) -{ - if (radProgressBar1.Value1 < radProgressBar1.Maximum) - { - radProgressBar1.Value1++; - } - else - { - radProgressBar1.Value1 = radProgressBar1.Minimum; - } -} - -```` -````VB.NET -Private Sub radRepeatButton1_Click(ByVal sender As Object, ByVal e As EventArgs) - If radProgressBar1.Value1 < radProgressBar1.Maximum Then - System.Math.Max(System.Threading.Interlocked.Increment(radProgressBar1.Value1), radProgressBar1.Value1 - 1) - Else - radProgressBar1.Value1 = radProgressBar1.Minimum - End If -End Sub - -```` - -{{endregion}} + + ![WinForms RadRepeatButton Overview](images/buttons-repeatbutton-overview001.gif) diff --git a/controls/buttons/splitbutton/customizing-appearance/accessing-and-customizing-elements.md b/controls/buttons/splitbutton/customizing-appearance/accessing-and-customizing-elements.md index a83a0b434..4f3984648 100644 --- a/controls/buttons/splitbutton/customizing-appearance/accessing-and-customizing-elements.md +++ b/controls/buttons/splitbutton/customizing-appearance/accessing-and-customizing-elements.md @@ -32,24 +32,5 @@ You can customize the nested elements at run time as well. #### Customize elements -{{source=..\SamplesCS\Buttons\SplitButton.cs region=AccessingCustomizingElements}} -{{source=..\SamplesVB\Buttons\SplitButton.vb region=AccessingCustomizingElements}} - -````C# -this.radSplitButton1.DropDownButtonElement.ActionButton.ButtonFillElement.BackColor = Color.Red; -this.radSplitButton1.DropDownButtonElement.ActionButton.ForeColor = Color.Yellow; -this.radSplitButton1.DropDownButtonElement.ArrowButton.Fill.BackColor = Color.Yellow; -this.radSplitButton1.DropDownButtonElement.ArrowButton.Border.BoxStyle = Telerik.WinControls.BorderBoxStyle.SingleBorder; -this.radSplitButton1.DropDownButtonElement.ArrowButton.Border.ForeColor = Color.Black; - -```` -````VB.NET -Me.radSplitButton1.DropDownButtonElement.ActionButton.ButtonFillElement.BackColor = Color.Red -Me.radSplitButton1.DropDownButtonElement.ActionButton.ForeColor = Color.Yellow -Me.radSplitButton1.DropDownButtonElement.ArrowButton.Fill.BackColor = Color.Yellow -Me.radSplitButton1.DropDownButtonElement.ArrowButton.Border.BoxStyle = Telerik.WinControls.BorderBoxStyle.SingleBorder -Me.radSplitButton1.DropDownButtonElement.ArrowButton.Border.ForeColor = Color.Black - -```` - -{{endregion}} + + \ No newline at end of file diff --git a/controls/buttons/splitbutton/right-to-left-support.md b/controls/buttons/splitbutton/right-to-left-support.md index 9e5a0f910..fd8deaeeb 100644 --- a/controls/buttons/splitbutton/right-to-left-support.md +++ b/controls/buttons/splitbutton/right-to-left-support.md @@ -15,19 +15,10 @@ previous_url: buttons-splitbutton-rtl You can present the content of your grid instance in a right-to-left direction by setting the __RightToLeft__ property to *Yes*: -{{source=..\SamplesCS\Buttons\SplitButton1.cs region=rtl}} -{{source=..\SamplesVB\Buttons\SplitButton1.vb region=rtl}} + + -````C# -radSplitButton1.RightToLeft = System.Windows.Forms.RightToLeft.Yes; -```` -````VB.NET -radSplitButton1.RightToLeft = System.Windows.Forms.RightToLeft.Yes - -```` - -{{endregion}} ![WinForms RadSplitButton Right to Left](images/buttons-splitbutton-rtl001.png) diff --git a/controls/buttons/splitbutton/tooltips.md b/controls/buttons/splitbutton/tooltips.md index fea88e4a6..cf8f31b45 100644 --- a/controls/buttons/splitbutton/tooltips.md +++ b/controls/buttons/splitbutton/tooltips.md @@ -14,19 +14,8 @@ There are two ways to assign tooltips to __RadSplitButton__, namely setting the #### Setting the ToolTipText property -{{source=..\SamplesCS\Buttons\SplitButton.cs region=SetToolTipText}} -{{source=..\SamplesVB\Buttons\SplitButton.vb region=SetToolTipText}} - -````C# -this.radSplitButton1.DropDownButtonElement.ToolTipText = "sample tooltip"; - -```` -````VB.NET -Me.radSplitButton1.DropDownButtonElement.ToolTipText = "sample tooltip" - -```` - -{{endregion}} + + >note In order to assign different tooltips for the action part and the arrow button, you must specify the __ToolTipText__ property of the RadSplitButtonElement.__ActionButton__ or RadSplitButtonElement.__ArrowButton__ element. @@ -34,39 +23,8 @@ Me.radSplitButton1.DropDownButtonElement.ToolTipText = "sample tooltip" #### Setting tool tips in the ToolTipTextNeeded event -{{source=..\SamplesCS\Buttons\SplitButton.cs region=ToolTipTextNeeded}} -{{source=..\SamplesVB\Buttons\SplitButton.vb region=ToolTipTextNeeded}} - -````C# -private void RadSplitButton1_ToolTipTextNeeded(object sender, Telerik.WinControls.ToolTipTextNeededEventArgs e) -{ - ActionButtonElement actionButtonElement = sender as ActionButtonElement; - RadArrowButtonElement arrowButtonElement = sender as RadArrowButtonElement; - if (actionButtonElement != null) - { - e.ToolTipText = "ActionButtonElement"; - } - else if (arrowButtonElement != null) - { - e.ToolTipText = "RadArrowButtonElement"; - } -} - -```` -````VB.NET -Private Sub RadSplitButton1_ToolTipTextNeeded(sender As Object, e As Telerik.WinControls.ToolTipTextNeededEventArgs) - Dim actionButtonElement As ActionButtonElement = TryCast(sender, ActionButtonElement) - Dim arrowButtonElement As RadArrowButtonElement = TryCast(sender, RadArrowButtonElement) - If actionButtonElement IsNot Nothing Then - e.ToolTipText = "ActionButtonElement" - ElseIf arrowButtonElement IsNot Nothing Then - e.ToolTipText = "RadArrowButtonElement" - End If -End Sub - -```` - -{{endregion}} + + ![WinForms RadSplitButton ToolTipTextNeededs](images/buttons-splitbutton-tooltips002.gif) diff --git a/controls/buttons/splitbutton/working-with-radsplitbutton-items.md b/controls/buttons/splitbutton/working-with-radsplitbutton-items.md index dd4e353f5..968dc40fe 100644 --- a/controls/buttons/splitbutton/working-with-radsplitbutton-items.md +++ b/controls/buttons/splitbutton/working-with-radsplitbutton-items.md @@ -48,35 +48,10 @@ To programmatically add a __RadSplitButton__ to a form, create a new instance of #### Adding a RadSplitButton at runtime -{{source=..\SamplesCS\Buttons\SplitButton.cs region=CreatingButton}} -{{source=..\SamplesVB\Buttons\SplitButton.vb region=CreatingButton}} - -````C# -RadSplitButton splitButton = new RadSplitButton(); -splitButton.Text = "Fruits"; -RadMenuItem item1 = new RadMenuItem("Orange"); -splitButton.Items.Add(item1); -RadMenuItem item2 = new RadMenuItem("Lemon"); -splitButton.Items.Add(item2); -RadMenuItem item3 = new RadMenuItem("Banana"); -splitButton.Items.Add(item3); -this.Controls.Add(splitButton); - -```` -````VB.NET -Dim splitButton As New RadSplitButton() -splitButton.Text = "Fruits" -Dim item1 As New RadMenuItem("Orange") -splitButton.Items.Add(item1) -Dim item2 As New RadMenuItem("Lemon") -splitButton.Items.Add(item2) -Dim item3 As New RadMenuItem("Banana") -splitButton.Items.Add(item3) -Me.Controls.Add(splitButton) - -```` - -{{endregion}} + + + + ### Working with RadSplitButton Items @@ -92,77 +67,20 @@ You can also add items to __RadSplitButton__ in code at run time. The following #### Adding a RadMenuItem -{{source=..\SamplesCS\Buttons\SplitButton.cs region=items}} -{{source=..\SamplesVB\Buttons\SplitButton.vb region=items}} - -````C# -private void Form1_Load(object sender, EventArgs e) -{ - RadMenuItem myRadMenuItem = new RadMenuItem(); - myRadMenuItem.Text = "My New Item"; - myRadMenuItem.Click += new EventHandler(myRadMenuItem_Click); - radSplitButton1.Items.Add(myRadMenuItem); -} -void myRadMenuItem_Click(object sender, EventArgs e) -{ - MessageBox.Show((sender as RadMenuItem).Text); -} - -```` -````VB.NET -Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load - Dim myRadMenuItem As New RadMenuItem() - myRadMenuItem.Text = "My New Item" - AddHandler myRadMenuItem.Click, AddressOf myRadMenuItem_Click - radSplitButton1.Items.Add(myRadMenuItem) -End Sub -Sub myRadMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) - MessageBox.Show((TryCast(sender, RadMenuItem)).Text) -End Sub - -```` - -{{endregion}} - + + + + + Create item hierarchies in code by adding new __RadMenuItem__ objects to the __Items__ collection of your existing __RadMenuItem__. #### Adding a sub item -{{source=..\SamplesCS\Buttons\SplitButton1.cs region=subitems}} -{{source=..\SamplesVB\Buttons\SplitButton1.vb region=subitems}} - -````C# -private void Form1_Load(object sender, EventArgs e) -{ - radSplitButton1.Items.Add(new RadMenuItem("AAA")); - RadMenuItem mySubMenuItem = new RadMenuItem(); - mySubMenuItem.Text = "Submenu Item"; - mySubMenuItem.Click += new EventHandler(mySubMenuItem_Click); - RadMenuItem mainItem = radSplitButton1.Items[0] as RadMenuItem; - mainItem.Items.Add(mySubMenuItem); -} -void mySubMenuItem_Click(object sender, EventArgs e) -{ - MessageBox.Show((sender as RadMenuItem).Text); -} - -```` -````VB.NET -Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load - Dim mySubMenuItem As New RadMenuItem() - mySubMenuItem.Text = "Submenu Item" - AddHandler mySubMenuItem.Click, AddressOf mySubMenuItem_Click - Dim mainItem As RadMenuItem = TryCast(radSplitButton1.Items(0), RadMenuItem) - mainItem.Items.Add(mySubMenuItem) -End Sub -Sub mySubMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) - MessageBox.Show((TryCast(sender, RadMenuItem)).Text) -End Sub - -```` - -{{endregion}} - + + + + + ### Displaying Images with Items You can display images as well as text on your menu items. @@ -185,20 +103,8 @@ The default item is the item whose __Click__ event is triggered by the user pres #### Assigning the default item -{{source=..\SamplesCS\Buttons\SplitButton1.cs region=mainItem}} -{{source=..\SamplesVB\Buttons\SplitButton1.vb region=mainItem}} - -````C# -radSplitButton1.DefaultItem = mainItem; - -```` -````VB.NET -radSplitButton1.DefaultItem = mainItem - -```` - -{{endregion}} - + + diff --git a/controls/buttons/togglebutton/customizing-appearance/accessing-and-customizing-elements.md b/controls/buttons/togglebutton/customizing-appearance/accessing-and-customizing-elements.md index 22656dc76..2930e6269 100644 --- a/controls/buttons/togglebutton/customizing-appearance/accessing-and-customizing-elements.md +++ b/controls/buttons/togglebutton/customizing-appearance/accessing-and-customizing-elements.md @@ -31,28 +31,5 @@ You can customize the nested elements at run time as well: #### Customize elements -{{source=..\SamplesCS\Buttons\ToggleButton.cs region=AccessingCustomizingElements}} -{{source=..\SamplesVB\Buttons\ToggleButton.vb region=AccessingCustomizingElements}} - -````C# -this.radToggleButton1.ButtonElement.TextElement.ForeColor = Color.Red; -this.radToggleButton1.ButtonElement.ButtonFillElement.BackColor = Color.Aqua; -this.radToggleButton1.ButtonElement.BorderElement.BoxStyle = Telerik.WinControls.BorderBoxStyle.FourBorders; -this.radToggleButton1.ButtonElement.BorderElement.TopColor = Color.Aqua; -this.radToggleButton1.ButtonElement.BorderElement.BottomColor = Color.Aqua; -this.radToggleButton1.ButtonElement.BorderElement.LeftColor = Color.Red; -this.radToggleButton1.ButtonElement.BorderElement.RightColor = Color.Red; - -```` -````VB.NET -Me.radToggleButton1.ButtonElement.TextElement.ForeColor = Color.Red -Me.radToggleButton1.ButtonElement.ButtonFillElement.BackColor = Color.Aqua -Me.radToggleButton1.ButtonElement.BorderElement.BoxStyle = Telerik.WinControls.BorderBoxStyle.FourBorders -Me.radToggleButton1.ButtonElement.BorderElement.TopColor = Color.Aqua -Me.radToggleButton1.ButtonElement.BorderElement.BottomColor = Color.Aqua -Me.radToggleButton1.ButtonElement.BorderElement.LeftColor = Color.Red -Me.radToggleButton1.ButtonElement.BorderElement.RightColor = Color.Red - -```` - -{{endregion}} + + \ No newline at end of file diff --git a/controls/buttons/togglebutton/getting-started.md b/controls/buttons/togglebutton/getting-started.md index bf9b40c8f..7d4833abd 100644 --- a/controls/buttons/togglebutton/getting-started.md +++ b/controls/buttons/togglebutton/getting-started.md @@ -47,27 +47,9 @@ To programmatically add a __RadToggleButton__ to a form, create a new instance #### Adding a RadToggleButton at runtime -{{source=..\SamplesCS\Buttons\ToggleButton.cs region=creatingbutton}} -{{source=..\SamplesVB\Buttons\ToggleButton.vb region=creatingbutton}} - -````C# -RadToggleButton myToggleButton = new RadToggleButton(); -myToggleButton.Text = "Pin"; -myToggleButton.Width = 150; -myToggleButton.Height = 50; -this.Controls.Add(myToggleButton); - -```` -````VB.NET -Dim myToggleButton As New RadToggleButton() -myToggleButton.Text = "Pin" -myToggleButton.Width = 150 -myToggleButton.Height = 50 -Me.Controls.Add(myToggleButton) - -```` - -{{endregion}} + + + ## Telerik UI for WinForms Learning Resources diff --git a/controls/buttons/togglebutton/handling-radtogglebutton-states.md b/controls/buttons/togglebutton/handling-radtogglebutton-states.md index b7007c581..347aa4cd3 100644 --- a/controls/buttons/togglebutton/handling-radtogglebutton-states.md +++ b/controls/buttons/togglebutton/handling-radtogglebutton-states.md @@ -25,24 +25,10 @@ You can handle the __ToggleStateChanged__ event of __RadToggleButton__ to take a #### Handling the ToggleStateChanged event -{{source=..\SamplesCS\Buttons\ToggleButton.cs region=handlingToggleStateChanged}} -{{source=..\SamplesVB\Buttons\ToggleButton.vb region=handlingToggleStateChanged}} + + -````C# -void radToggleButton1_ToggleStateChanged(object sender, StateChangedEventArgs args) -{ - MessageBox.Show(args.ToggleState.ToString()); -} -```` -````VB.NET -Private Sub radToggleButton1_ToggleStateChanged(ByVal sender As Object, ByVal args As Telerik.WinControls.UI.StateChangedEventArgs) - MessageBox.Show(args.ToggleState.ToString()) -End Sub - -```` - -{{endregion}} You can also handle the __ToggleStateChanging__ event. This event provides an opportunity to cancel the toggle state change. The __StateChangingEventArgs__ passed as a parameter to the event handler have __NewValue__ and __OldValue__ __ToggleState__ members and a Boolean __Cancel__ member. __NewValue__ holds the value of __ToggleState__ that will be applied when the event is completed without being canceled. __OldValue__ holds the value of __ToggleState__ at the time the state change was initiated. __Cancel__ controls which value of __ToggleState__ is applied when the event completes. The default is *false*. Setting the __Canceled__ proeprty to *true* will prevent the __ToggleStateChanged__ from firing and will leave the __ToggleState__ value as it was prior to the event. @@ -50,35 +36,10 @@ The example below allows a __RadToggleButton__ to toggle only when a second __Ra #### Handling the ToggleStateChanging event -{{source=..\SamplesCS\Buttons\ToggleButton.cs region=handlingToggleStateChanging}} -{{source=..\SamplesVB\Buttons\ToggleButton.vb region=handlingToggleStateChanging}} - -````C# -private void radToggleButton2_ToggleStateChanging(object sender, - Telerik.WinControls.UI.StateChangingEventArgs args) -{ - bool attemptingOn = args.NewValue == - Telerik.WinControls.Enumerations.ToggleState.On; - args.Cancel = true; -} -private void radToggleButton2_ToggleStateChanged(object sender, - Telerik.WinControls.UI.StateChangedEventArgs args) -{ - radToggleButton1.Text = args.ToggleState.ToString(); -} - -```` -````VB.NET -Private Sub radToggleButton2_ToggleStateChanging(ByVal sender As Object, ByVal args As Telerik.WinControls.UI.StateChangingEventArgs) - args.Cancel = True -End Sub -Private Sub radToggleButton2_ToggleStateChanged(ByVal sender As Object, ByVal args As Telerik.WinControls.UI.StateChangedEventArgs) - radToggleButton1.Text = args.ToggleState.ToString() -End Sub - -```` - -{{endregion}} + + + + >note Due to the specifics of the [simple data binding](http://msdn.microsoft.com/en-us/library/system.windows.forms.binding(v=vs.110).aspx) we have introduced the __CheckChanging__ / __CheckChanged__ events together with the __CheckState__ property. These events and property provide the same functionality as the __ToggleStateChanged__, __ToggleStateChanging__ and the __ToggleState__ property, but give you the ability to simple data bind the control. > diff --git a/controls/buttons/togglebutton/tooltips.md b/controls/buttons/togglebutton/tooltips.md index 23c66651b..cf57f115d 100644 --- a/controls/buttons/togglebutton/tooltips.md +++ b/controls/buttons/togglebutton/tooltips.md @@ -14,42 +14,15 @@ There are two ways to assign tooltips to __RadToggleButton__, namely setting the #### Setting the ToolTipText property -{{source=..\SamplesCS\Buttons\ToggleButton.cs region=SetToolTipText}} -{{source=..\SamplesVB\Buttons\ToggleButton.vb region=SetToolTipText}} - -````C# -this.radToggleButton1.ButtonElement.ToolTipText = "I am a toggle button"; - -```` -````VB.NET -Me.radToggleButton1.ButtonElement.ToolTipText = "I am a toggle button" - -```` - -{{endregion}} + + ![WinForms RadToggleButton ToolTipText](images/buttons-togglebutton-tooltips001.png) #### Setting tool tips in the ToolTipTextNeeded event -{{source=..\SamplesCS\Buttons\ToggleButton.cs region=ToolTipTextNeeded}} -{{source=..\SamplesVB\Buttons\ToggleButton.vb region=ToolTipTextNeeded}} - -````C# -private void RadToggleButton1_ToolTipTextNeeded(object sender, Telerik.WinControls.ToolTipTextNeededEventArgs e) -{ - e.ToolTipText = "Click me"; -} - -```` -````VB.NET -Private Sub RadToggleButton1_ToolTipTextNeeded(sender As Object, e As Telerik.WinControls.ToolTipTextNeededEventArgs) - e.ToolTipText = "Click me" -End Sub - -```` - -{{endregion}} + + ![WinForms RadToggleButton ToolTipTextNeeded](images/buttons-togglebutton-tooltips002.png) diff --git a/controls/buttons/toggleswitch/customizing-appearance/accessing-and-customizing-elements.md b/controls/buttons/toggleswitch/customizing-appearance/accessing-and-customizing-elements.md index de56c0397..d4ed2db11 100644 --- a/controls/buttons/toggleswitch/customizing-appearance/accessing-and-customizing-elements.md +++ b/controls/buttons/toggleswitch/customizing-appearance/accessing-and-customizing-elements.md @@ -30,41 +30,5 @@ __Customizing elements at run time__ -{{source=..\SamplesCS\Buttons\ToggleSwitch.cs region=CustomizeElements}} -{{source=..\SamplesVB\Buttons\ToggleSwitch.vb region=CustomizeElements}} - -````C# - -this.radToggleSwitch1.OnElement.BackColor = Color.GreenYellow; -this.radToggleSwitch1.OnElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid; -this.radToggleSwitch1.OnElement.ForeColor = Color.DarkCyan; - -this.radToggleSwitch1.OffElement.BackColor = Color.Red; -this.radToggleSwitch1.OffElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid; -this.radToggleSwitch1.OffElement.ForeColor = Color.Yellow; - -this.radToggleSwitch1.Thumb.BackColor = Color.Aqua; -this.radToggleSwitch1.Thumb.GradientStyle = Telerik.WinControls.GradientStyles.Solid; -this.radToggleSwitch1.Thumb.BorderColor = Color.DarkViolet; - -this.radToggleSwitch1.ToggleSwitchElement.BorderColor = Color.Fuchsia; - -```` -````VB.NET -Me.RadToggleSwitch1.OnElement.BackColor = System.Drawing.Color.GreenYellow -Me.RadToggleSwitch1.OnElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid -Me.RadToggleSwitch1.OnElement.ForeColor = System.Drawing.Color.DarkCyan -Me.RadToggleSwitch1.OffElement.BackColor = System.Drawing.Color.Red -Me.RadToggleSwitch1.OffElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid -Me.RadToggleSwitch1.OffElement.ForeColor = System.Drawing.Color.Yellow -Me.RadToggleSwitch1.Thumb.BackColor = System.Drawing.Color.Aqua -Me.RadToggleSwitch1.Thumb.GradientStyle = Telerik.WinControls.GradientStyles.Solid -Me.RadToggleSwitch1.Thumb.BorderColor = System.Drawing.Color.DarkViolet -Me.RadToggleSwitch1.ToggleSwitchElement.BorderColor = System.Drawing.Color.Fuchsia - -```` - -{{endregion}} - - - + + \ No newline at end of file diff --git a/controls/buttons/toggleswitch/getting-started.md b/controls/buttons/toggleswitch/getting-started.md index 804d7f3eb..66a5b768b 100644 --- a/controls/buttons/toggleswitch/getting-started.md +++ b/controls/buttons/toggleswitch/getting-started.md @@ -50,24 +50,8 @@ Adding __RadToggleSwitch__ programmatically: create a new instance of __RadToggl #### Adding RadToggleSwitch programmatically -{{source=..\SamplesCS\Buttons\ToggleSwitch.cs region=AddProgrammatically}} -{{source=..\SamplesVB\Buttons\ToggleSwitch.vb region=AddProgrammatically}} - -````C# - -Telerik.WinControls.UI.RadToggleSwitch toggleSwitch = new Telerik.WinControls.UI.RadToggleSwitch(); -this.Controls.Add(toggleSwitch); - -```` -````VB.NET -Dim toggleSwitch As New Telerik.WinControls.UI.RadToggleSwitch() -Me.Controls.Add(toggleSwitch) - -```` - -{{endregion}} - - + + >caption Figure 1: RadToggleSwitch added at run time diff --git a/controls/buttons/toggleswitch/tooltips.md b/controls/buttons/toggleswitch/tooltips.md index 418c3934b..b0c00b0ca 100644 --- a/controls/buttons/toggleswitch/tooltips.md +++ b/controls/buttons/toggleswitch/tooltips.md @@ -15,42 +15,15 @@ There are two ways to assign tooltips to __RadToggleSwitch__, namely setting the #### Setting the ToolTipText property -{{source=..\SamplesCS\Buttons\ToggleSwitch.cs region=SetToolTipText}} -{{source=..\SamplesVB\Buttons\ToggleSwitch.vb region=SetToolTipText}} - -````C# -this.radToggleSwitch1.ToggleSwitchElement.ToolTipText = "sample tooltip"; - -```` -````VB.NET -Me.RadToggleSwitch1.ToggleSwitchElement.ToolTipText = "sample tooltip" - -```` - -{{endregion}} + + ![WinForms RadToggleSwitch ToolTipText](images/buttons-toggleswitch-tooltips001.png) #### Setting tool tips in the ToolTipTextNeeded event -{{source=..\SamplesCS\Buttons\ToggleSwitch.cs region=ToolTipTextNeeded}} -{{source=..\SamplesVB\Buttons\ToggleSwitch.vb region=ToolTipTextNeeded}} - -````C# -private void RadToggleSwitch1_ToolTipTextNeeded(object sender, Telerik.WinControls.ToolTipTextNeededEventArgs e) -{ - e.ToolTipText = "Click me"; -} - -```` -````VB.NET -Private Sub RadToggleSwitch1_ToolTipTextNeeded(sender As Object, e As Telerik.WinControls.ToolTipTextNeededEventArgs) - e.ToolTipText = "Click me" -End Sub - -```` - -{{endregion}} + + ![WinForms RadToggleSwitch ToolTipTextNeeded](images/buttons-toggleswitch-tooltips002.png) diff --git a/controls/calculator/calculationbehavior.md b/controls/calculator/calculationbehavior.md index 2ec55b372..38363bf1d 100644 --- a/controls/calculator/calculationbehavior.md +++ b/controls/calculator/calculationbehavior.md @@ -20,97 +20,17 @@ It offers a convenient public API that can be used for any customization purpose 2\. Restrict all memory commands considering the passed CalculatorButtonType. In addition to this, Keys.NumPad5 is also forbidden by the keyboard: -{{source=..\SamplesCS\Calculator\CalculatorGettingStarted.cs region=Behavior}} -{{source=..\SamplesVB\Calculator\CalculatorGettingStarted.vb region=Behavior}} - -````C# - -public class CustomStandardCalculatorCalculationBehavior : StandardCalculatorCalculationBehavior -{ - public CustomStandardCalculatorCalculationBehavior(ICalculatorElement calculatorElement):base(calculatorElement) - { - } - //Handles keyboard input - public override void OnButtonKeyDown(KeyEventArgs e) - { - if (e.KeyData== Keys.NumPad5) - { - //restricts 5 from the Numpad - return; - } - base.OnButtonKeyDown(e); - } - - public override void OnButtonKeyPress(KeyPressEventArgs e) - { - //If someone needs to handle the input char, can use this method. - base.OnButtonKeyPress(e); - } - - //Handles mouse input - public override void OnButtonMouseUp(CalculatorButtonType buttonType, CalculatorAction buttonAction, MouseEventArgs e) - { - if (buttonType == CalculatorButtonType.Memory) - { - //restrict the memory commands - return; - } - base.OnButtonMouseUp(buttonType, buttonAction, e); - } -} - -```` -````VB.NET - -Public Class CustomStandardCalculatorCalculationBehavior - Inherits StandardCalculatorCalculationBehavior - - Public Sub New(ByVal calculatorElement As ICalculatorElement) - MyBase.New(calculatorElement) - End Sub - - Public Overrides Sub OnButtonKeyDown(ByVal e As KeyEventArgs) - If e.KeyData = Keys.NumPad5 Then - Return - End If - - MyBase.OnButtonKeyDown(e) - End Sub - - Public Overrides Sub OnButtonKeyPress(ByVal e As KeyPressEventArgs) - MyBase.OnButtonKeyPress(e) - End Sub - - Public Overrides Sub OnButtonMouseUp(ByVal buttonType As CalculatorButtonType, ByVal buttonAction As CalculatorAction, ByVal e As MouseEventArgs) - If buttonType = CalculatorButtonType.Memory Then - Return - End If - - MyBase.OnButtonMouseUp(buttonType, buttonAction, e) - End Sub -End Class - -```` - -{{endregion}} + + -3\. Apply the custom behavior to the CalculatorElement.**CalculationBehavior** property. - -{{source=..\SamplesCS\Calculator\CalculatorGettingStarted.cs region=Apply}} -{{source=..\SamplesVB\Calculator\CalculatorGettingStarted.vb region=Apply}} -````C# -this.radCalculator1.CalculatorElement.CalculationBehavior = new CustomStandardCalculatorCalculationBehavior(this.radCalculator1.CalculatorElement); - -```` -````VB.NET +3\. Apply the custom behavior to the CalculatorElement.**CalculationBehavior** property. -radCalculator1.CalculatorElement.CalculationBehavior = New CustomStandardCalculatorCalculationBehavior(radCalculator1.CalculatorElement) + + -```` -{{endregion}} # See Also diff --git a/controls/calculator/custom-functions.md b/controls/calculator/custom-functions.md index 9e9ea0194..01b5b7750 100644 --- a/controls/calculator/custom-functions.md +++ b/controls/calculator/custom-functions.md @@ -18,143 +18,10 @@ This article aims to show a sample approach how to create a custom function, |Ab >note The exact implementation of the custom calculation is just a sample approach. It may be customized according to the specific custom requirements that need to be covered. -{{source=..\SamplesCS\Calculator\CalculatorGettingStarted.cs region=CustomFunction}} -{{source=..\SamplesVB\Calculator\CalculatorGettingStarted.vb region=CustomFunction}} + + -````C# -public class CustomCalculator : RadCalculator -{ - public override string ThemeClassName - { - get - { - return typeof(RadCalculator).FullName; - } - } - protected override RadCalculatorElement CreateCalculatorElement() - { - return new CustomRadCalculatorElement(); - } -} - -public class CustomRadCalculatorElement : RadCalculatorElement -{ - protected override Type ThemeEffectiveType - { - get - { - return typeof(RadCalculatorElement); - } - } - - protected override RadCalculatorContentElement CreateContentElement() - { - return new CustomRadCalculatorContentElement(this); - } -} - -public class CustomRadCalculatorContentElement : RadCalculatorContentElement -{ - public CustomRadCalculatorContentElement(ICalculatorElement owner) : base(owner) - { - } - - protected override void CreateChildElements() - { - base.CreateChildElements(); - this.ButtonReciprocal.Visibility = ElementVisibility.Collapsed; - RadCalculatorOperationButtonElement button = new RadCalculatorOperationButtonElement("|Abs|", CalculatorAction.None); - button.SetValue(Telerik.WinControls.Layouts.GridLayout.RowIndexProperty, 3); - button.SetValue(Telerik.WinControls.Layouts.GridLayout.ColumnIndexProperty, 4); - button.Click += Button_Click; - button.SetValue(Telerik.WinControls.Layouts.GridLayout.CellPaddingProperty, new Padding(3)); - this.GridLayout.Children.Add(button); - } - - private void Button_Click(object sender, EventArgs e) - { - RadCalculatorElement calcElement = this.Owner as RadCalculatorElement; - - decimal entry = 0; - if (decimal.TryParse(calcElement.CalculationBehavior.DisplayedValue, out entry)) - { - calcElement.CalculationBehavior.ClearEverything(); - calcElement.CalculationBehavior.ClearStacksAndHistory(); - calcElement.CalculationBehavior.Value = Math.Abs(entry); - calcElement.CalculationBehavior.DisplayedValue = calcElement.CalculationBehavior.Value.ToString(calcElement.Culture); - } - } -} - - -```` -````VB.NET - -Public Class CustomCalculator - Inherits RadCalculator - - Public Overrides Property ThemeClassName As String - Get - Return GetType(RadCalculator).FullName - End Get - Set(value As String) - MyBase.ThemeClassName = value - End Set - End Property - Protected Overrides Function CreateCalculatorElement() As RadCalculatorElement - Return New CustomRadCalculatorElement() - End Function -End Class - -Public Class CustomRadCalculatorElement - Inherits RadCalculatorElement - - Protected Overrides ReadOnly Property ThemeEffectiveType As Type - Get - Return GetType(RadCalculatorElement) - End Get - End Property - - Protected Overrides Function CreateContentElement() As RadCalculatorContentElement - Return New CustomRadCalculatorContentElement(Me) - End Function -End Class - -Public Class CustomRadCalculatorContentElement - Inherits RadCalculatorContentElement - - Public Sub New(ByVal owner As ICalculatorElement) - MyBase.New(owner) - End Sub - - Protected Overrides Sub CreateChildElements() - MyBase.CreateChildElements() - Me.ButtonReciprocal.Visibility = ElementVisibility.Collapsed - Dim button As RadCalculatorOperationButtonElement = New RadCalculatorOperationButtonElement("|Abs|", CalculatorAction.None) - button.SetValue(Telerik.WinControls.Layouts.GridLayout.RowIndexProperty, 3) - button.SetValue(Telerik.WinControls.Layouts.GridLayout.ColumnIndexProperty, 4) - AddHandler button.Click, AddressOf Button_Click - button.SetValue(Telerik.WinControls.Layouts.GridLayout.CellPaddingProperty, New Padding(3)) - Me.GridLayout.Children.Add(button) - End Sub - - Private Sub Button_Click(ByVal sender As Object, ByVal e As EventArgs) - Dim calcElement As RadCalculatorElement = TryCast(Me.Owner, RadCalculatorElement) - Dim entry As Decimal = 0 - - If Decimal.TryParse(calcElement.CalculationBehavior.DisplayedValue, entry) Then - calcElement.CalculationBehavior.ClearEverything() - calcElement.CalculationBehavior.ClearStacksAndHistory() - calcElement.CalculationBehavior.Value = Math.Abs(entry) - calcElement.CalculationBehavior.DisplayedValue = calcElement.CalculationBehavior.Value.ToString(calcElement.Culture) - End If - End Sub -End Class - -```` - -{{endregion}} # See Also diff --git a/controls/calculator/getting-started.md b/controls/calculator/getting-started.md index 7eae802b3..374cb0222 100644 --- a/controls/calculator/getting-started.md +++ b/controls/calculator/getting-started.md @@ -40,30 +40,10 @@ The Telerik UI for WinForms assemblies can be install by using one of the availa To start using the __RadCalculator__ control, you can just add it to the Controls collection of your Form or drop it from the Toolbox. -{{source=..\SamplesCS\Calculator\CalculatorGettingStarted.cs region=GettingStarted}} -{{source=..\SamplesVB\Calculator\CalculatorGettingStarted.vb region=GettingStarted}} + + -````C# - public void AddCalculator() - { - var calculator = new RadCalculator(); - this.Controls.Add(calculator); - } - - -```` -````VB.NET - - Public Sub AddCalculator() - Dim calculator = New RadCalculator() - Me.Controls.Add(calculator) - End Sub - - -```` - -{{endregion}} ## See Also diff --git a/controls/calendar/customizing-appearance/formatting-items.md b/controls/calendar/customizing-appearance/formatting-items.md index 5485e455a..0627a4c34 100644 --- a/controls/calendar/customizing-appearance/formatting-items.md +++ b/controls/calendar/customizing-appearance/formatting-items.md @@ -14,38 +14,10 @@ The __ElementRender__ event will be fired before every element is painted. This #### Formating items in the ElementRender event. -{{source=..\SamplesCS\Calendar\FormattingItems.cs region=RenderEvent}} -{{source=..\SamplesVB\Calendar\FormattingItems.vb region=RenderEvent}} -````C# -private void RadCalendar1_ElementRender(object sender, RenderElementEventArgs e) -{ - if (e.Day.Date.DayOfWeek == DayOfWeek.Monday || e.Day.Date.DayOfWeek == DayOfWeek.Thursday) - { - e.Element.DrawBorder = true; - e.Element.BorderColor = ColorTranslator.FromHtml("#51ab2e"); - } - else - { - e.Element.ResetValue(LightVisualElement.DrawBorderProperty, ValueResetFlags.Local); - e.Element.ResetValue(LightVisualElement.BorderColorProperty, ValueResetFlags.Local); - } -} - -```` -````VB.NET -Private Sub RadCalendar1_ElementRender(ByVal sender As Object, ByVal e As RenderElementEventArgs) - If e.Day.Date.DayOfWeek = DayOfWeek.Monday OrElse e.Day.Date.DayOfWeek = DayOfWeek.Thursday Then - e.Element.DrawBorder = True - e.Element.BorderColor = ColorTranslator.FromHtml("#51ab2e ") - Else - e.Element.ResetValue(LightVisualElement.DrawBorderProperty, ValueResetFlags.Local) - e.Element.ResetValue(LightVisualElement.BorderColorProperty, ValueResetFlags.Local) - End If -End Sub - -```` - -{{endregion}} + + + + >caption Figure 1: RadCalendar with custom cells border. ![WinForms RadCalendar With custom Cells Border](images/calendar-formatting-items001.png) @@ -56,18 +28,10 @@ Since the event is called when the calendar is made visible, you may need to tri #### Trigger the ElementRender event at run-time. -{{source=..\SamplesCS\Calendar\FormattingItems.cs region=refresh}} -{{source=..\SamplesVB\Calendar\FormattingItems.vb region=refresh}} -````C# -radCalendar1.CalendarElement.RefreshVisuals(); - -```` -````VB.NET -radCalendar1.CalendarElement.RefreshVisuals() + + -```` -{{endregion}} ## See Also diff --git a/controls/calendar/customizing-appearance/using-templates.md b/controls/calendar/customizing-appearance/using-templates.md index 94864b171..0b093ae4c 100644 --- a/controls/calendar/customizing-appearance/using-templates.md +++ b/controls/calendar/customizing-appearance/using-templates.md @@ -23,27 +23,10 @@ In the example below a __PictureBox__ control is created and assigned an image f #### Assigning a TemplateItem -{{source=..\SamplesCS\Calendar\Calendar1.cs region=templateItem}} -{{source=..\SamplesVB\Calendar\Calendar1.vb region=templateItem}} - -````C# -PictureBox pictureBox = new PictureBox(); -pictureBox.SizeMode = PictureBoxSizeMode.StretchImage; -pictureBox.Image = imageList1.Images[0]; -RadHostItem hostItem = new RadHostItem(pictureBox); -radCalendar1.SpecialDays[0].TemplateItem = hostItem; - -```` -````VB.NET -Dim pictureBox As New PictureBox() -pictureBox.SizeMode = PictureBoxSizeMode.StretchImage -pictureBox.Image = ImageList1.Images(0) -Dim hostItem As New RadHostItem(pictureBox) -RadCalendar1.SpecialDays(0).TemplateItem = hostItem - -```` - -{{endregion}} + + + + ## See Also diff --git a/controls/calendar/customizing-behavior/customizing-zoom-navigation.md b/controls/calendar/customizing-behavior/customizing-zoom-navigation.md index 8cdf2e17c..ed645a850 100644 --- a/controls/calendar/customizing-behavior/customizing-zoom-navigation.md +++ b/controls/calendar/customizing-behavior/customizing-zoom-navigation.md @@ -13,56 +13,18 @@ previous_url: calendar-customizing-behavior-customizing-zoom-navigation This article will guide you through the process of creating a month-year picker. For this purpose, it is necessary to set the __HeaderNavigationMode__ property to HeaderNavigationMode.*Zoom* and set the __ZoomLevel__ property to ZoomLevel.*Months*. This will allow the user to select a specific __CalendarCellElement__ and navigate upwards/downwards in the __RadCalendar__ similar to Windows calendar. -{{source=..\SamplesCS\Calendar\Calendar1.cs region=monthYearPicker}} -{{source=..\SamplesVB\Calendar\Calendar1.vb region=monthYearPicker}} + + -````C# -this.radCalendar1.HeaderNavigationMode = HeaderNavigationMode.Zoom; -this.radCalendar1.ZoomLevel = ZoomLevel.Months; -this.radCalendar1.ZoomChanging += new CalendarZoomChangingEventHandler(radCalendar1_ZoomChanging); -```` -````VB.NET -Me.RadCalendar1.HeaderNavigationMode = HeaderNavigationMode.Zoom -Me.RadCalendar1.ZoomLevel = ZoomLevel.Months -AddHandler Me.RadCalendar1.ZoomChanging, AddressOf radCalendar1_ZoomChanging -```` - -{{endregion}} In addition, you should subscribe to the __ZoomChanging__ event and stop navigation from the currently selected month to its days representation and from a year to a range of years. -{{source=..\SamplesCS\Calendar\Calendar1.cs region=monthYearPickerEvent}} -{{source=..\SamplesVB\Calendar\Calendar1.vb region=monthYearPickerEvent}} - -````C# -void radCalendar1_ZoomChanging(object sender, CalendarZoomChangingEventArgs e) -{ - if (this.radCalendar1.ZoomLevel == ZoomLevel.Years && e.Direction == DrillDirection.Up) - { - e.Cancel = true; - } - if (this.radCalendar1.ZoomLevel == ZoomLevel.Months && e.Direction == DrillDirection.Down) - { - e.Cancel = true; - } -} - -```` -````VB.NET -Private Sub radCalendar1_ZoomChanging(sender As Object, e As CalendarZoomChangingEventArgs) - If Me.RadCalendar1.ZoomLevel = ZoomLevel.Years AndAlso e.Direction = DrillDirection.Up Then - e.Cancel = True - End If - If Me.RadCalendar1.ZoomLevel = ZoomLevel.Months AndAlso e.Direction = DrillDirection.Down Then - e.Cancel = True - End If -End Sub + + -```` -{{endregion}} >caption Figure 1: The zoom level is limited to months. diff --git a/controls/calendar/features/column-and-row-headers.md b/controls/calendar/features/column-and-row-headers.md index d10f8e3ee..77bca0df8 100644 --- a/controls/calendar/features/column-and-row-headers.md +++ b/controls/calendar/features/column-and-row-headers.md @@ -17,44 +17,19 @@ __RadCalendar__ supports row and column headers that can be enabled by setting t ![WinForms RadCalendar The Column/Row Headers and The View Selector](images/calendar-features-column-and-row-headers001.png) -{{source=..\SamplesCS\Calendar\ColumnRowHeaders.cs region=showingHeaders}} -{{source=..\SamplesVB\Calendar\ColumnRowHeaders.vb region=showingHeaders}} + + -````C# -this.radCalendar1.ShowRowHeaders = true; -this.radCalendar1.ShowColumnHeaders = true; -this.radCalendar1.ShowViewSelector = true; -```` -````VB.NET -Me.RadCalendar1.ShowRowHeaders = True -Me.RadCalendar1.ShowColumnHeaders = True -Me.RadCalendar1.ShowViewSelector = True - -```` - -{{endregion}} These headers can be used as selectors which allow you to quickly select groups of days in multi-select mode. The __ViewSelector__ allows you to select the whole month view at once. -{{source=..\SamplesCS\Calendar\ColumnRowHeaders.cs region=allowMultiSelect}} -{{source=..\SamplesVB\Calendar\ColumnRowHeaders.vb region=allowMultiSelect}} - -````C# -this.radCalendar1.AllowMultipleSelect = true; -this.radCalendar1.AllowColumnHeaderSelectors = true; -this.radCalendar1.AllowRowHeaderSelectors = true; + + -```` -````VB.NET -Me.RadCalendar1.AllowMultipleSelect = True -Me.RadCalendar1.AllowColumnHeaderSelectors = True -Me.RadCalendar1.AllowRowHeaderSelectors = True -```` -{{endregion}} >caption Selecting specific day with column header ![WinForms RadCalendar Selecting Specific Day With Column Header](images/calendar-fatures-column-and-row-headers002.png) diff --git a/controls/calendar/features/footer.md b/controls/calendar/features/footer.md index dd65b0b96..62833c212 100644 --- a/controls/calendar/features/footer.md +++ b/controls/calendar/features/footer.md @@ -25,21 +25,11 @@ By default the footer contains a string showing the current date and time and tw #### Using the Today button -{{source=..\SamplesCS\Calendar\Calendar1.cs region=usingTodayButton}} -{{source=..\SamplesVB\Calendar\Calendar1.vb region=usingTodayButton}} + + -````C# -radCalendar1.TodayButton.Text = "Go to Today"; -radCalendar1.TodayButton.Image = imageList1.Images[0]; -```` -````VB.NET -RadCalendar1.TodayButton.Text = "Go to Today" -RadCalendar1.TodayButton.Image = ImageList1.Images(0) -```` - -{{endregion}} * __ClearButton__: Gets an instance of RadButtonElement representing the Clear button in the footer. diff --git a/controls/calendar/features/multiview-mode.md b/controls/calendar/features/multiview-mode.md index 8d583e4de..cb0639e3f 100644 --- a/controls/calendar/features/multiview-mode.md +++ b/controls/calendar/features/multiview-mode.md @@ -20,27 +20,10 @@ The code sample below shows how multiple views can be configured and positioned. #### Configuring multiple views -{{source=..\SamplesCS\Calendar\MultiViewCalendar.cs region=multiView}} -{{source=..\SamplesVB\Calendar\MultiViewCalendar.vb region=multiView}} - -````C# -radCalendar1.AllowMultipleView = true; -radCalendar1.MultiViewColumns = 3; -radCalendar1.MultiViewRows = 3; -radCalendar1.CurrentViewColumn = 0; -radCalendar1.CurrentViewRow = 0; - -```` -````VB.NET -RadCalendar1.AllowMultipleView = True -RadCalendar1.MultiViewColumns = 3 -RadCalendar1.MultiViewRows = 3 -RadCalendar1.CurrentViewColumn = 0 -RadCalendar1.CurrentViewRow = 0 - -```` - -{{endregion}} + + + + >caption Figure 2: MultiView with 3 rows and 3 columns ![WinForms RadCalendar MultiView with 3 rows and 3 columns](images/calendar-features-multi-view-mode002.png) diff --git a/controls/calendar/features/repeating-events.md b/controls/calendar/features/repeating-events.md index 0f9c9c9fe..1c2c4a2d4 100644 --- a/controls/calendar/features/repeating-events.md +++ b/controls/calendar/features/repeating-events.md @@ -38,27 +38,10 @@ The example below creates a __RadCalendarDay__ and assigns the __Date__. The __R __Configuring a recurring event__ -{{source=..\SamplesCS\Calendar\Calendar1.cs region=calendarDays}} -{{source=..\SamplesVB\Calendar\Calendar1.vb region=calendarDays}} - -````C# -RadCalendarDay day = new RadCalendarDay(); -day.Date = new DateTime(2011, 2, 5, 0, 0, 0, 0); -day.Recurring = RecurringEvents.DayInMonth; -day.Selectable = false; -radCalendar1.SpecialDays.Add(day); - -```` -````VB.NET -Dim day As New RadCalendarDay() -day.Date = New DateTime(2011, 2, 5, 0, 0, 0, 0) -day.Recurring = RecurringEvents.DayInMonth -day.Selectable = False -RadCalendar1.SpecialDays.Add(day) - -```` - -{{endregion}} + + + + ## See Also diff --git a/controls/calendar/features/selecting-dates.md b/controls/calendar/features/selecting-dates.md index 014d36ea8..b8955974a 100644 --- a/controls/calendar/features/selecting-dates.md +++ b/controls/calendar/features/selecting-dates.md @@ -29,46 +29,17 @@ To select a single day assign a __DateTime__ value to the __SelectedDate__ prope #### Selecting dates -{{source=..\SamplesCS\Calendar\Calendar1.cs region=selectingDates}} -{{source=..\SamplesVB\Calendar\Calendar1.vb region=selectingDates}} - -````C# -radCalendar1.AllowMultipleSelect = true; -radCalendar1.SelectedDates.Add(new DateTime(2006, 10, 20, 0, 0, 0, 0)); -radCalendar1.SelectedDates.Add(new DateTime(2006, 10, 19, 0, 0, 0, 0)); -radCalendar1.SelectedDates.Add(new DateTime(2006, 10, 18, 0, 0, 0, 0)); - -```` -````VB.NET -RadCalendar1.AllowMultipleSelect = True -RadCalendar1.SelectedDates.Add(New DateTime(2006, 10, 20, 0, 0, 0, 0)) -RadCalendar1.SelectedDates.Add(New DateTime(2006, 10, 19, 0, 0, 0, 0)) -RadCalendar1.SelectedDates.Add(New DateTime(2006, 10, 18, 0, 0, 0, 0)) - -```` - -{{endregion}} + + + You may also use the SelectedDates.AddRange() method to add an array of DateTime values: #### Using the AddRange method -{{source=..\SamplesCS\Calendar\Calendar1.cs region=usingAddRange}} -{{source=..\SamplesVB\Calendar\Calendar1.vb region=usingAddRange}} - -````C# -radCalendar1.SelectedDate = new System.DateTime(2007, 9, 17, 0, 0, 0, 0); -radCalendar1.SelectedDates.AddRange(new DateTime[] { new DateTime(2007, 9, 17, 0, 0, 0, 0) }); - -```` -````VB.NET -RadCalendar1.SelectedDate = New Date(2007, 9, 17, 0, 0, 0, 0) -RadCalendar1.SelectedDates.AddRange(New Date() {New Date(2007, 9, 17, 0, 0, 0, 0)}) - -```` - -{{endregion}} + + ## See Also diff --git a/controls/calendar/getting-started.md b/controls/calendar/getting-started.md index 7d89be8ea..ad4ab04b6 100644 --- a/controls/calendar/getting-started.md +++ b/controls/calendar/getting-started.md @@ -63,38 +63,10 @@ The Telerik UI for WinForms assemblies can be install by using one of the availa #### Iterating the SelectedDates and SpecialDates collections -{{source=..\SamplesCS\Calendar\Calendar1.cs region=iteratingSpecialSelected}} -{{source=..\SamplesVB\Calendar\Calendar1.vb region=iteratingSpecialSelected}} - -````C# -private void radButton1_Click(object sender, EventArgs e) -{ - foreach (DateTime dateTime in radCalendar1.SelectedDates) - { - radListControl1.Items.Add( - new RadListDataItem("Selected: " + dateTime.ToShortDateString())); - } - foreach (RadCalendarDay day in radCalendar1.SpecialDays) - { - radListControl1.Items.Add( - new RadListDataItem("Special: " + day.Date.ToShortDateString())); - } -} - -```` -````VB.NET -Private Sub radButton1_Click(ByVal sender As Object, ByVal e As EventArgs) - For Each dateTime As DateTime In RadCalendar1.SelectedDates - RadListControl1.Items.Add(New RadListDataItem("Selected: " + dateTime.ToShortDateString())) - Next - For Each day As RadCalendarDay In RadCalendar1.SpecialDays - RadListControl1.Items.Add(New RadListDataItem("Special: " + day.[Date].ToShortDateString())) - Next -End Sub - -```` - -{{endregion}} + + + + Run the application. Notice the three selected and the highlighted special day. Use the navigation buttons at the top of the calendar ">" to move to another month. Because you set the special day __Recurring__ property to *DayInMonth*, the special day is highlighted in every month. diff --git a/controls/calendar/localization/cultureinfo-and-regioninfo-basics.md b/controls/calendar/localization/cultureinfo-and-regioninfo-basics.md index 405283b75..9315314b3 100644 --- a/controls/calendar/localization/cultureinfo-and-regioninfo-basics.md +++ b/controls/calendar/localization/cultureinfo-and-regioninfo-basics.md @@ -39,19 +39,10 @@ The table below is a sample list of the names and identifiers found in the Cult ![WinForms RadCalendar Setting Pashto Culture](images/calendar-localization-cultureinfo-and-regioninfo-basics001.png) -{{source=..\SamplesCS\Calendar\Calendar1.cs region=SetPashtoCulture}} -{{source=..\SamplesVB\Calendar\Calendar1.vb region=SetPashtoCulture}} + + -````C# -this.radCalendar1.Culture = new System.Globalization.CultureInfo("ps-AF"); -```` -````VB.NET -Me.RadCalendar1.Culture = New System.Globalization.CultureInfo("ps-AF") - -```` - -{{endregion}} >note There is a known issue in the .NET Framework considering the "fa-IR" culture. Please refer to the following MSDN resource for a solution: [Fixing Persian Locale for Persian Calendar and Month Names](https://code.msdn.microsoft.com/Fixing-Persian-Locale-for-6e66e044) diff --git a/controls/calendar/localization/globalization-properties.md b/controls/calendar/localization/globalization-properties.md index 23066769b..76b2ba567 100644 --- a/controls/calendar/localization/globalization-properties.md +++ b/controls/calendar/localization/globalization-properties.md @@ -20,19 +20,10 @@ The __Culture__ property can be set using the drop down list in the Properties #### Setting CultureInfo in code -{{source=..\SamplesCS\Calendar\ColumnRowHeaders.cs region=globalization}} -{{source=..\SamplesVB\Calendar\ColumnRowHeaders.vb region=globalization}} + + -````C# -radCalendar1.Culture = CultureInfo.GetCultureInfo("fr-FR"); -```` -````VB.NET -RadCalendar1.Culture = CultureInfo.GetCultureInfo("fr-FR") - -```` - -{{endregion}} diff --git a/controls/calendar/localization/localization-provider.md b/controls/calendar/localization/localization-provider.md index 2691e1e3f..1b79dfaf2 100644 --- a/controls/calendar/localization/localization-provider.md +++ b/controls/calendar/localization/localization-provider.md @@ -26,61 +26,14 @@ To localize RadCalendar to display control text and messages in a specific langu Below is a sample implementation of an English localization provider: -{{source=..\SamplesCS\Calendar\Localization\LocalizationProvider.cs region=Localization}} -{{source=..\SamplesVB\Calendar\Localization\LocalizationProvider.vb region=Localization}} - -````C# -public class MyEnglishCalendarLocalizationProvider : CalendarLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case CalendarStringId.CalendarClearButton: - return "Close"; - case CalendarStringId.CalendarTodayButton: - return "Today"; - default: - return base.GetLocalizedString(id); - } - } -} - -```` -````VB.NET -Public Class MyEnglishCalendarLocalizationProvider - Inherits CalendarLocalizationProvider - Public Overrides Function GetLocalizedString(id As String) As String - Select Case id - Case CalendarStringId.CalendarClearButton - Return "Clear" - Case CalendarStringId.CalendarTodayButton - Return "Today" - Case Else - Return MyBase.GetLocalizedString(id) - End Select - End Function -End Class - -```` - -{{endregion}} + + + To apply the custom localization provider, instantiate and assign it to the current localization provider: -{{source=..\SamplesCS\Calendar\Localization\LocalizationProvider.cs region=Usage}} -{{source=..\SamplesVB\Calendar\Localization\LocalizationProvider.vb region=Usage}} - -````C# -CalendarLocalizationProvider.CurrentProvider = new MyEnglishCalendarLocalizationProvider(); - -```` -````VB.NET -CalendarLocalizationProvider.CurrentProvider = New MyEnglishCalendarLocalizationProvider() - -```` - -{{endregion}} + + ## See Also diff --git a/controls/calendar/localization/properties-that-can-be-localized.md b/controls/calendar/localization/properties-that-can-be-localized.md index e8494bbe3..3c283be6d 100644 --- a/controls/calendar/localization/properties-that-can-be-localized.md +++ b/controls/calendar/localization/properties-that-can-be-localized.md @@ -1,68 +1,57 @@ ---- -title: Properties that can be Localized -page_title: Properties that can be localized - WinForms Calendar Control -description: WinForms Calendar offers properties that can be localized. -slug: winforms/calendar/localization/properties-that-can-be-localized -tags: properties,that,can,be,localized -published: True -position: 4 -previous_url: calendar-localization-properties-that-can-be-localized ---- - -# Properties that can be Localized - -The following properties can be localized: - - -| Property | Description | -| ------ | ------ | -|NavigationPrevText|Gets or sets the text displayed for the previous month navigation control.| -|NavigationNextText|Gets or sets the text displayed for the next month navigation control.| -|FastNavigationPrevText|Gets or sets the text displayed for the fast previous navigation control.| -|FastNavigationNextText|Gets or sets the text displayed for the fast next navigation control.| -|NavigationPrevToolTip|Gets or sets the text displayed as a tooltip for the previous month navigation control.| -|NavigationNextToolTip|Gets or sets the text displayed as a tooltip for the next month navigation control.| -|FastNavigationPrevToolTip|Gets or sets the text displayed as a tooltip for the fast navigation previous month control.| -|FastNavigationNextToolTip|Gets or sets the text displayed as a tooltip for the fast navigation next month control.| -|RowHeaderText|Provides custom text for the row header cells.| -|ColumnHeaderText|Provides custom text for the column header cells.| -|ViewSelectorText|The text displayed in the view selector cell.| - -__TodayButton__ - - -| Property | Description | -| ------ | ------ | -|Text|Gets or sets the text associated with Today button.|#_[C#] Assigning the TodayButton Text_ - - -{{source=..\SamplesCS\Calendar\Calendar1.cs region=localizingText}} -{{source=..\SamplesVB\Calendar\Calendar1.vb region=localizingText}} - -````C# -this.radCalendar1.TodayButton.Text = "Aujourd'hui"; - -```` -````VB.NET -Me.RadCalendar1.TodayButton.Text = "Aujourd'hui" - -```` - -{{endregion}} - -__ClearButton__ - - -| Property | Description | -| ------ | ------ | -|Text|Gets or sets the text associated with Clear button.| - - -## See Also - -* [Date Format Pattern]({%slug winforms/calendar/localization/date-format-pattern%}) -* [Globalization Properties]({%slug winforms/calendar/localization/globalization-properties%}) -* [Localization]({%slug winforms/calendar/localization%}) -* [Localization Provider]({%slug winforms/calendar/localization/localization-provider%}) -* [CultureInfo and RegionInfo Basics]({%slug winforms/calendar/localization/cultureinfo-and-regioninfo-basics%}) -* [Right-To-Left Support]({%slug winforms/calendar/localization/right-to-left-support%}) +--- +title: Properties that can be Localized +page_title: Properties that can be localized - WinForms Calendar Control +description: WinForms Calendar offers properties that can be localized. +slug: winforms/calendar/localization/properties-that-can-be-localized +tags: properties,that,can,be,localized +published: True +position: 4 +previous_url: calendar-localization-properties-that-can-be-localized +--- + +# Properties that can be Localized + +The following properties can be localized: + + +| Property | Description | +| ------ | ------ | +|NavigationPrevText|Gets or sets the text displayed for the previous month navigation control.| +|NavigationNextText|Gets or sets the text displayed for the next month navigation control.| +|FastNavigationPrevText|Gets or sets the text displayed for the fast previous navigation control.| +|FastNavigationNextText|Gets or sets the text displayed for the fast next navigation control.| +|NavigationPrevToolTip|Gets or sets the text displayed as a tooltip for the previous month navigation control.| +|NavigationNextToolTip|Gets or sets the text displayed as a tooltip for the next month navigation control.| +|FastNavigationPrevToolTip|Gets or sets the text displayed as a tooltip for the fast navigation previous month control.| +|FastNavigationNextToolTip|Gets or sets the text displayed as a tooltip for the fast navigation next month control.| +|RowHeaderText|Provides custom text for the row header cells.| +|ColumnHeaderText|Provides custom text for the column header cells.| +|ViewSelectorText|The text displayed in the view selector cell.| + +__TodayButton__ + + +| Property | Description | +| ------ | ------ | +|Text|Gets or sets the text associated with Today button.|#_[C#] Assigning the TodayButton Text_ + + + + + +__ClearButton__ + + +| Property | Description | +| ------ | ------ | +|Text|Gets or sets the text associated with Clear button.| + + +## See Also + +* [Date Format Pattern]({%slug winforms/calendar/localization/date-format-pattern%}) +* [Globalization Properties]({%slug winforms/calendar/localization/globalization-properties%}) +* [Localization]({%slug winforms/calendar/localization%}) +* [Localization Provider]({%slug winforms/calendar/localization/localization-provider%}) +* [CultureInfo and RegionInfo Basics]({%slug winforms/calendar/localization/cultureinfo-and-regioninfo-basics%}) +* [Right-To-Left Support]({%slug winforms/calendar/localization/right-to-left-support%}) diff --git a/controls/calendar/localization/right-to-left-support.md b/controls/calendar/localization/right-to-left-support.md index d3e2f5a78..125a5651c 100644 --- a/controls/calendar/localization/right-to-left-support.md +++ b/controls/calendar/localization/right-to-left-support.md @@ -24,19 +24,10 @@ __RadCalendar__ fully supports right-to-left (RTL) language locales. You can ena #### Setting RightToLeft -{{source=..\SamplesCS\Calendar\ColumnRowHeaders.cs region=rtl}} -{{source=..\SamplesVB\Calendar\ColumnRowHeaders.vb region=rtl}} + + -````C# -radCalendar1.RightToLeft = RightToLeft.Yes; -```` -````VB.NET -RadCalendar1.RightToLeft = RightToLeft.Yes - -```` - -{{endregion}} ## See Also diff --git a/controls/callout/getting-started.md b/controls/callout/getting-started.md index 2d1124429..2192dabde 100644 --- a/controls/callout/getting-started.md +++ b/controls/callout/getting-started.md @@ -66,24 +66,10 @@ The following UserControl contains: #### Showing the RadCallout -{{source=..\SamplesCS\Callout\CalloutSettings.cs region=ShowCallout}} -{{source=..\SamplesVB\Callout\CalloutSettings.vb region=ShowCallout}} + + -````C# -private void radButton1_Click(object sender, EventArgs e) -{ - this.radCallout1.Show(this.radButton1); -} -```` -````VB.NET -Private Sub RadButton1_Click(sender As Object, e As EventArgs) Handles RadButton1.Click - Me.RadCallout1.Show(Me.RadButton1) -End Sub - -```` - -{{endregion}} 6\. Run the project and click the button. Once the callout is shown, it will be automatically hidden if you click outside the callout's bounds. @@ -91,45 +77,11 @@ End Sub #### Closing the RadCallout -{{source=..\SamplesCS\Callout\CalloutSettings.cs region=CloseCallout}} -{{source=..\SamplesVB\Callout\CalloutSettings.vb region=CloseCallout}} - -````C# -public CalloutSettings() -{ - InitializeComponent(); - - RadButton closeButton = calloutUserControl1.Controls["headerPanel"].Controls["closeButton"] as RadButton; - closeButton.Click += CloseButton_Click; -} - -private void CloseButton_Click(object sender, EventArgs e) -{ - if (this.radCallout1.CalloutForm.Visible) - { - this.radCallout1.Close(); - } -} - - -```` -````VB.NET -Public Sub New() - InitializeComponent() - Dim closeButton As RadButton = TryCast(CalloutUserControl1.Controls("headerPanel").Controls("closeButton"), RadButton) - AddHandler closeButton.Click, AddressOf CloseButton_Click -End Sub - -Private Sub CloseButton_Click(ByVal sender As Object, ByVal e As EventArgs) - If Me.RadCallout1.CalloutForm.Visible Then - Me.RadCallout1.Close() - End If -End Sub - - -```` - -{{endregion}} + + + + + # See Also diff --git a/controls/callout/key-features.md b/controls/callout/key-features.md index 6e61d9fc4..d9d7467e7 100644 --- a/controls/callout/key-features.md +++ b/controls/callout/key-features.md @@ -58,27 +58,11 @@ CalloutAnimationManager offers the following public properties: #### Callout Animation Settings -{{source=..\SamplesCS\Callout\CalloutSettings.cs region=Animations}} -{{source=..\SamplesVB\Callout\CalloutSettings.vb region=Animations}} + + -````C# -this.radCallout1.AnimationManager.ShowAnimationType = Telerik.WinControls.UI.Callout.CalloutAnimationType.Slide; -this.radCallout1.AnimationManager.ShowAnimationDuration = 2000; -this.radCallout1.AnimationManager.CloseAnimationType = Telerik.WinControls.UI.Callout.CalloutAnimationType.Fade; -this.radCallout1.AnimationManager.CloseAnimationDuration = 3000; -```` -````VB.NET -Me.RadCallout1.AnimationManager.ShowAnimationType = Telerik.WinControls.UI.Callout.CalloutAnimationType.Slide -Me.RadCallout1.AnimationManager.ShowAnimationDuration = 2000 -Me.RadCallout1.AnimationManager.CloseAnimationType = Telerik.WinControls.UI.Callout.CalloutAnimationType.Fade -Me.RadCallout1.AnimationManager.CloseAnimationDuration = 3000 - -```` - -{{endregion}} - >caption Callout Animation ![WinForms RadCallout Animation](images/callout-key-features005.gif) diff --git a/controls/callout/shapes.md b/controls/callout/shapes.md index e5c9752c1..0577a5540 100644 --- a/controls/callout/shapes.md +++ b/controls/callout/shapes.md @@ -17,39 +17,19 @@ CTAControlName: Callout ![WinForms RadCallout Rectangle](images/callout-shapes001.png) -{{source=..\SamplesCS\Callout\CalloutSettings.cs region=Rectangle}} -{{source=..\SamplesVB\Callout\CalloutSettings.vb region=Rectangle}} + + -````C# - this.radCallout1.CalloutType = Telerik.WinControls.UI.Callout.CalloutType.Rectangle; - -```` -````VB.NET - Me.RadCallout1.CalloutType = Callout.CalloutType.Rectangle - -```` - -{{endregion}} * **CalloutType.RoundedRectangle**: ![WinForms RadCallout RoundedRectangle](images/callout-shapes002.png) -{{source=..\SamplesCS\Callout\CalloutSettings.cs region=RoundedRectangle}} -{{source=..\SamplesVB\Callout\CalloutSettings.vb region=RoundedRectangle}} - -````C# - - this.radCallout1.CalloutType = Telerik.WinControls.UI.Callout.CalloutType.RoundedRectangle; + + -```` -````VB.NET - Me.RadCallout1.CalloutType = Callout.CalloutType.RoundedRectangle -```` - -{{endregion}} All predefined callout shapes are defined as a **CalloutElementShape** which is a derivative of PathElementShape. @@ -65,115 +45,20 @@ The following code snippet demonstrates how to apply one of the predefined [Elem #### Custom Predefined Shape -{{source=..\SamplesCS\Callout\CalloutSettings.cs region=PredefinedCustomShape}} -{{source=..\SamplesVB\Callout\CalloutSettings.vb region=PredefinedCustomShape}} - -````C# - - this.radCallout1.CalloutForm.Shape = new DiamondShape(); - -```` -````VB.NET + + -Me.RadCallout1.CalloutForm.Shape = New DiamondShape() -```` - -{{endregion}} Since the default callout shapes are defined as **CalloutElementShape**, you can create a derivative of the **PathElementShape** class and override the **CreatePath(Rectangle bounds)** method. Thus, you can construct any custom shape that you need. The following two examples demonstrate how to create a Cloud and Kaboom shapes for RadCallout. #### Cloud Shape -{{source=..\SamplesCS\Callout\CalloutSettings.cs region=CloudShape}} -{{source=..\SamplesVB\Callout\CalloutSettings.vb region=CloudShape}} - -````C# -public class CloudCalloutShape : PathElementShape -{ - private string CloudRelativePoints = "0.98,0.508;0.966,0.481;0.941,0.451;0.913,0.446;0.917,0.442;0.92,0.438;0.924,0.434;0.935," + - "0.421;0.944,0.406;0.952,0.39;0.967,0.358;0.974,0.323;0.972,0.287;0.969,0.217;0.932,0.149;0.868,0.13;0.852,0.126;0.835,0.125;0.818," + - "0.128;0.806,0.13;0.791,0.134;0.782,0.142;0.782,0.131;0.777,0.12;0.773,0.11;0.768,0.096;0.761,0.082;0.752,0.07;0.735,0.044;0.712,0.024;" + - "0.685,0.012;0.631,-0.013;0.57,0.002;0.526,0.044;0.505,0.065;0.489,0.09;0.482,0.12;0.476,0.11;0.47,0.1;0.461,0.091;0.45,0.079;0.437,0.069;" + - "0.423,0.06;0.397,0.044;0.367,0.035;0.336,0.037;0.275,0.04;0.219,0.083;0.2,0.149;0.195,0.166;0.193,0.185;0.195,0.203;0.195,0.212;0.196,0.223;" + - "0.199,0.232;0.199,0.232;0.198,0.232;0.198,0.232;0.191,0.227;0.184,0.225;0.176,0.222;0.163,0.218;0.148,0.214;0.134,0.215;0.104,0.218;0.08,0.237;" + - "0.062,0.263;0.03,0.309;0.024,0.374;0.046,0.427;0.053,0.445;0.066,0.464;0.083,0.473;0.062,0.481;0.044,0.499;0.031,0.519;0.011,0.548;-0.001,0.585;" + - "0,0.622;0.001,0.658;0.015,0.692;0.04,0.715;0.051,0.726;0.065,0.735;0.08,0.739;0.09,0.742;0.105,0.745;0.116,0.74;0.084,0.791;0.125,0.868;0.169,0.91;" + - "0.224,0.96;0.303,0.954;0.363,0.921;0.388,0.907;0.414,0.888;0.43,0.862;0.451,0.926;0.511,0.976;0.55,0.988;0.631,1.013;0.695,0.998;0.749,0.952;0.782," + - "0.924;0.81,0.869;0.806,0.789;0.814,0.791;0.822,0.792;0.83,0.792;0.847,0.792;0.864,0.789;0.879,0.784;0.911,0.773;0.94,0.753;0.961,0.725;1.005,0.665;" + - "1.012,0.576;0.979,0.508;"; - - private PointF PointFromString(string s) - { - var pointStrings = s.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); - float x = float.Parse(pointStrings[0]); - float y = float.Parse(pointStrings[1]); - return new PointF(x, y); - } - - public override GraphicsPath CreatePath(Rectangle bounds) - { - string[] pointStrings = CloudRelativePoints.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToArray(); - System.Collections.Generic.IEnumerable points = pointStrings.Select(x => this.PointFromString(x)); - List adjustedPoints = points.Select(p => new PointF((float)(p.X * bounds.Width), (float)(p.Y * bounds.Height))).ToList(); - GraphicsPath path = new GraphicsPath(FillMode.Winding); - path.StartFigure(); - for (int i = 1; i < adjustedPoints.Count; i += 3) - { - path.AddBezier(adjustedPoints[i - 1], adjustedPoints[i], adjustedPoints[i + 1], adjustedPoints[i + 2]); - } - - path.CloseFigure(); - return path; - } -} - - -```` -````VB.NET -Public Class CloudCalloutShape - Inherits PathElementShape - - Private CloudRelativePoints As String = "0.98,0.508;0.966,0.481;0.941,0.451;0.913,0.446;0.917,0.442;0.92,0.438;0.924,0.434;0.935," & - "0.421;0.944,0.406;0.952,0.39;0.967,0.358;0.974,0.323;0.972,0.287;0.969,0.217;0.932,0.149;0.868,0.13;0.852,0.126;0.835,0.125;0.818," & - "0.128;0.806,0.13;0.791,0.134;0.782,0.142;0.782,0.131;0.777,0.12;0.773,0.11;0.768,0.096;0.761,0.082;0.752,0.07;0.735,0.044;0.712,0.024;" & - "0.685,0.012;0.631,-0.013;0.57,0.002;0.526,0.044;0.505,0.065;0.489,0.09;0.482,0.12;0.476,0.11;0.47,0.1;0.461,0.091;0.45,0.079;0.437,0.069;" & - "0.423,0.06;0.397,0.044;0.367,0.035;0.336,0.037;0.275,0.04;0.219,0.083;0.2,0.149;0.195,0.166;0.193,0.185;0.195,0.203;0.195,0.212;0.196,0.223;" & - "0.199,0.232;0.199,0.232;0.198,0.232;0.198,0.232;0.191,0.227;0.184,0.225;0.176,0.222;0.163,0.218;0.148,0.214;0.134,0.215;0.104,0.218;0.08,0.237;" & - "0.062,0.263;0.03,0.309;0.024,0.374;0.046,0.427;0.053,0.445;0.066,0.464;0.083,0.473;0.062,0.481;0.044,0.499;0.031,0.519;0.011,0.548;-0.001,0.585;" & - "0,0.622;0.001,0.658;0.015,0.692;0.04,0.715;0.051,0.726;0.065,0.735;0.08,0.739;0.09,0.742;0.105,0.745;0.116,0.74;0.084,0.791;0.125,0.868;0.169,0.91;" & - "0.224,0.96;0.303,0.954;0.363,0.921;0.388,0.907;0.414,0.888;0.43,0.862;0.451,0.926;0.511,0.976;0.55,0.988;0.631,1.013;0.695,0.998;0.749,0.952;0.782," & - "0.924;0.81,0.869;0.806,0.789;0.814,0.791;0.822,0.792;0.83,0.792;0.847,0.792;0.864,0.789;0.879,0.784;0.911,0.773;0.94,0.753;0.961,0.725;1.005,0.665;" & - "1.012,0.576;0.979,0.508;" - - Private Function PointFromString(ByVal s As String) As PointF - Dim pointStrings = s.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) - Dim x As Single = Single.Parse(pointStrings(0)) - Dim y As Single = Single.Parse(pointStrings(1)) - Return New PointF(x, y) - End Function - - Public Overrides Function CreatePath(ByVal bounds As Rectangle) As GraphicsPath - Dim pointStrings As String() = CloudRelativePoints.Split(New Char() {";"c}, StringSplitOptions.RemoveEmptyEntries).ToArray() - Dim points As System.Collections.Generic.IEnumerable(Of PointF) = pointStrings.[Select](Function(x) Me.PointFromString(x)) - Dim adjustedPoints As List(Of PointF) = points.[Select](Function(p) New PointF(CSng((p.X * bounds.Width)), CSng((p.Y * bounds.Height)))).ToList() - Dim path As GraphicsPath = New GraphicsPath(FillMode.Winding) - path.StartFigure() - - For i As Integer = 1 To adjustedPoints.Count - 1 Step 3 - path.AddBezier(adjustedPoints(i - 1), adjustedPoints(i), adjustedPoints(i + 1), adjustedPoints(i + 2)) - Next - - path.CloseFigure() - Return path - End Function -End Class - - -```` - -{{endregion}} + + + + >caption Custom Cloud Shape @@ -181,65 +66,10 @@ End Class #### Kaboom Shape -{{source=..\SamplesCS\Callout\CalloutSettings.cs region=KaboomShape}} -{{source=..\SamplesVB\Callout\CalloutSettings.vb region=KaboomShape}} - -````C# -public class KaboomCalloutShape : PathElementShape -{ - private string KaboomRelativePoints = "0.3625,0;0.433,0.147;0.457,0.017;0.519,0.154;0.568,0;0.633,0.12;0.688,0.034;0.725,0.147;0.809,0.039;0.84,0.191;" + - "0.94,0.204;0.893,0.318;1,0.406;0.911,0.531;0.957,0.698;0.865,0.715;0.853,0.887;0.765,0.773;0.713,0.961;0.633,0.81;0.533,1;0.443,0.86;0.401,0.941;0.348," + - "0.814;0.266,0.95;0.209,0.782;0.116,0.82;0.128,0.671;0.037,0.639;0.09,0.463;0,0.324;0.112,0.259;0.086,0.103;0.188,0.213;0.222,0.028;0.297,0.171;"; - private PointF PointFromString(string s) - { - var pointStrings = s.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); - float x = float.Parse(pointStrings[0]); - float y = float.Parse(pointStrings[1]); - return new PointF(x, y); - } - - public override GraphicsPath CreatePath(Rectangle bounds) - { - string[] pointStrings = KaboomRelativePoints.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToArray(); - System.Collections.Generic.IEnumerable points = pointStrings.Select(x => this.PointFromString(x)); - List adjustedPoints = points.Select(p => new PointF(p.X * bounds.Width, p.Y * bounds.Height)).ToList(); - GraphicsPath path = new GraphicsPath(FillMode.Winding); - path.AddLines(adjustedPoints.ToArray()); - return path; - } -} - - -```` -````VB.NET -Public Class KaboomCalloutShape - Inherits PathElementShape - - Private KaboomRelativePoints As String = "0.3625,0;0.433,0.147;0.457,0.017;0.519,0.154;0.568,0;0.633,0.12;0.688,0.034;0.725,0.147;0.809,0.039;0.84,0.191;" & - "0.94,0.204;0.893,0.318;1,0.406;0.911,0.531;0.957,0.698;0.865,0.715;0.853,0.887;0.765,0.773;0.713,0.961;0.633,0.81;0.533,1;0.443,0.86;0.401,0.941;0.348," & - "0.814;0.266,0.95;0.209,0.782;0.116,0.82;0.128,0.671;0.037,0.639;0.09,0.463;0,0.324;0.112,0.259;0.086,0.103;0.188,0.213;0.222,0.028;0.297,0.171;" - - Private Function PointFromString(ByVal s As String) As PointF - Dim pointStrings = s.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) - Dim x As Single = Single.Parse(pointStrings(0)) - Dim y As Single = Single.Parse(pointStrings(1)) - Return New PointF(x, y) - End Function - - Public Overrides Function CreatePath(ByVal bounds As Rectangle) As GraphicsPath - Dim pointStrings As String() = KaboomRelativePoints.Split(New Char() {";"c}, StringSplitOptions.RemoveEmptyEntries).ToArray() - Dim points As System.Collections.Generic.IEnumerable(Of PointF) = pointStrings.[Select](Function(x) Me.PointFromString(x)) - Dim adjustedPoints As List(Of PointF) = points.[Select](Function(p) New PointF(p.X * bounds.Width, p.Y * bounds.Height)).ToList() - Dim path As GraphicsPath = New GraphicsPath(FillMode.Winding) - path.AddLines(adjustedPoints.ToArray()) - Return path - End Function -End Class - - -```` - -{{endregion}} + + + + >caption Custom Kaboom Shape @@ -247,20 +77,10 @@ End Class The last needed step is to apply the custom shape to the CalloutForm: -{{source=..\SamplesCS\Callout\CalloutSettings.cs region=ApplyShape}} -{{source=..\SamplesVB\Callout\CalloutSettings.vb region=ApplyShape}} - -````C# - -this.radCallout1.CalloutForm.Shape = new CloudCalloutShape(); - -```` -````VB.NET -Me.RadCallout1.CalloutForm.Shape = New CloudCalloutShape() + + -```` -{{endregion}} # See Also diff --git a/controls/cardview/custom-items.md b/controls/cardview/custom-items.md index 72643cbe8..73d42bba1 100644 --- a/controls/cardview/custom-items.md +++ b/controls/cardview/custom-items.md @@ -23,179 +23,26 @@ First let's create our custom items: #### Creating Custom CardViewItem -{{source=..\SamplesCS\CardView\CadViewCustomItems.cs region=CustomCardViewItem}} -{{source=..\SamplesVB\CardView\CadViewCustomItems.vb region=CustomCardViewItem}} -````C# -public class CheckBoxCardViewItem : CardViewItem -{ - protected override void CreateChildElements() - { - base.CreateChildElements(); - this.TextSizeMode = LayoutItemTextSizeMode.Proportional; - this.TextProportionalSize = 0; - } - protected override CardViewEditorItem CreateEditorItem() - { - return new CheckBoxEditorItem(); - } - public override void Synchronize() - { - CardListViewVisualItem cardVisualItem = this.FindAncestor(); - if (this.CardField == null || cardVisualItem == null || cardVisualItem.Data == null) - { - return; - } - RadCheckBoxElement checkBox = ((CheckBoxEditorItem)this.EditorItem).Checkbox; - checkBox.Text = this.CardField.HeaderText; - checkBox.Checked = this.ContainsFeature(cardVisualItem.Data, this.FieldName); - } - private bool ContainsFeature(ListViewDataItem item, string feature) - { - return item[feature] != null && Convert.ToInt32(item[feature]) != 0; - } -} - -```` -````VB.NET -Public Class CheckBoxCardViewItem - Inherits CardViewItem - Protected Overrides Sub CreateChildElements() - MyBase.CreateChildElements() - Me.TextSizeMode = LayoutItemTextSizeMode.Proportional - Me.TextProportionalSize = 0 - End Sub - Protected Overrides Function CreateEditorItem() As CardViewEditorItem - Return New CheckBoxEditorItem() - End Function - Public Overrides Sub Synchronize() - Dim cardVisualItem As CardListViewVisualItem = Me.FindAncestor(Of CardListViewVisualItem)() - If Me.CardField Is Nothing OrElse cardVisualItem Is Nothing OrElse cardVisualItem.Data Is Nothing Then - Return - End If - Dim checkBox As RadCheckBoxElement = DirectCast(Me.EditorItem, CheckBoxEditorItem).Checkbox - checkBox.Text = Me.CardField.HeaderText - checkBox.Checked = Me.ContainsFeature(cardVisualItem.Data, Me.FieldName) - End Sub - Private Function ContainsFeature(item As ListViewDataItem, feature As String) As Boolean - Return item(feature) IsNot Nothing AndAlso Convert.ToInt32(item(feature)) <> 0 - End Function -End Class - -```` - - - -{{endregion}} + + + + #### Creating Custom CardViewEditorItem -{{source=..\SamplesCS\CardView\CadViewCustomItems.cs region=CustomCardViewEditorItem}} -{{source=..\SamplesVB\CardView\CadViewCustomItems.vb region=CustomCardViewEditorItem}} -````C# -public class CheckBoxEditorItem : CardViewEditorItem -{ - private RadCheckBoxElement checkbox; - public RadCheckBoxElement Checkbox - { - get { return this.checkbox; } - set { this.checkbox = value; } - } - protected override void CreateChildElements() - { - base.CreateChildElements(); - this.checkbox = new RadCheckBoxElement(); - this.Children.Add(this.checkbox); - } -} - -```` -````VB.NET -Public Class CheckBoxEditorItem - Inherits CardViewEditorItem - Private m_checkbox As RadCheckBoxElement - Public Property Checkbox() As RadCheckBoxElement - Get - Return Me.m_checkbox - End Get - Set(value As RadCheckBoxElement) - Me.m_checkbox = value - End Set - End Property - Protected Overrides Sub CreateChildElements() - MyBase.CreateChildElements() - Me.m_checkbox = New RadCheckBoxElement() - Me.Children.Add(Me.m_checkbox) - End Sub -End Class - -```` - - - -{{endregion}} + + + + Back in our form we need to populate some sample data for the checkboxes as well as subscribe and handle the __CardViewItemCreating__ event. For the purpose of this example we are data binding the control to the SofiaCarRental database which is available in the installation folder of the suite. #### Use the custom item -{{source=..\SamplesCS\CardView\CadViewCustomItems.cs region=CardViewForm}} -{{source=..\SamplesVB\CardView\CadViewCustomItems.vb region=CardViewForm}} -````C# -private List features; -public CadViewCustomItems() -{ - InitializeComponent(); - this.features = new List() { "AirConditioner", "Mp3Player", "DVDPlayer", "ABS", "ASR", "Navigation", "Available" }; - this.radCardView1.CardViewItemCreating += radCardView1_CardViewItemCreating; -} -private void radCardView1_CardViewItemCreating(object sender, CardViewItemCreatingEventArgs e) -{ - CardViewItem cardViewItem = e.NewItem as CardViewItem; - if (cardViewItem != null && this.features.Contains(cardViewItem.FieldName)) - { - CheckBoxCardViewItem checkBoxItem = new CheckBoxCardViewItem(); - checkBoxItem.FieldName = cardViewItem.FieldName; - e.NewItem = checkBoxItem; - } -} -private void CadViewCustomItems_Load(object sender, EventArgs e) -{ - this.carsTableAdapter.Fill(this.sofiaCarRentalDataSet.Cars); -} - -```` -````VB.NET -Private features As List(Of String) -Public Sub New() - InitializeComponent() - Me.features = New List(Of String)() From { _ - "AirConditioner", _ - "Mp3Player", _ - "DVDPlayer", _ - "ABS", _ - "ASR", _ - "Navigation", _ - "Available" _ - } - AddHandler Me.RadCardView1.CardViewItemCreating, AddressOf radCardView1_CardViewItemCreating -End Sub -Private Sub radCardView1_CardViewItemCreating(sender As Object, e As CardViewItemCreatingEventArgs) - Dim cardViewItem As CardViewItem = TryCast(e.NewItem, CardViewItem) - If cardViewItem IsNot Nothing AndAlso Me.features.Contains(cardViewItem.FieldName) Then - Dim checkBoxItem As New CheckBoxCardViewItem() - checkBoxItem.FieldName = cardViewItem.FieldName - e.NewItem = checkBoxItem - End If -End Sub -Private Sub CadViewCustomItems_Load(sender As Object, e As EventArgs) Handles MyBase.Load - Me.CarsTableAdapter.Fill(Me.SofiaCarRentalDataSet.Cars) -End Sub - -```` - - - -{{endregion}} + + + + # See Also diff --git a/controls/cardview/customizing-appearance/formatting-items.md b/controls/cardview/customizing-appearance/formatting-items.md index f2c5dee20..5762be809 100644 --- a/controls/cardview/customizing-appearance/formatting-items.md +++ b/controls/cardview/customizing-appearance/formatting-items.md @@ -23,53 +23,10 @@ The appearance of the visual items can be fully customized by handling the __Car #### Formatting the Visual Item -{{source=..\SamplesCS\CardView\CardviewCustomizingAppearance.cs region=CardViewVisualItemFormatting}} -{{source=..\SamplesVB\CardView\CardviewCustomizingAppearance.vb region=CardViewVisualItemFormatting}} - -````C# -Font font = new Font("Consolas", 14, FontStyle.Bold); -private void radCardView1_CardViewItemFormatting(object sender, CardViewItemFormattingEventArgs e) -{ - if (e.VisualItem.Selected) - { - e.VisualItem.NumberOfColors = 1; - e.VisualItem.BackColor = Color.LightGreen; - e.VisualItem.ForeColor = Color.Coral; - e.VisualItem.BorderColor = Color.LightBlue; - e.VisualItem.Font = font; - } - else - { - e.VisualItem.ResetValue(LightVisualElement.NumberOfColorsProperty, Telerik.WinControls.ValueResetFlags.Local); - e.VisualItem.ResetValue(LightVisualElement.BackColorProperty, Telerik.WinControls.ValueResetFlags.Local); - e.VisualItem.ResetValue(LightVisualElement.ForeColorProperty, Telerik.WinControls.ValueResetFlags.Local); - e.VisualItem.ResetValue(LightVisualElement.BorderColorProperty, Telerik.WinControls.ValueResetFlags.Local); - e.VisualItem.ResetValue(LightVisualElement.FontProperty, Telerik.WinControls.ValueResetFlags.Local); - } -} - -```` -````VB.NET -Private font As New Font("Consolas", 14, FontStyle.Bold) -Private Sub RadCardView1_CardViewItemFormatting(sender As Object, e As CardViewItemFormattingEventArgs) - If e.VisualItem.Selected Then - e.VisualItem.NumberOfColors = 1 - e.VisualItem.BackColor = Color.LightGreen - e.VisualItem.ForeColor = Color.Coral - e.VisualItem.BorderColor = Color.LightBlue - e.VisualItem.Font = font - Else - e.VisualItem.ResetValue(LightVisualElement.NumberOfColorsProperty, Telerik.WinControls.ValueResetFlags.Local) - e.VisualItem.ResetValue(LightVisualElement.BackColorProperty, Telerik.WinControls.ValueResetFlags.Local) - e.VisualItem.ResetValue(LightVisualElement.ForeColorProperty, Telerik.WinControls.ValueResetFlags.Local) - e.VisualItem.ResetValue(LightVisualElement.BorderColorProperty, Telerik.WinControls.ValueResetFlags.Local) - e.VisualItem.ResetValue(LightVisualElement.FontProperty, Telerik.WinControls.ValueResetFlags.Local) - End If -End Sub - -```` - -{{endregion}} + + + + ## Formatting CardViewItiem @@ -80,49 +37,10 @@ By handling the __CardViewItemFormatting__ event each of the individual card vie #### Formatting CardViewItiem -{{source=..\SamplesCS\CardView\CardviewCustomizingAppearance.cs region=CardViewItemFormatting}} -{{source=..\SamplesVB\CardView\CardviewCustomizingAppearance.vb region=CardViewItemFormatting}} - -````C# -private void radCardView1_CardViewItemFormatting1(object sender, CardViewItemFormattingEventArgs e) -{ - CardViewItem item = e.Item as CardViewItem; - if (item != null && item.FieldName == "CustomerID") - { - e.Item.NumberOfColors = 1; - e.Item.ForeColor = Color.Coral; - e.Item.BorderColor = Color.LightBlue; - e.Item.Font = font; - } - else - { - e.Item.ResetValue(LightVisualElement.NumberOfColorsProperty, Telerik.WinControls.ValueResetFlags.Local); - e.Item.ResetValue(LightVisualElement.ForeColorProperty, Telerik.WinControls.ValueResetFlags.Local); - e.Item.ResetValue(LightVisualElement.BorderColorProperty, Telerik.WinControls.ValueResetFlags.Local); - e.Item.ResetValue(LightVisualElement.FontProperty, Telerik.WinControls.ValueResetFlags.Local); - } -} - -```` -````VB.NET -Private Sub RadCardView1_CardViewItemFormatting1(sender As Object, e As CardViewItemFormattingEventArgs) - Dim item As CardViewItem = TryCast(e.Item, CardViewItem) - If item IsNot Nothing AndAlso item.FieldName = "CustomerID" Then - e.Item.NumberOfColors = 1 - e.Item.ForeColor = Color.Coral - e.Item.BorderColor = Color.LightBlue - e.Item.Font = font - Else - e.Item.ResetValue(LightVisualElement.NumberOfColorsProperty, Telerik.WinControls.ValueResetFlags.Local) - e.Item.ResetValue(LightVisualElement.ForeColorProperty, Telerik.WinControls.ValueResetFlags.Local) - e.Item.ResetValue(LightVisualElement.BorderColorProperty, Telerik.WinControls.ValueResetFlags.Local) - e.Item.ResetValue(LightVisualElement.FontProperty, Telerik.WinControls.ValueResetFlags.Local) - End If -End Sub - -```` - -{{endregion}} + + + + ## See Also diff --git a/controls/cardview/customizing-appearance/visual-data-representation.md b/controls/cardview/customizing-appearance/visual-data-representation.md index c22357054..59dcae856 100644 --- a/controls/cardview/customizing-appearance/visual-data-representation.md +++ b/controls/cardview/customizing-appearance/visual-data-representation.md @@ -41,59 +41,10 @@ The collection with these __RadProperties__ is static and it it accessible, ther #### Formatting the Visual Item -{{source=..\SamplesCS\CardView\CardviewCustomizingAppearance.cs region=CustomizeAppearance}} -{{source=..\SamplesVB\CardView\CardviewCustomizingAppearance.vb region=CustomizeAppearance}} + + -````C# -public CardviewCustomizingAppearance() -{ - InitializeComponent(); - CardListViewElement.ItemSynchronizationProperties.Add(LightVisualElement.VisibilityProperty); - this.CustomizeAppearance(); -} -private void CustomizeAppearance() -{ - LayoutControlGroupItem group = this.radCardView1.CardTemplate.Items[0] as LayoutControlGroupItem; - CardViewItem item = (CardViewItem)group.Items[3]; - item.TextAlignment = ContentAlignment.MiddleCenter; - item = (CardViewItem)group.Items[2]; - item.ForeColor = Color.Green; - item = (CardViewItem)group.Items[1]; - item.Font = new Font("Arial", 14, FontStyle.Bold); - item = (CardViewItem)group.Items[0]; - item.DrawFill = true; - item.BackColor = Color.LightBlue; - item.GradientStyle = GradientStyles.Solid; - item = (CardViewItem)group.Items.Last; - item.Visibility = ElementVisibility.Hidden; -} -```` -````VB.NET -Public Sub New() - InitializeComponent() - CardListViewElement.ItemSynchronizationProperties.Add(LightVisualElement.VisibilityProperty) - Me.CustomizeAppearance() -End Sub -Private Sub CustomizeAppearance() - Dim group As LayoutControlGroupItem = TryCast(Me.RadCardView1.CardTemplate.Items(0), LayoutControlGroupItem) - Dim item As CardViewItem = DirectCast(group.Items(3), CardViewItem) - item.TextAlignment = ContentAlignment.MiddleCenter - item = DirectCast(group.Items(2), CardViewItem) - item.ForeColor = Color.Green - item = DirectCast(group.Items(1), CardViewItem) - item.Font = New Font("Arial", 14, FontStyle.Bold) - item = DirectCast(group.Items(0), CardViewItem) - item.DrawFill = True - item.BackColor = Color.LightBlue - item.GradientStyle = GradientStyles.Solid - item = DirectCast(group.Items.Last, CardViewItem) - item.Visibility = ElementVisibility.Hidden -End Sub - -```` - -{{endregion}} ## See Also diff --git a/controls/cardview/editors/overview.md b/controls/cardview/editors/overview.md index d1296e14f..57ef65210 100644 --- a/controls/cardview/editors/overview.md +++ b/controls/cardview/editors/overview.md @@ -14,20 +14,10 @@ __RadCardView__ supports editing of its content out of the box. This operation c #### Disable Editing -{{source=..\SamplesCS\CardView\CardViewEditors.cs region=AllowEdit}} -{{source=..\SamplesVB\CardView\CardViewEditors.vb region=AllowEdit}} -````C# -this.radCardView1.AllowEdit = false; + + -```` -````VB.NET -Me.RadCardView1.AllowEdit = False -```` - - - -{{endregion}} ## Editing Lifecycle @@ -62,45 +52,10 @@ The Following example demonstrates the __ItemValidating__ event handling integer #### Data Validation -{{source=..\SamplesCS\CardView\CardViewEditors.cs region=DataValidation}} -{{source=..\SamplesVB\CardView\CardViewEditors.vb region=DataValidation}} -````C# -private void radCardView1_ItemValidating(object sender, ListViewItemValidatingEventArgs e) -{ - int newInt = 0; - if (int.TryParse(Convert.ToString(e.NewValue), out newInt)) - { - e.NewValue = newInt; - } - else - { - e.Cancel = true; - } -} -private void radCardView1_ValidationError(object sender, EventArgs e) -{ - RadMessageBox.Show("Invalid Value"); -} - -```` -````VB.NET -Private Sub radCardView1_ItemValidating(sender As Object, e As ListViewItemValidatingEventArgs) - Dim newInt As Integer = 0 - If Integer.TryParse(Convert.ToString(e.NewValue), newInt) Then - e.NewValue = newInt - Else - e.Cancel = True - End If -End Sub -Private Sub radCardView1_ValidationError(sender As Object, e As EventArgs) - RadMessageBox.Show("Invalid Value") -End Sub - -```` - - - -{{endregion}} + + + + ## Telerik UI for WinForms Additional Resources diff --git a/controls/cardview/editors/switching-editors.md b/controls/cardview/editors/switching-editors.md index 275c3926a..644d1eba8 100644 --- a/controls/cardview/editors/switching-editors.md +++ b/controls/cardview/editors/switching-editors.md @@ -19,56 +19,10 @@ The following example shows how you can change the editor type: #### Changing Editor Type -{{source=..\SamplesCS\CardView\CardViewEditors.cs region=ChangingEditorType}} -{{source=..\SamplesVB\CardView\CardViewEditors.vb region=ChangingEditorType}} -````C# -private void radCardView1_EditorRequired(object sender, Telerik.WinControls.UI.ListViewItemEditorRequiredEventArgs e) -{ - if (e.ListViewElement.CurrentColumn.FieldName == "TitleOfCourtesy") - { - ListViewDropDownListEditor editor = new ListViewDropDownListEditor(); - (editor.EditorElement as BaseDropDownListEditorElement).Items.Add("Ms."); - (editor.EditorElement as BaseDropDownListEditorElement).Items.Add("Mr."); - (editor.EditorElement as BaseDropDownListEditorElement).Items.Add("Mrs."); - e.Editor = editor; - } - else if (e.ListViewElement.CurrentColumn.FieldName == "EmployeeID") - { - e.EditorType = typeof(ListViewSpinEditor); - } - else if (e.ListViewElement.CurrentColumn.FieldName == "BirthDate" || e.ListViewElement.CurrentColumn.FieldName == "HireDate") - { - e.EditorType = typeof(ListViewDateTimeEditor); - } - else - { - e.EditorType = typeof(ListViewTextBoxEditor); - } -} + + -```` -````VB.NET -Private Sub radCardView1_EditorRequired(sender As Object, e As Telerik.WinControls.UI.ListViewItemEditorRequiredEventArgs) - If e.ListViewElement.CurrentColumn.FieldName = "TitleOfCourtesy" Then - Dim editor As New ListViewDropDownListEditor() - TryCast(editor.EditorElement, BaseDropDownListEditorElement).Items.Add("Ms.") - TryCast(editor.EditorElement, BaseDropDownListEditorElement).Items.Add("Mr.") - TryCast(editor.EditorElement, BaseDropDownListEditorElement).Items.Add("Mrs.") - e.Editor = editor - ElseIf e.ListViewElement.CurrentColumn.FieldName = "EmployeeID" Then - e.EditorType = GetType(ListViewSpinEditor) - ElseIf e.ListViewElement.CurrentColumn.FieldName = "BirthDate" OrElse e.ListViewElement.CurrentColumn.FieldName = "HireDate" Then - e.EditorType = GetType(ListViewDateTimeEditor) - Else - e.EditorType = GetType(ListViewTextBoxEditor) - End If -End Sub -```` - - - -{{endregion}} # See Also diff --git a/controls/cardview/features/filtering.md b/controls/cardview/features/filtering.md index 999a67128..c06ce49aa 100644 --- a/controls/cardview/features/filtering.md +++ b/controls/cardview/features/filtering.md @@ -14,39 +14,19 @@ __RadCardView__ allows filtering applied to its __CardViewItems__. To enable fil #### Enable Filtering -{{source=..\SamplesCS\CardView\CardViewFeatures.cs region=EnableFiltering}} -{{source=..\SamplesVB\CardView\CardViewFeatures.vb region=EnableFiltering}} + + -````C# -this.radCardView1.EnableFiltering = true; -```` -````VB.NET -Me.RadCardView1.EnableFiltering = True - -```` - -{{endregion}} Once the filtering is enabled, we have to create a new __FilterDescriptor__ and assign its __PropertyName__, __FilterOperator__ and __SearchCriteria__. First, let’s filter the items by their value and look for items containing with `Capital`. #### Filter by Column -{{source=..\SamplesCS\CardView\CardViewFeatures.cs region=FilterDescriptor}} -{{source=..\SamplesVB\CardView\CardViewFeatures.vb region=FilterDescriptor}} - -````C# -FilterDescriptor columnFilter = new FilterDescriptor("Address", FilterOperator.Contains, "Capital"); -this.radCardView1.FilterDescriptors.Add(columnFilter); - -```` -````VB.NET -Dim valueFilter As New FilterDescriptor("Address", FilterOperator.Contains, "Capital") -Me.RadCardView1.FilterDescriptors.Add(valueFilter) + + -```` -{{endregion}} >caption Figure 1: Before ![WinForms RadCardView Before](images/radcardview-features-filtering001.png) diff --git a/controls/cardview/features/grouping.md b/controls/cardview/features/grouping.md index 4b12bb3d3..b058d0d50 100644 --- a/controls/cardview/features/grouping.md +++ b/controls/cardview/features/grouping.md @@ -14,39 +14,16 @@ __RadCardView__ allows grouping of its __CardViewItems__ and it can be enabled b #### Enable Grouping -{{source=..\SamplesCS\CardView\CardViewFeatures.cs region=EnableGrouping}} -{{source=..\SamplesVB\CardView\CardViewFeatures.vb region=EnableGrouping}} + + -````C# -this.radCardView1.EnableGrouping = true; -this.radCardView1.ShowGroups = true; -```` -````VB.NET -Me.RadCardView1.EnableGrouping = True -Me.RadCardView1.ShowGroups = True - -```` - -{{endregion}} Once the grouping is enabled, we have to create a new __GroupDescriptor__ and assign its __PropertyName__ and __ListSortDirection__. Let's group the items by `Address` in `Descending` direction. #### Group by Column -{{source=..\SamplesCS\CardView\CardViewFeatures.cs region=GroupDescriptor}} -{{source=..\SamplesVB\CardView\CardViewFeatures.vb region=GroupDescriptor}} - -````C# -GroupDescriptor groupByAddress = new GroupDescriptor(new SortDescriptor[] { - new SortDescriptor("Address", ListSortDirection.Descending),}); -this.radCardView1.GroupDescriptors.Add(groupByAddress); - -```` -````VB.NET -Dim groupByAddress As New GroupDescriptor(New SortDescriptor() {New SortDescriptor("Address", ListSortDirection.Descending)}) -Me.RadCardView1.GroupDescriptors.Add(groupByAddress) + + -```` -{{endregion}} diff --git a/controls/cardview/features/sorting.md b/controls/cardview/features/sorting.md index 2058ba154..c2917d621 100644 --- a/controls/cardview/features/sorting.md +++ b/controls/cardview/features/sorting.md @@ -14,36 +14,16 @@ Enabling sorting is done by setting __EnableSorting__ property to *true*. You sh #### Enable Column Sorting -{{source=..\SamplesCS\CardView\CardViewFeatures.cs region=EnableSorting}} -{{source=..\SamplesVB\CardView\CardViewFeatures.vb region=EnableSorting}} + + -````C# -this.radCardView1.EnableSorting = true; -```` -````VB.NET -Me.RadCardView1.EnableSorting = True - -```` - -{{endregion}} The following code demonstrates how to add __SortDescriptor__ to __RadCardView__: #### Adding SortDescriptors -{{source=..\SamplesCS\CardView\CardViewFeatures.cs region=SortDescriptor}} -{{source=..\SamplesVB\CardView\CardViewFeatures.vb region=SortDescriptor}} - -````C# -SortDescriptor sortDescriptor = new SortDescriptor("Id", ListSortDirection.Ascending); -this.radCardView1.SortDescriptors.Add(sortDescriptor); - -```` -````VB.NET -Dim sortDescriptor As New SortDescriptor("Id", ListSortDirection.Ascending) -Me.RadCardView1.SortDescriptors.Add(sortDescriptor) + + -```` -{{endregion}} diff --git a/controls/cardview/populating-with-data/binding-to-data.md b/controls/cardview/populating-with-data/binding-to-data.md index ee960b91d..b8d2f739b 100644 --- a/controls/cardview/populating-with-data/binding-to-data.md +++ b/controls/cardview/populating-with-data/binding-to-data.md @@ -31,192 +31,17 @@ The example below will demonstrate how to bind __RadCardView__ to a collection o #### Bind RadCardView -{{source=..\SamplesCS\CardView\CardViewDataBindingProgramatically.cs region=BindRadCardView}} -{{source=..\SamplesVB\CardView\CardViewDataBindingProgramatically.vb region=BindRadCardView}} -````C# -BindingList dataSource = new BindingList() -{ - new CardViewModel("1", "Nancy Davolio","507 - 20th Ave. E.Apt. 2A", DateTime.Parse("12/8/1948", CultureInfo.InvariantCulture)), - new CardViewModel("2", "Andrew Fuller","908 W. Capital Way", DateTime.Parse("2/19/1952", CultureInfo.InvariantCulture)), - new CardViewModel("3", "Janet Leverling","722 Moss Bay Blvd.", DateTime.Parse("8/30/1963", CultureInfo.InvariantCulture)), - new CardViewModel("4", "Margaret Peacock","110 Old Redmond Rd.", DateTime.Parse("9/19/1937", CultureInfo.InvariantCulture)) -}; -this.radCardView1.DataSource = dataSource; - -```` -````VB.NET -Dim dataSource As New BindingList(Of CardViewModel)() From { - New CardViewModel("1", "Nancy Davolio", "507 - 20th Ave. E.Apt. 2A", DateTime.Parse("12/8/1948", CultureInfo.InvariantCulture)), - New CardViewModel("2", "Andrew Fuller", "908 W. Capital Way", DateTime.Parse("2/19/1952", CultureInfo.InvariantCulture)), - New CardViewModel("3", "Janet Leverling", "722 Moss Bay Blvd.", DateTime.Parse("8/30/1963", CultureInfo.InvariantCulture)), - New CardViewModel("4", "Margaret Peacock", "110 Old Redmond Rd.", DateTime.Parse("9/19/1937", CultureInfo.InvariantCulture)) -} -Me.RadCardView1.DataSource = dataSource - -```` - - - -{{endregion}} + + + + #### Sample Data Object -{{source=..\SamplesCS\CardView\CardViewDataBindingProgramatically.cs region=SampleDataObject}} -{{source=..\SamplesVB\CardView\CardViewDataBindingProgramatically.vb region=SampleDataObject}} -````C# -public class CardViewModel : INotifyPropertyChanged -{ - private string id; - private string name; - private string address; - private DateTime dateOfBirth; - public event PropertyChangedEventHandler PropertyChanged; - public CardViewModel(string id, string name, string address, DateTime dateOfBirth) - { - this.id = id; - this.name = name; - this.address = address; - this.dateOfBirth = dateOfBirth; - } - public string Id - { - get - { - return this.id; - } - set - { - if (this.id != value) - { - this.id = value; - OnPropertyChanged("Id"); - } - } - } - public string Name - { - get - { - return this.name; - } - set - { - if (this.name != value) - { - this.name = value; - OnPropertyChanged("Name"); - } - } - } - public string Address - { - get - { - return this.address; - } - set - { - if (this.address != value) - { - this.address = value; - OnPropertyChanged("Address"); - } - } - } - public DateTime DateOfBirth - { - get - { - return this.dateOfBirth; - } - set - { - if (this.dateOfBirth != value) - { - this.dateOfBirth = value; - OnPropertyChanged("DateOfBirth"); - } - } - } - protected virtual void OnPropertyChanged(string propertyName) - { - if (PropertyChanged != null) - { - PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); - } - } -} - -```` -````VB.NET -Public Class CardViewModel - Implements INotifyPropertyChanged - Private m_id As String - Private m_name As String - Private m_address As String - Private m_dateOfBirth As DateTime - Public Event PropertyChanged As PropertyChangedEventHandler - Public Sub New(id As String, name As String, address As String, dateOfBirth As DateTime) - Me.m_id = id - Me.m_name = name - Me.m_address = address - Me.m_dateOfBirth = dateOfBirth - End Sub - Public Property Id() As String - Get - Return Me.m_id - End Get - Set(value As String) - If Me.m_id <> value Then - Me.m_id = value - OnPropertyChanged("Id") - End If - End Set - End Property - Public Property Name() As String - Get - Return Me.m_name - End Get - Set(value As String) - If Me.m_name <> value Then - Me.m_name = value - OnPropertyChanged("Name") - End If - End Set - End Property - Public Property Address() As String - Get - Return Me.m_address - End Get - Set(value As String) - If Me.m_address <> value Then - Me.m_address = value - OnPropertyChanged("Address") - End If - End Set - End Property - Public Property DateOfBirth() As DateTime - Get - Return Me.m_dateOfBirth - End Get - Set(value As DateTime) - If Me.m_dateOfBirth <> value Then - Me.m_dateOfBirth = value - OnPropertyChanged("DateOfBirth") - End If - End Set - End Property - Protected Overridable Sub OnPropertyChanged(propertyName As String) - RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName)) - End Sub - Public Event PropertyChanged1(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged -End Class - -```` - - - -{{endregion}} + + + + ## See Also diff --git a/controls/cardview/populating-with-data/unbound-mode.md b/controls/cardview/populating-with-data/unbound-mode.md index 2b4b68d93..6bda10378 100644 --- a/controls/cardview/populating-with-data/unbound-mode.md +++ b/controls/cardview/populating-with-data/unbound-mode.md @@ -35,26 +35,10 @@ The columns of __RadCardView__ are stored in a collection that is accessible thr #### Adding columns -{{source=..\SamplesCS\CardView\CardViewUnboundMode.cs region=AddColumns}} -{{source=..\SamplesVB\CardView\CardViewUnboundMode.vb region=AddColumns}} -````C# -this.radCardView1.Columns.Add("Id"); -this.radCardView1.Columns.Add("Column2", "First Name"); -this.radCardView1.Columns.Add(new ListViewDetailColumn("Column3", "Last Name")); -this.radCardView1.Columns.Add("Address"); + + -```` -````VB.NET -Me.RadCardView1.Columns.Add("Id") -Me.RadCardView1.Columns.Add("Column2", "First Name") -Me.RadCardView1.Columns.Add(New ListViewDetailColumn("Column3", "Last Name")) -Me.RadCardView1.Columns.Add("Address") -```` - - - -{{endregion}} ### Adding Items and Populating Cells @@ -62,49 +46,18 @@ The items of __RadCardView__ are stored in a collection that is also accessible #### Adding items -{{source=..\SamplesCS\CardView\CardViewUnboundMode.cs region=AddItems}} -{{source=..\SamplesVB\CardView\CardViewUnboundMode.vb region=AddItems}} - -````C# -this.radCardView1.Items.Add(new ListViewDataItem("First CardViewItem")); -this.radCardView1.Items.Add("2", "Nancy", "Davolio", "507 - 20th Ave. E.Apt. 2A"); -this.radCardView1.Items.Add("Third CardViewItem"); + + -```` -````VB.NET -Me.RadCardView1.Items.Add(New ListViewDataItem("First CardViewItem")) -Me.RadCardView1.Items.Add("2", "Nancy", "Davolio", "507 - 20th Ave. E.Apt. 2A") -Me.RadCardView1.Items.Add("Third CardViewItem") -```` - -{{endregion}} #### Populating cells -{{source=..\SamplesCS\CardView\CardViewUnboundMode.cs region=PopulateCells}} -{{source=..\SamplesVB\CardView\CardViewUnboundMode.vb region=PopulateCells}} -````C# -ListViewDataItem item = this.radCardView1.Items[0]; -item[0] = "1"; -item["Column2"] = "Andrew"; -item[radCardView1.Columns[2]] = "Fuller"; -item["Address"] = "908 W. Capital Way"; - -```` -````VB.NET -Dim item As ListViewDataItem = Me.RadCardView1.Items(0) -item(0) = "1" -item("Column2") = "Andrew" -item(RadCardView1.Columns(2)) = "Fuller" -item("Address") = "908 W. Capital Way" - -```` + + -{{endregion}} - >note To use these indexers the item must have a valid owner e.g. it first has to be added to the __Items__ collection of the __RadCardView__. > @@ -114,51 +67,19 @@ Aside from using __GroupDescriptors__, custom groups can also be added to __RadC #### Adding groups -{{source=..\SamplesCS\CardView\CardViewUnboundMode.cs region=AddGroups}} -{{source=..\SamplesVB\CardView\CardViewUnboundMode.vb region=AddGroups}} -````C# -this.radCardView1.EnableGrouping = true; -this.radCardView1.ShowGroups = true; -this.radCardView1.EnableCustomGrouping = true; -this.radCardView1.CardViewElement.ViewElement.Orientation = Orientation.Vertical; -this.radCardView1.Groups.Add(new ListViewDataItemGroup("First Group")); -this.radCardView1.Groups.Add(new ListViewDataItemGroup("Second Group")); - -```` -````VB.NET -Me.RadCardView1.EnableGrouping = True -Me.RadCardView1.ShowGroups = True -Me.RadCardView1.EnableCustomGrouping = True -Me.RadCardView1.CardViewElement.ViewElement.Orientation = Orientation.Vertical -Me.RadCardView1.Groups.Add(New ListViewDataItemGroup("First Group")) -Me.RadCardView1.Groups.Add(New ListViewDataItemGroup("Second Group")) - -```` - -{{endregion}} - -In order to assign an item to a group, you should set the item’s __Group__ property: + + -#### Assign item to a group -{{source=..\SamplesCS\CardView\CardViewUnboundMode.cs region=AssignItemToAGroup}} -{{source=..\SamplesVB\CardView\CardViewUnboundMode.vb region=AssignItemToAGroup}} -````C# -this.radCardView1.Items[0].Group = this.radCardView1.Groups[0]; -this.radCardView1.Items[1].Group = this.radCardView1.Groups[1]; -this.radCardView1.Items[2].Group = this.radCardView1.Groups[1]; -```` -````VB.NET -Me.RadCardView1.Items(0).Group = Me.RadCardView1.Groups(0) -Me.RadCardView1.Items(1).Group = Me.RadCardView1.Groups(1) -Me.RadCardView1.Items(2).Group = Me.RadCardView1.Groups(1) +In order to assign an item to a group, you should set the item’s __Group__ property: -```` +#### Assign item to a group + + -{{endregion}} In order to enable this kind of grouping the __EnableCustomGrouping__ property needs to be set to *true*. In order to display the groups the __ShowGroups__ property needs to be set to *true*. diff --git a/controls/carousel/customizing-appearance/customizing-appearance.md b/controls/carousel/customizing-appearance/customizing-appearance.md index a82453715..9875c17b9 100644 --- a/controls/carousel/customizing-appearance/customizing-appearance.md +++ b/controls/carousel/customizing-appearance/customizing-appearance.md @@ -22,21 +22,10 @@ The following snippet shows how you can change the back color of the navigation #### Change Navigation Buttons BackColor -{{source=..\SamplesCS\Carousel\CarouselGettingStarted.cs region=NavBackColor}} -{{source=..\SamplesVB\Carousel\CarouselGettingStarted.vb region=NavBackColor}} + + -````C# -radCarousel1.ButtonNext.ButtonFillElement.BackColor = ColorTranslator.FromHtml("#91c930"); -radCarousel1.ButtonPrevious.ButtonFillElement.BackColor = ColorTranslator.FromHtml("#91c930"); -```` -````VB.NET -RadCarousel1.ButtonNext.ButtonFillElement.BackColor = ColorTranslator.FromHtml("#91c930") -RadCarousel1.ButtonPrevious.ButtonFillElement.BackColor = ColorTranslator.FromHtml("#91c930") - -```` - -{{endregion}} >caption Figure 2: Navigation Buttons BackColor Changed. diff --git a/controls/carousel/data-binding.md b/controls/carousel/data-binding.md index 62ac751bd..373aac130 100644 --- a/controls/carousel/data-binding.md +++ b/controls/carousel/data-binding.md @@ -29,167 +29,18 @@ The example below creates a generic list of an object called "Feature". "Feature #### The Features Object -{{source=..\SamplesCS\Carousel\CarouselDataBinding.cs region=createGenericListClass}} -{{source=..\SamplesVB\Carousel\CarouselDataBinding.vb region=createGenericListClass}} - -````C# -public class Features -{ - public Features(int id, string name) - { - _id = id; - _name = name; - } - private int _id; - public int ID - { - get - { - return _id; - } - set - { - _id = value; - } - } - private string _name; - public string Name - { - get - { - return _name; - } - set - { - _name = value; - } - } -} - -```` -````VB.NET -Public Class Features - Public Sub New(ByVal id As Integer, ByVal name As String) - _id = id - _name = name - End Sub - Private _id As Integer - Public Property ID() As Integer - Get - Return _id - End Get - Set(ByVal value As Integer) - _id = value - End Set - End Property - Private _name As String - Public Property Name() As String - Get - Return _name - End Get - Set(ByVal value As String) - _name = value - End Set - End Property -End Class - -```` - -{{endregion}} + + + + #### Binding RadCarousel to Generic List -{{source=..\SamplesCS\Carousel\CarouselDataBinding.cs region=bindingCarousel}} -{{source=..\SamplesVB\Carousel\CarouselDataBinding.vb region=bindingCarousel}} - -````C# -private void CarouselDataBinding_Load(object sender, EventArgs e) -{ - // Describe the carousel path - CarouselBezierPath path = new CarouselBezierPath(); - path.CtrlPoint1 = new Telerik.WinControls.UI.Point3D(86, 76, 70); - path.CtrlPoint2 = new Telerik.WinControls.UI.Point3D(10, 20, 0); - path.FirstPoint = new Telerik.WinControls.UI.Point3D(14, 77, 70); - path.LastPoint = new Telerik.WinControls.UI.Point3D(90, 20, 0); - path.ZScale = 500; - this.radCarousel1.CarouselPath = path; - radCarousel1.ItemDataBound += new ItemDataBoundEventHandler(radCarousel1_ItemDataBound); - radCarousel1.NewCarouselItemCreating += new NewCarouselItemCreatingEventHandler(radCarousel1_NewCarouselItemCreating); - this.Click += new EventHandler(CarouselDataBinding_Click); - // Create a generic list of Feature objects and bind it - List products = new List(); - products.Add(new Features(1, "Products")); - products.Add(new Features(2, "Services")); - products.Add(new Features(3, "Consulting")); - radCarousel1.DataSource = products; -} -private void radCarousel1_ItemDataBound(object sender, ItemDataBoundEventArgs e) -{ - if (e.DataBoundItem is RadButtonElement) - { - // get the RadButtonElement created in the NewCarouselItemCreating event. - // The RadItem is represented by the e.DataBoundItem property. - // Assign properties based on bound data - represented by e.DataItem - RadButtonElement button = (e.DataBoundItem as RadButtonElement); - button.Text = (e.DataItem as Features).Name; - button.Tag = (e.DataItem as Features).ID; - button.Font = new Font("Arial", 20); - button.Click += new EventHandler(CarouselDataBinding_Click); - } -} -private void radCarousel1_NewCarouselItemCreating(object sender, NewCarouselItemCreatingEventArgs e) -{ - e.NewCarouselItem = new RadButtonElement(); -} -void CarouselDataBinding_Click(object sender, EventArgs e) -{ - MessageBox.Show("You clicked ID " + (sender as RadButtonElement).Tag.ToString()); -} - -```` -````VB.NET -Private Sub CarouselDataBinding_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load - ' Describe the carousel path - Dim CarouselBezierPath1 As Telerik.WinControls.UI.CarouselBezierPath = New Telerik.WinControls.UI.CarouselBezierPath - CarouselBezierPath1.CtrlPoint1 = New Telerik.WinControls.UI.Point3D(86, 76, 70) - CarouselBezierPath1.CtrlPoint2 = New Telerik.WinControls.UI.Point3D(10, 20, 0) - CarouselBezierPath1.FirstPoint = New Telerik.WinControls.UI.Point3D(14, 77, 70) - CarouselBezierPath1.LastPoint = New Telerik.WinControls.UI.Point3D(90, 20, 0) - CarouselBezierPath1.ZScale = 500 - Me.RadCarousel1.CarouselPath = CarouselBezierPath1 - AddHandler RadCarousel1.ItemDataBound, AddressOf radCarousel1_ItemDataBound - AddHandler RadCarousel1.NewCarouselItemCreating, AddressOf radCarousel1_NewCarouselItemCreating - AddHandler Me.Click, AddressOf Form1_Click - ' Create a generic list of Feature objects and bind it - Dim products As New List(Of Features)() - products.Add(New Features(1, "Products")) - products.Add(New Features(2, "Services")) - products.Add(New Features(3, "Consulting")) - RadCarousel1.DataSource = products -End Sub -Private Sub radCarousel1_ItemDataBound(ByVal sender As Object, ByVal e As ItemDataBoundEventArgs) - If TypeOf e.DataBoundItem Is RadButtonElement Then - ' get the RadButtonElement created in the NewCarouselItemCreating event. - ' The RadItemis represented by the e.DataBoundItem property. - ' Assign properties based on bound data - represented by e.DataItem - Dim button As RadButtonElement = (TryCast(e.DataBoundItem, RadButtonElement)) - button.Text = (TryCast(e.DataItem, Features)).Name - button.Tag = (TryCast(e.DataItem, Features)).ID - button.Font = New Font("Arial", 20) - AddHandler button.Click, AddressOf Form1_Click - End If -End Sub -Private Sub radCarousel1_NewCarouselItemCreating(ByVal sender As Object, ByVal e As NewCarouselItemCreatingEventArgs) - e.NewCarouselItem = New RadButtonElement() -End Sub -Sub Form1_Click(ByVal sender As Object, ByVal e As EventArgs) - MessageBox.Show("You clicked ID " + (TryCast(sender, RadButtonElement)).Tag.ToString()) -End Sub - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/carousel/getting-started.md b/controls/carousel/getting-started.md index 8670a3a8d..324e89e15 100644 --- a/controls/carousel/getting-started.md +++ b/controls/carousel/getting-started.md @@ -45,57 +45,10 @@ The example below demonstrates creating an elliptical path and populating the ca 1\. In a new WinForms project, add a __RadCarousel__ to the default form. Set its __Dock__ property to *Fill*. 2\. Add the following code to the form's `Load` event handler: -{{source=..\SamplesCS\Carousel\CarouselGettingStarted.cs region=carouselGettingStarted}} -{{source=..\SamplesVB\Carousel\CarouselGettingStarted.vb region=carouselGettingStarted}} -````C# -private void CarouselGettingStarted_Load(object sender, EventArgs e) -{ - // define an elliptical path - CarouselEllipsePath path = new CarouselEllipsePath(); - // put the center point of the path in the center of the form - path.Center = new Telerik.WinControls.UI.Point3D(50, 50, 0); - path.FinalAngle = -100; - path.InitialAngle = -90; - path.U = new Telerik.WinControls.UI.Point3D(-20, -17, -50); - path.V = new Telerik.WinControls.UI.Point3D(30, -25, -60); - this.radCarousel1.CarouselPath = path; - // populate carousel items - radCarousel1.Items.Add(new RadButtonElement("Products")); - radCarousel1.Items.Add(new RadButtonElement("Services")); - radCarousel1.Items.Add(new RadButtonElement("Consulting")); - radCarousel1.Items.Add(new RadButtonElement("Support")); - RadLabelElement label = new RadLabelElement(); - label.Text = "Preferences"; - label.Font = new Font("Arial", 7, FontStyle.Italic | FontStyle.Bold); - radCarousel1.Items.Add(label); -} - -```` -````VB.NET -Private Sub CarouselGettingStarted_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load - ' define an elliptical path - Dim path As New CarouselEllipsePath() - ' put the center point of the path in the center of the form - path.Center = New Point3D(50, 50, 0) - path.InitialAngle = -100 - path.FinalAngle = -90 - path.U = New Point3D(-20, -17, -50) - path.V = New Point3D(30, -25, -60) - RadCarousel1.CarouselPath = path - ' populate carousel items - RadCarousel1.Items.Add(New RadButtonElement("Products")) - RadCarousel1.Items.Add(New RadButtonElement("Services")) - RadCarousel1.Items.Add(New RadButtonElement("Consulting")) - RadCarousel1.Items.Add(New RadButtonElement("Support")) - Dim label As New RadLabelElement() - label.Text = "Preferences" - label.Font = New Font("Arial", 7, FontStyle.Italic Or FontStyle.Bold) - RadCarousel1.Items.Add(label) -End Sub - -```` - -{{endregion}} + + + + 3\. Press `F5` to run the application. You can use the button or directly click the items in order to select particular item. diff --git a/controls/carousel/using-radcarousel/carousel-items.md b/controls/carousel/using-radcarousel/carousel-items.md index 4274fec69..f69746d2b 100644 --- a/controls/carousel/using-radcarousel/carousel-items.md +++ b/controls/carousel/using-radcarousel/carousel-items.md @@ -21,45 +21,10 @@ To add items to the carousel without [data binding]({%slug winforms/carousel/usi #### Adding Items -{{source=..\SamplesCS\Carousel\CarouselItems.cs region=carouselItems}} -{{source=..\SamplesVB\Carousel\CarouselItems.vb region=carouselItems}} + + -````C# -radCarousel1.Items.Add(new RadButtonElement("My Button")); -RadCheckBoxElement checkbox = new RadCheckBoxElement(); -checkbox.Text = "My Checkbox"; -radCarousel1.Items.Add(checkbox); -RadRadioButtonElement radio1 = new RadRadioButtonElement(); -radio1.Text = "Choice 1"; -radio1.ToggleState = ToggleState.On; -RadRadioButtonElement radio2 = new RadRadioButtonElement(); -radio2.Text = "Choice 2"; -RadRadioButtonElement radio3 = new RadRadioButtonElement(); -radio3.Text = "Choice 3"; -radCarousel1.Items.Add(radio1); -radCarousel1.Items.Add(radio2); -radCarousel1.Items.Add(radio3); - -```` -````VB.NET -RadCarousel1.Items.Add(New RadButtonElement("My Button")) -Dim checkbox As New RadCheckBoxElement() -checkbox.Text = "My Checkbox" -RadCarousel1.Items.Add(checkbox) -Dim radio1 As New RadRadioButtonElement() -radio1.Text = "Choice 1" -radio1.ToggleState = ToggleState.On -Dim radio2 As New RadRadioButtonElement() -radio2.Text = "Choice 2" -Dim radio3 As New RadRadioButtonElement() -radio3.Text = "Choice 3" -RadCarousel1.Items.Add(radio1) -RadCarousel1.Items.Add(radio2) -RadCarousel1.Items.Add(radio3) - -```` - -{{endregion}} + ### Deleting Items @@ -67,21 +32,10 @@ To delete an entry from the carousel __Items__ collection, use the __Remove__ or #### Deleting Carousel Items -{{source=..\SamplesCS\Carousel\CarouselItems.cs region=carouselDeletingItems}} -{{source=..\SamplesVB\Carousel\CarouselItems.vb region=carouselDeletingItems}} + + -````C# -radCarousel1.Items.Remove(radCarousel1.Items[0]); -radCarousel1.Items.RemoveAt(0); - -```` -````VB.NET -RadCarousel1.Items.Remove(RadCarousel1.Items(0)) -RadCarousel1.Items.RemoveAt(0) - -```` - -{{endregion}} + # See Also diff --git a/controls/carousel/using-radcarousel/carousel-path.md b/controls/carousel/using-radcarousel/carousel-path.md index 21f75f67e..554fa7d05 100644 --- a/controls/carousel/using-radcarousel/carousel-path.md +++ b/controls/carousel/using-radcarousel/carousel-path.md @@ -29,33 +29,10 @@ The __CarouselPath__ property defines the route that the carousel items will be #### Defining ellipse path -{{source=..\SamplesCS\Carousel\CarouselPath.cs region=definingEllipsePath}} -{{source=..\SamplesVB\Carousel\CarouselPath.vb region=definingEllipsePath}} - -````C# -CarouselEllipsePath ellipsePath = new CarouselEllipsePath(); -ellipsePath.Center = new Telerik.WinControls.UI.Point3D(50, 50, 0); -ellipsePath.FinalAngle = -100; -ellipsePath.InitialAngle = -90; -ellipsePath.U = new Telerik.WinControls.UI.Point3D(-20, -17, -50); -ellipsePath.V = new Telerik.WinControls.UI.Point3D(30, -25, -60); -ellipsePath.ZScale = 500; -this.radCarousel1.CarouselPath = ellipsePath; - -```` -````VB.NET -Dim ellipsePath As CarouselEllipsePath = New CarouselEllipsePath -ellipsePath.Center = New Telerik.WinControls.UI.Point3D(50, 50, 0) -ellipsePath.FinalAngle = 360 -ellipsePath.InitialAngle = 0 -ellipsePath.U = New Telerik.WinControls.UI.Point3D(-20, -17, -50) -ellipsePath.V = New Telerik.WinControls.UI.Point3D(30, -25, -60) -ellipsePath.ZScale = 500 -Me.RadCarousel1.CarouselPath = ellipsePath - -```` - -{{endregion}} + + + + ## CarouselBezierPath @@ -69,29 +46,10 @@ __CarouselBezierPath__ describes two end points and two "control" points in thr __Defining bezier path__ -{{source=..\SamplesCS\Carousel\CarouselPath.cs region=definingBezierPath}} -{{source=..\SamplesVB\Carousel\CarouselPath.vb region=definingBezierPath}} - -````C# -CarouselBezierPath bezierPath = new CarouselBezierPath(); -bezierPath.FirstPoint = new Point3D(10, 20, 0); -bezierPath.CtrlPoint1 = new Point3D(14, 76, 70); -bezierPath.CtrlPoint2 = new Point3D(86, 76, 70); -bezierPath.LastPoint = new Point3D(90, 20, 0); -this.radCarousel1.CarouselPath = bezierPath; - -```` -````VB.NET -Dim bezierPath As New CarouselBezierPath() -bezierPath.FirstPoint = New Point3D(10, 20, 0) -bezierPath.CtrlPoint1 = New Point3D(14, 76, 70) -bezierPath.CtrlPoint2 = New Point3D(86, 76, 70) -bezierPath.LastPoint = New Point3D(90, 20, 0) -Me.RadCarousel1.CarouselPath = bezierPath - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/chartview/axes/axes.md b/controls/chartview/axes/axes.md index 3d0fff62c..c66a0cbdc 100644 --- a/controls/chartview/axes/axes.md +++ b/controls/chartview/axes/axes.md @@ -58,95 +58,19 @@ The following example demonstrates how some of the above properties are set: #### Set Properties -{{source=..\SamplesCS\ChartView\Axes\AxisForm.cs region=axis}} -{{source=..\SamplesVB\ChartView\Axes\AxisForm.vb region=axis}} - -````C# -BarSeries series = new BarSeries(); -series.DataPoints.Add(new CategoricalDataPoint(10, "First")); -series.DataPoints.Add(new CategoricalDataPoint(30, "Second")); -series.DataPoints.Add(new CategoricalDataPoint(22, "Third")); -series.DataPoints.Add(new CategoricalDataPoint(15, "Fourth")); -series.DataPoints.Add(new CategoricalDataPoint(40, "Fifth")); -series.DataPoints.Add(new CategoricalDataPoint(80, "Sixth")); -this.radChartView1.Series.Add(series); -CategoricalAxis categoricalAxis = radChartView1.Axes[0] as CategoricalAxis; -categoricalAxis.PlotMode = AxisPlotMode.OnTicksPadded; -categoricalAxis.LabelFitMode = AxisLabelFitMode.Rotate; -categoricalAxis.LabelRotationAngle = 310; -LinearAxis verticalAxis = radChartView1.Axes[1] as LinearAxis; -verticalAxis.ForeColor = Color.Green; -verticalAxis.BorderColor = Color.DarkOrange; -verticalAxis.MajorStep = 10; -verticalAxis.Maximum = 100; -verticalAxis.Minimum = 0; -verticalAxis.LabelInterval = 2; -verticalAxis.LabelFormat = "{0:c}"; - -```` -````VB.NET -Dim series As New BarSeries() -series.DataPoints.Add(New CategoricalDataPoint(10, "First")) -series.DataPoints.Add(New CategoricalDataPoint(30, "Second")) -series.DataPoints.Add(New CategoricalDataPoint(22, "Third")) -series.DataPoints.Add(New CategoricalDataPoint(15, "Fourth")) -series.DataPoints.Add(New CategoricalDataPoint(40, "Fifth")) -series.DataPoints.Add(New CategoricalDataPoint(80, "Sixth")) -Me.RadChartView1.Series.Add(series) -Dim categoricalAxis As CategoricalAxis = TryCast(RadChartView1.Axes(0), CategoricalAxis) -categoricalAxis.PlotMode = AxisPlotMode.OnTicksPadded -categoricalAxis.LabelFitMode = AxisLabelFitMode.Rotate -categoricalAxis.LabelRotationAngle = 310 -Dim verticalAxis As LinearAxis = TryCast(RadChartView1.Axes(1), LinearAxis) -verticalAxis.ForeColor = Color.Green -verticalAxis.BorderColor = Color.DarkOrange -verticalAxis.MajorStep = 10 -verticalAxis.Maximum = 100 -verticalAxis.Minimum = 0 -verticalAxis.LabelInterval = 2 -verticalAxis.LabelFormat = "{0:c}" - -```` - -{{endregion}} + + + + Having the **BorderColor** property of the axis set to a color different than the one defined in the theme will also set the border color of the axis labels. As this might not be desired one can access each of the labels and explicitly set their **BorderColor** to *Transparent*. A suitable place for this is the **Shown** event of the form #### Labels Border Color -{{source=..\SamplesCS\ChartView\Axes\AxisForm.cs region=ShownEvent}} -{{source=..\SamplesVB\ChartView\Axes\AxisForm.vb region=ShownEvent}} -````C# -private void AxisForm_Shown(object sender, EventArgs e) -{ - LinearAxis verticalAxis = (LinearAxis)this.radChartView1.Axes[1]; - foreach (var item in verticalAxis.Children) - { - AxisLabelElement labelElement = item as AxisLabelElement; - if (labelElement != null) - { - labelElement.BorderColor = Color.Transparent; - } - } -} - -```` -````VB.NET -Private Sub AxisForm_Shown(sender As Object, e As EventArgs) - Dim verticalAxis As LinearAxis = CType(Me.RadChartView1.Axes(1), LinearAxis) - For Each item In verticalAxis.Children - Dim labelElement As AxisLabelElement = TryCast(item, AxisLabelElement) - If labelElement IsNot Nothing Then - labelElement.BorderColor = Color.Transparent - End If - Next -End Sub - -```` - - - -{{endregion}} + + + + >caption Figure 2: Property Settings ![WinForms RadChartView Property Settings](images/chartview-axes002.png) diff --git a/controls/chartview/axes/axis-alignment.md b/controls/chartview/axes/axis-alignment.md index 26f93dcc7..7a3f53f96 100644 --- a/controls/chartview/axes/axis-alignment.md +++ b/controls/chartview/axes/axis-alignment.md @@ -23,56 +23,10 @@ This example sets offset of the horizontal axis along the vertical axis. #### One Axis Offset -{{source=..\SamplesCS\ChartView\Axes\AxisAlignmentForm.cs region=one-axis-offset}} -{{source=..\SamplesVB\ChartView\Axes\AxisAlignmentForm.vb region=one-axis-offset}} - -````C# -LineSeries tempSeries = new LineSeries(); -tempSeries.DataPoints.Add(new CategoricalDataPoint(-3, "Jan")); -tempSeries.DataPoints.Add(new CategoricalDataPoint(-2, "Feb")); -tempSeries.DataPoints.Add(new CategoricalDataPoint(2, "Mar")); -tempSeries.DataPoints.Add(new CategoricalDataPoint(7, "Apr")); -tempSeries.DataPoints.Add(new CategoricalDataPoint(12, "May")); -tempSeries.DataPoints.Add(new CategoricalDataPoint(18, "Jun")); -tempSeries.DataPoints.Add(new CategoricalDataPoint(20, "Jul")); -tempSeries.DataPoints.Add(new CategoricalDataPoint(20, "Aug")); -tempSeries.DataPoints.Add(new CategoricalDataPoint(16, "Sep")); -tempSeries.DataPoints.Add(new CategoricalDataPoint(10, "Oct")); -tempSeries.DataPoints.Add(new CategoricalDataPoint(5, "Nov")); -tempSeries.DataPoints.Add(new CategoricalDataPoint(0, "Dec")); -radChartView1.Series.Add(tempSeries); -CategoricalAxis tempHorizontalAxis = tempSeries.HorizontalAxis as CategoricalAxis; -tempHorizontalAxis.StartPositionAxis = tempSeries.VerticalAxis; -tempHorizontalAxis.StartPositionValue = 9; -tempHorizontalAxis.Title = "New York"; -LinearAxis tempVerticalAxis = tempSeries.VerticalAxis as LinearAxis; -tempVerticalAxis.Title = " ºC"; - -```` -````VB.NET -Dim tempSeries As New LineSeries() -tempSeries.DataPoints.Add(New CategoricalDataPoint(-3, "Jan")) -tempSeries.DataPoints.Add(New CategoricalDataPoint(-2, "Feb")) -tempSeries.DataPoints.Add(New CategoricalDataPoint(2, "Mar")) -tempSeries.DataPoints.Add(New CategoricalDataPoint(7, "Apr")) -tempSeries.DataPoints.Add(New CategoricalDataPoint(12, "May")) -tempSeries.DataPoints.Add(New CategoricalDataPoint(18, "Jun")) -tempSeries.DataPoints.Add(New CategoricalDataPoint(20, "Jul")) -tempSeries.DataPoints.Add(New CategoricalDataPoint(20, "Aug")) -tempSeries.DataPoints.Add(New CategoricalDataPoint(16, "Sep")) -tempSeries.DataPoints.Add(New CategoricalDataPoint(10, "Oct")) -tempSeries.DataPoints.Add(New CategoricalDataPoint(5, "Nov")) -tempSeries.DataPoints.Add(New CategoricalDataPoint(0, "Dec")) -RadChartView1.Series.Add(tempSeries) -Dim tempHorizontalAxis As CategoricalAxis = TryCast(tempSeries.HorizontalAxis, CategoricalAxis) -tempHorizontalAxis.StartPositionAxis = tempSeries.VerticalAxis -tempHorizontalAxis.StartPositionValue = 9 -Dim tempVerticalAxis As LinearAxis = TryCast(tempSeries.VerticalAxis, LinearAxis) -tempVerticalAxis.Title = " ºC" - -```` - -{{endregion}} + + + + >caption Figure 1: One Axis Offset ![WinForms RadChartView One Axis Offset](images/chartview-axes-axis-alignment001.png) @@ -83,47 +37,10 @@ This example sets offset offset of the two axes of the __RadChartView__. #### Two Axis Offset -{{source=..\SamplesCS\ChartView\Axes\AxisAlignmentForm.cs region=two-axes-offset}} -{{source=..\SamplesVB\ChartView\Axes\AxisAlignmentForm.vb region=two-axes-offset}} - -````C# -LineSeries cubicSeries = new LineSeries(); -cubicSeries.DataPoints.Add(new CategoricalDataPoint(-27, -3)); -cubicSeries.DataPoints.Add(new CategoricalDataPoint(-8, -2)); -cubicSeries.DataPoints.Add(new CategoricalDataPoint(-1, -1)); -cubicSeries.DataPoints.Add(new CategoricalDataPoint(0, 0)); -cubicSeries.DataPoints.Add(new CategoricalDataPoint(1, 1)); -cubicSeries.DataPoints.Add(new CategoricalDataPoint(8, 2)); -cubicSeries.DataPoints.Add(new CategoricalDataPoint(27, 3)); -radChartView1.Series.Add(cubicSeries); -CategoricalAxis cubicHorizontalAxis = cubicSeries.HorizontalAxis as CategoricalAxis; -cubicHorizontalAxis.StartPositionAxis = cubicSeries.VerticalAxis; -cubicHorizontalAxis.StartPositionValue = 0; -LinearAxis cubicVerticalAxis = cubicSeries.VerticalAxis as LinearAxis; -cubicVerticalAxis.StartPositionAxis = cubicSeries.HorizontalAxis; -cubicVerticalAxis.StartPositionValue = 0; - -```` -````VB.NET -Dim cubicSeries As New LineSeries() -cubicSeries.DataPoints.Add(New CategoricalDataPoint(-27, -3)) -cubicSeries.DataPoints.Add(New CategoricalDataPoint(-8, -2)) -cubicSeries.DataPoints.Add(New CategoricalDataPoint(-1, -1)) -cubicSeries.DataPoints.Add(New CategoricalDataPoint(0, 0)) -cubicSeries.DataPoints.Add(New CategoricalDataPoint(1, 1)) -cubicSeries.DataPoints.Add(New CategoricalDataPoint(8, 2)) -cubicSeries.DataPoints.Add(New CategoricalDataPoint(27, 3)) -RadChartView1.Series.Add(cubicSeries) -Dim cubicHorizontalAxis As CategoricalAxis = TryCast(cubicSeries.HorizontalAxis, CategoricalAxis) -cubicHorizontalAxis.StartPositionAxis = cubicSeries.VerticalAxis -cubicHorizontalAxis.StartPositionValue = 0 -Dim cubicVerticalAxis As LinearAxis = TryCast(cubicSeries.VerticalAxis, LinearAxis) -cubicVerticalAxis.StartPositionAxis = cubicSeries.HorizontalAxis -cubicVerticalAxis.StartPositionValue = 0 - -```` - -{{endregion}} + + + + >caption Figure 2: Two Axis Offset ![WinForms RadChartView Two Axis Offset](images/chartview-axes-axis-alignment002.png) diff --git a/controls/chartview/axes/categorical.md b/controls/chartview/axes/categorical.md index 25f1e7760..3232e6d05 100644 --- a/controls/chartview/axes/categorical.md +++ b/controls/chartview/axes/categorical.md @@ -27,40 +27,10 @@ __RadChartView__ uses Categorical axes to plot data that contains categorical va #### Categоrical Axes Setup -{{source=..\SamplesCS\ChartView\Axes\CategoricalAxisForm.cs region=catAxis}} -{{source=..\SamplesVB\ChartView\Axes\CategoricalAxisForm.vb region=catAxis}} + + -````C# -LineSeries series = new LineSeries(); -series.DataPoints.Add(new CategoricalDataPoint(20, "Jackets and Flackets")); -series.DataPoints.Add(new CategoricalDataPoint(40, "Accessories and Watches")); -series.DataPoints.Add(new CategoricalDataPoint(35, "Long Sleeve Tees")); -series.DataPoints.Add(new CategoricalDataPoint(45, "Dresses and Skirts")); -radChartView1.Series.Add(series); -CategoricalAxis horizontalAxis = series.HorizontalAxis as CategoricalAxis; -if (horizontalAxis != null) -{ - horizontalAxis.PlotMode = AxisPlotMode.BetweenTicks; - horizontalAxis.LabelFitMode = AxisLabelFitMode.MultiLine; -} -```` -````VB.NET -Dim series As New LineSeries() -series.DataPoints.Add(New CategoricalDataPoint(20, "Jackets and Flackets")) -series.DataPoints.Add(New CategoricalDataPoint(40, "Accessories and Watches")) -series.DataPoints.Add(New CategoricalDataPoint(35, "Long Sleeve Tees")) -series.DataPoints.Add(New CategoricalDataPoint(45, "Dresses and Skirts")) -RadChartView1.Series.Add(series) -Dim horizontalAxis As CategoricalAxis = TryCast(series.HorizontalAxis, CategoricalAxis) -If horizontalAxis IsNot Nothing Then - horizontalAxis.PlotMode = AxisPlotMode.BetweenTicks - horizontalAxis.LabelFitMode = AxisLabelFitMode.MultiLine -End If - -```` - -{{endregion}} >caption Figure 1: Categorical Axes Setup ![WinForms RadChartView Categorical Axes Setup](images/chartview-axes-categorical001.png) diff --git a/controls/chartview/axes/datetime.md b/controls/chartview/axes/datetime.md index 947f26e8b..e23d2ff29 100644 --- a/controls/chartview/axes/datetime.md +++ b/controls/chartview/axes/datetime.md @@ -37,41 +37,10 @@ DateTimeCategorical axis is not added by default to Cartesian series. For this r #### DateTimeCategoricalAxis Setup -{{source=..\SamplesCS\ChartView\Axes\DateTimeAxisForm.cs region=dateTimeCategoricalAxis}} -{{source=..\SamplesVB\ChartView\Axes\DateTimeAxisForm.vb region=dateTimeCategoricalAxis}} - -````C# -LineSeries series = new LineSeries(); -series.DataPoints.Add(new CategoricalDataPoint(6, DateTime.Now)); -series.DataPoints.Add(new CategoricalDataPoint(4, DateTime.Now.AddDays(1))); -series.DataPoints.Add(new CategoricalDataPoint(7, DateTime.Now.AddDays(2))); -series.DataPoints.Add(new CategoricalDataPoint(5, DateTime.Now.AddDays(3))); -DateTimeCategoricalAxis categoricalAxis = new DateTimeCategoricalAxis(); -categoricalAxis.DateTimeComponent = DateTimeComponent.Day; -categoricalAxis.PlotMode = AxisPlotMode.BetweenTicks; -categoricalAxis.LabelFormat = "{0:m}"; -//First assign the axis to the VerticalAxis property and then add the series to the chart -series.HorizontalAxis = categoricalAxis; -radChartView1.Series.Add(series); - -```` -````VB.NET -Dim series As New LineSeries() -series.DataPoints.Add(New CategoricalDataPoint(6, DateTime.Now)) -series.DataPoints.Add(New CategoricalDataPoint(4, DateTime.Now.AddDays(1))) -series.DataPoints.Add(New CategoricalDataPoint(7, DateTime.Now.AddDays(2))) -series.DataPoints.Add(New CategoricalDataPoint(5, DateTime.Now.AddDays(3))) -Dim categoricalAxis As New DateTimeCategoricalAxis() -categoricalAxis.DateTimeComponent = DateTimeComponent.Day -categoricalAxis.PlotMode = AxisPlotMode.BetweenTicks -categoricalAxis.LabelFormat = "{0:m}" -'First assign the axis to the VerticalAxis property and then add the series to the chart -series.HorizontalAxis = categoricalAxis -RadChartView1.Series.Add(series) - -```` - -{{endregion}} + + + + >caption Figure 1: DateTimeCategoricalAxis Setup ![WinForms RadChartView DateTimeCategoricalAxis Setup](images/chartview-axes-datetimel001.png) @@ -104,39 +73,10 @@ DateTimeContinuous axis is not added by default to Cartesian series. For this re #### DateTimeContinuousAxis Setup -{{source=..\SamplesCS\ChartView\Axes\DateTimeAxisForm.cs region=dateTimeContinuousAxis}} -{{source=..\SamplesVB\ChartView\Axes\DateTimeAxisForm.vb region=dateTimeContinuousAxis}} - -````C# -LineSeries lineSeries = new LineSeries(); -lineSeries.DataPoints.Add(new CategoricalDataPoint(6, DateTime.Now)); -lineSeries.DataPoints.Add(new CategoricalDataPoint(4, DateTime.Now.AddDays(1))); -lineSeries.DataPoints.Add(new CategoricalDataPoint(7, DateTime.Now.AddDays(2))); -lineSeries.DataPoints.Add(new CategoricalDataPoint(5, DateTime.Now.AddDays(3))); -DateTimeContinuousAxis continuousAxis = new DateTimeContinuousAxis(); -continuousAxis.PlotMode = AxisPlotMode.BetweenTicks; -continuousAxis.LabelFormat = "{0:d}"; -//First assign the axis to the VerticalAxis property and then add the series to the chart -lineSeries.HorizontalAxis = continuousAxis; -radChartView1.Series.Add(lineSeries); - -```` -````VB.NET -Dim lineSeries As New LineSeries() -lineSeries.DataPoints.Add(New CategoricalDataPoint(6, DateTime.Now)) -lineSeries.DataPoints.Add(New CategoricalDataPoint(4, DateTime.Now.AddDays(1))) -lineSeries.DataPoints.Add(New CategoricalDataPoint(7, DateTime.Now.AddDays(2))) -lineSeries.DataPoints.Add(New CategoricalDataPoint(5, DateTime.Now.AddDays(3))) -Dim continuousAxis As New DateTimeContinuousAxis() -continuousAxis.PlotMode = AxisPlotMode.BetweenTicks -continuousAxis.LabelFormat = "{0:d}" -'First assign the axis to the VerticalAxis property and then add the series to the chart -lineSeries.HorizontalAxis = continuousAxis -RadChartView1.Series.Add(lineSeries) - -```` - -{{endregion}} + + + + >caption Figure 2: DateTimeContinuousAxis Setup Setup ![WinForms RadChartView DateTimeContinuousAxis Setup](images/chartview-axes-datetimel002.png) diff --git a/controls/chartview/axes/inverse-axis.md b/controls/chartview/axes/inverse-axis.md index 8055c2757..b971403b3 100644 --- a/controls/chartview/axes/inverse-axis.md +++ b/controls/chartview/axes/inverse-axis.md @@ -19,114 +19,10 @@ This example will demosntrate the depths of crude oil wells in the period betwee #### Axis Inversion -{{source=..\SamplesCS\ChartView\Axes\InverseAxisForm.cs region=inverse-axis}} -{{source=..\SamplesVB\ChartView\Axes\InverseAxisForm.vb region=inverse-axis}} + + -````C# -DataTable tableDryHoles = new DataTable("CrudeOil"); -tableDryHoles.Columns.Add("Time", typeof(DateTime)); -tableDryHoles.Columns.Add("Depth", typeof(double)); -Color dryHoleColor = Color.FromArgb(245, 151, 0); -Dictionary data = new Dictionary(); -data[new DateTime(1988, 06, 30)] = 4171.0; -data[new DateTime(1989, 06, 30)] = 4116.0; -data[new DateTime(1990, 06, 30)] = 4326.0; -data[new DateTime(1991, 06, 30)] = 4434.0; -data[new DateTime(1992, 06, 30)] = 4877.0; -data[new DateTime(1993, 06, 30)] = 4986.0; -data[new DateTime(1994, 06, 30)] = 5278.0; -data[new DateTime(1995, 06, 30)] = 4998.0; -data[new DateTime(1996, 06, 30)] = 4735.0; -data[new DateTime(1997, 06, 30)] = 4944.0; -data[new DateTime(1998, 06, 30)] = 4941.0; -data[new DateTime(1999, 06, 30)] = 4507.0; -data[new DateTime(2000, 06, 30)] = 4493.0; -data[new DateTime(2001, 06, 30)] = 4791.0; -data[new DateTime(2002, 06, 30)] = 4496.0; -data[new DateTime(2003, 06, 30)] = 4684.0; -data[new DateTime(2004, 06, 30)] = 4675.0; -data[new DateTime(2005, 06, 30)] = 4669.0; -data[new DateTime(2006, 06, 30)] = 4706.0; -data[new DateTime(2007, 06, 30)] = 4945.0; -data[new DateTime(2008, 06, 30)] = 4938.0; -foreach (KeyValuePair hole in data) -{ - tableDryHoles.Rows.Add(hole.Key, hole.Value); -} -LinearAxis verticalAxis = new LinearAxis(); -verticalAxis.AxisType = AxisType.Second; -verticalAxis.LabelFormat = "{0}m"; -verticalAxis.IsInverse = true; -DateTimeContinuousAxis horizontalAxis = new DateTimeContinuousAxis(); -horizontalAxis.LabelFormat = "{0:yyyy}"; -horizontalAxis.VerticalLocation = AxisVerticalLocation.Top; -horizontalAxis.MajorStep = 2; -horizontalAxis.MajorStepUnit = Telerik.Charting.TimeInterval.Year; -AreaSeries dryHoles = new AreaSeries(); -dryHoles.BackColor = Color.FromArgb(100, dryHoleColor); -dryHoles.BorderColor = dryHoleColor; -dryHoles.DataMember = "CrudeOil"; -dryHoles.ValueMember = "Depth"; -dryHoles.CategoryMember = "Time"; -dryHoles.VerticalAxis = verticalAxis; -dryHoles.HorizontalAxis = horizontalAxis; -this.radChartView1.DataSource = tableDryHoles; -this.radChartView1.Series.Add(dryHoles); -```` -````VB.NET -Dim tableDryHoles As New DataTable("CrudeOil") -tableDryHoles.Columns.Add("Time", GetType(DateTime)) -tableDryHoles.Columns.Add("Depth", GetType(Double)) -Dim dryHoleColor As Color = Color.FromArgb(245, 151, 0) -Dim data As New Dictionary(Of DateTime, Double)() -data(New DateTime(1988, 6, 30)) = 4171.0 -data(New DateTime(1989, 6, 30)) = 4116.0 -data(New DateTime(1990, 6, 30)) = 4326.0 -data(New DateTime(1991, 6, 30)) = 4434.0 -data(New DateTime(1992, 6, 30)) = 4877.0 -data(New DateTime(1993, 6, 30)) = 4986.0 -data(New DateTime(1994, 6, 30)) = 5278.0 -data(New DateTime(1995, 6, 30)) = 4998.0 -data(New DateTime(1996, 6, 30)) = 4735.0 -data(New DateTime(1997, 6, 30)) = 4944.0 -data(New DateTime(1998, 6, 30)) = 4941.0 -data(New DateTime(1999, 6, 30)) = 4507.0 -data(New DateTime(2000, 6, 30)) = 4493.0 -data(New DateTime(2001, 6, 30)) = 4791.0 -data(New DateTime(2002, 6, 30)) = 4496.0 -data(New DateTime(2003, 6, 30)) = 4684.0 -data(New DateTime(2004, 6, 30)) = 4675.0 -data(New DateTime(2005, 6, 30)) = 4669.0 -data(New DateTime(2006, 6, 30)) = 4706.0 -data(New DateTime(2007, 6, 30)) = 4945.0 -data(New DateTime(2008, 6, 30)) = 4938.0 -For Each hole As KeyValuePair(Of DateTime, Double) In data - tableDryHoles.Rows.Add(hole.Key, hole.Value) -Next -Dim verticalAxis As New LinearAxis() -verticalAxis.AxisType = AxisType.Second -verticalAxis.LabelFormat = "{0}m" -verticalAxis.IsInverse = True -Dim horizontalAxis As New DateTimeContinuousAxis() -horizontalAxis.LabelFormat = "{0:yyyy}" -horizontalAxis.VerticalLocation = AxisVerticalLocation.Top -horizontalAxis.MajorStep = 2 -horizontalAxis.MajorStepUnit = Telerik.Charting.TimeInterval.Year -Dim dryHoles As New AreaSeries() -dryHoles.BackColor = Color.FromArgb(100, dryHoleColor) -dryHoles.BorderColor = dryHoleColor -dryHoles.DataMember = "CrudeOil" -dryHoles.ValueMember = "Depth" -dryHoles.CategoryMember = "Time" -dryHoles.VerticalAxis = verticalAxis -dryHoles.HorizontalAxis = horizontalAxis -Me.RadChartView1.DataSource = tableDryHoles -Me.RadChartView1.Series.Add(dryHoles) - -```` - -{{endregion}} >caption Figure 1: Inverse Axis ![WinForms RadChartView Inverse Axis](images/chartview-axes-inverse-axis001.png) diff --git a/controls/chartview/axes/linear.md b/controls/chartview/axes/linear.md index 5a7c600bd..b573d907c 100644 --- a/controls/chartview/axes/linear.md +++ b/controls/chartview/axes/linear.md @@ -37,51 +37,10 @@ Here is how to set properties of the LinearAxes: #### LinearAxis Setup -{{source=..\SamplesCS\ChartView\Axes\LinearAxisForm.cs region=axis}} -{{source=..\SamplesVB\ChartView\Axes\LinearAxisForm.vb region=axis}} - -````C# -ScatterSeries series = new ScatterSeries(); -series.DataPoints.Add(new ScatterDataPoint(5, 5)); -series.DataPoints.Add(new ScatterDataPoint(4, 2)); -series.DataPoints.Add(new ScatterDataPoint(-1, 3)); -series.DataPoints.Add(new ScatterDataPoint(11, 4)); -radChartView1.Series.Add(series); -LinearAxis horizontalAxis = radChartView1.Axes.Get(0); -// or horizontalAxis = series.HorizontalAxis as LinearAxis; -horizontalAxis.Minimum = -5; -horizontalAxis.Maximum = 15; -horizontalAxis.MajorStep = 5; -LinearAxis verticalAxis = radChartView1.Axes.Get(1); -// or verticalAxis = series.VerticalAxis as LinearAxis; -verticalAxis.Minimum = 1; -verticalAxis.Maximum = 7; -verticalAxis.MajorStep = 2; -verticalAxis.HorizontalLocation = AxisHorizontalLocation.Right; - -```` -````VB.NET -Dim series As New ScatterSeries() -series.DataPoints.Add(New ScatterDataPoint(5, 5)) -series.DataPoints.Add(New ScatterDataPoint(4, 2)) -series.DataPoints.Add(New ScatterDataPoint(-1, 3)) -series.DataPoints.Add(New ScatterDataPoint(11, 4)) -RadChartView1.Series.Add(series) -Dim horizontalAxis As LinearAxis = RadChartView1.Axes.[Get](Of LinearAxis)(0) -'or horizontalAxis = TryCast(series.HorizontalAxis, LinearAxis) -horizontalAxis.Minimum = -5 -horizontalAxis.Maximum = 15 -horizontalAxis.MajorStep = 5 -Dim verticalAxis As LinearAxis = RadChartView1.Axes.[Get](Of LinearAxis)(1) -' or verticalAxis = TryCast(series.VerticalAxis, LinearAxis) -verticalAxis.Minimum = 1 -verticalAxis.Maximum = 7 -verticalAxis.MajorStep = 2 -verticalAxis.HorizontalLocation = AxisHorizontalLocation.Right - -```` - -{{endregion}} + + + + >caption Figure 1: LinearAxis Setup ![WinForms RadChartView LinearAxis Setup](images/chartview-axes-linear001.png) diff --git a/controls/chartview/axes/logarithmic.md b/controls/chartview/axes/logarithmic.md index d9b860700..9b23c94d2 100644 --- a/controls/chartview/axes/logarithmic.md +++ b/controls/chartview/axes/logarithmic.md @@ -39,40 +39,10 @@ Logarithmic axis is not added by default to Cartesian series. For this reason yo #### LogarithmicAxis Setup -{{source=..\SamplesCS\ChartView\Axes\LogarithmicAxisForm.cs region=axis}} -{{source=..\SamplesVB\ChartView\Axes\LogarithmicAxisForm.vb region=axis}} - -````C# -BarSeries series = new BarSeries(); -series.DataPoints.Add(new CategoricalDataPoint(10000, "Category 1")); -series.DataPoints.Add(new CategoricalDataPoint(100, "Category 2")); -series.DataPoints.Add(new CategoricalDataPoint(1000, "Category 3")); -series.DataPoints.Add(new CategoricalDataPoint(10, "Category 4")); -LogarithmicAxis verticalAxis = new LogarithmicAxis(); -verticalAxis.AxisType = AxisType.Second; -verticalAxis.LogarithmBase = 10; - -//First assign the axis to the VerticalAxis property and then add the series to the chart -series.VerticalAxis = verticalAxis; -radChartView1.Series.Add(series); - -```` -````VB.NET - Dim series As New BarSeries() - series.DataPoints.Add(New CategoricalDataPoint(10000, "Category 1")) - series.DataPoints.Add(New CategoricalDataPoint(100, "Category 2")) - series.DataPoints.Add(New CategoricalDataPoint(1000, "Category 3")) - series.DataPoints.Add(New CategoricalDataPoint(10, "Category 4")) - Dim verticalAxis As New LogarithmicAxis() - verticalAxis.AxisType = AxisType.Second - verticalAxis.LogarithmBase = 10 - 'First assign the axis to the VerticalAxis property and then add the series to the chart - series.VerticalAxis = verticalAxis - RadChartView1.Series.Add(series) - -```` - -{{endregion}} + + + + >caption Figure 1: LogarithmicAxis Setup ![WinForms RadChartView LogarithmicAxis Setup](images/chartview-axes-logarithmic001.png) diff --git a/controls/chartview/axes/multiple-axes.md b/controls/chartview/axes/multiple-axes.md index 2e06cec7d..f49680aad 100644 --- a/controls/chartview/axes/multiple-axes.md +++ b/controls/chartview/axes/multiple-axes.md @@ -34,71 +34,10 @@ The following example shows how to create a chart with two series sharing their #### One Common Axis -{{source=..\SamplesCS\ChartView\Axes\MultiAxes.cs region=SetupOneCommonAxis}} -{{source=..\SamplesVB\ChartView\Axes\MultiAxes.vb region=SetupOneCommonAxis}} + + -````C# -DateTimeContinuousAxis horizontalAxis = new DateTimeContinuousAxis(); -horizontalAxis.MajorStepUnit = Telerik.Charting.TimeInterval.Day; -horizontalAxis.MajorStep = 1; -horizontalAxis.LabelFormat = "{0:dd/MM/yyyy}"; -LinearAxis verticalAxis1 = new LinearAxis(); -verticalAxis1.AxisType = AxisType.Second; -LinearAxis verticalAxis2 = new LinearAxis(); -verticalAxis2.AxisType = AxisType.Second; -verticalAxis2.HorizontalLocation = AxisHorizontalLocation.Right; -LineSeries line1 = new LineSeries(); -line1.HorizontalAxis = horizontalAxis; -line1.VerticalAxis = verticalAxis1; -LineSeries line2 = new LineSeries(); -line2.HorizontalAxis = horizontalAxis; -line2.VerticalAxis = verticalAxis2; -line1.DataPoints.Add(new CategoricalDataPoint(26d, DateTime.Now.AddDays(-6))); -line1.DataPoints.Add(new CategoricalDataPoint(20d, DateTime.Now.AddDays(-5))); -line1.DataPoints.Add(new CategoricalDataPoint(12d, DateTime.Now.AddDays(-4))); -line1.DataPoints.Add(new CategoricalDataPoint(15d, DateTime.Now.AddDays(-2))); -line1.DataPoints.Add(new CategoricalDataPoint(21d, DateTime.Now.AddDays(-1))); -line2.DataPoints.Add(new CategoricalDataPoint(32d, DateTime.Now.AddDays(-6))); -line2.DataPoints.Add(new CategoricalDataPoint(52d, DateTime.Now.AddDays(-4))); -line2.DataPoints.Add(new CategoricalDataPoint(35d, DateTime.Now.AddDays(-3))); -line2.DataPoints.Add(new CategoricalDataPoint(36d, DateTime.Now.AddDays(-2))); -line2.DataPoints.Add(new CategoricalDataPoint(11d, DateTime.Now.AddDays(-1))); -this.radChartView1.Series.Add(line1); -this.radChartView1.Series.Add(line2); -```` -````VB.NET -Dim horizontalAxis As New DateTimeContinuousAxis() -horizontalAxis.MajorStepUnit = Telerik.Charting.TimeInterval.Day -horizontalAxis.MajorStep = 1 -horizontalAxis.LabelFormat = "{0:dd/MM/yyyy}" -Dim verticalAxis1 As New LinearAxis() -verticalAxis1.AxisType = AxisType.Second -Dim verticalAxis2 As New LinearAxis() -verticalAxis2.AxisType = AxisType.Second -verticalAxis2.HorizontalLocation = AxisHorizontalLocation.Right -Dim line1 As New LineSeries() -line1.HorizontalAxis = horizontalAxis -line1.VerticalAxis = verticalAxis1 -Dim line2 As New LineSeries() -line2.HorizontalAxis = horizontalAxis -line2.VerticalAxis = verticalAxis2 -line1.DataPoints.Add(New CategoricalDataPoint(26.0, DateTime.Now.AddDays(-6))) -line1.DataPoints.Add(New CategoricalDataPoint(20.0, DateTime.Now.AddDays(-5))) -line1.DataPoints.Add(New CategoricalDataPoint(12.0, DateTime.Now.AddDays(-4))) -line1.DataPoints.Add(New CategoricalDataPoint(15.0, DateTime.Now.AddDays(-2))) -line1.DataPoints.Add(New CategoricalDataPoint(21.0, DateTime.Now.AddDays(-1))) -line2.DataPoints.Add(New CategoricalDataPoint(32.0, DateTime.Now.AddDays(-6))) -line2.DataPoints.Add(New CategoricalDataPoint(52.0, DateTime.Now.AddDays(-4))) -line2.DataPoints.Add(New CategoricalDataPoint(35.0, DateTime.Now.AddDays(-3))) -line2.DataPoints.Add(New CategoricalDataPoint(36.0, DateTime.Now.AddDays(-2))) -line2.DataPoints.Add(New CategoricalDataPoint(11.0, DateTime.Now.AddDays(-1))) -Me.radChartView1.Series.Add(line1) -Me.radChartView1.Series.Add(line2) - -```` - -{{endregion}} ## Each series with own axes @@ -112,69 +51,10 @@ If you need series to have different axes but still plot them on one chart view #### Setup Four Axes -{{source=..\SamplesCS\ChartView\Axes\MultiAxes.cs region=SetupTwoSeriesFourAxes}} -{{source=..\SamplesVB\ChartView\Axes\MultiAxes.vb region=SetupTwoSeriesFourAxes}} - -````C# -CategoricalAxis horizontalAxis1 = new CategoricalAxis(); -CategoricalAxis horizontalAxis2 = new CategoricalAxis(); -horizontalAxis2.VerticalLocation = AxisVerticalLocation.Top; -LinearAxis verticalAxis1 = new LinearAxis(); -verticalAxis1.AxisType = AxisType.Second; -LinearAxis verticalAxis2 = new LinearAxis(); -verticalAxis2.AxisType = AxisType.Second; -verticalAxis2.HorizontalLocation = AxisHorizontalLocation.Right; -LineSeries line1 = new LineSeries(); -line1.HorizontalAxis = horizontalAxis1; -line1.VerticalAxis = verticalAxis1; -LineSeries line2 = new LineSeries(); -line2.HorizontalAxis = horizontalAxis2; -line2.VerticalAxis = verticalAxis2; -line1.DataPoints.Add(new CategoricalDataPoint(26d, "A")); -line1.DataPoints.Add(new CategoricalDataPoint(20d, "B")); -line1.DataPoints.Add(new CategoricalDataPoint(12d, "C")); -line1.DataPoints.Add(new CategoricalDataPoint(15d, "D")); -line1.DataPoints.Add(new CategoricalDataPoint(21d, "E")); -line2.DataPoints.Add(new CategoricalDataPoint(320d, "F")); -line2.DataPoints.Add(new CategoricalDataPoint(520d, "G")); -line2.DataPoints.Add(new CategoricalDataPoint(350d, "H")); -line2.DataPoints.Add(new CategoricalDataPoint(360d, "I")); -line2.DataPoints.Add(new CategoricalDataPoint(110d, "J")); -this.radChartView1.Series.Add(line1); -this.radChartView1.Series.Add(line2); + + -```` -````VB.NET -Dim horizontalAxis1 As New CategoricalAxis() -Dim horizontalAxis2 As New CategoricalAxis() -horizontalAxis2.VerticalLocation = AxisVerticalLocation.Top -Dim verticalAxis1 As New LinearAxis() -verticalAxis1.AxisType = AxisType.Second -Dim verticalAxis2 As New LinearAxis() -verticalAxis2.AxisType = AxisType.Second -verticalAxis2.HorizontalLocation = AxisHorizontalLocation.Right -Dim line1 As New LineSeries() -line1.HorizontalAxis = horizontalAxis1 -line1.VerticalAxis = verticalAxis1 -Dim line2 As New LineSeries() -line2.HorizontalAxis = horizontalAxis2 -line2.VerticalAxis = verticalAxis2 -line1.DataPoints.Add(New CategoricalDataPoint(26.0, "A")) -line1.DataPoints.Add(New CategoricalDataPoint(20.0, "B")) -line1.DataPoints.Add(New CategoricalDataPoint(12.0, "C")) -line1.DataPoints.Add(New CategoricalDataPoint(15.0, "D")) -line1.DataPoints.Add(New CategoricalDataPoint(21.0, "E")) -line2.DataPoints.Add(New CategoricalDataPoint(320.0, "F")) -line2.DataPoints.Add(New CategoricalDataPoint(520.0, "G")) -line2.DataPoints.Add(New CategoricalDataPoint(350.0, "H")) -line2.DataPoints.Add(New CategoricalDataPoint(360.0, "I")) -line2.DataPoints.Add(New CategoricalDataPoint(110.0, "J")) -Me.radChartView1.Series.Add(line1) -Me.radChartView1.Series.Add(line2) -```` - -{{endregion}} ## Mixed multi axes @@ -183,87 +63,10 @@ Mixing the above two modes: >caption Figure 4: Mixed Multi Axes ![WinForms RadChartView Mixed Multi Axes](images/chartview-axes-multiple-axes005.png) -{{source=..\SamplesCS\ChartView\Axes\MultiAxes.cs region=SetupMixed}} -{{source=..\SamplesVB\ChartView\Axes\MultiAxes.vb region=SetupMixed}} - -````C# -CategoricalAxis horizontalAxis1 = new CategoricalAxis(); -CategoricalAxis horizontalAxis2 = new CategoricalAxis(); -LinearAxis verticalAxis1 = new LinearAxis(); -verticalAxis1.AxisType = AxisType.Second; -LinearAxis verticalAxis2 = new LinearAxis(); -verticalAxis2.AxisType = AxisType.Second; -LinearAxis verticalAxis3 = new LinearAxis(); -verticalAxis3.AxisType = AxisType.Second; -LineSeries line1 = new LineSeries(); -line1.HorizontalAxis = horizontalAxis1; -line1.VerticalAxis = verticalAxis1; -LineSeries line2 = new LineSeries(); -line2.HorizontalAxis = horizontalAxis2; -line2.VerticalAxis = verticalAxis2; -LineSeries line3 = new LineSeries(); -line3.HorizontalAxis = horizontalAxis1; -line3.VerticalAxis = verticalAxis1; -line1.DataPoints.Add(new CategoricalDataPoint(26d, "A")); -line1.DataPoints.Add(new CategoricalDataPoint(20d, "B")); -line1.DataPoints.Add(new CategoricalDataPoint(12d, "C")); -line1.DataPoints.Add(new CategoricalDataPoint(15d, "D")); -line1.DataPoints.Add(new CategoricalDataPoint(21d, "E")); -line2.DataPoints.Add(new CategoricalDataPoint(820d, "F")); -line2.DataPoints.Add(new CategoricalDataPoint(520d, "G")); -line2.DataPoints.Add(new CategoricalDataPoint(350d, "H")); -line2.DataPoints.Add(new CategoricalDataPoint(360d, "I")); -line2.DataPoints.Add(new CategoricalDataPoint(710d, "J")); -line3.DataPoints.Add(new CategoricalDataPoint(56d, "A")); -line3.DataPoints.Add(new CategoricalDataPoint(23d, "B")); -line3.DataPoints.Add(new CategoricalDataPoint(54d, "C")); -line3.DataPoints.Add(new CategoricalDataPoint(44d, "D")); -line3.DataPoints.Add(new CategoricalDataPoint(22d, "E")); -this.radChartView1.Series.Add(line1); -this.radChartView1.Series.Add(line2); -this.radChartView1.Series.Add(line3); - -```` -````VB.NET -Dim horizontalAxis1 As New CategoricalAxis() -Dim horizontalAxis2 As New CategoricalAxis() -Dim verticalAxis1 As New LinearAxis() -verticalAxis1.AxisType = AxisType.Second -Dim verticalAxis2 As New LinearAxis() -verticalAxis2.AxisType = AxisType.Second -Dim verticalAxis3 As New LinearAxis() -verticalAxis3.AxisType = AxisType.Second -Dim line1 As New LineSeries() -line1.HorizontalAxis = horizontalAxis1 -line1.VerticalAxis = verticalAxis1 -Dim line2 As New LineSeries() -line2.HorizontalAxis = horizontalAxis2 -line2.VerticalAxis = verticalAxis2 -Dim line3 As New LineSeries() -line3.HorizontalAxis = horizontalAxis1 -line3.VerticalAxis = verticalAxis1 -line1.DataPoints.Add(New CategoricalDataPoint(26.0, "A")) -line1.DataPoints.Add(New CategoricalDataPoint(20.0, "B")) -line1.DataPoints.Add(New CategoricalDataPoint(12.0, "C")) -line1.DataPoints.Add(New CategoricalDataPoint(15.0, "D")) -line1.DataPoints.Add(New CategoricalDataPoint(21.0, "E")) -line2.DataPoints.Add(New CategoricalDataPoint(820.0, "F")) -line2.DataPoints.Add(New CategoricalDataPoint(520.0, "G")) -line2.DataPoints.Add(New CategoricalDataPoint(350.0, "H")) -line2.DataPoints.Add(New CategoricalDataPoint(360.0, "I")) -line2.DataPoints.Add(New CategoricalDataPoint(710.0, "J")) -line3.DataPoints.Add(New CategoricalDataPoint(56.0, "A")) -line3.DataPoints.Add(New CategoricalDataPoint(23.0, "B")) -line3.DataPoints.Add(New CategoricalDataPoint(54.0, "C")) -line3.DataPoints.Add(New CategoricalDataPoint(44.0, "D")) -line3.DataPoints.Add(New CategoricalDataPoint(22.0, "E")) -Me.radChartView1.Series.Add(line1) -Me.radChartView1.Series.Add(line2) -Me.radChartView1.Series.Add(line3) + + -```` -{{endregion}} # See Also diff --git a/controls/chartview/axes/plot-mode.md b/controls/chartview/axes/plot-mode.md index e68065b0b..a392b3ab7 100644 --- a/controls/chartview/axes/plot-mode.md +++ b/controls/chartview/axes/plot-mode.md @@ -23,39 +23,10 @@ The following example creates a CategoricalAxis and assigns it to a BarSeries be #### BetweenTicks PlotMode -{{source=..\SamplesCS\ChartView\Axes\PlotModeForm.cs region=axis}} -{{source=..\SamplesVB\ChartView\Axes\PlotModeForm.vb region=axis}} - -````C# -CategoricalAxis horizontalAxis = new CategoricalAxis(); -horizontalAxis.PlotMode = AxisPlotMode.BetweenTicks; -horizontalAxis.GapLength = 0.3; -BarSeries series = new BarSeries(); -series.HorizontalAxis = horizontalAxis; -series.DataPoints.Add(new CategoricalDataPoint(10, "1")); -series.DataPoints.Add(new CategoricalDataPoint(4, "2")); -series.DataPoints.Add(new CategoricalDataPoint(7, "3")); -series.DataPoints.Add(new CategoricalDataPoint(11, "4")); -series.DataPoints.Add(new CategoricalDataPoint(15, "5")); -this.radChartView1.Series.Add(series); - -```` -````VB.NET -Dim horizontalAxis As New CategoricalAxis() -horizontalAxis.PlotMode = AxisPlotMode.BetweenTicks -horizontalAxis.GapLength = 0.3 -Dim series As New BarSeries() -series.HorizontalAxis = horizontalAxis -series.DataPoints.Add(New CategoricalDataPoint(10, "1")) -series.DataPoints.Add(New CategoricalDataPoint(4, "2")) -series.DataPoints.Add(New CategoricalDataPoint(7, "3")) -series.DataPoints.Add(New CategoricalDataPoint(11, "4")) -series.DataPoints.Add(New CategoricalDataPoint(15, "5")) -Me.RadChartView1.Series.Add(series) - -```` - -{{endregion}} + + + + >caption Figure 1: BetweenTicks PlotMode ![WinForms RadChartView BetweenTicks PlotMode](images/chartview-axes-plot-mode001.png) @@ -64,21 +35,10 @@ You can always change the PlotMode property, even if the CategoricalAxis was aut #### OnTicks PlotMode -{{source=..\SamplesCS\ChartView\Axes\PlotModeForm.cs region=axis2}} -{{source=..\SamplesVB\ChartView\Axes\PlotModeForm.vb region=axis2}} - -````C# -CategoricalAxis axis = radChartView1.Axes.Get(0); -axis.PlotMode = AxisPlotMode.OnTicks; + + -```` -````VB.NET -Dim axis As CategoricalAxis = RadChartView1.Axes.[Get](Of CategoricalAxis)(0) -axis.PlotMode = AxisPlotMode.OnTicks -```` - -{{endregion}} >caption Figure 2: OnTicks PlotMode ![WinForms RadChartView OnTicks PlotMode](images/chartview-axes-plot-mode002.png) @@ -87,19 +47,10 @@ Using the aforementioned approach you can set the PlotMode property to OnTicksPa #### OnTicksPadded PlotMode -{{source=..\SamplesCS\ChartView\Axes\PlotModeForm.cs region=axis3}} -{{source=..\SamplesVB\ChartView\Axes\PlotModeForm.vb region=axis3}} - -````C# -axis.PlotMode = AxisPlotMode.OnTicksPadded; - -```` -````VB.NET -axis.PlotMode = AxisPlotMode.OnTicksPadded + + -```` -{{endregion}} >caption Figure 3: OnTicksPadded PlotMode ![WinForms RadChartView OnTicksPadded PlotMode](images/chartview-axes-plot-mode003.png) diff --git a/controls/chartview/axes/polar.md b/controls/chartview/axes/polar.md index b345a1ab3..8a540f1bf 100644 --- a/controls/chartview/axes/polar.md +++ b/controls/chartview/axes/polar.md @@ -23,53 +23,10 @@ Polar axis is created by default when you add Polar or Radar series to the Polar #### PolarAxis Setup -{{source=..\SamplesCS\ChartView\Axes\PolarAxisForm.cs region=axis}} -{{source=..\SamplesVB\ChartView\Axes\PolarAxisForm.vb region=axis}} + + -````C# -PolarAreaSeries series = new PolarAreaSeries(); -PolarDataPoint pt = new PolarDataPoint(); -pt.Angle = 30; -pt.Value = 4; -series.DataPoints.Add(pt); -pt = new PolarDataPoint(); -pt.Angle = 135; -pt.Value = 7; -series.DataPoints.Add(pt); -pt = new PolarDataPoint(); -pt.Angle = 270; -pt.Value = 9; -series.DataPoints.Add(pt); -radChartView1.AreaType = ChartAreaType.Polar; -radChartView1.Series.Add(series); -PolarAxis axis = radChartView1.Axes.Get(0); -axis.MajorStep = 4; -axis.Maximum = 12; -```` -````VB.NET -Dim series As New PolarAreaSeries() -Dim pt As New PolarDataPoint() -pt.Angle = 30 -pt.Value = 4 -series.DataPoints.Add(pt) -pt = New PolarDataPoint() -pt.Angle = 135 -pt.Value = 7 -series.DataPoints.Add(pt) -pt = New PolarDataPoint() -pt.Angle = 270 -pt.Value = 9 -series.DataPoints.Add(pt) -RadChartView1.AreaType = ChartAreaType.Polar -RadChartView1.Series.Add(series) -Dim axis As PolarAxis = RadChartView1.Axes.[Get](Of PolarAxis)(0) -axis.MajorStep = 4 -axis.Maximum = 12 - -```` - -{{endregion}} >caption Figure 1: PolarAxis Setup ![WinForms RadChartView PolarAxis Setup](images/chartview-axes-polar001.png) diff --git a/controls/chartview/axes/radial.md b/controls/chartview/axes/radial.md index 73380b709..8e8f2946a 100644 --- a/controls/chartview/axes/radial.md +++ b/controls/chartview/axes/radial.md @@ -28,38 +28,10 @@ CategoricalRadial axis is added automatically when you add RadarPoint, RadarLine #### CategoricalRadialAxis Setup -{{source=..\SamplesCS\ChartView\Axes\RadialAxisForm.cs region=radialCategoricalAxis}} -{{source=..\SamplesVB\ChartView\Axes\RadialAxisForm.vb region=radialCategoricalAxis}} - -````C# -RadarAreaSeries areaSeries = new RadarAreaSeries(); -areaSeries.DataPoints.Add(new CategoricalDataPoint(4, "Bread")); -areaSeries.DataPoints.Add(new CategoricalDataPoint(7, "Fruit")); -areaSeries.DataPoints.Add(new CategoricalDataPoint(7, "Meat")); -radChartView1.AreaType = ChartAreaType.Polar; -radChartView1.Series.Add(areaSeries); -CategoricalRadialAxis categoricalAxis = areaSeries.RadialAxis as CategoricalRadialAxis; -if (categoricalAxis != null) -{ - categoricalAxis.BorderColor = Color.DarkGray; -} - -```` -````VB.NET -Dim areaSeries As New RadarAreaSeries() -areaSeries.DataPoints.Add(New CategoricalDataPoint(4, "Bread")) -areaSeries.DataPoints.Add(New CategoricalDataPoint(7, "Fruit")) -areaSeries.DataPoints.Add(New CategoricalDataPoint(7, "Meat")) -RadChartView1.AreaType = ChartAreaType.Polar -RadChartView1.Series.Add(areaSeries) -Dim categoricalAxis As CategoricalRadialAxis = TryCast(areaSeries.RadialAxis, CategoricalRadialAxis) -If categoricalAxis IsNot Nothing Then - categoricalAxis.BorderColor = Color.DarkGray -End If - -```` - -{{endregion}} + + + + >caption Figure 1: CategoricalRadialAxis Setup ![WinForms RadChartView CategoricalRadialAxis Setup](images/chartview-axes-radial001.png) @@ -80,59 +52,10 @@ NumericRadial axis is added automatically when you add __PolarPoint__, __PolarLi #### NumericRadialAxis Setup -{{source=..\SamplesCS\ChartView\Axes\RadialAxisForm.cs region=radialNumericalAxis}} -{{source=..\SamplesVB\ChartView\Axes\RadialAxisForm.vb region=radialNumericalAxis}} - -````C# -PolarAreaSeries series = new PolarAreaSeries(); -PolarDataPoint pt = new PolarDataPoint(); -pt.Angle = 30; -pt.Value = 4; -series.DataPoints.Add(pt); - -pt = new PolarDataPoint(); -pt.Angle = 135; -pt.Value = 7; -series.DataPoints.Add(pt); -pt = new PolarDataPoint(); -pt.Angle = 270; -pt.Value = 9; -series.DataPoints.Add(pt); -radChartView1.AreaType = ChartAreaType.Polar; -radChartView1.Series.Add(series); -NumericRadialAxis numericalAxis = series.RadialAxis as NumericRadialAxis; -if (numericalAxis != null) -{ - numericalAxis.BorderColor = Color.DarkGray; - numericalAxis.MajorStep = 45; -} - -```` -````VB.NET -Dim series As New PolarAreaSeries() -Dim pt As New PolarDataPoint() -pt.Angle = 30 -pt.Value = 4 -series.DataPoints.Add(pt) -pt = New PolarDataPoint() -pt.Angle = 135 -pt.Value = 7 -series.DataPoints.Add(pt) -pt = New PolarDataPoint() -pt.Angle = 270 -pt.Value = 9 -series.DataPoints.Add(pt) -RadChartView1.AreaType = ChartAreaType.Polar -RadChartView1.Series.Add(series) -Dim numericalAxis As NumericRadialAxis = TryCast(series.RadialAxis, NumericRadialAxis) -If numericalAxis IsNot Nothing Then - numericalAxis.BorderColor = Color.DarkGray - numericalAxis.MajorStep = 45 -End If - -```` - -{{endregion}} + + + + >caption Figure 1: NumericRadialAxis Setup ![WinForms RadChartView NumericRadialAxis Setup](images/chartview-axes-radial002.png) diff --git a/controls/chartview/axes/scale-breaks.md b/controls/chartview/axes/scale-breaks.md index c80beac63..dae23a519 100644 --- a/controls/chartview/axes/scale-breaks.md +++ b/controls/chartview/axes/scale-breaks.md @@ -20,39 +20,10 @@ To add a scale break you show use the __ScaleBreaks__ collection of the axis. Fi #### ScaleBreak Initial Setup -{{source=..\SamplesCS\ChartView\Axes\ScaleBreaksCode.cs region=Break1}} -{{source=..\SamplesVB\ChartView\Axes\ScaleBreaksCode.vb region=Break1}} - -````C# -LinearAxis verticalAxis = radChartView1.Axes.Get(1); -AxisScaleBreak scaleBreakItem = new AxisScaleBreak(); -scaleBreakItem.Name = "Item1"; -scaleBreakItem.From = 200d; -scaleBreakItem.To = 900d; -verticalAxis.ScaleBreaks.Add(scaleBreakItem); -AxisScaleBreak scaleBreakItem1 = new AxisScaleBreak(); -scaleBreakItem.Name = "Item2"; -scaleBreakItem1.From = 2100d; -scaleBreakItem1.To = 4900; -verticalAxis.ScaleBreaks.Add(scaleBreakItem1); - -```` -````VB.NET -Dim verticalAxis As LinearAxis = radChartView1.Axes.Get(Of LinearAxis)(1) -Dim scaleBreakItem As New AxisScaleBreak() -scaleBreakItem.Name = "Item1" -scaleBreakItem.From = 200.0R -scaleBreakItem.To = 900.0R -verticalAxis.ScaleBreaks.Add(scaleBreakItem) -Dim scaleBreakItem1 As New AxisScaleBreak() -scaleBreakItem.Name = "Item2" -scaleBreakItem1.From = 2100.0R -scaleBreakItem1.To = 4900 -verticalAxis.ScaleBreaks.Add(scaleBreakItem1) - -```` - -{{endregion}} + + + + >caption Figure 1: ScaleBreak ![WinForms RadChartView ScaleBreak](images/chartview-axes-scale-breaks001.png) @@ -79,27 +50,10 @@ The following example shows how you can set the scale breaks settings: #### ScaleBreaks Settings -{{source=..\SamplesCS\ChartView\Axes\ScaleBreaksCode.cs region=Settings}} -{{source=..\SamplesVB\ChartView\Axes\ScaleBreaksCode.vb region=Settings}} - -````C# -LinearAxis verticalAxis = radChartView1.Axes.Get(1); -verticalAxis.ScaleBreakStyle = ScaleBreakStyle.Waved; -verticalAxis.ScaleBreakBackColor = Color.Silver; -verticalAxis.ScaleBreakBorderColor = Color.Red; -verticalAxis.ScaleBreakSize = 10; - -```` -````VB.NET -Dim verticalAxis As LinearAxis = radChartView1.Axes.Get(Of LinearAxis)(1) -verticalAxis.ScaleBreakStyle = ScaleBreakStyle.Waved -verticalAxis.ScaleBreakBackColor = Color.Silver -verticalAxis.ScaleBreakBorderColor = Color.Red -verticalAxis.ScaleBreakSize = 10 + + -```` -{{endregion}} >caption Figure 2: ScaleBreaks Settings ![WinForms RadChartView ScaleBreaks Settings](images/chartview-axes-scale-breaks002.png) diff --git a/controls/chartview/context-menu/modifying-the-default-context-menu.md b/controls/chartview/context-menu/modifying-the-default-context-menu.md index e7ea9970b..5b86c4a1e 100644 --- a/controls/chartview/context-menu/modifying-the-default-context-menu.md +++ b/controls/chartview/context-menu/modifying-the-default-context-menu.md @@ -21,61 +21,17 @@ In order to add custom menu items to the default context menu, you should create #### Subscribe to Event -{{source=..\SamplesCS\ChartView\ContextMenu\RadChartViewContextMenuForm.cs region=SubscribeToEvent}} -{{source=..\SamplesVB\ChartView\ContextMenu\RadChartViewContextMenuForm.vb region=SubscribeToEvent}} -````C# -this.radChartView1.ContextMenuOpening += radChartView1_ContextMenuOpening; + + -```` -````VB.NET -AddHandler RadChartView1.ContextMenuOpening, AddressOf RadChartView1_ContextMenuOpening -```` - - - -{{endregion}} #### Handle Event -{{source=..\SamplesCS\ChartView\ContextMenu\RadChartViewContextMenuForm.cs region=HandleEvent}} -{{source=..\SamplesVB\ChartView\ContextMenu\RadChartViewContextMenuForm.vb region=HandleEvent}} -````C# -private void radChartView1_ContextMenuOpening(object sender, ChartViewContextMenuOpeningEventArgs e) -{ - RadMenuItem customMenuItem = new RadMenuItem(); - customMenuItem.Text = "Export Chart"; - customMenuItem.Click += customMenuItem_Click; - RadMenuSeparatorItem separator = new RadMenuSeparatorItem(); - e.ContextMenu.Items.Add(separator); - e.ContextMenu.Items.Add(customMenuItem); -} -private void customMenuItem_Click(object sender, EventArgs e) -{ - string filePath = @"..\..\..\exportedChart.png"; - this.radChartView1.ExportToImage(filePath, this.radChartView1.Size, System.Drawing.Imaging.ImageFormat.Png); -} - -```` -````VB.NET -Private Sub RadChartView1_ContextMenuOpening(sender As Object, e As ChartViewContextMenuOpeningEventArgs) - Dim customMenuItem As New RadMenuItem() - customMenuItem.Text = "Export Chart" - AddHandler customMenuItem.Click, AddressOf CustomMenuItem_Click - Dim separator As New RadMenuSeparatorItem() - e.ContextMenu.Items.Add(separator) - e.ContextMenu.Items.Add(customMenuItem) -End Sub -Private Sub CustomMenuItem_Click(sender As Object, e As EventArgs) - Dim filePath As String = "..\..\..\exportedChart.png" - Me.RadChartView1.ExportToImage(filePath, Me.RadChartView1.Size, System.Drawing.Imaging.ImageFormat.Png) -End Sub - -```` - + + -{{endregion}} # See Also diff --git a/controls/chartview/customization/custom-labels-text.md b/controls/chartview/customization/custom-labels-text.md index 15d37849d..86c4bc040 100644 --- a/controls/chartview/customization/custom-labels-text.md +++ b/controls/chartview/customization/custom-labels-text.md @@ -17,81 +17,19 @@ __RadChartView__ allows you to easily change the axes labels text by using a cus #### Label Format -{{source=..\SamplesCS\ChartView\Customization\CustomLabels.cs region=FormatProvider}} -{{source=..\SamplesVB\ChartView\Customization\CustomLabels.vb region=FormatProvider}} - -````C# -public class MyFormatProvider : IFormatProvider, ICustomFormatter -{ - public object GetFormat(Type formatType) - { - return this; - } - public string Format(string format, object arg, IFormatProvider formatProvider) - { - string s = arg.ToString(); - switch (s) - { - case "0": - return "0 seconds"; - case "30": - return "1/2 min"; - case "60": - return "1 min"; - case "90": - return "90 seconds"; - } - return null; - } -} - -```` -````VB.NET -Class MyFormatProvider - Implements IFormatProvider - Implements ICustomFormatter - Public Function GetFormat(formatType As Type) As Object Implements IFormatProvider.GetFormat - Return Me - End Function - Public Function Format(format__1 As String, arg As Object, formatProvider As IFormatProvider) As String Implements ICustomFormatter.Format - Dim s As String = arg.ToString() - Select Case s - Case "0" - Return "0 seconds" - Case "30" - Return "1/2 min" - Case "60" - Return "1 min" - Case "90" - Return "90 seconds" - End Select - Return Nothing - End Function -End Class - -```` - -{{endregion}} + + -Then you can just change the horizontal axis __LabelFormatProvider__ by using the corresponding property. -#### Assign Format Provider -{{source=..\SamplesCS\ChartView\Customization\CustomLabels.cs region=propertyChange}} -{{source=..\SamplesVB\ChartView\Customization\CustomLabels.vb region=propertyChange}} +Then you can just change the horizontal axis __LabelFormatProvider__ by using the corresponding property. -````C# -LinearAxis horizontalAxis = radChartView1.Axes.Get(0); -horizontalAxis.LabelFormatProvider = new MyFormatProvider(); +#### Assign Format Provider -```` -````VB.NET -Dim horizontalAxis As LinearAxis = RadChartView1.Axes.[Get](Of LinearAxis)(0) -horizontalAxis.LabelFormatProvider = New MyFormatProvider() + + -```` -{{endregion}} >caption Figure 1: Format Provider ![WinForms RadChartView Format Provider](images/chartview-customization-custom-labels001.png) @@ -100,71 +38,19 @@ horizontalAxis.LabelFormatProvider = New MyFormatProvider() #### DateTime Format Provider -{{source=..\SamplesCS\ChartView\Customization\CustomLabels.cs region=FormatProvider2}} -{{source=..\SamplesVB\ChartView\Customization\CustomLabels.vb region=FormatProvider2}} - -````C# -public class DateTimeFormatProvider : IFormatProvider, ICustomFormatter -{ - public object GetFormat(Type formatType) - { - return this; - } - public string Format(string format, object arg, IFormatProvider formatProvider) - { - DateTime val = (DateTime)arg; - if (val.Hour == 0) - { - return val.ToShortDateString(); - } - else - { - return val.ToString("H\\h"); - } - } -} - -```` -````VB.NET -Class DateTimeFormatProvider - Implements IFormatProvider - Implements ICustomFormatter - Public Function GetFormat(formatType As Type) As Object Implements IFormatProvider.GetFormat - Return Me - End Function - Public Function Format(format__1 As String, arg As Object, formatProvider As IFormatProvider) As String Implements ICustomFormatter.Format - Dim val As DateTime = DirectCast(arg, DateTime) - If val.Hour = 0 Then - Return val.ToShortDateString() - Else - Return val.ToString("H\h") - End If - End Function -End Class - -```` - -{{endregion}} + + + + Again you can just change the horizontal axis __LabelFormatProvider__ by using the corresponding property. #### Assign DateTime Format Provider -{{source=..\SamplesCS\ChartView\Customization\CustomLabels.cs region=PropertyChange2}} -{{source=..\SamplesVB\ChartView\Customization\CustomLabels.vb region=PropertyChange2}} - -````C# -DateTimeContinuousAxis dateTimeAxis = new DateTimeContinuousAxis(); -dateTimeAxis.LabelFormatProvider = new DateTimeFormatProvider(); - -```` -````VB.NET -Dim dateTimeAxis As New DateTimeContinuousAxis() -dateTimeAxis.LabelFormatProvider = New DateTimeFormatProvider() + + -```` -{{endregion}} >caption Figure 2: DateTime Format Provider ![WinForms RadChartView DateTime Format Provider](images/chartview-customization-custom-labels002.png) diff --git a/controls/chartview/customization/custom-rendering.md b/controls/chartview/customization/custom-rendering.md index 8a0fc6abb..42eb8e509 100644 --- a/controls/chartview/customization/custom-rendering.md +++ b/controls/chartview/customization/custom-rendering.md @@ -41,387 +41,37 @@ the series to appropriate values. Further, subscribe to the __CreateRenderer__ o #### Add Points and Create A Custom Renderer -{{source=..\SamplesCS\ChartView\Customization\CustomRenderer.cs region=CustomRendererRegion}} -{{source=..\SamplesVB\ChartView\Customization\CustomRenderer.vb region=CustomRendererRegion}} - -````C# -public partial class CustomRenderer : Form -{ - public CustomRenderer() - { - InitializeComponent(); - this.radChartView1.CreateRenderer += new ChartViewCreateRendererEventHandler(radChartView1_CreateRenderer); - } - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - LineSeries series = new LineSeries(); - Random rnd = new Random(); - for (int i = 0; i < 30; i++) - { - series.DataPoints.Add(new CategoricalDataPoint(rnd.Next(0, 30), DateTime.Now.AddDays(i))); - } - this.radChartView1.Series.Add(series); - series.VerticalAxis.LabelFormat = "{0}°"; - series.HorizontalAxis.LabelFormat = "{0:M}"; - series.HorizontalAxis.LabelFitMode = AxisLabelFitMode.MultiLine; - this.radChartView1.ShowGrid = true; - } - void radChartView1_CreateRenderer(object sender, ChartViewCreateRendererEventArgs e) - { - e.Renderer = new CustomCartesianRenderer(e.Area as CartesianArea); - } -} - -```` -````VB.NET -Public Class CustomRenderer - Protected Overrides Sub OnLoad(e As System.EventArgs) - MyBase.OnLoad(e) - AddHandler RadChartView1.CreateRenderer, AddressOf RadChartView1_CreateRenderer - Dim series As New LineSeries() - Dim rnd As New Random() - For i = 0 To 30 - series.DataPoints.Add(New CategoricalDataPoint(rnd.Next(0, 40), DateTime.Now.AddDays(i))) - Next - Me.RadChartView1.Series.Add(series) - series.VerticalAxis.LabelFormat = "{0}°" - series.HorizontalAxis.LabelFormat = "{0:M}" - series.HorizontalAxis.LabelFitMode = AxisLabelFitMode.MultiLine - Me.RadChartView1.ShowGrid = True - End Sub - Private Sub RadChartView1_CreateRenderer(sender As System.Object, e As Telerik.WinControls.UI.ChartViewCreateRendererEventArgs) - e.Renderer = New CustomCartesianRenderer(DirectCast(e.Area, CartesianArea)) - End Sub -End Class - -```` - -{{endregion}} + + + + Now you need to create a CustomCartesianRenderer class that inherits __CartesianRenderer__ and overrides the __Initialize__ method. This method creates and arranges draw parts responsible for the rendering of each __RadChartView__ segment. After calling the base method, the __DrawParts__ collection contains objects that know how to draw axes, labels, series etc. The particular draw part you would like to replace is of type __LineSeriesDrawPart__. Your code should be like the following: #### Custom Renderer Class -{{source=..\SamplesCS\ChartView\Customization\CustomRenderer.cs region=CustomCartesianRendererRegion}} -{{source=..\SamplesVB\ChartView\Customization\CustomRenderer.vb region=CustomCartesianRendererRegion}} - -````C# -public class CustomCartesianRenderer : CartesianRenderer -{ - public CustomCartesianRenderer(CartesianArea area) - : base(area) - { } - protected override void Initialize() - { - base.Initialize(); - for (int i = 0; i < this.DrawParts.Count; i++) - { - LineSeriesDrawPart linePart = this.DrawParts[i] as LineSeriesDrawPart; - if (linePart != null) - { - this.DrawParts[i] = new CustomLineSeriesDrawPart((LineSeries)linePart.Element, this); - } - } - } -} - -```` -````VB.NET -Public Class CustomCartesianRenderer - Inherits CartesianRenderer - Public Sub New(area As CartesianArea) - MyBase.New(area) - End Sub - Protected Overrides Sub Initialize() - MyBase.Initialize() - For i As Integer = 0 To Me.DrawParts.Count - 1 - Dim linePart As LineSeriesDrawPart = TryCast(Me.DrawParts(i), LineSeriesDrawPart) - If linePart IsNot Nothing Then - Me.DrawParts(i) = New CustomLineSeriesDrawPart(DirectCast(linePart.Element, LineSeries), Me) - End If - Next - End Sub -End Class - -```` - -{{endregion}} + + + + Let us further focus on the __CustomLineSeriesDrawPart__ implementation. To introduce custom rendering of the line you need to override the __DrawLine__ method and use the GraphicsPath object provided by the __GetLinePath__ method. In order to draw a path with gradient colors, you need to use a LinearGradientBrush and use its ColorBlend to set appropriate positions and colors. So, before we get to the CustomLineSeriesDrawPart class, let us create a class that will let us easily store Color-Position couples: #### Color Storage -{{source=..\SamplesCS\ChartView\Customization\CustomRenderer.cs region=ColorPositionBlendRegion}} -{{source=..\SamplesVB\ChartView\Customization\CustomRenderer.vb region=ColorPositionBlendRegion}} - -````C# -public class ColorPositionBlend -{ - private List positions; - private List colors; - public ColorPositionBlend() - { - positions = new List(); - colors = new List(); - } - public void Add(Color color, float position) - { - this.colors.Add(color); - this.positions.Add(position); - } - public void Add(ColorPositionBlend colorPositionBlend) - { - this.positions.AddRange(colorPositionBlend.positions); - this.colors.AddRange(colorPositionBlend.colors); - } - public float[] Positions - { - get { return this.positions.ToArray(); } - } - public Color[] Colors - { - get { return this.colors.ToArray(); } - } -} - -```` -````VB.NET -Public Class ColorPositionBlend - Private m_positions As List(Of Single) - Private m_colors As List(Of Color) - Public Sub New() - m_positions = New List(Of Single)() - m_colors = New List(Of Color)() - End Sub - Public Sub Add(color As Color, position As Single) - Me.m_colors.Add(color) - Me.m_positions.Add(position) - End Sub - Public Sub Add(colorPositionBlend As ColorPositionBlend) - Me.m_positions.AddRange(colorPositionBlend.Positions) - Me.m_colors.AddRange(colorPositionBlend.Colors) - End Sub - Public ReadOnly Property Positions() As Single() - Get - Return Me.m_positions.ToArray() - End Get - End Property - Public ReadOnly Property Colors() As Color() - Get - Return Me.m_colors.ToArray() - End Get - End Property -End Class - -```` - -{{endregion}} + + + + Getting back to the CustomLineSeriesDrawPart, you need to create a method which calculates the positions and colors that need to be assigned to the ColorBlend of the brush. Additionally, you have to calculate the color of the points that fall between two predefined values, e.g. if the input value is 16, the color should be one fifth orange and four fifths red. Further, you have to make sure that the line segments between each two consecutive points are colored properly, regardless of points’ values. For example, if a point with value 0 is followed by a point with value 30, you need to ensure that the line that connects them does not go from green to dark red directly, but contains also orange and red when it crosses 15 and 20, respectively. Here is one possible implementation of the above scenario: #### DrawLine Method Implementation -{{source=..\SamplesCS\ChartView\Customization\CustomRenderer.cs region=CustomLineSeriesDrawPartRegion}} -{{source=..\SamplesVB\ChartView\Customization\CustomRenderer.vb region=CustomLineSeriesDrawPartRegion}} - -````C# -public class CustomLineSeriesDrawPart : LineSeriesDrawPart -{ - float[] predefinedValues = new float[] { 10, 15, 20, 25 }; - Color[] predefinedColors = new Color[] { Color.Green, Color.Orange, Color.Red, Color.DarkRed }; - - public CustomLineSeriesDrawPart(LineSeriesBase series, IChartRenderer renderer) - : base(series, renderer) - { } - protected override void DrawLine() - { - LineSeries series = this.Element as LineSeries; - if (series.DataPoints.Count < 2) - { - return; - } - RectangleF rect = this.Element.Bounds; - rect.Offset(this.OffsetX, this.OffsetY); - if (rect.IsEmpty) - { - return; - } - GraphicsPath path = GetLinePath(); - LinearGradientBrush linearBrush = new LinearGradientBrush(rect, Color.Transparent, Color.Transparent, 0f); - ColorPositionBlend colorPositionBlend = GetColorPositionBlend(series.DataPoints); - System.Drawing.Drawing2D.ColorBlend blend = new System.Drawing.Drawing2D.ColorBlend(); - blend.Positions = colorPositionBlend.Positions; - blend.Colors = colorPositionBlend.Colors; - linearBrush.InterpolationColors = blend; - Graphics graphics = this.Renderer.Surface as Graphics; - graphics.SmoothingMode = SmoothingMode.AntiAlias; - graphics.DrawPath(new Pen(linearBrush, 3), path); - } - private ColorPositionBlend GetColorPositionBlend(ChartDataPointCollection dataPoints) - { - ColorPositionBlend blend = new ColorPositionBlend(); - decimal majorStep = 1m / (dataPoints.Count - 1); - for (int i = 0; i < dataPoints.Count; i++) - { - float position = (float)(i * majorStep); - Color color = GetValueColor((double)((CategoricalDataPoint)dataPoints[i]).Value); - blend.Add(color, position); - if (i < dataPoints.Count - 1) - { - double currentValue = (double)((CategoricalDataPoint)dataPoints[i]).Value; - double nextValue = (double)((CategoricalDataPoint)dataPoints[i + 1]).Value; - ColorPositionBlend additionalBlends = GetAdditionalColorPositionBlend(currentValue, nextValue, majorStep, i); - blend.Add(additionalBlends); - } - } - return blend; - } - private ColorPositionBlend GetAdditionalColorPositionBlend(double currentValue, double nextValue, decimal majorStep, int iteration) - { - ColorPositionBlend blend = new ColorPositionBlend(); - if (currentValue < nextValue) - { - for (int j = 0; j < predefinedValues.Length; j++) - { - float colorValue = predefinedValues[j]; - if (currentValue < colorValue && colorValue < nextValue) - { - float additionalPosition = (float)(iteration * majorStep) + (float)((colorValue - currentValue) / (nextValue - currentValue)) * (float)(majorStep); - Color additionalColor = GetValueColor(colorValue); - blend.Add(additionalColor, additionalPosition); - } - } - } - if (currentValue > nextValue) - { - for (int j = predefinedValues.Length - 1; j >= 0; j--) - { - float colorValue = predefinedValues[j]; - if (currentValue > colorValue && colorValue > nextValue) - { - float additionalPosition = (float)(iteration * majorStep) + (float)((currentValue - colorValue) / (currentValue - nextValue)) * (float)(majorStep); - Color additionalColor = GetValueColor(colorValue); - blend.Add(additionalColor, additionalPosition); - } - } - } - return blend; - } - private Color GetValueColor(double value) - { - if (value <= predefinedValues[0]) - { - return predefinedColors[0]; - } - if (value >= predefinedValues[predefinedValues.Length - 1]) - { - return predefinedColors[predefinedValues.Length - 1]; - } - for (int i = 0; i < predefinedValues.Length - 1; i++) - { - if (predefinedValues[i] <= value && value <= predefinedValues[i + 1]) - { - double c = (predefinedValues[i + 1] - value) / (predefinedValues[i + 1] - predefinedValues[i]); - return Color.FromArgb((int)(predefinedColors[i].R * c + predefinedColors[i + 1].R * (1 - c)), - (int)(predefinedColors[i].G * c + predefinedColors[i + 1].G * (1 - c)), - (int)(predefinedColors[i].B * c + predefinedColors[i + 1].B * (1 - c))); - } - } - return Color.Transparent; - } -} - -```` -````VB.NET -Public Class CustomLineSeriesDrawPart - Inherits LineSeriesDrawPart - Public Sub New(series As LineSeriesBase, renderer As IChartRenderer) - MyBase.New(series, renderer) - End Sub - Private predefinedValues As Integer() = New Integer() {5, 16, 25, 35} - Private predefinedColors As Color() = New Color() {Color.Green, Color.Orange, Color.Red, Color.DarkRed} - Protected Overrides Sub DrawLine() - Dim series As LineSeries = TryCast(Me.Element, LineSeries) - If series.DataPoints.Count < 2 Then - Return - End If - Dim rect As RectangleF = Me.Element.Bounds - rect.Offset(Me.OffsetX, Me.OffsetY) - If rect.IsEmpty Then - Return - End If - Dim path As GraphicsPath = GetLinePath() - Dim linearBrush As New LinearGradientBrush(rect, Color.Transparent, Color.Transparent, 0.0F) - Dim colorPositionBlend As ColorPositionBlend = GetColorPositionBlend(series.DataPoints) - Dim blend As New System.Drawing.Drawing2D.ColorBlend() - blend.Positions = colorPositionBlend.Positions - blend.Colors = colorPositionBlend.Colors - linearBrush.InterpolationColors = blend - Dim graphics As Graphics = TryCast(Me.Renderer.Surface, Graphics) - graphics.SmoothingMode = SmoothingMode.AntiAlias - graphics.DrawPath(New Pen(linearBrush, 3), path) - End Sub - Private Function GetColorPositionBlend(dataPoints As ChartDataPointCollection) As ColorPositionBlend - Dim blend As New ColorPositionBlend() - Dim majorStep As Decimal = 1D / (dataPoints.Count - 1) - For i As Integer = 0 To dataPoints.Count - 1 - Dim position As Single = CSng(i * majorStep) - Dim color As Color = GetValueColor(CDbl(DirectCast(dataPoints(i), Telerik.Charting.CategoricalDataPoint).Value)) - blend.Add(color, position) - If i < dataPoints.Count - 1 Then - Dim currentValue As Double = CDbl(DirectCast(dataPoints(i), Telerik.Charting.CategoricalDataPoint).Value) - Dim nextValue As Double = CDbl(DirectCast(dataPoints(i + 1), Telerik.Charting.CategoricalDataPoint).Value) - Dim additionalBlends As ColorPositionBlend = GetAdditionalColorPositionBlend(currentValue, nextValue, majorStep, i) - blend.Add(additionalBlends) - End If - Next - Return blend - End Function - Private Function GetAdditionalColorPositionBlend(currentValue As Double, nextValue As Double, majorStep As Decimal, iteration As Integer) As ColorPositionBlend - Dim blend As New ColorPositionBlend() - If currentValue < nextValue Then - For j As Integer = 0 To predefinedValues.Length - 1 - Dim colorValue As Single = predefinedValues(j) - If currentValue < colorValue AndAlso colorValue < nextValue Then - Dim additionalPosition As Single = CSng(iteration * majorStep) + CSng((colorValue - currentValue) / (nextValue - currentValue)) * CSng(majorStep) - Dim additionalColor As Color = GetValueColor(colorValue) - blend.Add(additionalColor, additionalPosition) - End If - Next - End If - If currentValue > nextValue Then - For j As Integer = predefinedValues.Length - 1 To 0 Step -1 - Dim colorValue As Single = predefinedValues(j) - If currentValue > colorValue AndAlso colorValue > nextValue Then - Dim additionalPosition As Single = CSng(iteration * majorStep) + CSng((currentValue - colorValue) / (currentValue - nextValue)) * CSng(majorStep) - Dim additionalColor As Color = GetValueColor(colorValue) - blend.Add(additionalColor, additionalPosition) - End If - Next - End If - Return blend - End Function - Private Function GetValueColor(value As Double) As Color - If value <= predefinedValues(0) Then - Return predefinedColors(0) - End If - If value >= predefinedValues(predefinedValues.Length - 1) Then - Return predefinedColors(predefinedValues.Length - 1) - End If - For i As Integer = 0 To predefinedValues.Length - 2 - If predefinedValues(i) <= value AndAlso value <= predefinedValues(i + 1) Then - Dim c As Double = (predefinedValues(i + 1) - value) / (predefinedValues(i + 1) - predefinedValues(i)) - Return Color.FromArgb(CInt(predefinedColors(i).R * c + predefinedColors(i + 1).R * (1 - c)), CInt(predefinedColors(i).G * c + predefinedColors(i + 1).G * (1 - c)), CInt(predefinedColors(i).B * c + predefinedColors(i + 1).B * (1 - c))) - End If - Next - Return Color.Transparent - End Function -End Class - -```` - -{{endregion}} + + + + After you compile the project, you should get a result similar to the screenshot below: diff --git a/controls/chartview/customization/formatting-series-labels.md b/controls/chartview/customization/formatting-series-labels.md index ef66b66d1..77cb35038 100644 --- a/controls/chartview/customization/formatting-series-labels.md +++ b/controls/chartview/customization/formatting-series-labels.md @@ -20,62 +20,20 @@ This article demonstrates how to change the labels styles and text. The series l #### Show Labels -{{source=..\SamplesCS\ChartView\Customization\FormattingSeriesAndTrackballLabels.cs region=ShowLabels}} -{{source=..\SamplesVB\ChartView\Customization\FormattingSeriesAndTrackballLabels.vb region=ShowLabels}} + + -````C# -foreach (var series in radChartView1.Series) -{ - series.ShowLabels = true; -} - -```` -````VB.NET -For Each series In RadChartView1.Series - series.ShowLabels = True -Next - -```` - -{{endregion}} + 2\. Now you can change the labels styles and text. #### LabelFormatting Event -{{source=..\SamplesCS\ChartView\Customization\FormattingSeriesAndTrackballLabels.cs region=LabelFormatting}} -{{source=..\SamplesVB\ChartView\Customization\FormattingSeriesAndTrackballLabels.vb region=LabelFormatting}} - -````C# -private Font font1 = new Font("Segoe Script", 12, FontStyle.Regular); -private void radChartView1_LabelFormatting(object sender, ChartViewLabelFormattingEventArgs e) -{ - e.LabelElement.BackColor = ColorTranslator.FromHtml("#005BBc"); - e.LabelElement.ForeColor = ColorTranslator.FromHtml("#91c930"); - e.LabelElement.BorderColor = ColorTranslator.FromHtml("#ee8310"); - e.LabelElement.Font = font1; - CategoricalPointElement element = (CategoricalPointElement)e.LabelElement.Parent; - CategoricalDataPoint dataPoint = (CategoricalDataPoint)element.DataPoint; - e.LabelElement.Text = string.Format("Category: {0}, Value: {1}", dataPoint.Category, dataPoint.Value); -} - -```` -````VB.NET -Private font1 As New Font("Segoe Script", 12, FontStyle.Regular) -Private Sub radChartView1_LabelFormatting(sender As Object, e As ChartViewLabelFormattingEventArgs) - e.LabelElement.BackColor = ColorTranslator.FromHtml("#005BBc") - e.LabelElement.ForeColor = ColorTranslator.FromHtml("#91c930") - e.LabelElement.BorderColor = ColorTranslator.FromHtml("#ee8310") - e.LabelElement.Font = font1 - Dim element As CategoricalPointElement = DirectCast(e.LabelElement.Parent, CategoricalPointElement) - Dim dataPoint As CategoricalDataPoint = DirectCast(element.DataPoint, CategoricalDataPoint) - e.LabelElement.Text = String.Format("Category: {0}, " & vbLf & "Value: {1}", dataPoint.Category, dataPoint.Value) -End Sub - -```` - -{{endregion}} + + + + >note Since **R2 2017 SP1** you can control the label's text alignment by the newly introduced property ChartViewLabelFormattingEventArgs.LabelElement.**TextAlignment**. diff --git a/controls/chartview/customization/formatting-trackball-labels.md b/controls/chartview/customization/formatting-trackball-labels.md index 5effa056c..21abcd3e0 100644 --- a/controls/chartview/customization/formatting-trackball-labels.md +++ b/controls/chartview/customization/formatting-trackball-labels.md @@ -20,62 +20,19 @@ This article demonstrates how to customize the trackball labels text and styles. #### Add Controller -{{source=..\SamplesCS\ChartView\Customization\FormattingSeriesAndTrackballLabels.cs region=Trackball}} -{{source=..\SamplesVB\ChartView\Customization\FormattingSeriesAndTrackballLabels.vb region=Trackball}} + + -````C# -ChartTrackballController controler = new ChartTrackballController(); -controler.TextNeeded += controler_TextNeeded; -radChartView1.Controllers.Add(controler); - -```` -````VB.NET -Dim controler As New ChartTrackballController() -AddHandler controler.TextNeeded, AddressOf controler_TextNeeded -RadChartView1.Controllers.Add(controler) - -```` - -{{endregion}} + 2\. Now, you can use the __TextNeeded__ and change any properties you desire. #### Handle TextNeeded -{{source=..\SamplesCS\ChartView\Customization\FormattingSeriesAndTrackballLabels.cs region=TextNeeded}} -{{source=..\SamplesVB\ChartView\Customization\FormattingSeriesAndTrackballLabels.vb region=TextNeeded}} - -````C# -private Font font = new Font("Segoe Script", 12, FontStyle.Regular); -private void controler_TextNeeded(object sender, TextNeededEventArgs e) -{ - e.Element.BackColor = ColorTranslator.FromHtml("#91c930"); - e.Element.ForeColor = ColorTranslator.FromHtml("#bb2525"); - e.Element.BorderColor = ColorTranslator.FromHtml("#00Bde7"); - e.Element.Font = font; - e.Element.NumberOfColors = 1; - e.Element.BorderGradientStyle = Telerik.WinControls.GradientStyles.Solid; - CategoricalDataPoint dataPoint = e.Points[0].DataPoint as CategoricalDataPoint; - e.Text = string.Format("Category: {0}, Value: {1}", dataPoint.Category, dataPoint.Value); -} - -```` -````VB.NET -Private font As New Font("Segoe Script", 12, FontStyle.Regular) -Private Sub controler_TextNeeded(sender As Object, e As TextNeededEventArgs) - e.Element.BackColor = ColorTranslator.FromHtml("#91c930") - e.Element.ForeColor = ColorTranslator.FromHtml("#bb2525") - e.Element.BorderColor = ColorTranslator.FromHtml("#00Bde7") - e.Element.Font = font - e.Element.NumberOfColors = 1 - e.Element.BorderGradientStyle = Telerik.WinControls.GradientStyles.Solid - Dim dataPoint As CategoricalDataPoint = TryCast(e.Points(0).DataPoint, CategoricalDataPoint) - e.Text = String.Format("Category: {0}, Value: {1}", dataPoint.Category, dataPoint.Value) -End Sub - -```` + + -{{endregion}} + >important The code for getting the current data point can depend on the used series type. For example if you use scatter chart, you should use __ScatterDataPoint__ type. > diff --git a/controls/chartview/customization/palettes.md b/controls/chartview/customization/palettes.md index 70b89e028..4fa0fe2ca 100644 --- a/controls/chartview/customization/palettes.md +++ b/controls/chartview/customization/palettes.md @@ -33,19 +33,11 @@ To apply one of these predefined palettes all you have to do is execute the foll #### Apply a Palette -{{source=..\SamplesCS\ChartView\Customization\ChartViewPalettes.cs region=palette}} -{{source=..\SamplesVB\ChartView\Customization\ChartViewPalettes.vb region=palette}} + + -````C# -this.radChartView1.Area.View.Palette = KnownPalette.Metro; -```` -````VB.NET -Me.RadChartView1.Area.View.Palette = KnownPalette.Metro -```` - -{{endregion}} Here is how two of the palettes look like in action: >caption Figure 2: Autumn @@ -60,68 +52,26 @@ The predefined palettes consist of 8 palette entries which are applied to the se #### Specific Palette Entry -{{source=..\SamplesCS\ChartView\Customization\ChartViewPalettes.cs region=sample}} -{{source=..\SamplesVB\ChartView\Customization\ChartViewPalettes.vb region=sample}} - -````C# -lineSeria.Palette = KnownPalette.Flower.GlobalEntries[0]; -lineSeria.Palette = new PaletteEntry(Color.Yellow, Color.Red); - -```` -````VB.NET -lineSeria.Palette = KnownPalette.Flower.GlobalEntries(0) -lineSeria.Palette = New PaletteEntry(Color.Yellow, Color.Red) + + -```` -{{endregion}} Predefined palettes cannot be edited , however, you can define your own palettes by inheriting from __ChartPalette__ and creating a collection of palette entries. Here is an example: #### Create a Custom Palette -{{source=..\SamplesCS\ChartView\Customization\ChartViewPalettes.cs region=customPalette}} -{{source=..\SamplesVB\ChartView\Customization\ChartViewPalettes.vb region=customPalette}} - -````C# -public class CustomPalette : ChartPalette -{ - public CustomPalette() - { - this.GlobalEntries.Add(Color.Yellow, Color.Red); - this.GlobalEntries.Add(Color.Yellow, Color.Blue); - } -} - -```` -````VB.NET -Public Class CustomPalette - Inherits ChartPalette - Public Sub New() - Me.GlobalEntries.Add(Color.Yellow, Color.Red) - Me.GlobalEntries.Add(Color.Yellow, Color.Blue) - End Sub -End Class - -```` - -{{endregion}} + + -#### Apply a Custom Palette -{{source=..\SamplesCS\ChartView\Customization\ChartViewPalettes.cs region=setCustomPalette}} -{{source=..\SamplesVB\ChartView\Customization\ChartViewPalettes.vb region=setCustomPalette}} -````C# - this.radChartView1.Area.View.Palette = new CustomPalette(); +#### Apply a Custom Palette -```` -````VB.NET -Me.RadChartView1.Area.View.Palette = New CustomPalette() + + -```` -{{endregion}} >caption Figure 4: Custom Palette diff --git a/controls/chartview/features/annotations/free-figure-annotation.md b/controls/chartview/features/annotations/free-figure-annotation.md index ef28b3a42..dce34ac13 100644 --- a/controls/chartview/features/annotations/free-figure-annotation.md +++ b/controls/chartview/features/annotations/free-figure-annotation.md @@ -18,88 +18,10 @@ position: 4 #### Define Annotation -{{source=..\SamplesCS\ChartView\Annotations\CustomAnnotation.cs region=CustomAnnotation}} -{{source=..\SamplesVB\ChartView\Annotations\CustomAnnotation.vb region=CustomAnnotation}} + + -````C# -ScatterSeries scatterSeries = new ScatterSeries(); -scatterSeries.Name = "ChartData"; -scatterSeries.DataPoints.Add(new ScatterDataPoint(15, 19)); -scatterSeries.DataPoints.Add(new ScatterDataPoint(18, 10)); -scatterSeries.DataPoints.Add(new ScatterDataPoint(13, 15)); -scatterSeries.DataPoints.Add(new ScatterDataPoint(10, 8)); -scatterSeries.DataPoints.Add(new ScatterDataPoint(5, 12)); -scatterSeries.DataPoints.Add(new ScatterDataPoint(20, 20)); -scatterSeries.DataPoints.Add(new ScatterDataPoint(15, 10)); -scatterSeries.DataPoints.Add(new ScatterDataPoint(7, 6)); -scatterSeries.DataPoints.Add(new ScatterDataPoint(18, 22)); -scatterSeries.DataPoints.Add(new ScatterDataPoint(10, 10)); -scatterSeries.PointSize = new SizeF(8, 8); -this.radChartView1.Series.Add(scatterSeries); -CartesianFreeFigureAnnotation freeAnnotation = new CartesianFreeFigureAnnotation(); -freeAnnotation.Points.Add(new FreeFigurePoint(6, 8)); -freeAnnotation.Points.Add(new FreeFigurePoint(8, 15)); -freeAnnotation.Points.Add(new FreeFigurePoint(15, 17)); -freeAnnotation.Points.Add(new FreeFigurePoint(17, 8)); -freeAnnotation.Points.Add(new FreeFigurePoint(12, 5)); -freeAnnotation.Points.Add(new FreeFigurePoint(6, 8)); - -freeAnnotation.CloseFigure = true; -freeAnnotation.Spline = false; -freeAnnotation.Label = "Annotation"; -freeAnnotation.Font = new Font("Arial", 12f, FontStyle.Regular); -freeAnnotation.BackColor = Color.FromArgb(50, 37, 160, 219); -freeAnnotation.BorderDashStyle = DashStyle.Custom; -freeAnnotation.BorderDashPattern = new float[] { 9, 3, 2, 4 }; -freeAnnotation.BorderColor = Color.Orange; -freeAnnotation.BorderWidth = 2; - -freeAnnotation.PointShape = new StarShape(); -freeAnnotation.PointSize = new SizeF(24, 24); -this.radChartView1.Annotations.Add(freeAnnotation); - - -```` -````VB.NET -Dim scatterSeries As ScatterSeries = New ScatterSeries() -scatterSeries.Name = "ChartData" -scatterSeries.DataPoints.Add(New ScatterDataPoint(15, 19)) -scatterSeries.DataPoints.Add(New ScatterDataPoint(18, 10)) -scatterSeries.DataPoints.Add(New ScatterDataPoint(13, 15)) -scatterSeries.DataPoints.Add(New ScatterDataPoint(10, 8)) -scatterSeries.DataPoints.Add(New ScatterDataPoint(5, 12)) -scatterSeries.DataPoints.Add(New ScatterDataPoint(20, 20)) -scatterSeries.DataPoints.Add(New ScatterDataPoint(15, 10)) -scatterSeries.DataPoints.Add(New ScatterDataPoint(7, 6)) -scatterSeries.DataPoints.Add(New ScatterDataPoint(18, 22)) -scatterSeries.DataPoints.Add(New ScatterDataPoint(10, 10)) -scatterSeries.PointSize = New SizeF(8, 8) -Me.radChartView1.Series.Add(scatterSeries) - -Dim freeAnnotation As CartesianFreeFigureAnnotation = New CartesianFreeFigureAnnotation() -freeAnnotation.Points.Add(New FreeFigurePoint(6, 8)) -freeAnnotation.Points.Add(New FreeFigurePoint(8, 15)) -freeAnnotation.Points.Add(New FreeFigurePoint(15, 17)) -freeAnnotation.Points.Add(New FreeFigurePoint(17, 8)) -freeAnnotation.Points.Add(New FreeFigurePoint(12, 5)) -freeAnnotation.Points.Add(New FreeFigurePoint(6, 8)) -freeAnnotation.CloseFigure = True -freeAnnotation.Spline = False -freeAnnotation.Label = "Annotation" -freeAnnotation.Font = New Font("Arial", 12.0F, FontStyle.Regular) -freeAnnotation.BackColor = Color.FromArgb(50, 37, 160, 219) -freeAnnotation.BorderDashStyle = DashStyle.Custom -freeAnnotation.BorderDashPattern = New Single() {9, 3, 2, 4} -freeAnnotation.BorderColor = Color.Orange -freeAnnotation.BorderWidth = 2 -freeAnnotation.PointShape = New StarShape() -freeAnnotation.PointSize = New SizeF(24, 24) -Me.radChartView1.Annotations.Add(freeAnnotation) - -```` - -{{endregion}} ## Properties diff --git a/controls/chartview/features/annotations/grid-line.md b/controls/chartview/features/annotations/grid-line.md index de850c176..cdb163704 100644 --- a/controls/chartview/features/annotations/grid-line.md +++ b/controls/chartview/features/annotations/grid-line.md @@ -32,45 +32,11 @@ Here is what __CartesianGridLineAnnotation__ looks like: #### Cartesian Grid Line Setup -{{source=..\SamplesCS\ChartView\Annotations\GridLine.cs region=CartesianGridLine}} -{{source=..\SamplesVB\ChartView\Annotations\GridLine.vb region=CartesianGridLine}} - -````C# -CartesianGridLineAnnotation annotation1 = new CartesianGridLineAnnotation(); -annotation1.Axis = this.radChartView1.Axes[1] as CartesianAxis; -annotation1.Value = 5.8; -annotation1.BorderColor = Color.Red; -annotation1.BorderDashStyle = DashStyle.Solid; -annotation1.BorderWidth = 1; -this.radChartView1.Annotations.Add(annotation1); -CartesianGridLineAnnotation annotation2 = new CartesianGridLineAnnotation(); -annotation2.Axis = this.radChartView1.Axes[0] as CartesianAxis; -annotation2.Value = 2.9; -annotation2.BorderColor = Color.Blue; -annotation2.BorderDashStyle = DashStyle.Solid; -annotation2.BorderWidth = 1; -this.radChartView1.Annotations.Add(annotation2); - -```` -````VB.NET -Dim annotation1 As New CartesianGridLineAnnotation() -annotation1.Axis = TryCast(Me.radChartView1.Axes(1), CartesianAxis) -annotation1.Value = 5.8 -annotation1.BorderColor = Color.Red -annotation1.BorderDashStyle = DashStyle.Solid -annotation1.BorderWidth = 1 -Me.radChartView1.Annotations.Add(annotation1) -Dim annotation2 As New CartesianGridLineAnnotation() -annotation2.Axis = TryCast(Me.radChartView1.Axes(0), CartesianAxis) -annotation2.Value = 2.9 -annotation2.BorderColor = Color.Blue -annotation2.BorderDashStyle = DashStyle.Solid -annotation2.BorderWidth = 1 -Me.radChartView1.Annotations.Add(annotation2) - -```` - -{{endregion}} + + + + + Properties: @@ -92,53 +58,10 @@ Here is what __PolarAxisGridLineAnnotation__ looks like: #### Plar Grid Line Setup -{{source=..\SamplesCS\ChartView\Annotations\GridLine.cs region=PolarGridLine}} -{{source=..\SamplesVB\ChartView\Annotations\GridLine.vb region=PolarGridLine}} - -````C# -PolarAxisGridLineAnnotation annotation1 = new PolarAxisGridLineAnnotation(); -annotation1.Value = 2; -annotation1.BorderColor = Color.Red; -annotation1.BorderDashStyle = DashStyle.Solid; -annotation1.BorderWidth = 1; -this.radChartView1.Annotations.Add(annotation1); -PolarAxisGridLineAnnotation annotation2 = new PolarAxisGridLineAnnotation(); -annotation2.Value = 7; -annotation2.BorderColor = Color.LightGreen; -annotation2.BorderDashStyle = DashStyle.Solid; -annotation2.BorderWidth = 1; -this.radChartView1.Annotations.Add(annotation2); -PolarAxisGridLineAnnotation annotation3 = new PolarAxisGridLineAnnotation(); -annotation3.Value = 8; -annotation3.BorderColor = Color.LightBlue; -annotation3.BorderDashStyle = DashStyle.Solid; -annotation3.BorderWidth = 1; -this.radChartView1.Annotations.Add(annotation3); - -```` -````VB.NET -Dim annotation1 As New PolarAxisGridLineAnnotation() -annotation1.Value = 2 -annotation1.BorderColor = Color.Red -annotation1.BorderDashStyle = DashStyle.Solid -annotation1.BorderWidth = 1 -Me.radChartView1.Annotations.Add(annotation1) -Dim annotation2 As New PolarAxisGridLineAnnotation() -annotation2.Value = 7 -annotation2.BorderColor = Color.LightGreen -annotation2.BorderDashStyle = DashStyle.Solid -annotation2.BorderWidth = 1 -Me.radChartView1.Annotations.Add(annotation2) -Dim annotation3 As New PolarAxisGridLineAnnotation() -annotation3.Value = 8 -annotation3.BorderColor = Color.LightBlue -annotation3.BorderDashStyle = DashStyle.Solid -annotation3.BorderWidth = 1 -Me.radChartView1.Annotations.Add(annotation3) - -```` - -{{endregion}} + + + + Property: @@ -153,53 +76,10 @@ Here is what __RadialAxisGridLineAnnotation__ looks like: >capion Figure 3: RadialAxisGridLineAnnotation ![WinForms RadChartView Radial Axis Grid Line Annotation](images/chartview-annotations-gridline-annotations003.png) -{{source=..\SamplesCS\ChartView\Annotations\GridLine.cs region=RadialGridLine}} -{{source=..\SamplesVB\ChartView\Annotations\GridLine.vb region=RadialGridLine}} - -````C# -RadialAxisGridLineAnnotation annotation1 = new RadialAxisGridLineAnnotation(); -annotation1.Value = 30; -annotation1.BorderColor = Color.Red; -annotation1.BorderDashStyle = DashStyle.Solid; -annotation1.BorderWidth = 2; -this.radChartView1.Annotations.Add(annotation1); -RadialAxisGridLineAnnotation annotation2 = new RadialAxisGridLineAnnotation(); -annotation2.Value = 75; -annotation2.BorderColor = Color.LightGreen; -annotation2.BorderDashStyle = DashStyle.Solid; -annotation2.BorderWidth = 2; -this.radChartView1.Annotations.Add(annotation2); -RadialAxisGridLineAnnotation annotation3 = new RadialAxisGridLineAnnotation(); -annotation3.Value = 135; -annotation3.BorderColor = Color.LightBlue; -annotation3.BorderDashStyle = DashStyle.Solid; -annotation3.BorderWidth = 2; -this.radChartView1.Annotations.Add(annotation3); - -```` -````VB.NET -Dim annotation1 As New RadialAxisGridLineAnnotation() -annotation1.Value = 30 -annotation1.BorderColor = Color.Red -annotation1.BorderDashStyle = DashStyle.Solid -annotation1.BorderWidth = 2 -Me.radChartView1.Annotations.Add(annotation1) -Dim annotation2 As New RadialAxisGridLineAnnotation() -annotation2.Value = 75 -annotation2.BorderColor = Color.LightGreen -annotation2.BorderDashStyle = DashStyle.Solid -annotation2.BorderWidth = 2 -Me.radChartView1.Annotations.Add(annotation2) -Dim annotation3 As New RadialAxisGridLineAnnotation() -annotation3.Value = 135 -annotation3.BorderColor = Color.LightBlue -annotation3.BorderDashStyle = DashStyle.Solid -annotation3.BorderWidth = 2 -Me.radChartView1.Annotations.Add(annotation3) - -```` - -{{endregion}} + + + + Property: diff --git a/controls/chartview/features/annotations/marked-zone.md b/controls/chartview/features/annotations/marked-zone.md index 9ff37a939..98c512817 100644 --- a/controls/chartview/features/annotations/marked-zone.md +++ b/controls/chartview/features/annotations/marked-zone.md @@ -53,39 +53,10 @@ In the following example additional styling is applied to the default look of th #### Define Annotation -{{source=..\SamplesCS\ChartView\Annotations\MarkedZones.cs region=CartesianMarkedZone}} -{{source=..\SamplesVB\ChartView\Annotations\MarkedZones.vb region=CartesianMarkedZone}} - -````C# -CartesianMarkedZoneAnnotation annotation = new CartesianMarkedZoneAnnotation(); -annotation.HorizontalFrom = 4; -annotation.HorizontalTo = 9; -annotation.VerticalFrom = 10; -annotation.VerticalTo = 35; -annotation.BackColor = Color.FromArgb(50, 37, 160, 219); -annotation.BorderDashStyle = DashStyle.Custom; -annotation.BorderDashPattern = new float[] { 9, 3, 2, 4 }; -annotation.BorderColor = Color.Orange; -annotation.BorderWidth = 3; -this.radChartView1.Annotations.Add(annotation); - -```` -````VB.NET -Dim annotation As New CartesianMarkedZoneAnnotation() -annotation.HorizontalFrom = 4 -annotation.HorizontalTo = 9 -annotation.VerticalFrom = 10 -annotation.VerticalTo = 35 -annotation.BackColor = Color.FromArgb(50, 37, 160, 219) -annotation.BorderDashStyle = DashStyle.[Custom] -annotation.BorderDashPattern = New Single() {9, 3, 2, 4} -annotation.BorderColor = Color.Orange -annotation.BorderWidth = 3 -Me.radChartView1.Annotations.Add(annotation) - -```` - -{{endregion}} + + + + The flexible design of the marked zone annotation allows the user to omit one (or more) of the four __HorizontalFrom/To__ and __VerticalFrom/To__ properties. The following table details the relationship between the specified properties and the occupied interval on the axis: @@ -99,39 +70,10 @@ Here is the previous example with some of the settings commented #### Horizontally Defined Marked Zone -{{source=..\SamplesCS\ChartView\Annotations\MarkedZones.cs region=CartesianMarkedZone2}} -{{source=..\SamplesVB\ChartView\Annotations\MarkedZones.vb region=CartesianMarkedZone2}} - -````C# -CartesianMarkedZoneAnnotation annotation = new CartesianMarkedZoneAnnotation(); -annotation.HorizontalFrom = 4; -annotation.HorizontalTo = 9; -//annotation.VerticalFrom = 10; -//annotation.VerticalTo = 35; -annotation.BackColor = Color.FromArgb(50, 37, 160, 219); -//annotation.BorderDashStyle = DashStyle.Custom; -//annotation.BorderDashPattern = new float[] { 9, 3, 2, 4 }; -annotation.BorderColor = Color.Orange; -annotation.BorderWidth = 1; -this.radChartView1.Annotations.Add(annotation); - -```` -````VB.NET -Dim annotation As New CartesianMarkedZoneAnnotation() -annotation.HorizontalFrom = 4 -annotation.HorizontalTo = 9 -'annotation.VerticalFrom = 10; -'annotation.VerticalTo = 35; -annotation.BackColor = Color.FromArgb(50, 37, 160, 219) -'annotation.BorderDashStyle = DashStyle.Custom; -'annotation.BorderDashPattern = new float[] { 9, 3, 2, 4 }; -annotation.BorderColor = Color.Orange -annotation.BorderWidth = 1 -Me.radChartView1.Annotations.Add(annotation) - -```` - -{{endregion}} + + + + >caption Figure 3: Horizontally Defined Marked Zone ![WinForms RadChartView Horizontally Defined Marked Zone](images/chartview-annotations-markedzone-annotations003.png) @@ -166,60 +108,10 @@ The example below adds a **PolarMarkedZoneAnnotation** to a **PolarPointSeries** #### Polar Marked Zone Settings -{{source=..\SamplesCS\ChartView\Annotations\MarkedZones.cs region=PolarMarkedZone}} -{{source=..\SamplesVB\ChartView\Annotations\MarkedZones.vb region=PolarMarkedZone}} -````C# -this.radChartView1.AreaType = ChartAreaType.Polar; -PolarPointSeries polarPointSeries = new PolarPointSeries(); -PolarDataPoint dataPoint = new PolarDataPoint(); -dataPoint.Value = 40; -dataPoint.Angle = 25; -polarPointSeries.DataPoints.Add(dataPoint); -dataPoint = new PolarDataPoint(); -dataPoint.Value = 25; -dataPoint.Angle = 45; -polarPointSeries.DataPoints.Add(dataPoint); -this.radChartView1.AreaType = ChartAreaType.Polar; -this.radChartView1.Series.Add(polarPointSeries); -PolarMarkedZoneAnnotation annotation = new PolarMarkedZoneAnnotation(); -annotation.BorderWidth = 4; -annotation.BackColor = Color.FromArgb(100, Color.LightBlue); -annotation.BorderColor = Color.Red; -annotation.PolarFrom = 20; -annotation.PolarTo = 30; -annotation.RadialFrom = 30; -annotation.RadialTo = 60; -this.radChartView1.Annotations.Add(annotation); - -```` -````VB.NET -Me.radChartView1.AreaType = ChartAreaType.Polar -Dim polarPointSeries As PolarPointSeries = New PolarPointSeries() -Dim dataPoint As PolarDataPoint = New PolarDataPoint() -dataPoint.Value = 40 -dataPoint.Angle = 25 -polarPointSeries.DataPoints.Add(dataPoint) -dataPoint = New PolarDataPoint() -dataPoint.Value = 25 -dataPoint.Angle = 45 -polarPointSeries.DataPoints.Add(dataPoint) -Me.radChartView1.AreaType = ChartAreaType.Polar -Me.radChartView1.Series.Add(polarPointSeries) -Dim annotation As PolarMarkedZoneAnnotation = New PolarMarkedZoneAnnotation() -annotation.BorderWidth = 4 -annotation.BackColor = Color.FromArgb(100, Color.LightBlue) -annotation.BorderColor = Color.Red -annotation.PolarFrom = 20 -annotation.PolarTo = 30 -annotation.RadialFrom = 30 -annotation.RadialTo = 60 -Me.radChartView1.Annotations.Add(annotation) - -```` - - - -{{endregion}} + + + + # See Also diff --git a/controls/chartview/features/annotations/plot-band.md b/controls/chartview/features/annotations/plot-band.md index 89ceb8f93..96f4b89d3 100644 --- a/controls/chartview/features/annotations/plot-band.md +++ b/controls/chartview/features/annotations/plot-band.md @@ -34,49 +34,10 @@ Here is what __CartesianPlotBandAnnotation__ looks like: #### Plot Band Annotation Setup -{{source=..\SamplesCS\ChartView\Annotations\PlotBand.cs region=CartesianPlotBand}} -{{source=..\SamplesVB\ChartView\Annotations\PlotBand.vb region=CartesianPlotBand}} - -````C# -CartesianPlotBandAnnotation annotation1 = new CartesianPlotBandAnnotation(); -annotation1.Axis = this.radChartView1.Axes[0] as CartesianAxis; -annotation1.From = 0.5; -annotation1.To = 1.5; -annotation1.BackColor = Color.FromArgb(100, Color.LightBlue); -annotation1.BorderColor = Color.Black; -annotation1.BorderWidth = 1; -this.radChartView1.Annotations.Add(annotation1); -CartesianPlotBandAnnotation annotation2 = new CartesianPlotBandAnnotation(); -annotation2.Axis = this.radChartView1.Axes[1] as CartesianAxis; -annotation2.From = 4.5; -annotation2.To = 5.5; -annotation2.BackColor = Color.FromArgb(100, Color.LightBlue); -annotation2.BorderColor = Color.Black; -annotation2.BorderWidth = 1; -this.radChartView1.Annotations.Add(annotation2); - -```` -````VB.NET -Dim annotation1 As New CartesianPlotBandAnnotation() -annotation1.Axis = TryCast(Me.radChartView1.Axes(0), CartesianAxis) -annotation1.From = 0.5 -annotation1.[To] = 1.5 -annotation1.BackColor = Color.FromArgb(100, Color.LightBlue) -annotation1.BorderColor = Color.Black -annotation1.BorderWidth = 1 -Me.radChartView1.Annotations.Add(annotation1) -Dim annotation2 As New CartesianPlotBandAnnotation() -annotation2.Axis = TryCast(Me.radChartView1.Axes(1), CartesianAxis) -annotation2.From = 4.5 -annotation2.[To] = 5.5 -annotation2.BackColor = Color.FromArgb(100, Color.LightBlue) -annotation2.BorderColor = Color.Black -annotation2.BorderWidth = 1 -Me.radChartView1.Annotations.Add(annotation2) - -```` - -{{endregion}} + + + + Properties: @@ -99,33 +60,10 @@ Here is what __PolarAxisPlotBandAnnotation__ looks like: #### Polar Axis Annotation -{{source=..\SamplesCS\ChartView\Annotations\PlotBand.cs region=PolarPlotBand}} -{{source=..\SamplesVB\ChartView\Annotations\PlotBand.vb region=PolarPlotBand}} - -````C# -PolarAxisPlotBandAnnotation annotation1 = new PolarAxisPlotBandAnnotation(); -annotation1.From = 6; -annotation1.To = 8; -annotation1.BackColor = Color.FromArgb(100, Color.LightBlue); -annotation1.BorderColor = Color.Black; -annotation1.BorderWidth = 1; -annotation1.BorderDashStyle = DashStyle.Solid; -this.radChartView1.Annotations.Add(annotation1); - -```` -````VB.NET -Dim annotation1 As New PolarAxisPlotBandAnnotation() -annotation1.From = 6 -annotation1.[To] = 8 -annotation1.BackColor = Color.FromArgb(100, Color.LightBlue) -annotation1.BorderColor = Color.Black -annotation1.BorderWidth = 1 -annotation1.BorderDashStyle = DashStyle.Solid -Me.radChartView1.Annotations.Add(annotation1) - -```` - -{{endregion}} + + + + Properties: @@ -144,25 +82,10 @@ A plot band starting from *180* degrees and ending in *270* degrees will look li #### Radial Axis Annotations -{{source=..\SamplesCS\ChartView\Annotations\PlotBand.cs region=RadialPlotBand1}} -{{source=..\SamplesVB\ChartView\Annotations\PlotBand.vb region=RadialPlotBand1}} - -````C# -RadialAxisPlotBandAnnotation annotation1 = new RadialAxisPlotBandAnnotation(); -annotation1.From = 180; -annotation1.To = 270; -this.radChartView1.Annotations.Add(annotation1); + + -```` -````VB.NET -Dim annotation1 As New RadialAxisPlotBandAnnotation() -annotation1.From = 180 -annotation1.[To] = 270 -Me.radChartView1.Annotations.Add(annotation1) -```` - -{{endregion}} If you wonder how to annotate the bigger segment from the image above, then you should use the __From__ and __To__ values. @@ -171,25 +94,10 @@ If you wonder how to annotate the bigger segment from the image above, then you #### Define Bigger Segment -{{source=..\SamplesCS\ChartView\Annotations\PlotBand.cs region=RadialPlotBand2}} -{{source=..\SamplesVB\ChartView\Annotations\PlotBand.vb region=RadialPlotBand2}} - -````C# -RadialAxisPlotBandAnnotation annotation1 = new RadialAxisPlotBandAnnotation(); -annotation1.From = 270; -annotation1.To = 180; -this.radChartView1.Annotations.Add(annotation1); - -```` -````VB.NET -Dim annotation1 As New RadialAxisPlotBandAnnotation() -annotation1.From = 270 -annotation1.[To] = 180 -Me.radChartView1.Annotations.Add(annotation1) - -```` + + -{{endregion}} + Properties: diff --git a/controls/chartview/features/chart-grid.md b/controls/chartview/features/chart-grid.md index 93b14c4c7..b56df888f 100644 --- a/controls/chartview/features/chart-grid.md +++ b/controls/chartview/features/chart-grid.md @@ -15,43 +15,10 @@ __RadChartView__ areas, which support axes, can render a grid that facilitate th ## Cartesian Grid -{{source=..\SamplesCS\ChartView\ChartGrid.cs region=cartesian}} -{{source=..\SamplesVB\ChartView\ChartGrid.vb region=cartesian}} - -````C# -//add sample data -LineSeries series = new LineSeries(); -series.DataPoints.Add(new CategoricalDataPoint(500, "Jan")); -series.DataPoints.Add(new CategoricalDataPoint(300, "Apr")); -series.DataPoints.Add(new CategoricalDataPoint(400, "Jul")); -series.DataPoints.Add(new CategoricalDataPoint(250, "Oct")); -this.radChartView1.Series.Add(series); - -//setup the Cartesian Grid -CartesianArea area = this.radChartView1.GetArea(); -area.ShowGrid = true; -CartesianGrid grid = area.GetGrid(); -grid.DrawHorizontalFills = true; -grid.BorderDashStyle = System.Drawing.Drawing2D.DashStyle.DashDot; - -```` -````VB.NET -Me.RadChartView1.AreaType = ChartAreaType.Cartesian -Dim area As CartesianArea = Me.RadChartView1.GetArea(Of CartesianArea)() -Dim grid As CartesianGrid = area.GetGrid(Of CartesianGrid)() -area.ShowGrid = True -grid.DrawHorizontalFills = True -grid.BorderDashStyle = System.Drawing.Drawing2D.DashStyle.DashDot -Dim series As New LineSeries() -series.DataPoints.Add(New CategoricalDataPoint(500, "Jan")) -series.DataPoints.Add(New CategoricalDataPoint(300, "Apr")) -series.DataPoints.Add(New CategoricalDataPoint(400, "Jul")) -series.DataPoints.Add(New CategoricalDataPoint(250, "Oct")) -Me.RadChartView1.Series.Add(series) - -```` - -{{endregion}} + + + + >caption Figure 1: Cartesian Grid ![WinForms RadChartView Cartesian Grid](images/chartview-chart-grid001.png) @@ -86,59 +53,10 @@ The essential properties of CartesianGrid are the following: ## Polar Grid -{{source=..\SamplesCS\ChartView\ChartGrid.cs region=polar}} -{{source=..\SamplesVB\ChartView\ChartGrid.vb region=polar}} - -````C# -//add sample data -this.radChartView1.AreaType = ChartAreaType.Polar; - -PolarPointSeries polarPointSeries = new PolarPointSeries(); -PolarDataPoint dataPoint = new PolarDataPoint(); -dataPoint.Value = 40; -dataPoint.Angle = 20; -polarPointSeries.DataPoints.Add(dataPoint); -dataPoint = new PolarDataPoint(); -dataPoint.Value = 120; -dataPoint.Angle = 180; -polarPointSeries.DataPoints.Add(dataPoint); -this.radChartView1.Series.Add(polarPointSeries); - -//setup Polar Grid -PolarArea area = this.radChartView1.GetArea(); -area.ShowGrid = true; -PolarGrid grid = area.GetGrid(); -grid.BorderDashStyle = System.Drawing.Drawing2D.DashStyle.Dash; - -```` -````VB.NET -Me.RadChartView1.AreaType = ChartAreaType.Polar -Dim area As PolarArea = Me.RadChartView1.GetArea(Of PolarArea)() -Dim grid As PolarGrid = area.GetGrid(Of PolarGrid)() -area.ShowGrid = True -grid.BorderDashStyle = System.Drawing.Drawing2D.DashStyle.Dash -Dim polarPointSeries As New PolarPointSeries() -Dim dataPoint As New PolarDataPoint() -dataPoint.Value = 40 -dataPoint.Angle = 200 -polarPointSeries.DataPoints.Add(dataPoint) -dataPoint = New PolarDataPoint() -dataPoint.Value = 35 -dataPoint.Angle = 50 -polarPointSeries.DataPoints.Add(dataPoint) -dataPoint = New PolarDataPoint() -dataPoint.Value = 55 -dataPoint.Angle = 320 -polarPointSeries.DataPoints.Add(dataPoint) -dataPoint = New PolarDataPoint() -dataPoint.Value = 25 -dataPoint.Angle = 130 -polarPointSeries.DataPoints.Add(dataPoint) -Me.RadChartView1.Series.Add(polarPointSeries) - -```` - -{{endregion}} + + + + >caption Figure 2: Polar Grid ![WinForms RadChartView Polar Grid](images/chartview-chart-grid002.png) diff --git a/controls/chartview/features/drill-down.md b/controls/chartview/features/drill-down.md index 8e45a2cc5..4a5ed48d7 100644 --- a/controls/chartview/features/drill-down.md +++ b/controls/chartview/features/drill-down.md @@ -22,41 +22,19 @@ To support this functionality a __DrillDownControler__ should be used: #### Add Controller -{{source=..\SamplesCS\ChartView\Features\ChartDrillDown.cs region=DrillControler}} -{{source=..\SamplesVB\ChartView\Features\ChartDrillDown.vb region=DrillControler}} + + -````C# -DrillDownController drillControler = new DrillDownController(); -this.radChartView1.Controllers.Add(drillControler); -```` -````VB.NET -Dim drillControler As New DrillDownController() -Me.radChartView1.Controllers.Add(drillControler) - -```` - -{{endregion}} Then, you will need to add as many __ChartViews__ as you need. Each __ChartView__ represents different level of the drill operation. #### Add Views -{{source=..\SamplesCS\ChartView\Features\ChartDrillDown.cs region=AddNewView}} -{{source=..\SamplesVB\ChartView\Features\ChartDrillDown.vb region=AddNewView}} - -````C# -radChartView1.Views.AddNew("Revenue by Month"); -radChartView1.Views.AddNew("Revenue by Day"); - -```` -````VB.NET -radChartView1.Views.AddNew("Revenue by Month") -radChartView1.Views.AddNew("Revenue by Day") + + -```` -{{endregion}} >important In order to show the added __ChartViews__ you should set the __ShowDrillNavigation__ property to *true*. > @@ -65,109 +43,10 @@ To handle the different levels, the __Drill__ event should be used. Depending on #### Drill Event -{{source=..\SamplesCS\ChartView\Features\ChartDrillDown.cs region=DrillEvent}} -{{source=..\SamplesVB\ChartView\Features\ChartDrillDown.vb region=DrillEvent}} - -````C# -int year, month; -void radChartView1_Drill(object sender, DrillEventArgs e) -{ - CartesianSeries series = new BarSeries(); - series.ValueMember = "Value"; - series.CategoryMember = "Date"; - DateTimeCategoricalAxis horizontalAxis = new DateTimeCategoricalAxis(); - LinearAxis verticalAxis = new LinearAxis(); - verticalAxis.AxisType = AxisType.Second; - verticalAxis.Title = "USD"; - switch (e.Level) - { - case 0: - series.DataSource = LoadDataByYears(); - horizontalAxis.LabelFormat = "{0:yyyy}"; - horizontalAxis.Title = "Year"; - break; - case 1: - if (e.SelectedPoint != null) - year = ((DrillDownDataInfo)e.SelectedPoint.DataItem).Date.Year; - horizontalAxis.LabelFormat = "{0:MM}"; - horizontalAxis.Title = "Month"; - e.View.Palette = KnownPalette.Metro; - series.DataSource = ParseDataByMonth(year); - break; - case 2: - if (e.SelectedPoint != null) - month = ((DrillDownDataInfo)e.SelectedPoint.DataItem).Date.Month; - series = new LineSeries(); - series.ValueMember = "Value"; - series.CategoryMember = "Date"; - series.DataSource = ParseDataByDay(year, month); - series.ShowLabels = true; - horizontalAxis.LabelFormat = "{0:dd}"; - horizontalAxis.Title = "Day"; - break; - } - e.View.Series.Clear(); - e.View.Axes.Clear(); - series.HorizontalAxis = horizontalAxis; - series.VerticalAxis = verticalAxis; - e.View.Series.Add(series); - - series.DrawLinesToLabels = true; - series.BorderColor = series.BackColor = Color.FromArgb(142, 196, 65); -} - -```` -````VB.NET -Private year As Integer, month As Integer -Private Sub radChartView1_Drill(sender As Object, e As DrillEventArgs) - Dim series As CartesianSeries = New BarSeries() - series.ValueMember = "Value" - series.CategoryMember = "Date" - Dim horizontalAxis As New DateTimeCategoricalAxis() - Dim verticalAxis As New LinearAxis() - verticalAxis.AxisType = AxisType.Second - verticalAxis.Title = "USD" - Select Case e.Level - Case 0 - series.DataSource = LoadDataByYears() - horizontalAxis.LabelFormat = "{0:yyyy}" - horizontalAxis.Title = "Year" - Exit Select - Case 1 - If e.SelectedPoint IsNot Nothing Then - year = DirectCast(e.SelectedPoint.DataItem, DrillDownDataInfo).[Date].Year - End If - horizontalAxis.LabelFormat = "{0:MM}" - horizontalAxis.Title = "Month" - e.View.Palette = KnownPalette.Metro - series.DataSource = ParseDataByMonth(year) - Exit Select - Case 2 - If e.SelectedPoint IsNot Nothing Then - month = DirectCast(e.SelectedPoint.DataItem, DrillDownDataInfo).[Date].Month - End If - series = New LineSeries() - series.ValueMember = "Value" - series.CategoryMember = "Date" - series.DataSource = ParseDataByDay(year, month) - series.ShowLabels = True - horizontalAxis.LabelFormat = "{0:dd}" - horizontalAxis.Title = "Day" - Exit Select - End Select - e.View.Series.Clear() - e.View.Axes.Clear() - series.HorizontalAxis = horizontalAxis - series.VerticalAxis = verticalAxis - e.View.Series.Add(series) - series.DrawLinesToLabels = True - series.BorderColor = Color.FromArgb(142, 196, 65) - series.BackColor = Color.FromArgb(142, 196, 65) -End Sub - -```` - -{{endregion}} + + + + >important If your chart is being oriented horizontally, please make sure that in the **Drill** event you are setting the correct axes as **First** and **Second**. In the example above, for a horizontally oriented view, the horizontal axis should be set as **Second** and the vertical axis should be set as **First**. > @@ -181,235 +60,19 @@ To make the example complete you should make few more steps: #### Data Object -{{source=..\SamplesCS\ChartView\Features\ChartDrillDown.cs region=DrillDownDataInfo}} -{{source=..\SamplesVB\ChartView\Features\ChartDrillDown.vb region=DrillDownDataInfo}} - -````C# -public class DrillDownDataInfo : INotifyPropertyChanged -{ - double value; - DateTime date; - public DrillDownDataInfo(DateTime date, double value) - { - this.date = date; - this.value = value; - } - public double Value - { - get - { - return this.value; - } - set - { - this.value = value; - this.OnPropertyChanged("Value"); - } - } - public DateTime Date - { - get - { - return this.date; - } - set - { - this.date = value; - this.OnPropertyChanged("Date"); - } - } - public event PropertyChangedEventHandler PropertyChanged; - public void OnPropertyChanged(string propertyName) - { - if (PropertyChanged != null) - { - PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); - } - } -} - -```` -````VB.NET -Public Class DrillDownDataInfo - Implements INotifyPropertyChanged - Private m_value As Double - Private m_date As DateTime - Public Sub New([date] As DateTime, value As Double) - Me.m_date = [date] - Me.m_value = value - End Sub - Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged - Public Property Value() As Double - Get - Return Me.m_value - End Get - Set(value As Double) - Me.m_value = value - Me.OnPropertyChanged("Value") - End Set - End Property - Public Property [Date]() As DateTime - Get - Return Me.m_date - End Get - Set(value As DateTime) - Me.m_date = value - Me.OnPropertyChanged("Date") - End Set - End Property - Public Sub OnPropertyChanged(propertyName As String) - RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName)) - End Sub -End Class - -```` - -{{endregion}} + + + + 2\. Now you can use this class to create three binding lists. Each one will contain data for the chart view. These methods are used in the previously described Drill event handler. #### Load Data -{{source=..\SamplesCS\ChartView\Features\ChartDrillDown.cs region=LoadData}} -{{source=..\SamplesVB\ChartView\Features\ChartDrillDown.vb region=LoadData}} - -````C# -private BindingList LoadDataByYears() -{ - Stream stream = System.Reflection.Assembly.GetAssembly(this.GetType()).GetManifestResourceStream("SamplesCS.ChartView.Features.DJIA.csv"); - BindingList chartData = new BindingList(); - using (StreamReader streamReader = new StreamReader(stream)) - { - int yearsCount = 1; - while (streamReader.Peek() != -1) - { - string[] data = streamReader.ReadLine().Split(','); - DrillDownDataInfo dataItem = new DrillDownDataInfo( - DateTime.Parse(data[0], CultureInfo.InvariantCulture), - double.Parse(data[1], CultureInfo.InvariantCulture) - ); - chartData.Add(dataItem); - if (yearsCount++ > 10) - { - break; - } - } - } - return chartData; -} -internal BindingList ParseDataByMonth(int year) -{ - Stream stream = System.Reflection.Assembly.GetAssembly(this.GetType()).GetManifestResourceStream("SamplesCS.ChartView.Features.DJIAM.csv"); - BindingList chartData = new BindingList(); - using (StreamReader streamReader = new StreamReader(stream)) - { - while (streamReader.Peek() != -1) - { - string line = streamReader.ReadLine(); - if (string.IsNullOrEmpty(line)) - continue; - string[] data = line.Split(','); - DateTime date = DateTime.Parse(data[0], CultureInfo.InvariantCulture); - if (date.Year == year) - { - DrillDownDataInfo dataItem = new DrillDownDataInfo( - date, - double.Parse(data[1], CultureInfo.InvariantCulture) - ); - chartData.Add(dataItem); - } - } - } - return chartData; -} -internal BindingList ParseDataByDay(int year, int month) -{ - Stream stream = System.Reflection.Assembly.GetAssembly(this.GetType()).GetManifestResourceStream("SamplesCS.ChartView.Features.DJIAD.csv"); - BindingList chartData = new BindingList(); - using (StreamReader streamReader = new StreamReader(stream)) - { - while (streamReader.Peek() != -1) - { - string line = streamReader.ReadLine(); - if (string.IsNullOrEmpty(line)) - { - continue; - } - string[] data = line.Split(','); - DateTime date = DateTime.Parse(data[0], CultureInfo.InvariantCulture); - if (date.Year == year && date.Month == month && !string.IsNullOrEmpty(data[1])) - { - DrillDownDataInfo dataItem = new DrillDownDataInfo( - date, - double.Parse(data[1], CultureInfo.InvariantCulture) - ); - chartData.Add(dataItem); - } - } - return chartData; - } -} - -```` -````VB.NET -Private Function LoadDataByYears() As BindingList(Of DrillDownDataInfo) - Dim stream As Stream = System.Reflection.Assembly.GetAssembly(Me.[GetType]()).GetManifestResourceStream("SamplesCS.ChartView.Features.DJIA.csv") - Dim chartData As New BindingList(Of DrillDownDataInfo)() - Using streamReader As New StreamReader(stream) - Dim yearsCount As Integer = 1 - While streamReader.Peek() <> -1 - Dim data As String() = streamReader.ReadLine().Split(","c) - Dim dataItem As New DrillDownDataInfo(DateTime.Parse(data(0), CultureInfo.InvariantCulture), Double.Parse(data(1), CultureInfo.InvariantCulture)) - chartData.Add(dataItem) - If System.Math.Max(System.Threading.Interlocked.Increment(yearsCount), yearsCount - 1) > 10 Then - Exit While - End If - End While - End Using - Return chartData -End Function -Friend Function ParseDataByMonth(year As Integer) As BindingList(Of DrillDownDataInfo) - Dim stream As Stream = System.Reflection.Assembly.GetAssembly(Me.[GetType]()).GetManifestResourceStream("SamplesCS.ChartView.Features.DJIAM.csv") - Dim chartData As New BindingList(Of DrillDownDataInfo)() - Using streamReader As New StreamReader(stream) - While streamReader.Peek() <> -1 - Dim line As String = streamReader.ReadLine() - If String.IsNullOrEmpty(line) Then - Continue While - End If - Dim data As String() = line.Split(","c) - Dim [date] As DateTime = DateTime.Parse(data(0), CultureInfo.InvariantCulture) - If [date].Year = year Then - Dim dataItem As New DrillDownDataInfo([date], Double.Parse(data(1), CultureInfo.InvariantCulture)) - chartData.Add(dataItem) - End If - End While - End Using - Return chartData -End Function -Friend Function ParseDataByDay(year As Integer, month As Integer) As BindingList(Of DrillDownDataInfo) - Dim stream As Stream = System.Reflection.Assembly.GetAssembly(Me.[GetType]()).GetManifestResourceStream("SamplesCS.ChartView.Features.DJIAD.csv") - Dim chartData As New BindingList(Of DrillDownDataInfo)() - Using streamReader As New StreamReader(stream) - While streamReader.Peek() <> -1 - Dim line As String = streamReader.ReadLine() - If String.IsNullOrEmpty(line) Then - Continue While - End If - Dim data As String() = line.Split(","c) - Dim [date] As DateTime = DateTime.Parse(data(0), CultureInfo.InvariantCulture) - If [date].Year = year AndAlso [date].Month = month AndAlso Not String.IsNullOrEmpty(data(1)) Then - Dim dataItem As New DrillDownDataInfo([date], Double.Parse(data(1), CultureInfo.InvariantCulture)) - chartData.Add(dataItem) - End If - End While - Return chartData - End Using -End Function - -```` - -{{endregion}} + + + + >note Note that the data is loaded from external files. These files contain dates and values which are parsed and stored in out DrillDownDataInfo class objects. The files are included in __Telerik UI for WinForms__ suite (navigate to *Telerik\UI for WinForms Q3 2013\Examples\QuickStart\Resources* ). > @@ -418,45 +81,10 @@ End Function #### Add Series -{{source=..\SamplesCS\ChartView\Features\ChartDrillDown.cs region=DataByYears}} -{{source=..\SamplesVB\ChartView\Features\ChartDrillDown.vb region=DataByYears}} - -````C# -BarSeries barSeries = new BarSeries(); -barSeries.ValueMember = "Value"; -barSeries.CategoryMember = "Date"; -barSeries.DataSource = LoadDataByYears(); -this.radChartView1.View.Palette = KnownPalette.Metro; -DateTimeCategoricalAxis horizontalAxis = new DateTimeCategoricalAxis(); -horizontalAxis.LabelFormat = "{0:yyyy}"; -horizontalAxis.Title = "Year"; -barSeries.HorizontalAxis = horizontalAxis; -LinearAxis verticalAxis = new LinearAxis(); -verticalAxis.AxisType = AxisType.Second; -verticalAxis.Title = "USD"; -barSeries.VerticalAxis = verticalAxis; -radChartView1.Series.Add(barSeries); - -```` -````VB.NET -Dim barSeries As New BarSeries() -barSeries.ValueMember = "Value" -barSeries.CategoryMember = "Date" -barSeries.DataSource = LoadDataByYears() -Me.radChartView1.View.Palette = KnownPalette.Metro -Dim horizontalAxis As New DateTimeCategoricalAxis() -horizontalAxis.LabelFormat = "{0:yyyy}" -horizontalAxis.Title = "Year" -barSeries.HorizontalAxis = horizontalAxis -Dim verticalAxis As New LinearAxis() -verticalAxis.AxisType = AxisType.Second -verticalAxis.Title = "USD" -barSeries.VerticalAxis = verticalAxis -radChartView1.Series.Add(barSeries) - -```` - -{{endregion}} + + + + Now you can examine how this functionality works by clicking a data point in the chart. You can use the additional buttons to drill up or drill to top. diff --git a/controls/chartview/features/export.md b/controls/chartview/features/export.md index 201dbeb16..bab960f1d 100644 --- a/controls/chartview/features/export.md +++ b/controls/chartview/features/export.md @@ -25,22 +25,10 @@ You can export the __RadChartVew__ content by using one of the following overloa #### Export to Image -{{source=..\SamplesCS\ChartView\ChartViewExport.cs region=ExportToImage}} -{{source=..\SamplesVB\ChartView\ChartViewExport.vb region=ExportToImage}} + + -````C# - -string filePath = @"..\..\..\exprtedChart.png"; -this.radChartView1.ExportToImage(filePath, this.radChartView1.Size, System.Drawing.Imaging.ImageFormat.Png); - -```` -````VB.NET -Dim filePath As String = "..\..\..\exprtedChart.png" -Me.RadChartView1.ExportToImage(filePath, Me.RadChartView1.Size, System.Drawing.Imaging.ImageFormat.Png) - -```` - -{{endregion}} + >caption Figure 1: Exported Chart ![WinForms RadChartView Exported Chart](images/chartview-features-export001.png) diff --git a/controls/chartview/features/lasso-selection.md b/controls/chartview/features/lasso-selection.md index 2af014202..24170cf1a 100644 --- a/controls/chartview/features/lasso-selection.md +++ b/controls/chartview/features/lasso-selection.md @@ -17,107 +17,19 @@ position: 2 #### Add Sample Data and a Controller -{{source=..\SamplesCS\ChartView\Features\LassoSelection.cs region=SetupLassoSelection}} -{{source=..\SamplesVB\ChartView\Features\LassoSelection.vb region=SetupLassoSelection}} -````C# -private void AddLassoSelectionController() -{ - LineSeries lineSeries = new LineSeries() { Name = "San Diego"}; - lineSeries.DataPoints.Add(new CategoricalDataPoint(20, "Jan")); - lineSeries.DataPoints.Add(new CategoricalDataPoint(22, "Apr")); - lineSeries.DataPoints.Add(new CategoricalDataPoint(12, "Jul")); - lineSeries.DataPoints.Add(new CategoricalDataPoint(19, "Oct")); - lineSeries.PointSize = new SizeF(10, 10); - this.radChartView1.Series.Add(lineSeries); - LineSeries lineSeries2 = new LineSeries() { Name = "L.A." }; ; - lineSeries2.DataPoints.Add(new CategoricalDataPoint(18, "Jan")); - lineSeries2.DataPoints.Add(new CategoricalDataPoint(15, "Apr")); - lineSeries2.DataPoints.Add(new CategoricalDataPoint(17, "Jul")); - lineSeries2.DataPoints.Add(new CategoricalDataPoint(22, "Oct")); - lineSeries2.PointSize = new SizeF(10, 10); - this.radChartView1.Series.Add(lineSeries2); - LassoSelectionController lassoSelectionController = new LassoSelectionController(); - lassoSelectionController.LassoSelectedPointsChanged += LassoSelectionController_LassoSelectedPointsChanged; - this.radChartView1.Controllers.Add(lassoSelectionController); -} - -```` -````VB.NET -Private Sub AddLassoSelectionController() - Dim lineSeries As LineSeries = New LineSeries() With { - .Name = "San Diego" - } - lineSeries.DataPoints.Add(New CategoricalDataPoint(20, "Jan")) - lineSeries.DataPoints.Add(New CategoricalDataPoint(22, "Apr")) - lineSeries.DataPoints.Add(New CategoricalDataPoint(12, "Jul")) - lineSeries.DataPoints.Add(New CategoricalDataPoint(19, "Oct")) - lineSeries.PointSize = New SizeF(10, 10) - Me.RadChartView1.Series.Add(lineSeries) - Dim lineSeries2 As LineSeries = New LineSeries() With { - .Name = "L.A." - } - lineSeries2.DataPoints.Add(New CategoricalDataPoint(18, "Jan")) - lineSeries2.DataPoints.Add(New CategoricalDataPoint(15, "Apr")) - lineSeries2.DataPoints.Add(New CategoricalDataPoint(17, "Jul")) - lineSeries2.DataPoints.Add(New CategoricalDataPoint(22, "Oct")) - lineSeries2.PointSize = New SizeF(10, 10) - Me.RadChartView1.Series.Add(lineSeries2) - Dim lassoSelectionController As LassoSelectionController = New LassoSelectionController() - AddHandler lassoSelectionController.LassoSelectedPointsChanged, AddressOf LassoSelectionController_LassoSelectedPointsChanged - Me.RadChartView1.Controllers.Add(lassoSelectionController) -End Sub - -```` - - - -{{endregion}} + + + + The **LassoSelectionController** exposes a **LassoSelectedPointsChanged** event providing access to the data points within the bounds of the selection rectangle. In a scenario with multiple series, each of the series can be extracted from the **Presenter** property of the data point object #### The LassoSelectedPointsChanged Event -{{source=..\SamplesCS\ChartView\Features\LassoSelection.cs region=LassoSelectedPointsChangedEvent}} -{{source=..\SamplesVB\ChartView\Features\LassoSelection.vb region=LassoSelectedPointsChangedEvent}} -````C# -private void LassoSelectionController_LassoSelectedPointsChanged(object sender, ChartDataPointsEventArgs args) -{ - StringBuilder sb = new StringBuilder(); - foreach (DataPoint dp in args.SelectedDataPoints) - { - CategoricalDataPoint categoricalData = dp as CategoricalDataPoint; - if (dp == null) - { - continue; - } - CartesianSeries series = dp.Presenter as CartesianSeries; - sb.AppendLine("Series: " + series.Name); - sb.AppendLine("Data Point: " + categoricalData.Value); - } - RadMessageBox.Show(sb.ToString()); -} - -```` -````VB.NET -Private Sub LassoSelectionController_LassoSelectedPointsChanged(ByVal sender As Object, ByVal args As ChartDataPointsEventArgs) - Dim sb As StringBuilder = New StringBuilder() - For Each dp As DataPoint In args.SelectedDataPoints - Dim categoricalData As CategoricalDataPoint = TryCast(dp, CategoricalDataPoint) - If dp Is Nothing Then - Continue For - End If - Dim series As CartesianSeries = TryCast(dp.Presenter, CartesianSeries) - sb.AppendLine("Series: " & series.Name) - sb.AppendLine("Data Point: " & categoricalData.Value) - Next - RadMessageBox.Show(sb.ToString()) -End Sub - -```` - - - -{{endregion}} + + + + >note The controllers added in **RadChartView** are invoked in the order at which they have been added. In case a **LassoZoomController** is to be used together with a **LassoSelectionController**, the selection controller needs to be added first. @@ -126,34 +38,11 @@ End Sub #### Lasso and Zoom Selection Controllers -{{source=..\SamplesCS\ChartView\Features\LassoSelection.cs region=SetupLassoZoomControllers}} -{{source=..\SamplesVB\ChartView\Features\LassoSelection.vb region=SetupLassoZoomControllers}} -````C# -private void AddLassoZoomControllers() -{ - //Setup series - LassoSelectionController lassoSelectionController = new LassoSelectionController(); - lassoSelectionController.LassoSelectedPointsChanged += LassoSelectionController_LassoSelectedPointsChanged; - this.radChartView1.Controllers.Add(lassoSelectionController); - LassoZoomController lassoZoomController = new LassoZoomController(); - this.radChartView1.Controllers.Add(lassoZoomController); -} - -```` -````VB.NET -Private Sub AddLassoZoomControllers() - Dim lassoSelectionController As LassoSelectionController = New LassoSelectionController() - AddHandler lassoSelectionController.LassoSelectedPointsChanged, AddressOf LassoSelectionController_LassoSelectedPointsChanged - Me.RadChartView1.Controllers.Add(lassoSelectionController) - Dim lassoZoomController As LassoZoomController = New LassoZoomController() - Me.RadChartView1.Controllers.Add(lassoZoomController) -End Sub - -```` - - - -{{endregion}} + + + + + Using this approach you can zoom any area in the chart using the 0-100 percentage scale. # See Also diff --git a/controls/chartview/features/lasso-zoom.md b/controls/chartview/features/lasso-zoom.md index ab1844986..b0c27b294 100644 --- a/controls/chartview/features/lasso-zoom.md +++ b/controls/chartview/features/lasso-zoom.md @@ -17,60 +17,10 @@ First let’s start by adding some data points to the __RadChartView__ and __Las #### Add Controller -{{source=..\SamplesCS\ChartView\Features\LassoSelection.cs region=AddController}} -{{source=..\SamplesVB\ChartView\Features\LassoSelection.vb region=AddController}} - -````C# - -public LassoSelection() -{ - InitializeComponent(); - - LineSeries lineSeries = new LineSeries(); - lineSeries.DataPoints.Add(new CategoricalDataPoint(20, "Jan")); - lineSeries.DataPoints.Add(new CategoricalDataPoint(22, "Apr")); - lineSeries.DataPoints.Add(new CategoricalDataPoint(12, "Jul")); - lineSeries.DataPoints.Add(new CategoricalDataPoint(19, "Oct")); - lineSeries.PointSize = new SizeF(10,10); - radChartView1.Series.Add(lineSeries); - - LineSeries lineSeries2 = new LineSeries(); - lineSeries2.DataPoints.Add(new CategoricalDataPoint(18, "Jan")); - lineSeries2.DataPoints.Add(new CategoricalDataPoint(15, "Apr")); - lineSeries2.DataPoints.Add(new CategoricalDataPoint(17, "Jul")); - lineSeries2.DataPoints.Add(new CategoricalDataPoint(22, "Oct")); - lineSeries2.PointSize = new SizeF(10,10); - radChartView1.Series.Add(lineSeries2); - - LassoZoomController lassoZoomController = new LassoZoomController(); - radChartView1.Controllers.Add(lassoZoomController); -} - -```` -````VB.NET -Public Sub New() - InitializeComponent() - Dim lineSeries As New LineSeries() - lineSeries.DataPoints.Add(New CategoricalDataPoint(20, "Jan")) - lineSeries.DataPoints.Add(New CategoricalDataPoint(22, "Apr")) - lineSeries.DataPoints.Add(New CategoricalDataPoint(12, "Jul")) - lineSeries.DataPoints.Add(New CategoricalDataPoint(19, "Oct")) - lineSeries.PointSize = New SizeF(10, 10) - RadChartView1.Series.Add(lineSeries) - Dim lineSeries2 As New LineSeries() - lineSeries2.DataPoints.Add(New CategoricalDataPoint(18, "Jan")) - lineSeries2.DataPoints.Add(New CategoricalDataPoint(15, "Apr")) - lineSeries2.DataPoints.Add(New CategoricalDataPoint(17, "Jul")) - lineSeries2.DataPoints.Add(New CategoricalDataPoint(22, "Oct")) - lineSeries2.PointSize = New SizeF(10, 10) - RadChartView1.Series.Add(lineSeries2) - Dim lassoZoomController As New LassoZoomController() - RadChartView1.Controllers.Add(lassoZoomController) -End Sub - -```` - -{{endregion}} + + + + >caption Figure 1: Initial Chart ![WinForms RadChartView Initial Chart](images/chartview-features-lasso-selection001.png) @@ -89,31 +39,10 @@ __LassoZoomController__ supports zoom and pan functionality programmatically via #### Zoom and Pan -{{source=..\SamplesCS\ChartView\Features\LassoSelection.cs region=ZoomFirst}} -{{source=..\SamplesVB\ChartView\Features\LassoSelection.vb region=ZoomFirst}} - -````C# -private void LassoSelection_Load(object sender, EventArgs e) -{ - LassoZoomController lassoZoomController = radChartView1.Controllers[1] as LassoZoomController; - if (lassoZoomController != null) - { - lassoZoomController.ZoomAndPan(0, 50); - } -} - -```` -````VB.NET -Private Sub LassoSelection_Load(sender As Object, e As EventArgs) Handles MyBase.Load - Dim lassoZoomController As LassoZoomController = TryCast(RadChartView1.Controllers(1), LassoZoomController) - If lassoZoomController IsNot Nothing Then - lassoZoomController.ZoomAndPan(0, 50) - End If -End Sub - -```` - -{{endregion}} + + + + >caption Figure 4: Zoom and Pan ![WinForms RadChartView Zoom and Pan](images/chartview-features-lasso-selection004.png) diff --git a/controls/chartview/features/legend.md b/controls/chartview/features/legend.md index 6dfef35a9..2d3a8a78a 100644 --- a/controls/chartview/features/legend.md +++ b/controls/chartview/features/legend.md @@ -19,21 +19,10 @@ The __ShowLegend__ property of __RadChartView__ controls whether the legend is v #### Show Legend -{{source=..\SamplesCS\ChartView\Features\ChartViewLegend.cs region=ShowLegend}} -{{source=..\SamplesVB\ChartView\Features\ChartViewLegend.vb region=ShowLegend}} + + -````C# -this.radChartView1.ShowLegend = true; -this.radChartView1.LegendTitle = "Legend"; -```` -````VB.NET -Me.RadChartView1.ShowLegend = True -Me.RadChartView1.LegendTitle = "Legend" - -```` - -{{endregion}} >caption Figure 1: Show Legend @@ -45,23 +34,10 @@ The location of the title can be modified by the __TitlePosition__ property. Add #### Legend Settings -{{source=..\SamplesCS\ChartView\Features\ChartViewLegend.cs region=CustomizeLegendTitle}} -{{source=..\SamplesVB\ChartView\Features\ChartViewLegend.vb region=CustomizeLegendTitle}} - -````C# -this.radChartView1.ChartElement.LegendElement.TitlePosition = TitlePosition.Bottom; -this.radChartView1.ChartElement.LegendElement.TitleElement.Font = new Font("Arial", 12, FontStyle.Italic); -this.radChartView1.ChartElement.LegendElement.TitleElement.ForeColor = Color.Red; + + -```` -````VB.NET -Me.RadChartView1.ChartElement.LegendElement.TitlePosition = TitlePosition.Bottom -Me.RadChartView1.ChartElement.LegendElement.TitleElement.Font = New Drawing.Font("Arial", 12, Drawing.FontStyle.Italic) -Me.RadChartView1.ChartElement.LegendElement.TitleElement.ForeColor = Drawing.Color.Red -```` - -{{endregion}} >caption Figure 2: Legend Settings @@ -71,19 +47,10 @@ You can dock the legend to each of the four sides of the control by setting the #### Legend Position -{{source=..\SamplesCS\ChartView\Features\ChartViewLegend.cs region=LegendPositionBottom}} -{{source=..\SamplesVB\ChartView\Features\ChartViewLegend.vb region=LegendPositionBottom}} - -````C# -this.radChartView1.ChartElement.LegendPosition = LegendPosition.Bottom; - -```` -````VB.NET -Me.RadChartView1.ChartElement.LegendPosition = LegendPosition.Bottom + + -```` -{{endregion}} >caption Figure 3: Legend Position @@ -96,21 +63,10 @@ Alternatively, you can set it to float over the chart view. Here is how to set t #### Float Legend -{{source=..\SamplesCS\ChartView\Features\ChartViewLegend.cs region=LegendPositionFloat}} -{{source=..\SamplesVB\ChartView\Features\ChartViewLegend.vb region=LegendPositionFloat}} + + -````C# -this.radChartView1.ChartElement.LegendPosition = LegendPosition.Float; -this.radChartView1.ChartElement.LegendOffset = new Point(200, 0); -```` -````VB.NET -Me.RadChartView1.ChartElement.LegendPosition = LegendPosition.Float -Me.RadChartView1.ChartElement.LegendOffset = New Point(200, 0) - -```` - -{{endregion}} >caption Figure 4: Float Legend @@ -121,23 +77,10 @@ Me.RadChartView1.ChartElement.LegendOffset = New Point(200, 0) #### Wrap Legend Items -{{source=..\SamplesCS\ChartView\Features\ChartViewLegend.cs region=WrapLegend}} -{{source=..\SamplesVB\ChartView\Features\ChartViewLegend.vb region=WrapLegend}} - -````C# - -this.radChartView1.ChartElement.LegendItemsLayout = LegendItemsLayout.Wrap; -this.radChartView1.ChartElement.LegendElement.WrapPanelElement.Orientation = System.Windows.Forms.Orientation.Horizontal; - -```` -````VB.NET - -Me.RadChartView1.ChartElement.LegendItemsLayout = LegendItemsLayout.Wrap -Me.RadChartView1.ChartElement.LegendElement.WrapPanelElement.Orientation = System.Windows.Forms.Orientation.Horizontal + + -```` -{{endregion}} |LegendItemsLayout.Stack|LegendItemsLayout.Wrap| |----|----| @@ -149,23 +92,10 @@ The elements that provide legend items in the case of the Pie chart are the indi #### Legend Properties -{{source=..\SamplesCS\ChartView\Features\ChartViewLegend.cs region=LegendProperties}} -{{source=..\SamplesVB\ChartView\Features\ChartViewLegend.vb region=LegendProperties}} + + -````C# -LineSeries line = new LineSeries(); -line.IsVisibleInLegend = true; -line.LegendTitle = "Windows 8"; -```` -````VB.NET -Dim line As New LineSeries() -line.IsVisibleInLegend = True -line.LegendTitle = "Windows 8" - -```` - -{{endregion}} >caption Figure 5: Legend Properties @@ -177,21 +107,11 @@ You have access to the items displayed in the legend through the __Items__ prope #### Change Text -{{source=..\SamplesCS\ChartView\Features\ChartViewLegend.cs region=ChangeLegendItemText}} -{{source=..\SamplesVB\ChartView\Features\ChartViewLegend.vb region=ChangeLegendItemText}} -````C# -this.radChartView1.ChartElement.LegendElement.Items[0].Title = "Linux"; - -```` -````VB.NET -Me.RadChartView1.ChartElement.LegendElement.Items(0).Title = "Linux" + + -```` - -{{endregion}} - >caption Figure 6: Changed Text ![WinForms RadChartView Changed Text](images/chartview-features-legend006.png) @@ -202,29 +122,11 @@ You can add and remove items from the legend through the __Items__ collection. Y #### Add and Remove Legends -{{source=..\SamplesCS\ChartView\Features\ChartViewLegend.cs region=AddLegendItem}} -{{source=..\SamplesVB\ChartView\Features\ChartViewLegend.vb region=AddLegendItem}} -````C# -LegendItem item = new LegendItem(); -item.Element.BorderColor = Color.Black; -item.Element.BackColor = Color.Yellow; -item.Title = "Custom item"; -this.radChartView1.ChartElement.LegendElement.Items.Add(item); - -```` -````VB.NET -Dim item As New LegendItem() -item.Element.BorderColor = Color.Black -item.Element.BackColor = Color.Yellow -item.Title = "Custom item" -Me.RadChartView1.ChartElement.LegendElement.Items.Add(item) + + -```` - -{{endregion}} - >caption Figure 7: Added Item ![WinForms RadChartView Added Item](images/chartview-features-legend007.png) @@ -235,74 +137,17 @@ You can use your own legend item elements by handling the __VisualItemCreating__ #### Add a Custom Legend Item -{{source=..\SamplesCS\ChartView\Features\ChartViewLegend.cs region=CustomLegendItem1}} -{{source=..\SamplesVB\ChartView\Features\ChartViewLegend.vb region=CustomLegendItem1}} -````C# -this.radChartView1.ChartElement.LegendElement.VisualItemCreating +=new LegendItemElementCreatingEventHandler(LegendElement_VisualItemCreating); - -```` -````VB.NET -AddHandler Me.RadChartView1.ChartElement.LegendElement.VisualItemCreating, AddressOf LegendElement_VisualItemCreating + + -```` +#### Custom LegendItemElement Implementation: -{{endregion}} + + -#### Custom LegendItemElement Implementation: -{{source=..\SamplesCS\ChartView\Features\ChartViewLegend.cs region=CustomLegendItem2}} -{{source=..\SamplesVB\ChartView\Features\ChartViewLegend.vb region=CustomLegendItem2}} -````C# -public class CustomLegendItemElement : LegendItemElement -{ - public CustomLegendItemElement(LegendItem item) - : base(item) - { - this.Children.Remove(this.MarkerElement); - this.TitleElement.DrawFill = true; - this.TitleElement.DrawBorder = true; - this.StretchHorizontally = true; - } - protected override void Synchronize() - { - base.Synchronize(); - this.SyncVisualStyleProperties(this.LegendItem.Element, this.TitleElement); - this.TitleElement.ForeColor = Color.White; - } -} -private void LegendElement_VisualItemCreating(object sender, LegendItemElementCreatingEventArgs e) -{ - e.ItemElement = new CustomLegendItemElement(e.LegendItem); -} - -```` -````VB.NET -Public Class CustomLegendItemElement - Inherits LegendItemElement - Public Sub New(item As LegendItem) - MyBase.New(item) - Me.Children.Remove(Me.MarkerElement) - Me.TitleElement.DrawFill = True - Me.TitleElement.DrawBorder = True - Me.StretchHorizontally = True - End Sub - Protected Overrides Sub Synchronize() - MyBase.Synchronize() - Me.SyncVisualStyleProperties(Me.LegendItem.Element, Me.TitleElement) - Me.TitleElement.ForeColor = Color.White - End Sub -End Class -Private Sub LegendElement_VisualItemCreating(sender As Object, e As LegendItemElementCreatingEventArgs) - e.ItemElement = New CustomLegendItemElement(e.LegendItem) -End Sub - -```` - - - -{{endregion}} >caption Figure 8: Custom Legend Item diff --git a/controls/chartview/features/scroll-and-zoom.md b/controls/chartview/features/scroll-and-zoom.md index 464c06584..646b3fbc6 100644 --- a/controls/chartview/features/scroll-and-zoom.md +++ b/controls/chartview/features/scroll-and-zoom.md @@ -15,23 +15,10 @@ __RadChartView__ provides zoom and scroll interactivity with the __ChartPanZoomC #### ChartPanZoomController Setup -{{source=..\SamplesCS\ChartView\Features\ScrollAndZoom.cs region=controller}} -{{source=..\SamplesVB\ChartView\Features\ScrollAndZoom.vb region=controller}} + + -````C# -ChartPanZoomController panZoomController = new ChartPanZoomController(); -panZoomController.PanZoomMode = ChartPanZoomMode.Horizontal; -radChartView1.Controllers.Add(panZoomController); -```` -````VB.NET -Dim panZoomController As New ChartPanZoomController() -panZoomController.PanZoomMode = ChartPanZoomMode.Horizontal -RadChartView1.Controllers.Add(panZoomController) - -```` - -{{endregion}} >note When adding a new __ChartPanZoomController__ all other pan and zoom controllers are removed if such exists. > @@ -40,19 +27,10 @@ The __ChartPanAndZoomController__ will be added automatically if the __ShowPanZo #### Add Using the Property -{{source=..\SamplesCS\ChartView\Features\ScrollAndZoom.cs region=showPanZoom}} -{{source=..\SamplesVB\ChartView\Features\ScrollAndZoom.vb region=showPanZoom}} - -````C# -radChartView1.ShowPanZoom = true; + + -```` -````VB.NET -RadChartView1.ShowPanZoom = True -```` - -{{endregion}} The __PanZoomMode__ property allow developers to restrict zooming. Setting either of these properties to the __Both__ value removes any restrictions and the chart can be zoomed in both the horizontal and vertical axes. The last two values are __Horizontal__ and __Vertical__ which restrict the behavior horizontally and vertically respectively. You can now get/set the zoom and pan values of the RadChartView using the __Zoom__ and __Pan__ methods. Note that the offset should be provided in negative absolute values e.g Pan(-300,0) will offset the chart horizontally at 300px. You may use it to simultaneously set zoom for the both axes by separating the values with comma. For example a Zoom(3 , 1) setting specifies that the data will be zoomed 3 times according to the XAxis and won't be zoomed by YAxis. @@ -61,19 +39,10 @@ The __PanZoomMode__ property allow developers to restrict zooming. Setting eithe #### Zooming -{{source=..\SamplesCS\ChartView\Features\ScrollAndZoom.cs region=Zoom}} -{{source=..\SamplesVB\ChartView\Features\ScrollAndZoom.vb region=Zoom}} - -````C# -radChartView1.Zoom(3, 1); - -```` -````VB.NET -RadChartView1.Zoom(3, 1) + + -```` -{{endregion}} >caption Figure 2: Zooming ![WinForms RadChartView Zooming](images/chartview-features-scroll-and-zoom002.png) @@ -82,19 +51,10 @@ RadChartView1.Zoom(3, 1) Panning with 300 pixels: -{{source=..\SamplesCS\ChartView\Features\ScrollAndZoom.cs region=pan}} -{{source=..\SamplesVB\ChartView\Features\ScrollAndZoom.vb region=pan}} + + -````C# -radChartView1.Pan(-300, 0); -```` -````VB.NET -RadChartView1.Pan(-300, 0) - -```` - -{{endregion}} >caption Figure 3: Panning ![WinForms RadChartView Panning](images/chartview-features-scroll-and-zoom003.png) @@ -105,28 +65,10 @@ The zoom factor can be controlled using __Ctrl+MouseWheel__ for zoom in and zoom #### Current Zoom and Pan -{{source=..\SamplesCS\ChartView\Features\ScrollAndZoom.cs region=CurrentZoomPan}} -{{source=..\SamplesVB\ChartView\Features\ScrollAndZoom.vb region=CurrentZoomPan}} -````C# -IChartView view = this.radChartView1.ChartElement.View; -double zoomX = view.ZoomWidth; -double zoomY = view.ZoomHeight; -double panX = view.PlotOriginX; -double panY = view.PlotOriginY; - -```` -````VB.NET -Dim view As IChartView = Me.RadChartView1.ChartElement.View -Dim zoomX = view.ZoomWidth -Dim zoomY = view.ZoomHeight -Dim panX = view.PlotOriginX -Dim panY = view.PlotOriginY - -```` - + + -{{endregion}} # See Also diff --git a/controls/chartview/features/selection.md b/controls/chartview/features/selection.md index 58a58afa5..242dffd20 100644 --- a/controls/chartview/features/selection.md +++ b/controls/chartview/features/selection.md @@ -17,138 +17,28 @@ In order to utilize this behavior users simply have to add it to the chart's __C #### Add Controller -{{source=..\SamplesCS\ChartView\Features\ChartSelection.cs region=controller}} -{{source=..\SamplesVB\ChartView\Features\ChartSelection.vb region=controller}} + + -````C# -radChartView1.Controllers.Add(new ChartSelectionController()); -radChartView1.SelectionMode = ChartSelectionMode.SingleDataPoint; -radChartView1.SelectedPointChanged += new ChartViewSelectedChangedEventHandler(radChartView1_SelectedPointChanged); -```` -````VB.NET -RadChartView1.Controllers.Add(New ChartSelectionController()) -RadChartView1.SelectionMode = ChartSelectionMode.SingleDataPoint -AddHandler RadChartView1.SelectedPointChanged, AddressOf RadChartView1_SelectedPointChanged - -```` - -{{endregion}} The __ChartSelectionController__ will be added automatically if the __SelectionMode__ property of __RadChartView__ control is set to one of available options. #### ChartSelectionMode -{{source=..\SamplesCS\ChartView\Features\ChartSelection.cs region=selectionMode}} -{{source=..\SamplesVB\ChartView\Features\ChartSelection.vb region=selectionMode}} - -````C# -radChartView1.SelectionMode = ChartSelectionMode.SingleDataPoint; -radChartView1.SelectionMode = ChartSelectionMode.MultipleDataPoints; + + -```` -````VB.NET -radChartView1.SelectionMode = ChartSelectionMode.SingleDataPoint -radChartView1.SelectionMode = ChartSelectionMode.MultipleDataPoints -```` - -{{endregion}} Here is a sample using __PieSeries__ and multiple selection. When a slice is selected, it is being offsetted from the center: #### Sliced Pie -{{source=..\SamplesCS\ChartView\Features\ChartSelection.cs region=example}} -{{source=..\SamplesVB\ChartView\Features\ChartSelection.vb region=example}} - -````C# -public ChartSelection() -{ - InitializeComponent(); - radChartView1.AreaType = ChartAreaType.Pie; - PieSeries pieSeries = new PieSeries(); - pieSeries.ShowLabels = true; - pieSeries.PointSize = new SizeF(15, 15); - pieSeries.DataPoints.Add(new PieDataPoint(10)); - pieSeries.DataPoints.Add(new PieDataPoint(5)); - pieSeries.DataPoints.Add(new PieDataPoint(40)); - pieSeries.DataPoints.Add(new PieDataPoint(22)); - pieSeries.DataPoints.Add(new PieDataPoint(11)); - pieSeries.DataPoints.Add(new PieDataPoint(20)); - radChartView1.Series.Add(pieSeries); - radChartView1.Controllers.Add(new ChartSelectionController()); - radChartView1.SelectionMode = ChartSelectionMode.MultipleDataPoints; - radChartView1.SelectedPointChanged += new ChartViewSelectedChangedEventHandler(radChartView1_SelectedPointChanged); -} -void radChartView1_SelectedPointChanged(object sender, ChartViewSelectedPointChangedEventArgs args) -{ - if (args.NewSelectedPoint != null) - { - UpdateSelectedPoint(args.NewSelectedPoint); - } - if (args.OldSelectedPoint != null) - { - UpdateSelectedPoint(args.OldSelectedPoint); - } -} -void UpdateSelectedPoint(DataPoint point) -{ - PieDataPoint pieDataPoint = point as PieDataPoint; - if (pieDataPoint != null) - { - if (pieDataPoint.IsSelected) - { - pieDataPoint.OffsetFromCenter = 0.1; - } - else - { - pieDataPoint.OffsetFromCenter = 0; - } - } -} - -```` -````VB.NET -Public Sub New() - InitializeComponent() - radChartView1.AreaType = ChartAreaType.Pie - Dim pieSeries As New PieSeries() - pieSeries.ShowLabels = True - pieSeries.PointSize = New SizeF(15, 15) - pieSeries.DataPoints.Add(New PieDataPoint(10)) - pieSeries.DataPoints.Add(New PieDataPoint(5)) - pieSeries.DataPoints.Add(New PieDataPoint(40)) - pieSeries.DataPoints.Add(New PieDataPoint(22)) - pieSeries.DataPoints.Add(New PieDataPoint(11)) - pieSeries.DataPoints.Add(New PieDataPoint(20)) - radChartView1.Series.Add(pieSeries) - RadChartView1.Controllers.Add(New ChartSelectionController()) - RadChartView1.SelectionMode = ChartSelectionMode.MultipleDataPoints - AddHandler RadChartView1.SelectedPointChanged, AddressOf RadChartView1_SelectedPointChanged -End Sub -Private Sub RadChartView1_SelectedPointChanged(sender As Object, args As ChartViewSelectedPointChangedEventArgs) - If args.NewSelectedPoint IsNot Nothing Then - UpdateSelectedPoint(args.NewSelectedPoint) - End If - If args.OldSelectedPoint IsNot Nothing Then - UpdateSelectedPoint(args.OldSelectedPoint) - End If -End Sub -Private Sub UpdateSelectedPoint(point As DataPoint) - Dim pieDataPoint As PieDataPoint = TryCast(point, PieDataPoint) - If pieDataPoint IsNot Nothing Then - If pieDataPoint.IsSelected Then - pieDataPoint.OffsetFromCenter = 0.1 - Else - pieDataPoint.OffsetFromCenter = 0 - End If - End If -End Sub - -```` - -{{endregion}} + + + + >caption Figure 2: Sliced Pie ![WinForms RadChartView Sliced Pie](images/chartview-features-selection001.png) diff --git a/controls/chartview/features/smart-labels.md b/controls/chartview/features/smart-labels.md index 170ba3647..e9774f2f4 100644 --- a/controls/chartview/features/smart-labels.md +++ b/controls/chartview/features/smart-labels.md @@ -15,37 +15,20 @@ __RadChartView__ provides a built-in mechanism for resolving labels overlapping #### Add Controller -{{source=..\SamplesCS\ChartView\Features\SmartLabels.cs region=AddSmartLabelsController}} -{{source=..\SamplesVB\ChartView\Features\SmartLabels.vb region=AddSmartLabelsController}} + + -````C# -this.radChartView1.Controllers.Add(new SmartLabelsController()); -```` -````VB.NET -Me.radChartView1.Controllers.Add(New SmartLabelsController()) - -```` - -{{endregion}} Alternatively, you can leave __RadChartView__ do this for you by setting the __ShowSmartLabels__ property: #### Set Property -{{source=..\SamplesCS\ChartView\Features\SmartLabels.cs region=EnableSmartLabels}} -{{source=..\SamplesVB\ChartView\Features\SmartLabels.vb region=EnableSmartLabels}} - -````C# -this.radChartView1.ShowSmartLabels = true; + + -```` -````VB.NET -Me.radChartView1.ShowSmartLabels = True -```` -{{endregion}} Automatic label placement is one the most complex and time consuming operations in a chart that is NP-hard ([http://en.wikipedia.org/wiki/NP-Hard](http://en.wikipedia.org/wiki/NP-Hard)). There is no universal solution for all chart types and there is no solution that can guarantee solution for 100% of the label collisions in every case. @@ -75,142 +58,27 @@ In a specific scenario you may need to control the labels' position. For this pu #### Custom SmartLabelsStrategy -{{source=..\SamplesCS\ChartView\Features\SmartLabels.cs region=CustomSmartLabelsStrategy}} -{{source=..\SamplesVB\ChartView\Features\SmartLabels.vb region=CustomSmartLabelsStrategy}} - -````C# -public class MyStrategy : SmartLabelsStrategyBase -{ - public override void CalculateLocations(Telerik.WinControls.UI.ChartSeriesCollection series, Rectangle plotArea) - { - List labels = new List(); - List overlaps = new List(); - int x = 70; - int y = 30; - int spacing = 6; - foreach (Telerik.WinControls.UI.ChartSeries chartSeries in series) - { - if (!chartSeries.ShowLabels || !chartSeries.IsVisible) - { - continue; - } - foreach (DataPointElement point in chartSeries.Children) - { - LabelElement label = (LabelElement)point.Children[0]; - Rectangle labelRect = ChartRenderer.ToRectangle(label.GetLayoutSlot()); - var newRect = new Rectangle(x, y, labelRect.Width, labelRect.Height); - x += spacing + labelRect.Width; - if (x + spacing + labelRect.Width > plotArea.Width - 100) - { - y += spacing + labelRect.Height; - x = 70; - } - label.SmartRectangle = newRect; - labels.Add(label); - } - } - } -} -public class MySmartLabelsController : SmartLabelsController -{ - public override void CalculateLabelsPositions(Telerik.WinControls.UI.ChartSeriesCollection series, Rectangle plotArea) - { - if (this.Strategy != null) - { - this.Strategy.CalculateLocations(series, plotArea); - } - } -} - -```` -````VB.NET -Public Class MyStrategy - Inherits SmartLabelsStrategyBase - Public Overrides Sub CalculateLocations(series As Telerik.WinControls.UI.ChartSeriesCollection, plotArea As Rectangle) - Dim labels As New List(Of LabelElement)() - Dim overlaps As New List(Of Integer)() - Dim x As Integer = 70 - Dim y As Integer = 30 - Dim spacing As Integer = 6 - For Each chartSeries As Telerik.WinControls.UI.ChartSeries In series - If Not chartSeries.ShowLabels OrElse Not chartSeries.IsVisible Then - Continue For - End If - For Each point As DataPointElement In chartSeries.Children - Dim label As LabelElement = DirectCast(point.Children(0), LabelElement) - Dim labelRect As Rectangle = ChartRenderer.ToRectangle(label.GetLayoutSlot()) - Dim newRect = New Rectangle(x, y, labelRect.Width, labelRect.Height) - x += spacing + labelRect.Width - If x + spacing + labelRect.Width > plotArea.Width - 100 Then - y += spacing + labelRect.Height - x = 70 - End If - label.SmartRectangle = newRect - labels.Add(label) - Next - Next - End Sub -End Class -Public Class MySmartLabelsController - Inherits SmartLabelsController - Public Overrides Sub CalculateLabelsPositions(series As Telerik.WinControls.UI.ChartSeriesCollection, plotArea As Rectangle) - If Me.Strategy IsNot Nothing Then - Me.Strategy.CalculateLocations(series, plotArea) - End If - End Sub -End Class - -```` - -{{endregion}} + + -You must apply the custom __SmartLabelsController__ to __RadChartView__: -#### Apply custom strategy -{{source=..\SamplesCS\ChartView\Features\SmartLabels.cs region=ApplyCustomStrategy}} -{{source=..\SamplesVB\ChartView\Features\SmartLabels.vb region=ApplyCustomStrategy}} +You must apply the custom __SmartLabelsController__ to __RadChartView__: -````C# -MySmartLabelsController controler = new MySmartLabelsController(); -controler.Strategy = new MyStrategy(); -this.radChartView1.Controllers.Add(controler); +#### Apply custom strategy -```` -````VB.NET -roperty - Dim controler As SmartLabelsController = New SmartLabelsController() - controler.Strategy = New MyStrategy() - controler.RegisterCustomStrategyWithSeries(GetType(MyStrategy), New List(Of Type)() From {GetType(BarSeries)}) - Me.radChartView1.Controllers.Add(controler) + + -```` -{{endregion}} After the **R3 2018 SP1** release, the custom strategy can be applied after setting the Strategy property of the control and after regsitering it with all compatible series: -{{source=..\SamplesCS\ChartView\Features\SmartLabels.cs region=ApplyCustomStrategyProperty}} -{{source=..\SamplesVB\ChartView\Features\SmartLabels.vb region=ApplyCustomStrategyProperty}} -````C# -SmartLabelsController controler = new SmartLabelsController(); -controler.Strategy = new MyStrategy(); -controler.RegisterCustomStrategyWithSeries(typeof(MyStrategy), new List() { typeof(BarSeries) }); -this.radChartView1.Controllers.Add(controler); - -```` -````VB.NET -Dim controler As SmartLabelsController = New SmartLabelsController() -controler.Strategy = New MyStrategy() -controler.RegisterCustomStrategyWithSeries(GetType(MyStrategy), New List(Of Type)() From {GetType(BarSeries)}) -Me.radChartView1.Controllers.Add(controler) - -```` - + + -{{endregion}} |Before|After| |----|----| diff --git a/controls/chartview/features/title.md b/controls/chartview/features/title.md index 7cfc41658..c865d5e64 100644 --- a/controls/chartview/features/title.md +++ b/controls/chartview/features/title.md @@ -15,44 +15,20 @@ To show the title in __RadChartView__ you need to set the __ShowTitle__ property #### Showing Title -{{source=..\SamplesCS\ChartView\Features\ChartViewTitle.cs region=ShowTitle}} -{{source=..\SamplesVB\ChartView\Features\ChartViewTitle.vb region=ShowTitle}} + + -````C# -this.radChartView1.Title = "OS Platform statistics Q1"; -this.radChartView1.ShowTitle = true; -```` -````VB.NET -Me.RadChartView1.Title = "OS Platform statistics Q1" -Me.RadChartView1.ShowTitle = True - -```` - -{{endregion}} >caption Figure 1: Custom Title ![WinForms RadChartView Custom Title](images/chartview-features-title001.png) The title can be moved to all four sides of the chart using the __TitleLocation__ property. Also, you can access the title element, which allows you to set various options: -{{source=..\SamplesCS\ChartView\Features\ChartViewTitle.cs region=CustomizeTitle}} -{{source=..\SamplesVB\ChartView\Features\ChartViewTitle.vb region=CustomizeTitle}} - -````C# -this.radChartView1.ChartElement.TitleElement.TextOrientation = Orientation.Vertical; -this.radChartView1.ChartElement.TitlePosition = TitlePosition.Left; -this.radChartView1.ChartElement.TitleElement.FlipText = true; - -```` -````VB.NET -Me.RadChartView1.ChartElement.TitleElement.TextOrientation = Orientation.Vertical -Me.RadChartView1.ChartElement.TitlePosition = TitlePosition.Left -Me.RadChartView1.ChartElement.TitleElement.FlipText = True + + -```` -{{endregion}} >caption Figure 2: Title Positon ![WinForms RadChartView Title Positon](images/chartview-features-title002.png) diff --git a/controls/chartview/features/tooltip.md b/controls/chartview/features/tooltip.md index 960aa765c..e82ecabba 100644 --- a/controls/chartview/features/tooltip.md +++ b/controls/chartview/features/tooltip.md @@ -15,105 +15,28 @@ __RadChartView__ provides a tooltip interactivity with the __ChartTooltipContro #### Add Controller -{{source=..\SamplesCS\ChartView\Features\ChartTooltip.cs region=controller}} -{{source=..\SamplesVB\ChartView\Features\ChartTooltip.vb region=controller}} + + -````C# -radChartView1.Controllers.Add(new ChartTooltipController()); -```` -````VB.NET -radChartView1.Controllers.Add(New ChartTooltipController()) - -```` - -{{endregion}} The __ChartTooltipController__ will be added automatically if the __ShowToolTip__ property of __RadChartView__ control is set to *true*: #### Set Property -{{source=..\SamplesCS\ChartView\Features\ChartTooltip.cs region=showToolTip}} -{{source=..\SamplesVB\ChartView\Features\ChartTooltip.vb region=showToolTip}} - -````C# -radChartView1.ShowToolTip = true; + + -```` -````VB.NET -radChartView1.ShowToolTip = True -```` - -{{endregion}} A sample is shown below: #### Sample Setup -{{source=..\SamplesCS\ChartView\Features\ChartTooltip.cs region=example}} -{{source=..\SamplesVB\ChartView\Features\ChartTooltip.vb region=example}} - -````C# -radChartView1.AreaType = ChartAreaType.Cartesian; -BarSeries barSeries1 = new BarSeries(); -barSeries1.DataPoints.Add(new CategoricalDataPoint(10, "1")); -barSeries1.DataPoints.Add(new CategoricalDataPoint(4, "2")); -barSeries1.DataPoints.Add(new CategoricalDataPoint(23, "3")); -barSeries1.DataPoints.Add(new CategoricalDataPoint(11, "4")); -barSeries1.DataPoints.Add(new CategoricalDataPoint(15, "5")); -barSeries1.DataPoints.Add(new CategoricalDataPoint(10, "6")); -barSeries1.DataPoints.Add(new CategoricalDataPoint(4, "7")); -barSeries1.DataPoints.Add(new CategoricalDataPoint(7, "8")); -barSeries1.DataPoints.Add(new CategoricalDataPoint(11, "9")); -barSeries1.DataPoints.Add(new CategoricalDataPoint(15, "10")); -radChartView1.Series.Add(barSeries1); -BarSeries barSeries2 = new BarSeries(); -barSeries2.DataPoints.Add(new CategoricalDataPoint(6, "1")); -barSeries2.DataPoints.Add(new CategoricalDataPoint(20, "2")); -barSeries2.DataPoints.Add(new CategoricalDataPoint(7, "3")); -barSeries2.DataPoints.Add(new CategoricalDataPoint(8, "4")); -barSeries2.DataPoints.Add(new CategoricalDataPoint(4, "5")); -barSeries2.DataPoints.Add(new CategoricalDataPoint(10, "6")); -barSeries2.DataPoints.Add(new CategoricalDataPoint(24, "7")); -barSeries2.DataPoints.Add(new CategoricalDataPoint(17, "8")); -barSeries2.DataPoints.Add(new CategoricalDataPoint(18, "9")); -barSeries2.DataPoints.Add(new CategoricalDataPoint(43, "10")); -radChartView1.Series.Add(barSeries2); -radChartView1.ShowToolTip = true; - -```` -````VB.NET -radChartView1.AreaType = ChartAreaType.Cartesian -Dim barSeries1 As New BarSeries -barSeries1.DataPoints.Add(New CategoricalDataPoint(10, "1")) -barSeries1.DataPoints.Add(New CategoricalDataPoint(4, "2")) -barSeries1.DataPoints.Add(New CategoricalDataPoint(23, "3")) -barSeries1.DataPoints.Add(New CategoricalDataPoint(11, "4")) -barSeries1.DataPoints.Add(New CategoricalDataPoint(15, "5")) -barSeries1.DataPoints.Add(New CategoricalDataPoint(10, "6")) -barSeries1.DataPoints.Add(New CategoricalDataPoint(4, "7")) -barSeries1.DataPoints.Add(New CategoricalDataPoint(7, "8")) -barSeries1.DataPoints.Add(New CategoricalDataPoint(11, "9")) -barSeries1.DataPoints.Add(New CategoricalDataPoint(15, "10")) -radChartView1.Series.Add(barSeries1) -Dim barSeries2 As New BarSeries() -barSeries2.DataPoints.Add(New CategoricalDataPoint(6, "1")) -barSeries2.DataPoints.Add(New CategoricalDataPoint(20, "2")) -barSeries2.DataPoints.Add(New CategoricalDataPoint(7, "3")) -barSeries2.DataPoints.Add(New CategoricalDataPoint(8, "4")) -barSeries2.DataPoints.Add(New CategoricalDataPoint(4, "5")) -barSeries2.DataPoints.Add(New CategoricalDataPoint(10, "6")) -barSeries2.DataPoints.Add(New CategoricalDataPoint(24, "7")) -barSeries2.DataPoints.Add(New CategoricalDataPoint(17, "8")) -barSeries2.DataPoints.Add(New CategoricalDataPoint(18, "9")) -barSeries2.DataPoints.Add(New CategoricalDataPoint(43, "10")) -radChartView1.Series.Add(barSeries2) -radChartView1.ShowToolTip = True - -```` - -{{endregion}} + + + + >caption Figure 1: ToolTip ![WinForms RadChartView ToolTip](images/chartview-features-tooltips001.png) @@ -122,46 +45,17 @@ The __ChartTooltipController__ also exposes a tooltip event. The event handler i #### Subscribe to Event -{{source=..\SamplesCS\ChartView\Features\ChartTooltip.cs region=DataPointTooltipTextNeeded}} -{{source=..\SamplesVB\ChartView\Features\ChartTooltip.vb region=DataPointTooltipTextNeeded}} -````C# -ChartTooltipController tooltipController = new ChartTooltipController(); -tooltipController.DataPointTooltipTextNeeded += tooltipController_DataPointTooltipTextNeeded; -this.radChartView1.Controllers.Add(tooltipController); + + -```` -````VB.NET -Dim tooltipController As New ChartTooltipController() -AddHandler tooltipController.DataPointTooltipTextNeeded, AddressOf tooltipController_DataPointTooltipTextNeeded -Me.RadChartView1.Controllers.Add(tooltipController) -```` - - - -{{endregion}} #### Change ToolTip`s Text -{{source=..\SamplesCS\ChartView\Features\ChartTooltip.cs region=ChangeText}} -{{source=..\SamplesVB\ChartView\Features\ChartTooltip.vb region=ChangeText}} -````C# -private void tooltipController_DataPointTooltipTextNeeded(object sender, DataPointTooltipTextNeededEventArgs e) -{ - e.Text = "My special tooltip!"; -} - -```` -````VB.NET -Private Sub TooltipController_DataPointTooltipTextNeeded(sender As Object, e As DataPointTooltipTextNeededEventArgs) - e.Text = "My special tooltip!" -End Sub - -```` - + + -{{endregion}} >caption Figure 2: Modified ToolTip ![WinForms RadChartView Modified ToolTip](images/chartview-features-tooltips002.png) diff --git a/controls/chartview/features/trackball.md b/controls/chartview/features/trackball.md index 145654503..0ff871a13 100644 --- a/controls/chartview/features/trackball.md +++ b/controls/chartview/features/trackball.md @@ -17,109 +17,28 @@ In order to utilize this behavior users simply have to add it to the chart's __C #### Add Controller -{{source=..\SamplesCS\ChartView\Features\Trackball.cs region=controller}} -{{source=..\SamplesVB\ChartView\Features\Trackball.vb region=controller}} + + -````C# -radChartView1.Controllers.Add(new ChartTrackballController()); - -```` -````VB.NET -RadChartView1.Controllers.Add(New ChartTrackballController()) - -```` -{{endregion}} The __ChartTrackballController__ will be added automatically if the __ShowTrackBall__ property of __RadChartView__ control is set to *true*: #### Set Property -{{source=..\SamplesCS\ChartView\Features\Trackball.cs region=showTrackBall}} -{{source=..\SamplesVB\ChartView\Features\Trackball.vb region=showTrackBall}} + + -````C# -radChartView1.ShowTrackBall = true; -```` -````VB.NET -RadChartView1.ShowTrackBall = True - -```` - -{{endregion}} A sample is shown below: #### Sample Setup -{{source=..\SamplesCS\ChartView\Features\Trackball.cs region=example}} -{{source=..\SamplesVB\ChartView\Features\Trackball.vb region=example}} + + -````C# -radChartView1.AreaType = ChartAreaType.Cartesian; -LineSeries lineSeries1 = new LineSeries(); -lineSeries1.Name = "X"; -lineSeries1.DataPoints.Add(new CategoricalDataPoint(10, "1")); -lineSeries1.DataPoints.Add(new CategoricalDataPoint(4, "2")); -lineSeries1.DataPoints.Add(new CategoricalDataPoint(23, "3")); -lineSeries1.DataPoints.Add(new CategoricalDataPoint(11, "4")); -lineSeries1.DataPoints.Add(new CategoricalDataPoint(15, "5")); -lineSeries1.DataPoints.Add(new CategoricalDataPoint(10, "6")); -lineSeries1.DataPoints.Add(new CategoricalDataPoint(4, "7")); -lineSeries1.DataPoints.Add(new CategoricalDataPoint(7, "8")); -lineSeries1.DataPoints.Add(new CategoricalDataPoint(11, "9")); -lineSeries1.DataPoints.Add(new CategoricalDataPoint(15, "10")); -radChartView1.Series.Add(lineSeries1); -LineSeries lineSeries2 = new LineSeries(); -lineSeries2.Name = "Y"; -lineSeries2.DataPoints.Add(new CategoricalDataPoint(6, "1")); -lineSeries2.DataPoints.Add(new CategoricalDataPoint(20, "2")); -lineSeries2.DataPoints.Add(new CategoricalDataPoint(7, "3")); -lineSeries2.DataPoints.Add(new CategoricalDataPoint(8, "4")); -lineSeries2.DataPoints.Add(new CategoricalDataPoint(4, "5")); -lineSeries2.DataPoints.Add(new CategoricalDataPoint(10, "6")); -lineSeries2.DataPoints.Add(new CategoricalDataPoint(24, "7")); -lineSeries2.DataPoints.Add(new CategoricalDataPoint(17, "8")); -lineSeries2.DataPoints.Add(new CategoricalDataPoint(18, "9")); -lineSeries2.DataPoints.Add(new CategoricalDataPoint(43, "10")); -radChartView1.Series.Add(lineSeries2); -radChartView1.ShowTrackBall = true; -```` -````VB.NET -RadChartView1.AreaType = ChartAreaType.Cartesian -Dim lineSeries1 As New LineSeries -lineSeries1.Name = "X" -lineSeries1.DataPoints.Add(New CategoricalDataPoint(10, "1")) -lineSeries1.DataPoints.Add(New CategoricalDataPoint(4, "2")) -lineSeries1.DataPoints.Add(New CategoricalDataPoint(23, "3")) -lineSeries1.DataPoints.Add(New CategoricalDataPoint(11, "4")) -lineSeries1.DataPoints.Add(New CategoricalDataPoint(15, "5")) -lineSeries1.DataPoints.Add(New CategoricalDataPoint(10, "6")) -lineSeries1.DataPoints.Add(New CategoricalDataPoint(4, "7")) -lineSeries1.DataPoints.Add(New CategoricalDataPoint(7, "8")) -lineSeries1.DataPoints.Add(New CategoricalDataPoint(11, "9")) -lineSeries1.DataPoints.Add(New CategoricalDataPoint(15, "10")) -RadChartView1.Series.Add(lineSeries1) -Dim lineSeries2 As New LineSeries -lineSeries1.Name = "Y" -lineSeries2.DataPoints.Add(New CategoricalDataPoint(6, "1")) -lineSeries2.DataPoints.Add(New CategoricalDataPoint(20, "2")) -lineSeries2.DataPoints.Add(New CategoricalDataPoint(7, "3")) -lineSeries2.DataPoints.Add(New CategoricalDataPoint(8, "4")) -lineSeries2.DataPoints.Add(New CategoricalDataPoint(4, "5")) -lineSeries2.DataPoints.Add(New CategoricalDataPoint(10, "6")) -lineSeries2.DataPoints.Add(New CategoricalDataPoint(24, "7")) -lineSeries2.DataPoints.Add(New CategoricalDataPoint(17, "8")) -lineSeries2.DataPoints.Add(New CategoricalDataPoint(18, "9")) -lineSeries2.DataPoints.Add(New CategoricalDataPoint(43, "10")) -RadChartView1.Series.Add(lineSeries2) -RadChartView1.ShowTrackBall = True - -```` - -{{endregion}} >caption Figure 1: Trackball ![WinForms RadChartView Trackball](images/chartview-features-trackball001.png) diff --git a/controls/chartview/null-values-support-.md b/controls/chartview/null-values-support-.md index 091f67ce1..bd84b7a9b 100644 --- a/controls/chartview/null-values-support-.md +++ b/controls/chartview/null-values-support-.md @@ -15,36 +15,10 @@ __RadChartView__ supports empty values in the series. In general empty values me #### Data Containing Null -{{source=..\SamplesCS\ChartView\Features\NullValues.cs region=NULLVALUES}} -{{source=..\SamplesVB\ChartView\Features\NullValues.vb region=NULLVALUES}} + + -````C# - -barSeries.ShowLabels = true; -barSeries.PointSize = new SizeF(15, 15); -barSeries.DataPoints.Add(new CategoricalDataPoint(10)); -barSeries.DataPoints.Add(new CategoricalDataPoint(5)); -barSeries.DataPoints.Add(new CategoricalDataPoint(40)); -barSeries.DataPoints.Add(new CategoricalDataPoint(null)); -barSeries.DataPoints.Add(new CategoricalDataPoint(11)); -barSeries.DataPoints.Add(new CategoricalDataPoint(20)); -radChartView1.Series.Add(barSeries); -```` -````VB.NET -barSeries.ShowLabels = True -barSeries.PointSize = New SizeF(15, 15) -barSeries.DataPoints.Add(New CategoricalDataPoint(10)) -barSeries.DataPoints.Add(New CategoricalDataPoint(5)) -barSeries.DataPoints.Add(New CategoricalDataPoint(40)) -barSeries.DataPoints.Add(New CategoricalDataPoint(New Nullable(Of Double)())) -barSeries.DataPoints.Add(New CategoricalDataPoint(11)) -barSeries.DataPoints.Add(New CategoricalDataPoint(20)) -radChartView1.Series.Add(barSeries) - -```` - -{{endregion}} >caption Figure 1: BarSeries With Null DataPoint ![WinForms RadChartView BarSeries With Null DataPoint](images/chartview-null-values-support001.png) diff --git a/controls/chartview/populating-with-data/binding-to-bindinglist.md b/controls/chartview/populating-with-data/binding-to-bindinglist.md index 9862eee26..897f511af 100644 --- a/controls/chartview/populating-with-data/binding-to-bindinglist.md +++ b/controls/chartview/populating-with-data/binding-to-bindinglist.md @@ -13,50 +13,10 @@ previous_url: chartview-databinding-binding-to-bindinglist BindingList is a generic list type, that provides additional control over list items, i.e. the items in __RadChartView__ can be easily edited, removed or added. BindingList also surfaces events that notify when the list has been changed. The example below creates a list of MyCustomObject, initializes the list and assigns it to the __BarSeries__ object in __RadChartView__. -{{source=..\SamplesCS\ChartView\DataBinding\ChartViewDataBindingToBindingList.cs region=binding}} -{{source=..\SamplesVB\ChartView\DataBinding\ChartViewDataBindingToBindingList.vb region=binding}} - -````C# -BindingList myList; -protected override void OnLoad(EventArgs e) -{ - base.OnLoad(e); - myList = new BindingList(); - myList = new BindingList(); - myList.Add(new MyCustomObject(1, "Outdoor")); - myList.Add(new MyCustomObject(8, "Hardware")); - myList.Add(new MyCustomObject(3, "Tools")); - myList.Add(new MyCustomObject(6, "Books")); - myList.Add(new MyCustomObject(2, "Appliances")); - BarSeries barSeria = new BarSeries(); - radChartView1.Series.Add(barSeria); - barSeria.DataSource = myList; - barSeria.ValueMember = "MyInt"; - barSeria.CategoryMember = "MyString"; -} - -```` -````VB.NET -Private myList As BindingList(Of MyCustomObject) -Public Sub New() - InitializeComponent() - myList = New BindingList(Of MyCustomObject)() - myList = New BindingList(Of MyCustomObject)() - myList.Add(New MyCustomObject(1, "Outdoor")) - myList.Add(New MyCustomObject(8, "Hardware")) - myList.Add(New MyCustomObject(3, "Tools")) - myList.Add(New MyCustomObject(6, "Books")) - myList.Add(New MyCustomObject(2, "Appliances")) - Dim barSeria As New BarSeries() - RadChartView1.Series.Add(barSeria) - barSeria.DataSource = myList - barSeria.ValueMember = "MyInt" - barSeria.CategoryMember = "MyString" -End Sub - -```` - -{{endregion}} + + + + >caption Figure 1: Binding to BindingList ![WinForms RadChartView Binding to BindingList](images/chartview-databinding-binding-to-bindinglist001.png) @@ -65,110 +25,22 @@ In order to allow __RadChartView__ to automatically reflect changes in the data #### Binding to BindingList -{{source=..\SamplesCS\ChartView\DataBinding\ChartViewDataBindingToBindingList.cs region=customClass}} -{{source=..\SamplesVB\ChartView\DataBinding\ChartViewDataBindingToBindingList.vb region=customClass}} - -````C# -public class MyCustomObject : INotifyPropertyChanged -{ - private int _myInt; - private string _myString; - public MyCustomObject(int myInt, string myString) - { - _myInt = myInt; - _myString = myString; - } - public int MyInt - { - get { return _myInt; } - set - { - _myInt = value; - OnPropertyChanged("MyInt"); - } - } - public string MyString - { - get { return _myString; } - set - { - _myString = value; - OnPropertyChanged("MyString"); - } - } - public event PropertyChangedEventHandler PropertyChanged; - protected virtual void OnPropertyChanged(string propertyName) - { - if (PropertyChanged != null) - { - PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); - } - } -} - -```` -````VB.NET -Public Class MyCustomObject - Implements INotifyPropertyChanged - Private _myInt As Integer - Private _myString As String - Public Sub New(myInt As Integer, myString As String) - _myInt = myInt - _myString = myString - End Sub - Public Property MyInt() As Integer - Get - Return _myInt - End Get - Set(value As Integer) - _myInt = value - OnPropertyChanged("MyInt") - End Set - End Property - Public Property MyString() As String - Get - Return _myString - End Get - Set(value As String) - _myString = value - OnPropertyChanged("MyString") - End Set - End Property - Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged - Protected Overridable Sub OnPropertyChanged(propertyName As String) - RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName)) - End Sub -End Class - -```` - -{{endregion}} + + -Once the interface is implemented and your collection implement IBindingList, just like the BindingList does, changes are automatically reflected. Here is a sample of adding a new record: -#### Add Item -{{source=..\SamplesCS\ChartView\DataBinding\ChartViewDataBindingToBindingList.cs region=addingNewRecord}} -{{source=..\SamplesVB\ChartView\DataBinding\ChartViewDataBindingToBindingList.vb region=addingNewRecord}} +Once the interface is implemented and your collection implement IBindingList, just like the BindingList does, changes are automatically reflected. Here is a sample of adding a new record: -````C# -private void radButton1_Click(object sender, EventArgs e) -{ - myList.Add(new MyCustomObject(10, "Plants")); -} +#### Add Item -```` -````VB.NET -Private Sub RadButton1_Click(sender As System.Object, e As System.EventArgs) Handles RadButton1.Click - myList.Add(New MyCustomObject(10, "Plants")) -End Sub + + -```` -{{endregion}} >caption Figure 2: Reflect Object Changes ![WinForms RadChartView Reflect Object Changes](images/chartview-databinding-binding-to-bindinglist002.png) diff --git a/controls/chartview/populating-with-data/binding-to-datatable.md b/controls/chartview/populating-with-data/binding-to-datatable.md index f9dff83eb..830a034f7 100644 --- a/controls/chartview/populating-with-data/binding-to-datatable.md +++ b/controls/chartview/populating-with-data/binding-to-datatable.md @@ -17,52 +17,10 @@ Here is a sample demonstrating how to bind а [LineSeries]({%slug winforms/chart #### Binding to DataTable -{{source=..\SamplesCS\ChartView\DataBinding\ChartViewDataBindingToDataTable.cs region=binding}} -{{source=..\SamplesVB\ChartView\DataBinding\ChartViewDataBindingToDataTable.vb region=binding}} + + -````C# -DataTable table; -protected override void OnLoad(EventArgs e) -{ - base.OnLoad(e); - table = new DataTable(); - table.Columns.Add("Value", typeof(double)); - table.Columns.Add("Name", typeof(string)); - table.Rows.Add(1, "John"); - table.Rows.Add(3, "Adam"); - table.Rows.Add(5, "Peter"); - table.Rows.Add(12, "Sam"); - table.Rows.Add(6, "Paul"); - LineSeries lineSeria = new LineSeries(); - radChartView1.Series.Add(lineSeria); - lineSeria.ValueMember = "Value"; - lineSeria.CategoryMember = "Name"; - lineSeria.DataSource = table; -} -```` -````VB.NET -Private table As DataTable -Protected Overrides Sub OnLoad(e As EventArgs) - MyBase.OnLoad(e) - table = New DataTable() - table.Columns.Add("Value", GetType(Double)) - table.Columns.Add("Name", GetType(String)) - table.Rows.Add(1, "John") - table.Rows.Add(3, "Adam") - table.Rows.Add(5, "Peter") - table.Rows.Add(12, "Sam") - table.Rows.Add(6, "Paul") - Dim lineSeria As New LineSeries() - RadChartView1.Series.Add(lineSeria) - lineSeria.ValueMember = "Value" - lineSeria.CategoryMember = "Name" - lineSeria.DataSource = table -End Sub - -```` - -{{endregion}} >caption Figure 1: Binding to DataTable ![WinForms RadChartView Binding to DataTable](images/chartview-databinding-binding-to-datatable001.png) diff --git a/controls/chartview/printing-support/printing.md b/controls/chartview/printing-support/printing.md index 72d1195bb..61c8a3084 100644 --- a/controls/chartview/printing-support/printing.md +++ b/controls/chartview/printing-support/printing.md @@ -1,78 +1,42 @@ ---- -title: Printing -page_title: Printing - WinForms ChartView Control -description: WinForms ChartView provides printing support, which allows you to print the chart content by using RadPrintDocument -slug: winforms/chartview-/printing-support/printing -tags: printing -published: True -position: 0 -previous_url: chartview-printing-support-printing ---- - -# Printing - -__RadChartView__ provides printing support, which allows you to print the chart content by using [RadPrintDocument]({%slug winforms/telerik-presentation-framework/printing-support/radprintdocument%}) You are able to print: - -* __Series within the chart__ - -* __Title__ - -* __Legend__ - -__RadChartView__ has two public methods available for printing - __Print__ and __PrintPreview__. The first method will directly send a print job to the default printer. This method has one overload available which can show a system PrintDialog with the available printers and their options. - -#### Direct Printing - -{{source=..\SamplesCS\ChartView\Printing\ChartViewPrinting.cs region=Print}} -{{source=..\SamplesVB\ChartView\Printing\ChartViewPrinting.vb region=Print}} -````C# -this.radChartView1.Print(); - -```` -````VB.NET -Me.RadChartView1.Print() - -```` - - - -{{endregion}} - -#### Print with Dialog - -{{source=..\SamplesCS\ChartView\Printing\ChartViewPrinting.cs region=PrintDialog}} -{{source=..\SamplesVB\ChartView\Printing\ChartViewPrinting.vb region=PrintDialog}} -````C# -this.radChartView1.Print(true); - -```` -````VB.NET -Me.RadChartView1.Print(True) - -```` - - - -{{endregion}} - -#### Print Preview - -{{source=..\SamplesCS\ChartView\Printing\ChartViewPrinting.cs region=PrintPreview}} -{{source=..\SamplesVB\ChartView\Printing\ChartViewPrinting.vb region=PrintPreview}} -````C# -this.radChartView1.PrintPreview(); - -```` -````VB.NET -Me.RadChartView1.PrintPreview() - -```` - - - -{{endregion}} - -# See Also - -* [Series Types]({%slug winforms/chartview-/series-types%}) -* [Axes]({%slug winforms/chartview-/axes%}) +--- +title: Printing +page_title: Printing - WinForms ChartView Control +description: WinForms ChartView provides printing support, which allows you to print the chart content by using RadPrintDocument +slug: winforms/chartview-/printing-support/printing +tags: printing +published: True +position: 0 +previous_url: chartview-printing-support-printing +--- + +# Printing + +__RadChartView__ provides printing support, which allows you to print the chart content by using [RadPrintDocument]({%slug winforms/telerik-presentation-framework/printing-support/radprintdocument%}) You are able to print: + +* __Series within the chart__ + +* __Title__ + +* __Legend__ + +__RadChartView__ has two public methods available for printing - __Print__ and __PrintPreview__. The first method will directly send a print job to the default printer. This method has one overload available which can show a system PrintDialog with the available printers and their options. + +#### Direct Printing + + + + +#### Print with Dialog + + + + +#### Print Preview + + + + +# See Also + +* [Series Types]({%slug winforms/chartview-/series-types%}) +* [Axes]({%slug winforms/chartview-/axes%}) diff --git a/controls/chartview/series-types/area.md b/controls/chartview/series-types/area.md index 76b18b44c..4779e397d 100644 --- a/controls/chartview/series-types/area.md +++ b/controls/chartview/series-types/area.md @@ -15,41 +15,10 @@ As a derivative of __Categorical__ series, __AreaSeries__ plot their data points #### Initial Setup -{{source=..\SamplesCS\ChartView\Series\AreaSeriesForm.cs region=area}} -{{source=..\SamplesVB\ChartView\Series\AreaSeriesForm.vb region=area}} - -````C# -AreaSeries areaSeries = new AreaSeries(); -areaSeries.DataPoints.Add(new CategoricalDataPoint(13, "Jan")); -areaSeries.DataPoints.Add(new CategoricalDataPoint(20, "Apr")); -areaSeries.DataPoints.Add(new CategoricalDataPoint(15, "Jul")); -areaSeries.DataPoints.Add(new CategoricalDataPoint(16, "Oct")); -this.radChartView1.Series.Add(areaSeries); -AreaSeries areaSeries2 = new AreaSeries(); -areaSeries2.DataPoints.Add(new CategoricalDataPoint(15, "Jan")); -areaSeries2.DataPoints.Add(new CategoricalDataPoint(25, "Apr")); -areaSeries2.DataPoints.Add(new CategoricalDataPoint(27, "Jul")); -areaSeries2.DataPoints.Add(new CategoricalDataPoint(18, "Oct")); -this.radChartView1.Series.Add(areaSeries2); - -```` -````VB.NET -Dim series As New AreaSeries() -series.DataPoints.Add(New CategoricalDataPoint(13, "Jan")) -series.DataPoints.Add(New CategoricalDataPoint(20, "Apr")) -series.DataPoints.Add(New CategoricalDataPoint(15, "Jul")) -series.DataPoints.Add(New CategoricalDataPoint(16, "Oct")) -Me.RadChartView1.Series.Add(series) -Dim series2 As New AreaSeries() -series2.DataPoints.Add(New CategoricalDataPoint(15, "Jan")) -series2.DataPoints.Add(New CategoricalDataPoint(25, "Apr")) -series2.DataPoints.Add(New CategoricalDataPoint(27, "Jul")) -series2.DataPoints.Add(New CategoricalDataPoint(18, "Oct")) -Me.RadChartView1.Series.Add(series2) - -```` - -{{endregion}} + + + + >caption Figure 1: Initial Setup ![WinForms RadChartView Area Initial Setup](images/chartview-series-types-area001.png) diff --git a/controls/chartview/series-types/bar.md b/controls/chartview/series-types/bar.md index ecb2b43b8..26f58a8c7 100644 --- a/controls/chartview/series-types/bar.md +++ b/controls/chartview/series-types/bar.md @@ -15,49 +15,10 @@ __BarSeries__ are used to visualize data points as bar blocks where the height o #### Initial Setup -{{source=..\SamplesCS\ChartView\Series\BarSeriesForm.cs region=bar}} -{{source=..\SamplesVB\ChartView\Series\BarSeriesForm.vb region=bar}} - -````C# -BarSeries barSeries = new BarSeries("Performance", "RepresentativeName"); -barSeries.Name = "Q1"; -barSeries.DataPoints.Add(new CategoricalDataPoint(177, "Harley")); -barSeries.DataPoints.Add(new CategoricalDataPoint(128, "White")); -barSeries.DataPoints.Add(new CategoricalDataPoint(143, "Smith")); -barSeries.DataPoints.Add(new CategoricalDataPoint(111, "Jones")); -barSeries.DataPoints.Add(new CategoricalDataPoint(118, "Marshall")); -this.radChartView1.Series.Add(barSeries); -BarSeries barSeries2 = new BarSeries("Performance", "RepresentativeName"); -barSeries2.Name = "Q2"; -barSeries2.DataPoints.Add(new CategoricalDataPoint(153, "Harley")); -barSeries2.DataPoints.Add(new CategoricalDataPoint(141, "White")); -barSeries2.DataPoints.Add(new CategoricalDataPoint(130, "Smith")); -barSeries2.DataPoints.Add(new CategoricalDataPoint(88, "Jones")); -barSeries2.DataPoints.Add(new CategoricalDataPoint(109, "Marshall")); -this.radChartView1.Series.Add(barSeries2); - -```` -````VB.NET -Dim barSeries As New Telerik.WinControls.UI.BarSeries("Performance", "RepresentativeName") -barSeries.Name = "Q1" -barSeries.DataPoints.Add(New CategoricalDataPoint(177, "Harley")) -barSeries.DataPoints.Add(New CategoricalDataPoint(128, "White")) -barSeries.DataPoints.Add(New CategoricalDataPoint(143, "Smith")) -barSeries.DataPoints.Add(New CategoricalDataPoint(111, "Jones")) -barSeries.DataPoints.Add(New CategoricalDataPoint(118, "Marshall")) -Me.RadChartView1.Series.Add(barSeries) -Dim barSeries2 As New Telerik.WinControls.UI.BarSeries("Performance", "RepresentativeName") -barSeries2.Name = "Q2" -barSeries2.DataPoints.Add(New CategoricalDataPoint(153, "Harley")) -barSeries2.DataPoints.Add(New CategoricalDataPoint(141, "White")) -barSeries2.DataPoints.Add(New CategoricalDataPoint(130, "Smith")) -barSeries2.DataPoints.Add(New CategoricalDataPoint(88, "Jones")) -barSeries2.DataPoints.Add(New CategoricalDataPoint(109, "Marshall")) -Me.RadChartView1.Series.Add(barSeries2) - -```` - -{{endregion}} + + + + >caption Figure 1: Initial Setup ![WinForms RadChartView Bar Initial Setup](images/chartview-series-types-bar001.png) @@ -80,19 +41,10 @@ __BarSeries__ could be customized using the following properties: #### Setting GapLength -{{source=..\SamplesCS\ChartView\Series\BarSeriesForm.cs region=gapLength}} -{{source=..\SamplesVB\ChartView\Series\BarSeriesForm.vb region=gapLength}} - -````C# -(barSeries.HorizontalAxis as CategoricalAxis).GapLength = 0.75; - -```` -````VB.NET -TryCast(barSeries.HorizontalAxis, CategoricalAxis).GapLength = 0.75 + + -```` -{{endregion}} The following image demonstrates how different values of the __GapLength__ property change the __BarSeries__: diff --git a/controls/chartview/series-types/bezier.md b/controls/chartview/series-types/bezier.md index 986647c40..8e6dc73f2 100644 --- a/controls/chartview/series-types/bezier.md +++ b/controls/chartview/series-types/bezier.md @@ -15,41 +15,10 @@ The Bezier chart displays a series of points on a curved line. Two "control poi #### Initial Setup -{{source=..\SamplesCS\ChartView\Series\BezierSeriesForm.cs region=Bezier}} -{{source=..\SamplesVB\ChartView\Series\BezierSeriesForm.vb region=Bezier}} + + -````C# -BezierSeries bezier = new BezierSeries(); -bezier.DataPoints.Add(new BezierDataPoint(45, 30, 0, 0, 120, 140)); -bezier.DataPoints.Add(new BezierDataPoint(5, 23, 0, 0, 95, 110)); -this.radChartView1.Series.Add(bezier); -BezierSeries bezier2 = new BezierSeries(); -bezier2.DataPoints.Add(new BezierDataPoint(167, 173, 20, 15, 158, 190)); -bezier2.DataPoints.Add(new BezierDataPoint(85, 25, 42, 75, 85, 97)); -this.radChartView1.Series.Add(bezier2); -BezierSeries bezier3 = new BezierSeries(); -bezier3.DataPoints.Add(new BezierDataPoint(20, 150, 0, 0, 20, 250)); -bezier3.DataPoints.Add(new BezierDataPoint(80, 150, 80, 250, 0, 0)); -this.radChartView1.Series.Add(bezier3); -```` -````VB.NET -Dim bezier As New BezierSeries() -bezier.DataPoints.Add(New BezierDataPoint(45, 30, 0, 0, 120, 140)) -bezier.DataPoints.Add(New BezierDataPoint(5, 23, 0, 0, 95, 110)) -Me.RadChartView1.Series.Add(bezier) -Dim bezier2 As New BezierSeries() -bezier2.DataPoints.Add(New BezierDataPoint(167, 173, 20, 15, 158, 190)) -bezier2.DataPoints.Add(New BezierDataPoint(85, 25, 42, 75, 85, 97)) -Me.RadChartView1.Series.Add(bezier2) -Dim bezier3 As New BezierSeries() -bezier3.DataPoints.Add(New BezierDataPoint(20, 150, 0, 0, 20, 250)) -bezier3.DataPoints.Add(New BezierDataPoint(80, 150, 80, 250, 0, 0)) -Me.RadChartView1.Series.Add(bezier3) - -```` - -{{endregion}} >caption Figure 1: Initial Setup ![WinForms RadChartView Bezier Initial Setup](images/chartview-series-types-bezier001.png) diff --git a/controls/chartview/series-types/bubble.md b/controls/chartview/series-types/bubble.md index aee5bfcb8..244731f1f 100644 --- a/controls/chartview/series-types/bubble.md +++ b/controls/chartview/series-types/bubble.md @@ -15,51 +15,10 @@ __BubbleSeries__ are used to visualize data points as points with coordinates an #### Initial Setup -{{source=..\SamplesCS\ChartView\Series\BubbleSeriesForm.cs region=Bubble}} -{{source=..\SamplesVB\ChartView\Series\BubbleSeriesForm.vb region=Bubble}} + + -````C# - -BubbleSeries bubbleSeries = new BubbleSeries(); -bubbleSeries.Name = "Q1"; -bubbleSeries.DataPoints.Add(new BubbleDataPoint(15, 19,3)); -bubbleSeries.DataPoints.Add(new BubbleDataPoint(18, 10,15)); -bubbleSeries.DataPoints.Add(new BubbleDataPoint(13, 15,8)); -bubbleSeries.DataPoints.Add(new BubbleDataPoint(10, 8,4)); -bubbleSeries.DataPoints.Add(new BubbleDataPoint(5, 12,3)); -this.radChartView1.Series.Add(bubbleSeries); - -BubbleSeries bubbleSeries2 = new BubbleSeries(); -bubbleSeries2.Name = "Q2"; -bubbleSeries2.DataPoints.Add(new BubbleDataPoint(20, 20,4)); -bubbleSeries2.DataPoints.Add(new BubbleDataPoint(15, 10,3)); -bubbleSeries2.DataPoints.Add(new BubbleDataPoint(7, 6,6)); -bubbleSeries2.DataPoints.Add(new BubbleDataPoint(18, 22,2)); -bubbleSeries2.DataPoints.Add(new BubbleDataPoint(10, 10,4)); -this.radChartView1.Series.Add(bubbleSeries2); - -```` -````VB.NET -Dim bubbleSeries As New BubbleSeries() -bubbleSeries.Name = "Q1" -bubbleSeries.DataPoints.Add(New BubbleDataPoint(15, 19, 3)) -bubbleSeries.DataPoints.Add(New BubbleDataPoint(18, 10, 15)) -bubbleSeries.DataPoints.Add(New BubbleDataPoint(13, 15, 8)) -bubbleSeries.DataPoints.Add(New BubbleDataPoint(10, 8, 4)) -bubbleSeries.DataPoints.Add(New BubbleDataPoint(5, 12, 3)) -Me.RadChartView1.Series.Add(bubbleSeries) -Dim bubbleSeries2 As New BubbleSeries() -bubbleSeries2.Name = "Q2" -bubbleSeries2.DataPoints.Add(New BubbleDataPoint(20, 20, 4)) -bubbleSeries2.DataPoints.Add(New BubbleDataPoint(15, 10, 3)) -bubbleSeries2.DataPoints.Add(New BubbleDataPoint(7, 6, 6)) -bubbleSeries2.DataPoints.Add(New BubbleDataPoint(18, 22, 2)) -bubbleSeries2.DataPoints.Add(New BubbleDataPoint(10, 10, 4)) -Me.RadChartView1.Series.Add(bubbleSeries2) - -```` -{{endregion}} >caption Figure 1: Initial Setup ![WinForms RadChartView Bubble Initial Setup](images/chartview-series-types-bubble001.png) diff --git a/controls/chartview/series-types/donut.md b/controls/chartview/series-types/donut.md index 15bc31212..e7cecfbeb 100644 --- a/controls/chartview/series-types/donut.md +++ b/controls/chartview/series-types/donut.md @@ -15,33 +15,10 @@ Similarly to Pie series, Donut series do not use axes. They visualize each data #### Initial Setup -{{source=..\SamplesCS\ChartView\Series\DonutSeriesForm.cs region=donut}} -{{source=..\SamplesVB\ChartView\Series\DonutSeriesForm.vb region=donut}} - -````C# -this.radChartView1.AreaType = ChartAreaType.Pie; -DonutSeries series = new DonutSeries(); -series.DataPoints.Add(new PieDataPoint(50, "Germany")); -series.DataPoints.Add(new PieDataPoint(70, "United States")); -series.DataPoints.Add(new PieDataPoint(40, "France")); -series.DataPoints.Add(new PieDataPoint(25, "United Kingdom")); -series.ShowLabels = true; -this.radChartView1.Series.Add(series); - -```` -````VB.NET -Me.RadChartView1.AreaType = ChartAreaType.Pie -Dim series As New DonutSeries() -series.DataPoints.Add(New PieDataPoint(50, "Germany")) -series.DataPoints.Add(New PieDataPoint(70, "United States")) -series.DataPoints.Add(New PieDataPoint(40, "France")) -series.DataPoints.Add(New PieDataPoint(25, "United Kingdom")) -series.ShowLabels = True -Me.RadChartView1.Series.Add(series) - -```` - -{{endregion}} + + + + >caption Figure 1: Initial Setup ![WinForms RadChartView Donut Initial Setup](images/chartview-series-types-donut001.png) @@ -52,21 +29,10 @@ DonutSeries can be customized using the following properties: #### AngleRange -{{source=..\SamplesCS\ChartView\Series\DonutSeriesForm.cs region=donutAngleRange}} -{{source=..\SamplesVB\ChartView\Series\DonutSeriesForm.vb region=donutAngleRange}} - -````C# -AngleRange range = new AngleRange(270, 300); -series.Range = range; + + -```` -````VB.NET -Dim range As New AngleRange(270, 300) -series.Range = range -```` - -{{endregion}} >caption Figure 2: AngleRange ![WinForms RadChartView Donut AngleRange](images/chartview-series-types-donut002.png) @@ -81,26 +47,10 @@ Additionally, DonutSeries allows offsetting a pie segment from the rest of the s #### Donut Offset -{{source=..\SamplesCS\ChartView\Series\DonutSeriesForm.cs region=donutOffset}} -{{source=..\SamplesVB\ChartView\Series\DonutSeriesForm.vb region=donutOffset}} - -````C# -PieDataPoint point = series.DataPoints[3] as PieDataPoint; -if (point != null) -{ - point.OffsetFromCenter = 0.1; -} - -```` -````VB.NET -Dim point As PieDataPoint = TryCast(series.DataPoints(3), PieDataPoint) -If point IsNot Nothing Then - point.OffsetFromCenter = 0.1 -End If + + -```` -{{endregion}} >caption Figure 3: Donut Offset ![WinForms RadChartView Donut Offset](images/chartview-series-types-donut003.png) diff --git a/controls/chartview/series-types/fastline.md b/controls/chartview/series-types/fastline.md index 16f24941b..271034e01 100644 --- a/controls/chartview/series-types/fastline.md +++ b/controls/chartview/series-types/fastline.md @@ -17,36 +17,10 @@ The following code snipped shows how you can add __FastLineSeries__ to __RadChar #### Initial Setup -{{source=..\SamplesCS\ChartView\Series\LineSeriesForm.cs region=fast}} -{{source=..\SamplesVB\ChartView\Series\LineSeriesForm.vb region=fast}} - -````C# -Random rnd = new Random(); -FastLineSeries series = new FastLineSeries(); -FastLineSeries series1 = new FastLineSeries(); -for (int i = 0; i < 50; i++) -{ - series.DataPoints.Add(new CategoricalDataPoint(rnd.Next(50, 100), i)); - series1.DataPoints.Add(new CategoricalDataPoint(rnd.Next(50), i)); -} -radChartView1.Series.Add(series); -radChartView1.Series.Add(series1); - -```` -````VB.NET -Dim rnd As New Random() -Dim series As New FastLineSeries() -Dim series1 As New FastLineSeries() -For i As Integer = 0 To 49 - series.DataPoints.Add(New CategoricalDataPoint(rnd.Next(50, 100), i)) - series1.DataPoints.Add(New CategoricalDataPoint(rnd.Next(50), i)) -Next i -RadChartView1.Series.Add(series) -RadChartView1.Series.Add(series1) - -```` - -{{endregion}} + + + + >caption Figure 1: Initial Setup diff --git a/controls/chartview/series-types/funnel.md b/controls/chartview/series-types/funnel.md index 3bbcaad67..a0fb7b791 100644 --- a/controls/chartview/series-types/funnel.md +++ b/controls/chartview/series-types/funnel.md @@ -30,37 +30,10 @@ The following example shows how you can add funnel series in code. #### Initial Setup -{{source=..\SamplesCS\ChartView\Series\FunnelSeriesCode.cs region=funnel}} -{{source=..\SamplesVB\ChartView\Series\FunnelSeriesCode.vb region=funnel}} - -````C# -radChartView1.AreaType = Telerik.WinControls.UI.ChartAreaType.Funnel; -FunnelSeries funnelSeries = new FunnelSeries(); -funnelSeries.DataPoints.Add(new FunnelDataPoint(5442, "Visited the website")); -funnelSeries.DataPoints.Add(new FunnelDataPoint(1519, "Watched the demos")); -funnelSeries.DataPoints.Add(new FunnelDataPoint(1131, "Downloaded a trial")); -funnelSeries.DataPoints.Add(new FunnelDataPoint(811, "Purchased a license")); -funnelSeries.DataPoints.Add(new FunnelDataPoint(704, "Renewed a license")); -funnelSeries.ShowLabels = true; -radChartView1.ShowLegend = true; -radChartView1.Series.Add(funnelSeries); - -```` -````VB.NET -radChartView1.AreaType = Telerik.WinControls.UI.ChartAreaType.Funnel -Dim funnelSeries As New FunnelSeries() -funnelSeries.DataPoints.Add(New FunnelDataPoint(5442, "Visited the website")) -funnelSeries.DataPoints.Add(New FunnelDataPoint(1519, "Watched the demos")) -funnelSeries.DataPoints.Add(New FunnelDataPoint(1131, "Downloaded a trial")) -funnelSeries.DataPoints.Add(New FunnelDataPoint(811, "Purchased a license")) -funnelSeries.DataPoints.Add(New FunnelDataPoint(704, "Renewed a license")) -funnelSeries.ShowLabels = True -radChartView1.ShowLegend = True -radChartView1.Series.Add(funnelSeries) - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/chartview/series-types/hlc.md b/controls/chartview/series-types/hlc.md index e2588dd5d..900b07a2a 100644 --- a/controls/chartview/series-types/hlc.md +++ b/controls/chartview/series-types/hlc.md @@ -23,29 +23,10 @@ Here is how to setup the __Hlc__ series: #### Initial Setup -{{source=..\SamplesCS\ChartView\Series\HlcSeriesForm.cs region=hlc}} -{{source=..\SamplesVB\ChartView\Series\HlcSeriesForm.vb region=hlc}} - -````C# - HlcSeries hlcSeries = new HlcSeries(); - hlcSeries.DataPoints.Add(new HlcDataPoint(11, 7, 8, DateTime.Now)); - hlcSeries.DataPoints.Add(new HlcDataPoint(9, 5, 9, DateTime.Now.AddDays(1))); - hlcSeries.DataPoints.Add(new HlcDataPoint(12, 9, 10, DateTime.Now.AddDays(2))); - hlcSeries.DataPoints.Add(new HlcDataPoint(10, 6, 9, DateTime.Now.AddDays(3))); - this.radChartView1.Series.Add(hlcSeries); - -```` -````VB.NET -Dim hlcSeries As New HlcSeries() -hlcSeries.DataPoints.Add(New HlcDataPoint(11, 7, 8, DateTime.Now)) -hlcSeries.DataPoints.Add(New HlcDataPoint(9, 5, 9, DateTime.Now.AddDays(1))) -hlcSeries.DataPoints.Add(New HlcDataPoint(12, 9, 10, DateTime.Now.AddDays(2))) -hlcSeries.DataPoints.Add(New HlcDataPoint(10, 6, 9, DateTime.Now.AddDays(3))) -Me.RadChartView1.Series.Add(hlcSeries) - -```` - -{{endregion}} + + + + >caption Figure 1: Initial Setup ![WinForms RadChartView Hlc Initial Setup](images/chartview-series-types-hlc002.png) diff --git a/controls/chartview/series-types/indicators/custom-indicators.md b/controls/chartview/series-types/indicators/custom-indicators.md index b27b939bb..88e6ff8b9 100644 --- a/controls/chartview/series-types/indicators/custom-indicators.md +++ b/controls/chartview/series-types/indicators/custom-indicators.md @@ -29,36 +29,10 @@ Now that we have all variables from the formula above, let us start constructing #### DI Indicator -{{source=..\SamplesCS\ChartView\Series\Indicators\CustomIndicatorsDIForm.cs region=DIIndicator}} -{{source=..\SamplesVB\ChartView\Series\Indicators\CustomIndicatorsDIForm.vb region=DIIndicator}} - -````C# -public class DisparityIndexIndicator: ExponentialMovingAverageIndicator -{ - public override double GetProcessedValue(int currentIndex) - { - double close = (this.DataPoints[currentIndex] as IndicatorValueDataPoint).BaseValue; - double ema = base.GetProcessedValue(currentIndex); - double result = ((close - ema) / ema) * 100; - return result; - } -} - -```` -````VB.NET -Public Class DisparityIndexIndicator - Inherits ExponentialMovingAverageIndicator - Public Overrides Function GetProcessedValue(currentIndex As Integer) As Double - Dim close As Double = TryCast(Me.DataPoints(currentIndex), IndicatorValueDataPoint).BaseValue - Dim ema As Double = MyBase.GetProcessedValue(currentIndex) - Dim result As Double = ((close - ema) / ema) * 100 - Return result - End Function -End Class - -```` - -{{endregion}} + + + + Now let’s create a new __DI__ indicator instance and add it to our __RadChartView__. In order to do that, however, we will need some sample data. The snippet below creates a __BindingList__ of __ClosingPriceObjects__. Each __ClosingPriceObject__ is a simple structure that holds the closing price and date it was registered. The class implements __INotifyPropertyChanged__ in order to make sure that any changes in the object's data will be reflected in the indicator’s values. @@ -67,152 +41,24 @@ Now let’s create a new __DI__ indicator instance and add it to our __RadChartV #### Custom Object -{{source=..\SamplesCS\ChartView\Series\Indicators\CustomIndicatorsDIForm.cs region=CustomObject}} -{{source=..\SamplesVB\ChartView\Series\Indicators\CustomIndicatorsDIForm.vb region=CustomObject}} -````C# -public class ClosingPriceObject : INotifyPropertyChanged -{ - private double close; - private DateTime date; - public ClosingPriceObject(double close, DateTime date) - { - this.close = close; - this.date = date; - } - public double Close - { - get - { - return this.close; - } - set - { - this.close = value; - OnNotifyPropertyChanged("Close"); - } - } - public DateTime Date - { - get - { - return this.date; - } - set - { - this.date = value; - OnNotifyPropertyChanged("Date"); - } - } - public event PropertyChangedEventHandler PropertyChanged; - public void OnNotifyPropertyChanged(string propertyName) - { - PropertyChangedEventHandler handler = PropertyChanged; - if (handler != null) - { - this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); - } - } -} - -```` -````VB.NET -Public Class ClosingPriceObject - Implements INotifyPropertyChanged - Private m_close As Double - Private m_date As DateTime - Public Property Close() As Double - Get - Return Me.m_close - End Get - Set(value As Double) - Me.m_close = value - OnNotifyPropertyChanged("Close") - End Set - End Property - Public Property [Date]() As DateTime - Get - Return Me.m_date - End Get - Set(value As DateTime) - Me.m_date = value - OnNotifyPropertyChanged("Date") - End Set - End Property - Public Sub New(close As Double, [date] As DateTime) - Me.Close = close - Me.[Date] = [date] - End Sub - Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged - Public Sub OnNotifyPropertyChanged(propertyName As String) - RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName)) - End Sub -End Class - -```` - -{{endregion}} + + + + #### Create Data -{{source=..\SamplesCS\ChartView\Series\Indicators\CustomIndicatorsDIForm.cs region=CreateData}} -{{source=..\SamplesVB\ChartView\Series\Indicators\CustomIndicatorsDIForm.vb region=CreateData}} -````C# -BindingList dataSource = new BindingList(); -dataSource.Add(new ClosingPriceObject(4, DateTime.Now)); -dataSource.Add(new ClosingPriceObject(7, DateTime.Now.AddDays(1))); -dataSource.Add(new ClosingPriceObject(4, DateTime.Now.AddDays(2))); -dataSource.Add(new ClosingPriceObject(2, DateTime.Now.AddDays(3))); -dataSource.Add(new ClosingPriceObject(6, DateTime.Now.AddDays(4))); -dataSource.Add(new ClosingPriceObject(7, DateTime.Now.AddDays(5))); -dataSource.Add(new ClosingPriceObject(4, DateTime.Now.AddDays(6))); -dataSource.Add(new ClosingPriceObject(3, DateTime.Now.AddDays(7))); -dataSource.Add(new ClosingPriceObject(7, DateTime.Now.AddDays(8))); - -```` -````VB.NET -Dim dataSource As New BindingList(Of ClosingPriceObject)() -dataSource.Add(New ClosingPriceObject(4, DateTime.Now)) -dataSource.Add(New ClosingPriceObject(7, DateTime.Now.AddDays(1))) -dataSource.Add(New ClosingPriceObject(4, DateTime.Now.AddDays(2))) -dataSource.Add(New ClosingPriceObject(2, DateTime.Now.AddDays(3))) -dataSource.Add(New ClosingPriceObject(6, DateTime.Now.AddDays(4))) -dataSource.Add(New ClosingPriceObject(7, DateTime.Now.AddDays(5))) -dataSource.Add(New ClosingPriceObject(4, DateTime.Now.AddDays(6))) -dataSource.Add(New ClosingPriceObject(3, DateTime.Now.AddDays(7))) -dataSource.Add(New ClosingPriceObject(7, DateTime.Now.AddDays(8))) - -```` -{{endregion}} + + + + #### SetupDIIndicator -{{source=..\SamplesCS\ChartView\Series\Indicators\CustomIndicatorsDIForm.cs region=SetupDIIndicator}} -{{source=..\SamplesVB\ChartView\Series\Indicators\CustomIndicatorsDIForm.vb region=SetupDIIndicator}} - -````C# -DisparityIndexIndicator indicator = new DisparityIndexIndicator(); -indicator.ValueMember = "Close"; -indicator.CategoryMember = "Date"; -indicator.DataSource = dataSource; -indicator.Period = 5; -indicator.BorderColor = Color.Red; -indicator.PointSize = SizeF.Empty; -this.radChartView1.Series.Add(indicator); - -```` -````VB.NET -Dim indicator As New DisparityIndexIndicator -indicator.Period = 5 -indicator.ValueMember = "Close" -indicator.CategoryMember = "Date" -indicator.DataSource = dataSource -indicator.BorderColor = Color.Red -indicator.PointSize = SizeF.Empty -Me.RadChartView1.Series.Add(indicator) - -```` - -{{endregion}} + + + + ## Moving Average Envelopes (MAE) @@ -233,311 +79,37 @@ Because __Moving Average Envelopes__ requires a property that sets the bands per #### Base Class -{{source=..\SamplesCS\ChartView\Series\Indicators\CustomIndicatorsMAForm.cs region=MAEBase}} -{{source=..\SamplesVB\ChartView\Series\Indicators\CustomIndicatorsMAForm.vb region=MAEBase}} - -````C# -public class MovingAverageEnvelopeBase : MovingAverageIndicator -{ - public static readonly RadProperty PercentProperty = RadProperty.Register("Percent", typeof(double), typeof(MovingAverageEnvelopeBase), new RadPropertyMetadata(0d)); - public double Percent - { - get - { - return (double)GetValue(PercentProperty); - } - set - { - SetValue(PercentProperty, value); - } - } -} - -```` -````VB.NET -Public Class MovingAverageEnvelopeBase - Inherits MovingAverageIndicator - Public Shared ReadOnly PercentProperty As RadProperty = RadProperty.Register("Percent", GetType(Double), GetType(MovingAverageEnvelopeBase), New RadPropertyMetadata(0.0)) - Public Property Percent() As Double - Get - Return CDbl(GetValue(PercentProperty)) - End Get - Set(value As Double) - SetValue(PercentProperty, value) - End Set - End Property -End Class - -```` - -{{endregion}} + + + + Let’s now create two classes: __MovingAverageEnvelopeChild__, containing the lower band’s logic and __MovingAverageEnvelopeIndicator__, holding the upper band’s formula. They should both inherit __MovingAverageEnvelopeBase__ class. Here are the steps that set up the __MovingAverageEnvelopeChild__ class, first, make sure the __MovingAverageEnvelopeChild__ class implements the __IChildIndicator__ interface. Further, add a field that holds the parent indicator and use it when implementing the __OwnerIndicator__ property. Also, override the __GetProcessedValue__ method and use the __Percent__ property to calculate the correct lower envelope value. Here is a sample snippet of the __MovingAverageEnvelopeChild__: #### Child Class -{{source=..\SamplesCS\ChartView\Series\Indicators\CustomIndicatorsMAForm.cs region=MAEChild}} -{{source=..\SamplesVB\ChartView\Series\Indicators\CustomIndicatorsMAForm.vb region=MAEChild}} - -````C# -public class MovingAverageEnvelopeChild : MovingAverageEnvelopeBase, IChildIndicator -{ - MovingAverageEnvelopeIndicator owner; - public MovingAverageEnvelopeChild(MovingAverageEnvelopeIndicator owner) - { - this.owner = owner; - } - public IndicatorBase OwnerIndicator - { - get { return this.owner; } - } - public override double GetProcessedValue(int currentIndex) - { - double movingAverage = base.GetProcessedValue(currentIndex); - double result = movingAverage - (movingAverage * this.Percent); - return result; - } -} - -```` -````VB.NET -Public Class MovingAverageEnvelopeChild - Inherits MovingAverageEnvelopeBase - Implements IChildIndicator - Private owner As MovingAverageEnvelopeIndicator - Public Sub New(owner As MovingAverageEnvelopeIndicator) - Me.owner = owner - End Sub - Public ReadOnly Property OwnerIndicator() As IndicatorBase Implements IChildIndicator.OwnerIndicator - Get - Return Me.owner - End Get - End Property - Public Overrides Function GetProcessedValue(currentIndex As Integer) As Double - Dim movingAverage As Double = MyBase.GetProcessedValue(currentIndex) - Dim result As Double = movingAverage - (movingAverage * Me.Percent) - Return result - End Function -End Class - -```` - -{{endregion}} + + + + The __MovingAverageEnvelopeIndicator__ class requires a bit more steps that the indicator child. First, make the class implement the __IParentIndicator__ interface. Create a field of type __MovingAverageEnvelopeChild__, initialize it in the indicator’s constructor, and return it when implementing the __ChildIndicator__ property. To make sure the inner indicator will be attached and detached, override both __OnAttached__ and __OnDettached__ methods and manually attach and detach the __ChildIndicator__. To ensure the inner indicator will be bound properly, override the __OnNotifyPropertyChanged__ method and pass any important property values to the child indicator. Here is a sample snippet: #### MAE Indicator -{{source=..\SamplesCS\ChartView\Series\Indicators\CustomIndicatorsMAForm.cs region=MAEIndicator}} -{{source=..\SamplesVB\ChartView\Series\Indicators\CustomIndicatorsMAForm.vb region=MAEIndicator}} - -````C# -public class MovingAverageEnvelopeIndicator : MovingAverageEnvelopeBase, IParentIndicator -{ - MovingAverageEnvelopeChild childIndicator; - public MovingAverageEnvelopeIndicator() - { - childIndicator = new MovingAverageEnvelopeChild(this); - } - public IndicatorBase ChildIndicator - { - get { return this.childIndicator; } - } - public override double GetProcessedValue(int currentIndex) - { - double movingAverage = base.GetProcessedValue(currentIndex); - double result = movingAverage + (movingAverage * this.Percent); - return result; - } - protected override void OnAttached(UIChartElement parent) - { - base.OnAttached(parent); - this.ChildIndicator.Attach(parent); - } - protected override void OnDettached() - { - base.OnDettached(); - this.ChildIndicator.Dettach(); - } - protected override void OnNotifyPropertyChanged(System.ComponentModel.PropertyChangedEventArgs e) - { - base.OnNotifyPropertyChanged(e); - if (e.PropertyName == "DataSource") - { - this.childIndicator.DataSource = this.DataSource; - } - if (e.PropertyName == "CategoryMember") - { - this.childIndicator.CategoryMember = this.CategoryMember; - } - if (e.PropertyName == "ValueMember") - { - this.childIndicator.ValueMember = this.ValueMember; - } - if (e.PropertyName == "Period") - { - this.childIndicator.Period = this.Period; - } - if (e.PropertyName == "Percent") - { - this.childIndicator.Percent = this.Percent; - } - } -} - -```` -````VB.NET -Public Class MovingAverageEnvelopeIndicator - Inherits MovingAverageEnvelopeBase - Implements IParentIndicator - Private m_childIndicator As MovingAverageEnvelopeChild - Public Sub New() - m_childIndicator = New MovingAverageEnvelopeChild(Me) - End Sub - Public ReadOnly Property ChildIndicator() As IndicatorBase Implements IParentIndicator.ChildIndicator - Get - Return Me.m_childIndicator - End Get - End Property - Public Overrides Function GetProcessedValue(currentIndex As Integer) As Double - Dim movingAverage As Double = MyBase.GetProcessedValue(currentIndex) - Dim result As Double = movingAverage + (movingAverage * Me.Percent) - Return result - End Function - Protected Overrides Sub OnAttached(parent As UIChartElement) - MyBase.OnAttached(parent) - Me.ChildIndicator.Attach(parent) - End Sub - Protected Overrides Sub OnDettached() - MyBase.OnDettached() - Me.ChildIndicator.Dettach() - End Sub - Protected Overrides Sub OnNotifyPropertyChanged(e As System.ComponentModel.PropertyChangedEventArgs) - MyBase.OnNotifyPropertyChanged(e) - If e.PropertyName = "DataSource" Then - Me.m_childIndicator.DataSource = Me.DataSource - End If - If e.PropertyName = "CategoryMember" Then - Me.m_childIndicator.CategoryMember = Me.CategoryMember - End If - If e.PropertyName = "ValueMember" Then - Me.m_childIndicator.ValueMember = Me.ValueMember - End If - If e.PropertyName = "Period" Then - Me.m_childIndicator.Period = Me.Period - End If - If e.PropertyName = "Percent" Then - Me.m_childIndicator.Percent = Me.Percent - End If - End Sub -End Class - -```` - -{{endregion}} + + + + Now that we have the __MovingAverageEnvelopeIndicator__ ready, let us set up some sample data and see how it looks like. The following snippet uses __BindingList__ of custom __OhlcObjects__. For the sake of presentation, this example adds __OhlcSeries__ and a simple __Moving Average indicator__ next to the __MovingAverageEnvelopeIndicator__. #### Create and Setup Indicator -{{source=..\SamplesCS\ChartView\Series\Indicators\CustomIndicatorsMAForm.cs region=CreateDataAndSetupIndicator}} -{{source=..\SamplesVB\ChartView\Series\Indicators\CustomIndicatorsMAForm.vb region=CreateDataAndSetupIndicator}} -````C# -BindingList dataSource = new BindingList(); -dataSource.Add(new OhlcObject(17, 18, 12, 14, DateTime.Now)); -dataSource.Add(new OhlcObject(16, 17, 11, 17, DateTime.Now.AddDays(1))); -dataSource.Add(new OhlcObject(18, 19, 12, 14, DateTime.Now.AddDays(2))); -dataSource.Add(new OhlcObject(15, 15, 12, 12, DateTime.Now.AddDays(3))); -dataSource.Add(new OhlcObject(15, 18, 15, 16, DateTime.Now.AddDays(4))); -dataSource.Add(new OhlcObject(15, 17, 11, 17, DateTime.Now.AddDays(5))); -dataSource.Add(new OhlcObject(12, 15, 12, 14, DateTime.Now.AddDays(6))); -dataSource.Add(new OhlcObject(15, 15, 12, 13, DateTime.Now.AddDays(7))); -dataSource.Add(new OhlcObject(15, 18, 15, 17, DateTime.Now.AddDays(8))); -dataSource.Add(new OhlcObject(15, 17, 11, 17, DateTime.Now.AddDays(9))); -dataSource.Add(new OhlcObject(12, 15, 12, 14, DateTime.Now.AddDays(10))); -dataSource.Add(new OhlcObject(17, 18, 12, 14, DateTime.Now.AddDays(11))); -dataSource.Add(new OhlcObject(15, 18, 15, 17, DateTime.Now.AddDays(12))); -dataSource.Add(new OhlcObject(15, 18, 15, 16, DateTime.Now.AddDays(13))); -dataSource.Add(new OhlcObject(17, 18, 12, 14, DateTime.Now.AddDays(14))); -MovingAverageIndicator maIndicator = new MovingAverageIndicator(); -maIndicator.ValueMember = "Close"; -maIndicator.CategoryMember = "Date"; -maIndicator.DataSource = dataSource; -maIndicator.Period = 5; -maIndicator.BorderColor = Color.Red; -maIndicator.PointSize = SizeF.Empty; -this.radChartView1.Series.Add(maIndicator); -MovingAverageEnvelopeIndicator envelopeIndicator = new MovingAverageEnvelopeIndicator(); -envelopeIndicator.ValueMember = "Close"; -envelopeIndicator.CategoryMember = "Date"; -envelopeIndicator.DataSource = dataSource; -envelopeIndicator.Period = 5; -envelopeIndicator.BorderColor = Color.Green; -envelopeIndicator.ChildIndicator.BorderColor = Color.Black; -envelopeIndicator.PointSize = SizeF.Empty; -envelopeIndicator.Percent = 0.25; -this.radChartView1.Series.Add(envelopeIndicator); -CandlestickSeries series = new CandlestickSeries(); -series.OpenValueMember = "Open"; -series.CloseValueMember = "Close"; -series.HighValueMember = "High"; -series.LowValueMember = "Low"; -series.CategoryMember = "Date"; -series.DataSource = dataSource; -this.radChartView1.Series.Add(series); -this.radChartView1.Axes[0].LabelFormat = "{0:dd}"; -(this.radChartView1.Axes[1] as LinearAxis).Minimum = 5; - -```` -````VB.NET -Dim dataSource As New BindingList(Of OhlcObject)() -dataSource.Add(New OhlcObject(17, 18, 12, 14, DateTime.Now)) -dataSource.Add(New OhlcObject(16, 17, 11, 17, DateTime.Now.AddDays(1))) -dataSource.Add(New OhlcObject(18, 19, 12, 14, DateTime.Now.AddDays(2))) -dataSource.Add(New OhlcObject(15, 15, 12, 12, DateTime.Now.AddDays(3))) -dataSource.Add(New OhlcObject(15, 18, 15, 16, DateTime.Now.AddDays(4))) -dataSource.Add(New OhlcObject(15, 17, 11, 17, DateTime.Now.AddDays(5))) -dataSource.Add(New OhlcObject(12, 15, 12, 14, DateTime.Now.AddDays(6))) -dataSource.Add(New OhlcObject(15, 15, 12, 13, DateTime.Now.AddDays(7))) -dataSource.Add(New OhlcObject(15, 18, 15, 17, DateTime.Now.AddDays(8))) -dataSource.Add(New OhlcObject(15, 17, 11, 17, DateTime.Now.AddDays(9))) -dataSource.Add(New OhlcObject(12, 15, 12, 14, DateTime.Now.AddDays(10))) -dataSource.Add(New OhlcObject(17, 18, 12, 14, DateTime.Now.AddDays(11))) -dataSource.Add(New OhlcObject(15, 18, 15, 17, DateTime.Now.AddDays(12))) -dataSource.Add(New OhlcObject(15, 18, 15, 16, DateTime.Now.AddDays(13))) -dataSource.Add(New OhlcObject(17, 18, 12, 14, DateTime.Now.AddDays(14))) -Dim maIndicator As New MovingAverageIndicator() -maIndicator.ValueMember = "Close" -maIndicator.CategoryMember = "Date" -maIndicator.DataSource = dataSource -maIndicator.Period = 5 -maIndicator.BorderColor = Color.Red -maIndicator.PointSize = SizeF.Empty -Me.RadChartView1.Series.Add(maIndicator) -Dim envelopeIndicator As New MovingAverageEnvelopeIndicator() -envelopeIndicator.ValueMember = "Close" -envelopeIndicator.CategoryMember = "Date" -envelopeIndicator.DataSource = dataSource -envelopeIndicator.Period = 5 -envelopeIndicator.BorderColor = Color.Green -envelopeIndicator.ChildIndicator.BorderColor = Color.Black -envelopeIndicator.PointSize = SizeF.Empty -envelopeIndicator.Percent = 0.25 -Me.RadChartView1.Series.Add(envelopeIndicator) -Dim series As New CandlestickSeries() -series.OpenValueMember = "Open" -series.CloseValueMember = "Close" -series.HighValueMember = "High" -series.LowValueMember = "Low" -series.CategoryMember = "Date" -series.DataSource = dataSource -Me.RadChartView1.Series.Add(series) -Me.RadChartView1.Axes(0).LabelFormat = "{0:dd}" -TryCast(Me.RadChartView1.Axes(1), LinearAxis).Minimum = 5 - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/chartview/series-types/indicators/indicators.md b/controls/chartview/series-types/indicators/indicators.md index 9f88702d3..76cc7c592 100644 --- a/controls/chartview/series-types/indicators/indicators.md +++ b/controls/chartview/series-types/indicators/indicators.md @@ -17,96 +17,21 @@ Let's start with creating some meaningful data that will be used by both indicat #### Initial Setup -{{source=..\SamplesCS\ChartView\Series\Indicators\IndicatorsOverviewForm.cs region=IndicatorsCommonData}} -{{source=..\SamplesVB\ChartView\Series\Indicators\IndicatorsOverviewForm.vb region=IndicatorsCommonData}} - -````C# -//Create data -BindingList dataSource = new BindingList(); -dataSource.Add(new OhlcObject(7, 8, 2, 4, DateTime.Now)); -dataSource.Add(new OhlcObject(6, 7, 1, 7, DateTime.Now.AddDays(1))); -dataSource.Add(new OhlcObject(8, 9, 2, 4, DateTime.Now.AddDays(2))); -dataSource.Add(new OhlcObject(5, 5, 2, 2, DateTime.Now.AddDays(3))); -dataSource.Add(new OhlcObject(5, 8, 5, 6, DateTime.Now.AddDays(4))); -dataSource.Add(new OhlcObject(5, 7, 1, 7, DateTime.Now.AddDays(5))); -dataSource.Add(new OhlcObject(2, 5, 2, 4, DateTime.Now.AddDays(6))); -dataSource.Add(new OhlcObject(5, 5, 2, 3, DateTime.Now.AddDays(7))); -dataSource.Add(new OhlcObject(5, 8, 5, 7, DateTime.Now.AddDays(8))); - -```` -````VB.NET -'Create data -Dim dataSource As New BindingList(Of OhlcObject)() -dataSource.Add(New OhlcObject(7, 8, 2, 4, DateTime.Now)) -dataSource.Add(New OhlcObject(6, 7, 1, 7, DateTime.Now.AddDays(1))) -dataSource.Add(New OhlcObject(8, 9, 2, 4, DateTime.Now.AddDays(2))) -dataSource.Add(New OhlcObject(5, 5, 2, 2, DateTime.Now.AddDays(3))) -dataSource.Add(New OhlcObject(5, 8, 5, 6, DateTime.Now.AddDays(4))) -dataSource.Add(New OhlcObject(5, 7, 1, 7, DateTime.Now.AddDays(5))) -dataSource.Add(New OhlcObject(2, 5, 2, 4, DateTime.Now.AddDays(6))) -dataSource.Add(New OhlcObject(5, 5, 2, 3, DateTime.Now.AddDays(7))) -dataSource.Add(New OhlcObject(5, 8, 5, 7, DateTime.Now.AddDays(8))) - -```` - -{{endregion}} - - + + + + + ## Moving Average Indicator Each value of MA is the average of past __n__ days, where __n__ is a parameter defined by the __Period__ property. #### Average Indicator -{{source=..\SamplesCS\ChartView\Series\Indicators\IndicatorsOverviewForm.cs region=ma}} -{{source=..\SamplesVB\ChartView\Series\Indicators\IndicatorsOverviewForm.vb region=ma}} - -````C# -//Create and add Moving Average indicator -MovingAverageIndicator maIndicator = new MovingAverageIndicator(); -maIndicator.ValueMember = "Close"; -maIndicator.CategoryMember = "Date"; -maIndicator.DataSource = dataSource; -maIndicator.Period = 2; -maIndicator.BorderColor = Color.Red; -maIndicator.PointSize = SizeF.Empty; -this.radChartView1.Series.Add(maIndicator); -//Create and add Ohlc series -OhlcSeries series = new OhlcSeries(); -series.OpenValueMember = "Open"; -series.CloseValueMember = "Close"; -series.HighValueMember = "High"; -series.LowValueMember = "Low"; -series.CategoryMember = "Date"; -series.DataSource = dataSource; -series.BorderColor = Color.Black; -this.radChartView1.Series.Add(series); - -```` -````VB.NET -'Create and add Moving Average indicator -Dim maIndicator As New MovingAverageIndicator() -maIndicator.ValueMember = "Close" -maIndicator.CategoryMember = "Date" -maIndicator.DataSource = dataSource -maIndicator.Period = 2 -maIndicator.BorderColor = Color.Red -maIndicator.PointSize = SizeF.Empty -Me.RadChartView1.Series.Add(maIndicator) -'Create and add Ohlc series -Dim series As New OhlcSeries() -series.OpenValueMember = "Open" -series.CloseValueMember = "Close" -series.HighValueMember = "High" -series.LowValueMember = "Low" -series.CategoryMember = "Date" -series.DataSource = dataSource -series.BorderColor = Color.Black -Me.RadChartView1.Series.Add(series) - -```` - -{{endregion}} + + + + >caption Figure 1: Average Indicator ![WinForms RadChartView Average Indicator](images/chartview-series-types-indicators001.png) @@ -125,59 +50,10 @@ The indicator consists of two bands that aim to provide a relative definition of #### Bollinger Indicator -{{source=..\SamplesCS\ChartView\Series\Indicators\IndicatorsOverviewForm.cs region=Bands}} -{{source=..\SamplesVB\ChartView\Series\Indicators\IndicatorsOverviewForm.vb region=Bands}} - -````C# -//Create and add Bollinger Bands indicator -BollingerBandsIndicator bollIndicator = new BollingerBandsIndicator(); -bollIndicator.ValueMember = "Close"; -bollIndicator.CategoryMember = "Date"; -bollIndicator.DataSource = dataSource; -bollIndicator.StandardDeviations = 2; -bollIndicator.Period = 5; -bollIndicator.InnerIndicator.BorderColor = Color.DarkGray; -bollIndicator.BorderColor = Color.Red; -bollIndicator.PointSize = SizeF.Empty; -this.radChartView1.Series.Add(bollIndicator); -//Create and add Ohlc series -OhlcSeries ohlcSeries = new OhlcSeries(); -ohlcSeries.OpenValueMember = "Open"; -ohlcSeries.CloseValueMember = "Close"; -ohlcSeries.HighValueMember = "High"; -ohlcSeries.LowValueMember = "Low"; -ohlcSeries.CategoryMember = "Date"; -ohlcSeries.DataSource = dataSource; -ohlcSeries.BorderColor = Color.Black; -this.radChartView1.Series.Add(ohlcSeries); - -```` -````VB.NET -'Create and add Bollinger Bands indicator -Dim bollIndicator As New BollingerBandsIndicator() -bollIndicator.ValueMember = "Close" -bollIndicator.CategoryMember = "Date" -bollIndicator.DataSource = dataSource -bollIndicator.StandardDeviations = 2 -bollIndicator.Period = 5 -bollIndicator.InnerIndicator.BorderColor = Color.DarkGray -bollIndicator.BorderColor = Color.Red -bollIndicator.PointSize = SizeF.Empty -Me.RadChartView1.Series.Add(bollIndicator) -'Create and add Ohlc series -Dim ohlcSeries As New OhlcSeries() -ohlcSeries.OpenValueMember = "Open" -ohlcSeries.CloseValueMember = "Close" -ohlcSeries.HighValueMember = "High" -ohlcSeries.LowValueMember = "Low" -ohlcSeries.CategoryMember = "Date" -ohlcSeries.DataSource = dataSource -ohlcSeries.BorderColor = Color.Black -Me.RadChartView1.Series.Add(ohlcSeries) - -```` - -{{endregion}} + + + + >caption Figure 2: Bollinger Indicator ![WinForms RadChartView Bollinger Indicator](images/chartview-series-types-indicators002.png) diff --git a/controls/chartview/series-types/line.md b/controls/chartview/series-types/line.md index 4fea674b1..52643b635 100644 --- a/controls/chartview/series-types/line.md +++ b/controls/chartview/series-types/line.md @@ -15,41 +15,9 @@ __LineSeries__ plot their Categorical data points on Cartesian Area using one ca #### Initial Setup -{{source=..\SamplesCS\ChartView\Series\LineSeriesForm.cs region=line}} -{{source=..\SamplesVB\ChartView\Series\LineSeriesForm.vb region=line}} - -````C# -LineSeries lineSeries = new LineSeries(); -lineSeries.DataPoints.Add(new CategoricalDataPoint(20, "Jan")); -lineSeries.DataPoints.Add(new CategoricalDataPoint(22, "Apr")); -lineSeries.DataPoints.Add(new CategoricalDataPoint(12, "Jul")); -lineSeries.DataPoints.Add(new CategoricalDataPoint(19, "Oct")); -this.radChartView1.Series.Add(lineSeries); -LineSeries lineSeries2 = new LineSeries(); -lineSeries2.DataPoints.Add(new CategoricalDataPoint(18, "Jan")); -lineSeries2.DataPoints.Add(new CategoricalDataPoint(15, "Apr")); -lineSeries2.DataPoints.Add(new CategoricalDataPoint(17, "Jul")); -lineSeries2.DataPoints.Add(new CategoricalDataPoint(22, "Oct")); -this.radChartView1.Series.Add(lineSeries2); - -```` -````VB.NET -Dim lineSeries As New LineSeries() -lineSeries.DataPoints.Add(New CategoricalDataPoint(20, "Jan")) -lineSeries.DataPoints.Add(New CategoricalDataPoint(22, "Apr")) -lineSeries.DataPoints.Add(New CategoricalDataPoint(12, "Jul")) -lineSeries.DataPoints.Add(New CategoricalDataPoint(19, "Oct")) -Me.RadChartView1.Series.Add(lineSeries) -Dim lineSeries2 As New LineSeries() -lineSeries2.DataPoints.Add(New CategoricalDataPoint(18, "Jan")) -lineSeries2.DataPoints.Add(New CategoricalDataPoint(15, "Apr")) -lineSeries2.DataPoints.Add(New CategoricalDataPoint(17, "Jul")) -lineSeries2.DataPoints.Add(New CategoricalDataPoint(22, "Oct")) -Me.RadChartView1.Series.Add(lineSeries2) - -```` - -{{endregion}} + + + >caption Figure 1: Initial Setup diff --git a/controls/chartview/series-types/ohlc-and-candlestick.md b/controls/chartview/series-types/ohlc-and-candlestick.md index c824c68bd..1f2176d58 100644 --- a/controls/chartview/series-types/ohlc-and-candlestick.md +++ b/controls/chartview/series-types/ohlc-and-candlestick.md @@ -24,29 +24,10 @@ Here is how to setup Ohlc series: #### Initial Setup OhlcSeries -{{source=..\SamplesCS\ChartView\Series\OhlcAndCandlestick\OhlcSeriesForm.cs region=ohlc}} -{{source=..\SamplesVB\ChartView\Series\OhlcAndCandlestick\OhlcSeriesForm.vb region=ohlc}} - -````C# -OhlcSeries ohlcSeries = new OhlcSeries(); -ohlcSeries.DataPoints.Add(new OhlcDataPoint(10, 11, 7, 8, DateTime.Now)); -ohlcSeries.DataPoints.Add(new OhlcDataPoint(8, 9, 5, 9, DateTime.Now.AddDays(1))); -ohlcSeries.DataPoints.Add(new OhlcDataPoint(12, 12, 9, 10, DateTime.Now.AddDays(2))); -ohlcSeries.DataPoints.Add(new OhlcDataPoint(7, 10, 6, 9, DateTime.Now.AddDays(3))); -this.radChartView1.Series.Add(ohlcSeries); - -```` -````VB.NET -Dim ohlcSeries As New OhlcSeries() -ohlcSeries.DataPoints.Add(New OhlcDataPoint(10, 11, 7, 8, DateTime.Now)) -ohlcSeries.DataPoints.Add(New OhlcDataPoint(8, 9, 5, 9, DateTime.Now.AddDays(1))) -ohlcSeries.DataPoints.Add(New OhlcDataPoint(12, 12, 9, 10, DateTime.Now.AddDays(2))) -ohlcSeries.DataPoints.Add(New OhlcDataPoint(7, 10, 6, 9, DateTime.Now.AddDays(3))) -Me.RadChartView1.Series.Add(ohlcSeries) - -```` - -{{endregion}} + + + + >caption Figure 1: Initial Setup OhlcSeries ![WinForms RadChartView Initial Setup OhlcSeries](images/chartview-series-types-ohlc-and-candlestick003.png) @@ -55,29 +36,10 @@ Here is how to setup Candlestick series: #### Initial Setup CandlestickSeries -{{source=..\SamplesCS\ChartView\Series\OhlcAndCandlestick\OhlcSeriesForm.cs region=candlestick}} -{{source=..\SamplesVB\ChartView\Series\OhlcAndCandlestick\OhlcSeriesForm.vb region=candlestick}} - -````C# -CandlestickSeries candlestickSeries = new CandlestickSeries(); -candlestickSeries.DataPoints.Add(new OhlcDataPoint(10, 11, 7, 8, DateTime.Now)); -candlestickSeries.DataPoints.Add(new OhlcDataPoint(8, 9, 5, 9, DateTime.Now.AddDays(1))); -candlestickSeries.DataPoints.Add(new OhlcDataPoint(12, 12, 9, 10, DateTime.Now.AddDays(2))); -candlestickSeries.DataPoints.Add(new OhlcDataPoint(7, 10, 6, 9, DateTime.Now.AddDays(3))); -this.radChartView1.Series.Add(candlestickSeries); - -```` -````VB.NET -Dim candlestickSeries As New CandlestickSeries() -candlestickSeries.DataPoints.Add(New OhlcDataPoint(10, 11, 7, 8, DateTime.Now)) -candlestickSeries.DataPoints.Add(New OhlcDataPoint(8, 9, 5, 9, DateTime.Now.AddDays(1))) -candlestickSeries.DataPoints.Add(New OhlcDataPoint(12, 12, 9, 10, DateTime.Now.AddDays(2))) -candlestickSeries.DataPoints.Add(New OhlcDataPoint(7, 10, 6, 9, DateTime.Now.AddDays(3))) -Me.RadChartView1.Series.Add(candlestickSeries) - -```` - -{{endregion}} + + + + >caption Figure 2: Initial Setup CandlestickSeries ![WinForms RadChartView Initial Setup CandlestickSeries](images/chartview-series-types-ohlc-and-candlestick004.png) diff --git a/controls/chartview/series-types/pie.md b/controls/chartview/series-types/pie.md index 02b385dbc..477ad8de3 100644 --- a/controls/chartview/series-types/pie.md +++ b/controls/chartview/series-types/pie.md @@ -15,33 +15,10 @@ Unlike all other series, __PieSeries__ do not require axes. They visualize each #### Initial Setup -{{source=..\SamplesCS\ChartView\Series\PieSeriesForm.cs region=pie}} -{{source=..\SamplesVB\ChartView\Series\PieSeriesForm.vb region=pie}} - -````C# -this.radChartView1.AreaType = ChartAreaType.Pie; -PieSeries series = new PieSeries(); -series.DataPoints.Add(new PieDataPoint(50, "Germany")); -series.DataPoints.Add(new PieDataPoint(70, "United States")); -series.DataPoints.Add(new PieDataPoint(40, "France")); -series.DataPoints.Add(new PieDataPoint(25, "United Kingdom")); -series.ShowLabels = true; -this.radChartView1.Series.Add(series); - -```` -````VB.NET -Me.RadChartView1.AreaType = ChartAreaType.Pie -Dim series As New PieSeries() -series.DataPoints.Add(New PieDataPoint(50, "Germany")) -series.DataPoints.Add(New PieDataPoint(70, "United States")) -series.DataPoints.Add(New PieDataPoint(40, "France")) -series.DataPoints.Add(New PieDataPoint(25, "United Kingdom")) -series.ShowLabels = True -Me.RadChartView1.Series.Add(series) - -```` - -{{endregion}} + + + + >caption Figure 1: Initial Setup ![WinForms RadChartView Pie Initial Setup](images/chartview-series-types-pie001.png) @@ -50,21 +27,10 @@ __PieSeries__ can be customized using the following properties: * __Range:__ The property consists of two parameters StartAngle and SweepAngle. StartAngle sets the angle in degrees from which the drawing of the pie segments will begin. Note that pie slices are always rendered in clockwise direction. SweepAngle determines if the chart will appear as a full circle or a partial circle.The snippet below illustrates PieSeries how to set the Range property: -{{source=..\SamplesCS\ChartView\Series\PieSeriesForm.cs region=angleRange}} -{{source=..\SamplesVB\ChartView\Series\PieSeriesForm.vb region=angleRange}} - -````C# -AngleRange range = new AngleRange(270, 300); -series.Range = range; + + -```` -````VB.NET -Dim range As New AngleRange(270, 300) -series.Range = range -```` - -{{endregion}} >caption Figure 2: Angle Range ![WinForms RadChartView Pie Angle Range](images/chartview-series-types-pie002.png) @@ -81,26 +47,10 @@ Additionally, PieSeries allows offsetting a pie segment from the rest of the sli #### Offset Segment -{{source=..\SamplesCS\ChartView\Series\PieSeriesForm.cs region=offset}} -{{source=..\SamplesVB\ChartView\Series\PieSeriesForm.vb region=offset}} - -````C# -PieDataPoint point = series.DataPoints[3] as PieDataPoint; -if (point != null) -{ - point.OffsetFromCenter = 0.1; -} - -```` -````VB.NET -Dim point As PieDataPoint = TryCast(series.DataPoints(3), PieDataPoint) -If point IsNot Nothing Then - point.OffsetFromCenter = 0.1 -End If + + -```` -{{endregion}} >caption Figure 3: Offset Segment ![WinForms RadChartView Pie Offset Segment](images/chartview-series-types-pie003.png) diff --git a/controls/chartview/series-types/polar.md b/controls/chartview/series-types/polar.md index 097305642..39acc79bd 100644 --- a/controls/chartview/series-types/polar.md +++ b/controls/chartview/series-types/polar.md @@ -15,155 +15,30 @@ __Polar series__ consists of a group of classes that plot data in radial plot ar #### Initial Setup -{{source=..\SamplesCS\ChartView\Series\PolarSeriesForm.cs region=polarPointSeries}} -{{source=..\SamplesVB\ChartView\Series\PolarSeriesForm.vb region=polarPointSeries}} - -````C# - -this.radChartView1.AreaType = ChartAreaType.Polar; -PolarPointSeries polarPointSeries = new PolarPointSeries(); - -PolarDataPoint dataPoint = new PolarDataPoint(); -dataPoint.Value = 40; -dataPoint.Angle = 200; -polarPointSeries.DataPoints.Add(dataPoint); - -dataPoint = new PolarDataPoint(); -dataPoint.Value = 35; -dataPoint.Angle = 50; -polarPointSeries.DataPoints.Add(dataPoint); - -dataPoint = new PolarDataPoint(); -dataPoint.Value = 55; -dataPoint.Angle = 320; -polarPointSeries.DataPoints.Add(dataPoint); - -this.radChartView1.Series.Add(polarPointSeries); - -```` -````VB.NET -Me.RadChartView1.AreaType = ChartAreaType.Polar -Dim polarPointSeries As New PolarPointSeries() -Dim dataPoint As New PolarDataPoint() -dataPoint.Value = 40 -dataPoint.Angle = 200 -polarPointSeries.DataPoints.Add(dataPoint) -dataPoint = New PolarDataPoint() -dataPoint.Value = 35 -dataPoint.Angle = 50 -polarPointSeries.DataPoints.Add(dataPoint) -dataPoint = New PolarDataPoint() -dataPoint.Value = 55 -dataPoint.Angle = 320 -polarPointSeries.DataPoints.Add(dataPoint) -Me.RadChartView1.Series.Add(polarPointSeries) - -```` - -{{endregion}} + + + + >caption Figure 1: Initial Setup ![WinForms RadChartView Polar Initial Setup](images/chartview-series-types-polar001.png) #### PolarLineSeries -{{source=..\SamplesCS\ChartView\Series\PolarSeriesForm.cs region=polarLineSeries}} -{{source=..\SamplesVB\ChartView\Series\PolarSeriesForm.vb region=polarLineSeries}} - -````C# -this.radChartView1.AreaType = ChartAreaType.Polar; -PolarLineSeries polarLineSeries = new PolarLineSeries(); - -PolarDataPoint point = new PolarDataPoint(); -point.Value = 35; -point.Angle = 50; -polarLineSeries.DataPoints.Add(point); - -point = new PolarDataPoint(); -point.Value = 40; -point.Angle = 200; -polarLineSeries.DataPoints.Add(point); - -point = new PolarDataPoint(); -point.Value = 55; -point.Angle = 320; -polarLineSeries.DataPoints.Add(point); -this.radChartView1.Series.Add(polarLineSeries); - -```` -````VB.NET -Me.RadChartView1.AreaType = ChartAreaType.Polar -Dim polarLineSeries As New PolarLineSeries() -Dim point As New PolarDataPoint() -point.Value = 35 -point.Angle = 50 -polarLineSeries.DataPoints.Add(point) -point = New PolarDataPoint() -point.Value = 40 -point.Angle = 200 -polarLineSeries.DataPoints.Add(point) -point = New PolarDataPoint() -point.Value = 55 -point.Angle = 320 -polarLineSeries.DataPoints.Add(point) -Me.RadChartView1.Series.Add(polarLineSeries) - -```` - -{{endregion}} + + + + >caption Figure 2: PolarLineSeries ![WinForms RadChartView Polar Line Series](images/chartview-series-types-polar002.png) #### PolarAreaSeries -{{source=..\SamplesCS\ChartView\Series\PolarSeriesForm.cs region=polarAreaSeries}} -{{source=..\SamplesVB\ChartView\Series\PolarSeriesForm.vb region=polarAreaSeries}} - -````C# - -this.radChartView1.AreaType = ChartAreaType.Polar; -PolarAreaSeries polarAreaSeries = new PolarAreaSeries(); -PolarDataPoint polarPoint = new PolarDataPoint(); -polarPoint.Value = 35; -polarPoint.Angle = 50; -polarAreaSeries.DataPoints.Add(polarPoint); -polarPoint = new PolarDataPoint(); -polarPoint.Value = 40; -polarPoint.Angle = 200; -polarAreaSeries.DataPoints.Add(polarPoint); -polarPoint = new PolarDataPoint(); -polarPoint.Value = 55; -polarPoint.Angle = 320; -polarAreaSeries.DataPoints.Add(polarPoint); - -this.radChartView1.Series.Add(polarAreaSeries); - -```` -````VB.NET -Me.RadChartView1.AreaType = ChartAreaType.Polar -Dim polarAreaSeries As New PolarAreaSeries() -Dim polarPoint As New PolarDataPoint() -polarPoint.Value = 35 -polarPoint.Angle = 50 -polarAreaSeries.DataPoints.Add(polarPoint) -polarPoint = New PolarDataPoint() -polarPoint.Value = 25 -polarPoint.Angle = 130 -polarAreaSeries.DataPoints.Add(polarPoint) -polarPoint = New PolarDataPoint() -polarPoint.Value = 40 -polarPoint.Angle = 200 -polarAreaSeries.DataPoints.Add(polarPoint) -polarPoint = New PolarDataPoint() -polarPoint.Value = 55 -polarPoint.Angle = 320 -polarAreaSeries.DataPoints.Add(polarPoint) -Me.RadChartView1.Series.Add(polarAreaSeries) - -```` - -{{endregion}} + + + + >caption Figure 3: PolarAreaSeries ![WinForms RadChartView Polar Area Series](images/chartview-series-types-polar003.png) diff --git a/controls/chartview/series-types/radar-column.md b/controls/chartview/series-types/radar-column.md index a81f5e81b..98f8d3868 100644 --- a/controls/chartview/series-types/radar-column.md +++ b/controls/chartview/series-types/radar-column.md @@ -20,75 +20,17 @@ Radar Column series visualize data in radial columns starting from one center po The following example shows how you can add RadarColumnSeries to RadChartView: -{{source=..\SamplesCS\ChartView\Series\RadarSeriesForm.cs region=radarColumnSeries}} -{{source=..\SamplesVB\ChartView\Series\RadarSeriesForm.vb region=radarColumnSeries}} -````C# -List categories = new List { - "Df", "Pr", "A", "C", "D", "E", - "Th", "Ri", "Ni", "B", "F", - "Se", "Mn", "Cu", "Zn", "K", "P", - "Fe", "Ca", "Na", "Ch", "Sf" }; -List values = new List() { - 5, 1, 1, 5, 0, 1, - 1, 2, 1, 2, 1, 0, - 0, 2, 1, 0, 3, 1, - 1, 1, 0, 0, }; -RadarColumnSeries series = new RadarColumnSeries(); -for (int i = 0; i < categories.Count; i++) -{ - series.DataPoints.Add(new CategoricalDataPoint(values[i], categories[i])); -} -radChartView1.AreaType = ChartAreaType.Polar; -radChartView1.Series.Add(series); - -```` -````VB.NET -Dim categories As New List(Of String) From {"Df", "Pr", "A", "C", "D", "E", "Th", "Ri", "Ni", "B", "F", "Se", "Mn", "Cu", "Zn", "K", "P", "Fe", "Ca", "Na", "Ch", "Sf"} -Dim values As New List(Of Integer)() From {5, 1, 1, 5, 0, 1, 1, 2, 1, 2, 1, 0, 0, 2, 1, 0, 3, 1, 1, 1, 0, 0} -Dim series As New RadarColumnSeries() -For i As Integer = 0 To categories.Count - 1 - series.DataPoints.Add(New CategoricalDataPoint(values(i), categories(i))) -Next i -RadChartView1.AreaType = ChartAreaType.Polar -RadChartView1.Series.Add(series) - -```` - - -{{endregion}} + + + The following example shows how you can change the BackColor of particular pieces: -{{source=..\SamplesCS\ChartView\Series\RadarSeriesForm.cs region=SetColors}} -{{source=..\SamplesVB\ChartView\Series\RadarSeriesForm.vb region=SetColors}} -````C# -for (int i = 0; i < series.Children.Count; i++) -{ - if (i % 2 == 0) - { - series.Children[i].BackColor = Color.FromArgb(61, 153, 231); - } - else - { - series.Children[i].BackColor = Color.FromArgb(249, 196, 0); - } -} - -```` -````VB.NET -For i As Integer = 0 To series.Children.Count - 1 - If i Mod 2 = 0 Then - series.Children(i).BackColor = Color.FromArgb(61, 153, 231) - Else - series.Children(i).BackColor = Color.FromArgb(249, 196, 0) - End If -Next i - -```` - - -{{endregion}} + + + + Figure 2 shows the the result from the above code. diff --git a/controls/chartview/series-types/radar.md b/controls/chartview/series-types/radar.md index f0586398d..f769958eb 100644 --- a/controls/chartview/series-types/radar.md +++ b/controls/chartview/series-types/radar.md @@ -15,125 +15,30 @@ The radar chart is a two-dimensional chart of three or more quantitative variabl #### Initial Setup RadarPointSeries -{{source=..\SamplesCS\ChartView\Series\RadarSeriesForm.cs region=radarPointSeries}} -{{source=..\SamplesVB\ChartView\Series\RadarSeriesForm.vb region=radarPointSeries}} - -````C# -this.radChartView1.AreaType = ChartAreaType.Polar; -RadarPointSeries radarPointSeries = new RadarPointSeries(); -radarPointSeries.DataPoints.Add(new CategoricalDataPoint(3.8d, "Oranges")); -radarPointSeries.DataPoints.Add(new CategoricalDataPoint(4d, "Bananas")); -radarPointSeries.DataPoints.Add(new CategoricalDataPoint(1.5d, "Apples")); -this.radChartView1.Series.Add(radarPointSeries); -RadarPointSeries radarPointSeries2 = new RadarPointSeries(); -radarPointSeries2.DataPoints.Add(new CategoricalDataPoint(3.1d, "Oranges")); -radarPointSeries2.DataPoints.Add(new CategoricalDataPoint(1.8d, "Bananas")); -radarPointSeries2.DataPoints.Add(new CategoricalDataPoint(2.9d, "Apples")); -this.radChartView1.Series.Add(radarPointSeries2); - -```` -````VB.NET -Me.RadChartView1.AreaType = ChartAreaType.Polar -Dim radarPointSeries As New RadarPointSeries() -radarPointSeries.DataPoints.Add(New CategoricalDataPoint(3.8D, "Oranges")) -radarPointSeries.DataPoints.Add(New CategoricalDataPoint(4D, "Bananas")) -radarPointSeries.DataPoints.Add(New CategoricalDataPoint(1.5D, "Apples")) -Me.RadChartView1.Series.Add(radarPointSeries) -Dim radarPointSeries2 As New RadarPointSeries() -radarPointSeries2.DataPoints.Add(New CategoricalDataPoint(3.1D, "Oranges")) -radarPointSeries2.DataPoints.Add(New CategoricalDataPoint(1.8D, "Bananas")) -radarPointSeries2.DataPoints.Add(New CategoricalDataPoint(2.9D, "Apples")) -Me.RadChartView1.Series.Add(radarPointSeries2) - -```` - -{{endregion}} + + + + >caption Figure 1: Initial Setup RadarPointSeries ![WinForms RadChartView Initial Setup Radar Point Series](images/chartview-series-types-radar001.png) #### Initial Setup RadarLineSeries -{{source=..\SamplesCS\ChartView\Series\RadarSeriesForm.cs region=radarLineSeries}} -{{source=..\SamplesVB\ChartView\Series\RadarSeriesForm.vb region=radarLineSeries}} - -````C# -this.radChartView1.AreaType = ChartAreaType.Polar; -RadarLineSeries radarLineSeries = new RadarLineSeries(); -radarLineSeries.DataPoints.Add(new CategoricalDataPoint(3.8d, "Oranges")); -radarLineSeries.DataPoints.Add(new CategoricalDataPoint(4d, "Bananas")); -radarLineSeries.DataPoints.Add(new CategoricalDataPoint(1.5d, "Apples")); -this.radChartView1.Series.Add(radarLineSeries); -RadarLineSeries radarLineSeries2 = new RadarLineSeries(); -radarLineSeries2.DataPoints.Add(new CategoricalDataPoint(3.1d, "Oranges")); -radarLineSeries2.DataPoints.Add(new CategoricalDataPoint(1.8d, "Bananas")); -radarLineSeries2.DataPoints.Add(new CategoricalDataPoint(2.9d, "Apples")); -this.radChartView1.Series.Add(radarLineSeries2); - -```` -````VB.NET -Me.RadChartView1.AreaType = ChartAreaType.Polar -Dim radarLineSeries As New RadarLineSeries() -radarLineSeries.DataPoints.Add(New CategoricalDataPoint(3.8D, "Oranges")) -radarLineSeries.DataPoints.Add(New CategoricalDataPoint(4D, "Bananas")) -radarLineSeries.DataPoints.Add(New CategoricalDataPoint(1.5D, "Apples")) -Me.RadChartView1.Series.Add(radarLineSeries) -Dim radarLineSeries2 As New RadarLineSeries() -radarLineSeries2.DataPoints.Add(New CategoricalDataPoint(3.1D, "Oranges")) -radarLineSeries2.DataPoints.Add(New CategoricalDataPoint(1.8D, "Bananas")) -radarLineSeries2.DataPoints.Add(New CategoricalDataPoint(2.9D, "Apples")) -Me.RadChartView1.Series.Add(radarLineSeries2) - -```` - -{{endregion}} + + + + >caption Figure 2: Initial Setup RadarLineSeries ![WinForms RadChartView Initial Setup Radar Line Series](images/chartview-series-types-radar002.png) #### Initial Setup RadarAreaSeries -{{source=..\SamplesCS\ChartView\Series\RadarSeriesForm.cs region=radarAreaSeries}} -{{source=..\SamplesVB\ChartView\Series\RadarSeriesForm.vb region=radarAreaSeries}} - -````C# -this.radChartView1.AreaType = ChartAreaType.Polar; -RadarAreaSeries radarAreaSeries = new RadarAreaSeries(); -radarAreaSeries.BackColor = Color.FromArgb(100, 142, 196, 65); -radarAreaSeries.BorderColor = Color.FromArgb(100, 142, 196, 65); -radarAreaSeries.DataPoints.Add(new CategoricalDataPoint(3.8d, "Oranges")); -radarAreaSeries.DataPoints.Add(new CategoricalDataPoint(4d, "Bananas")); -radarAreaSeries.DataPoints.Add(new CategoricalDataPoint(1.5d, "Apples")); -this.radChartView1.Series.Add(radarAreaSeries); -RadarAreaSeries radarAreaSeries2 = new RadarAreaSeries(); -radarAreaSeries2.BackColor = Color.FromArgb(100, 27, 157, 222); -radarAreaSeries2.BorderColor = Color.FromArgb(100, 27, 157, 222); -radarAreaSeries2.DataPoints.Add(new CategoricalDataPoint(3.1d, "Oranges")); -radarAreaSeries2.DataPoints.Add(new CategoricalDataPoint(1.8d, "Bananas")); -radarAreaSeries2.DataPoints.Add(new CategoricalDataPoint(2.9d, "Apples")); -this.radChartView1.Series.Add(radarAreaSeries2); - -```` -````VB.NET -Me.RadChartView1.AreaType = ChartAreaType.Polar -Dim radarAreaSeries As New RadarAreaSeries() -radarAreaSeries.BackColor = Color.FromArgb(100, 142, 196, 65) -radarAreaSeries.BorderColor = Color.FromArgb(100, 142, 196, 65) -radarAreaSeries.DataPoints.Add(New CategoricalDataPoint(3.8D, "Oranges")) -radarAreaSeries.DataPoints.Add(New CategoricalDataPoint(4D, "Bananas")) -radarAreaSeries.DataPoints.Add(New CategoricalDataPoint(1.5D, "Apples")) -Me.RadChartView1.Series.Add(radarAreaSeries) -Dim radarAreaSeries2 As New RadarAreaSeries() -radarAreaSeries2.BackColor = Color.FromArgb(100, 27, 157, 222) -radarAreaSeries2.BorderColor = Color.FromArgb(100, 27, 157, 222) -radarAreaSeries2.DataPoints.Add(New CategoricalDataPoint(3.1D, "Oranges")) -radarAreaSeries2.DataPoints.Add(New CategoricalDataPoint(1.8D, "Bananas")) -radarAreaSeries2.DataPoints.Add(New CategoricalDataPoint(2.9D, "Apples")) -Me.RadChartView1.Series.Add(radarAreaSeries2) - -```` - -{{endregion}} + + + + >caption Figure 3: Initial Setup RadarAreaSeries ![WinForms RadChartView Initial Setup Radar Area Series](images/chartview-series-types-radar003.png) @@ -154,51 +59,10 @@ When you have __RadarLineSeries__ or __RadarAreaSeries__ you can set the Spline #### Spline Settings -{{source=..\SamplesCS\ChartView\Series\RadarSeriesForm.cs region=spline}} -{{source=..\SamplesVB\ChartView\Series\RadarSeriesForm.vb region=spline}} - -````C# -this.radChartView1.AreaType = ChartAreaType.Polar; -RadarLineSeries radarLineSeries = new RadarLineSeries(); -radarLineSeries.DataPoints.Add(new CategoricalDataPoint(3.8d, "Oranges")); -radarLineSeries.DataPoints.Add(new CategoricalDataPoint(4d, "Bananas")); -radarLineSeries.DataPoints.Add(new CategoricalDataPoint(1.5d, "Apples")); -radarLineSeries.Spline = true; -radarLineSeries.SplineTension = 0.3f; -this.radChartView1.Series.Add(radarLineSeries); -RadarAreaSeries radarAreaSeries2 = new RadarAreaSeries(); -radarAreaSeries2.BackColor = Color.FromArgb(100, 27, 157, 222); -radarAreaSeries2.BorderColor = Color.FromArgb(100, 27, 157, 222); -radarAreaSeries2.DataPoints.Add(new CategoricalDataPoint(3.1d, "Oranges")); -radarAreaSeries2.DataPoints.Add(new CategoricalDataPoint(1.8d, "Bananas")); -radarAreaSeries2.DataPoints.Add(new CategoricalDataPoint(2.9d, "Apples")); -radarAreaSeries2.Spline = true; -radarAreaSeries2.SplineTension = 0.5f; -this.radChartView1.Series.Add(radarAreaSeries2); - -```` -````VB.NET -Me.RadChartView1.AreaType = ChartAreaType.Polar -Dim radarLineSeries As New RadarLineSeries() -radarLineSeries.DataPoints.Add(New CategoricalDataPoint(3.8, "Oranges")) -radarLineSeries.DataPoints.Add(New CategoricalDataPoint(4.0, "Bananas")) -radarLineSeries.DataPoints.Add(New CategoricalDataPoint(1.5, "Apples")) -radarLineSeries.Spline = True -radarLineSeries.SplineTension = 0.3F -Me.RadChartView1.Series.Add(radarLineSeries) -Dim radarAreaSeries2 As New RadarAreaSeries() -radarAreaSeries2.BackColor = Color.FromArgb(100, 27, 157, 222) -radarAreaSeries2.BorderColor = Color.FromArgb(100, 27, 157, 222) -radarAreaSeries2.DataPoints.Add(New CategoricalDataPoint(3.1, "Oranges")) -radarAreaSeries2.DataPoints.Add(New CategoricalDataPoint(1.8, "Bananas")) -radarAreaSeries2.DataPoints.Add(New CategoricalDataPoint(2.9, "Apples")) -radarAreaSeries2.Spline = True -radarAreaSeries2.SplineTension = 0.5F -Me.RadChartView1.Series.Add(radarAreaSeries2) - -```` - -{{endregion}} + + + + >caption Figure 4: Spline Settings ![WinForms RadChartView Spline Settings](images/chartview-series-types-radar004.png) diff --git a/controls/chartview/series-types/range-and-rangebar.md b/controls/chartview/series-types/range-and-rangebar.md index 5d3b577d9..efaf92c25 100644 --- a/controls/chartview/series-types/range-and-rangebar.md +++ b/controls/chartview/series-types/range-and-rangebar.md @@ -21,35 +21,10 @@ You can use the following code to display a simple __RangeSeries__ #### Initial Setup RangeSeries -{{source=..\SamplesCS\ChartView\Series\RangeAndRangeBarSeries.cs region=Range}} -{{source=..\SamplesVB\ChartView\Series\RangeAndRangeBarSeries.vb region=Range}} - -````C# -RangeSeries rangeSeries = new RangeSeries(); -rangeSeries.DataPoints.Add(new RangeDataPoint(9, 5, "January")); -rangeSeries.DataPoints.Add(new RangeDataPoint(7, 2, "February")); -rangeSeries.DataPoints.Add(new RangeDataPoint(6, 4, "March")); -rangeSeries.DataPoints.Add(new RangeDataPoint(8, 5, "April")); -rangeSeries.DataPoints.Add(new RangeDataPoint(4, 3, "May")); -rangeSeries.DataPoints.Add(new RangeDataPoint(9, 7, "June")); -rangeSeries.DataPoints.Add(new RangeDataPoint(3, 1, "July")); -radChartView1.Series.Add(rangeSeries); - -```` -````VB.NET -Dim rangeSeries As New RangeSeries() -rangeSeries.DataPoints.Add(New RangeDataPoint(5, 9, "January")) -rangeSeries.DataPoints.Add(New RangeDataPoint(7, 2, "February")) -rangeSeries.DataPoints.Add(New RangeDataPoint(6, 4, "March")) -rangeSeries.DataPoints.Add(New RangeDataPoint(8, 5, "April")) -rangeSeries.DataPoints.Add(New RangeDataPoint(4, 3, "May")) -rangeSeries.DataPoints.Add(New RangeDataPoint(9, 7, "June")) -rangeSeries.DataPoints.Add(New RangeDataPoint(3, 1, "July")) -radChartView1.Series.Add(rangeSeries) - -```` - -{{endregion}} + + + + >caption Figure 1: Initial Setup RangeSeries ![WinForms RadChartView Initial Setup Range Series](images/chartview-series-types-range001.png) @@ -62,35 +37,10 @@ You can use the following code to display a simple RangeBarSeries #### Initial Setup RangeBarSeries -{{source=..\SamplesCS\ChartView\Series\RangeAndRangeBarSeries.cs region=Bar}} -{{source=..\SamplesVB\ChartView\Series\RangeAndRangeBarSeries.vb region=Bar}} - -````C# -RangeBarSeries rangeBarSeries = new RangeBarSeries(); -rangeBarSeries.DataPoints.Add(new RangeDataPoint(7, 5, "January")); -rangeBarSeries.DataPoints.Add(new RangeDataPoint(4, 2, "February")); -rangeBarSeries.DataPoints.Add(new RangeDataPoint(8, 4, "March")); -rangeBarSeries.DataPoints.Add(new RangeDataPoint(8, 3, "April")); -rangeBarSeries.DataPoints.Add(new RangeDataPoint(6, 3, "May")); -rangeBarSeries.DataPoints.Add(new RangeDataPoint(6, 2, "June")); -rangeBarSeries.DataPoints.Add(new RangeDataPoint(3, 1, "July")); -radChartView1.Series.Add(rangeBarSeries); - -```` -````VB.NET -Dim rangeBarSeries As New RangeBarSeries() -rangeBarSeries.DataPoints.Add(New RangeDataPoint(7, 5, "January")) -rangeBarSeries.DataPoints.Add(New RangeDataPoint(4, 2, "February")) -rangeBarSeries.DataPoints.Add(New RangeDataPoint(8, 4, "March")) -rangeBarSeries.DataPoints.Add(New RangeDataPoint(8, 3, "April")) -rangeBarSeries.DataPoints.Add(New RangeDataPoint(6, 3, "May")) -rangeBarSeries.DataPoints.Add(New RangeDataPoint(6, 2, "June")) -rangeBarSeries.DataPoints.Add(New RangeDataPoint(3, 1, "July")) -radChartView1.Series.Add(rangeBarSeries) - -```` - -{{endregion}} + + + + >caption Figure 2: Initial Setup RangeBarSeries ![WinForms RadChartView Initial Setup Range Bar Series](images/chartview-series-types-range002.png) diff --git a/controls/chartview/series-types/scatter.md b/controls/chartview/series-types/scatter.md index cb311c3ea..e53122221 100644 --- a/controls/chartview/series-types/scatter.md +++ b/controls/chartview/series-types/scatter.md @@ -15,56 +15,9 @@ Unlike Categorical series, __ScatterSeries__ plots its data upon two numerical a #### Initial Setup -{{source=..\SamplesCS\ChartView\Series\ScatterSeriesForm.cs region=scatter}} -{{source=..\SamplesVB\ChartView\Series\ScatterSeriesForm.vb region=scatter}} - -````C# - -ScatterSeries scatterSeries = new ScatterSeries(); -scatterSeries.Name = ""; -scatterSeries.DataPoints.Add(new ScatterDataPoint(15, 19)); -scatterSeries.DataPoints.Add(new ScatterDataPoint(18, 10)); -scatterSeries.DataPoints.Add(new ScatterDataPoint(13, 15)); -scatterSeries.DataPoints.Add(new ScatterDataPoint(10, 8)); -scatterSeries.DataPoints.Add(new ScatterDataPoint(5, 12)); -scatterSeries.PointSize = new SizeF(8, 8); -this.radChartView1.Series.Add(scatterSeries); - -ScatterSeries scatterSeries2 = new ScatterSeries(); -scatterSeries2.Name = ""; -scatterSeries2.DataPoints.Add(new ScatterDataPoint(20, 20)); -scatterSeries2.DataPoints.Add(new ScatterDataPoint(15, 10)); -scatterSeries2.DataPoints.Add(new ScatterDataPoint(7, 6)); -scatterSeries2.DataPoints.Add(new ScatterDataPoint(18, 22)); -scatterSeries2.DataPoints.Add(new ScatterDataPoint(10, 10)); -scatterSeries2.PointSize = new SizeF(8, 8); -scatterSeries.Shape = new RoundRectShape(0); -this.radChartView1.Series.Add(scatterSeries2); - -```` -````VB.NET -Dim scatterSeries As New ScatterSeries() -scatterSeries.Name = "" -scatterSeries.DataPoints.Add(New ScatterDataPoint(15, 19)) -scatterSeries.DataPoints.Add(New ScatterDataPoint(18, 10)) -scatterSeries.DataPoints.Add(New ScatterDataPoint(13, 15)) -scatterSeries.DataPoints.Add(New ScatterDataPoint(10, 8)) -scatterSeries.DataPoints.Add(New ScatterDataPoint(5, 12)) -scatterSeries.PointSize = New SizeF(8, 8) -Me.RadChartView1.Series.Add(scatterSeries) -Dim scatterSeries2 As New ScatterSeries() -scatterSeries2.Name = "" -scatterSeries2.DataPoints.Add(New ScatterDataPoint(20, 20)) -scatterSeries2.DataPoints.Add(New ScatterDataPoint(15, 10)) -scatterSeries2.DataPoints.Add(New ScatterDataPoint(7, 6)) -scatterSeries2.DataPoints.Add(New ScatterDataPoint(18, 22)) -scatterSeries2.DataPoints.Add(New ScatterDataPoint(10, 10)) -scatterSeries2.PointSize = New SizeF(8, 8) -Me.RadChartView1.Series.Add(scatterSeries2) - -```` - -{{endregion}} + + + >caption Figure 1: Initial Setup @@ -82,22 +35,10 @@ __ScatterSeries__ have few important properties: #### Custom Shape -{{source=..\SamplesCS\ChartView\Series\ScatterSeriesForm.cs region=shape}} -{{source=..\SamplesVB\ChartView\Series\ScatterSeriesForm.vb region=shape}} - -````C# - -RoundRectShape shape = new RoundRectShape(0); -scatterSeries2.Shape = shape; - -```` -````VB.NET -Dim shape As New RoundRectShape(0) -scatterSeries2.Shape = shape + + -```` -{{endregion}} >caption Figure 2: Custom Shape ![WinForms RadChartView Scatter Custom Shape](images/chartview-series-types-scatter002.png) diff --git a/controls/chartview/series-types/scatterarea.md b/controls/chartview/series-types/scatterarea.md index 3aeb81dbd..946233a2a 100644 --- a/controls/chartview/series-types/scatterarea.md +++ b/controls/chartview/series-types/scatterarea.md @@ -15,47 +15,10 @@ __ScatterAreaSeries__ plot their data using two numerical values. Once positione #### Initial Setup -{{source=..\SamplesCS\ChartView\Series\ScatterAreraCode.cs region=Area}} -{{source=..\SamplesVB\ChartView\Series\ScatterAreraCode.vb region=Area}} - -````C# -ScatterAreaSeries scatterSeries = new ScatterAreaSeries(); -scatterSeries.DataPoints.Add(new ScatterDataPoint(15, 19)); -scatterSeries.DataPoints.Add(new ScatterDataPoint(18, 10)); -scatterSeries.DataPoints.Add(new ScatterDataPoint(13, 15)); -scatterSeries.DataPoints.Add(new ScatterDataPoint(10, 8)); -scatterSeries.DataPoints.Add(new ScatterDataPoint(5, 2)); -this.radChartView1.Series.Add(scatterSeries); -ScatterAreaSeries scatterSeries2 = new ScatterAreaSeries(); -scatterSeries2.DataPoints.Add(new ScatterDataPoint(2, 24)); -scatterSeries2.DataPoints.Add(new ScatterDataPoint(7, 12)); -scatterSeries2.DataPoints.Add(new ScatterDataPoint(15, 10)); -scatterSeries2.DataPoints.Add(new ScatterDataPoint(18, 22)); -scatterSeries2.DataPoints.Add(new ScatterDataPoint(19, 19)); -scatterSeries2.Spline = true; -this.radChartView1.Series.Add(scatterSeries2); - -```` -````VB.NET -Dim scatterSeries As New ScatterAreaSeries() -scatterSeries.DataPoints.Add(New ScatterDataPoint(15, 19)) -scatterSeries.DataPoints.Add(New ScatterDataPoint(18, 10)) -scatterSeries.DataPoints.Add(New ScatterDataPoint(13, 15)) -scatterSeries.DataPoints.Add(New ScatterDataPoint(10, 8)) -scatterSeries.DataPoints.Add(New ScatterDataPoint(5, 2)) -Me.radChartView1.Series.Add(scatterSeries) -Dim scatterSeries2 As New ScatterAreaSeries() -scatterSeries2.DataPoints.Add(New ScatterDataPoint(2, 24)) -scatterSeries2.DataPoints.Add(New ScatterDataPoint(7, 12)) -scatterSeries2.DataPoints.Add(New ScatterDataPoint(15, 10)) -scatterSeries2.DataPoints.Add(New ScatterDataPoint(18, 22)) -scatterSeries2.DataPoints.Add(New ScatterDataPoint(19, 19)) -scatterSeries2.Spline = True -Me.radChartView1.Series.Add(scatterSeries2) - -```` - -{{endregion}} + + + + >caption Figure 1: Initial Setup ![WinForms RadChartView ScatterArea Initial Setup](images/chartview-series-scatterarea001.png) @@ -76,19 +39,10 @@ The following list shows the most important properties of the __ScaterAreaSeries #### Set StrokeMode -{{source=..\SamplesCS\ChartView\Series\ScatterAreraCode.cs region=Stroke}} -{{source=..\SamplesVB\ChartView\Series\ScatterAreraCode.vb region=Stroke}} - -````C# -scatterSeries.StrokeMode = AreaSeriesStrokeMode.Points; - -```` -````VB.NET -scatterSeries2.StrokeMode = AreaSeriesStrokeMode.Points + + -```` -{{endregion}} >caption Figure 2: Stroke Mode ![WinForms RadChartView ScatterArea Stroke Mode](images/chartview-series-scatterarea002.png) diff --git a/controls/chartview/series-types/scatterline.md b/controls/chartview/series-types/scatterline.md index db0b02c92..423cc759f 100644 --- a/controls/chartview/series-types/scatterline.md +++ b/controls/chartview/series-types/scatterline.md @@ -15,51 +15,10 @@ __ScatterLineSeries__ allow data represented as a line to be plotted against two #### Initial Setup -{{source=..\SamplesCS\ChartView\Series\ScatterLineSeriesForm.cs region=scatterLineSetup}} -{{source=..\SamplesVB\ChartView\Series\ScatterLineSeriesForm.vb region=scatterLineSetup}} - -````C# -ScatterLineSeries scatterSeries = new ScatterLineSeries(); -scatterSeries.DataPoints.Add(new ScatterDataPoint(15, 19)); -scatterSeries.DataPoints.Add(new ScatterDataPoint(18, 10)); -scatterSeries.DataPoints.Add(new ScatterDataPoint(13, 15)); -scatterSeries.DataPoints.Add(new ScatterDataPoint(10, 8)); -scatterSeries.DataPoints.Add(new ScatterDataPoint(5, 2)); -scatterSeries.PointSize = new SizeF(8, 8); -this.radChartView1.Series.Add(scatterSeries); -ScatterLineSeries scatterSeries2 = new ScatterLineSeries(); -scatterSeries2.DataPoints.Add(new ScatterDataPoint(2, 24)); -scatterSeries2.DataPoints.Add(new ScatterDataPoint(7, 12)); -scatterSeries2.DataPoints.Add(new ScatterDataPoint(15, 10)); -scatterSeries2.DataPoints.Add(new ScatterDataPoint(18, 22)); -scatterSeries2.DataPoints.Add(new ScatterDataPoint(20, 20)); -scatterSeries2.Shape = new RoundRectShape(1); -scatterSeries2.PointSize = new SizeF(8, 8); -this.radChartView1.Series.Add(scatterSeries2); - -```` -````VB.NET -Dim scatterSeries As New ScatterLineSeries() -scatterSeries.DataPoints.Add(New ScatterDataPoint(15, 19)) -scatterSeries.DataPoints.Add(New ScatterDataPoint(18, 10)) -scatterSeries.DataPoints.Add(New ScatterDataPoint(13, 15)) -scatterSeries.DataPoints.Add(New ScatterDataPoint(10, 8)) -scatterSeries.DataPoints.Add(New ScatterDataPoint(5, 2)) -scatterSeries.PointSize = New SizeF(8, 8) -Me.radChartView1.Series.Add(scatterSeries) -Dim scatterSeries2 As New ScatterLineSeries() -scatterSeries2.DataPoints.Add(New ScatterDataPoint(2, 24)) -scatterSeries2.DataPoints.Add(New ScatterDataPoint(7, 12)) -scatterSeries2.DataPoints.Add(New ScatterDataPoint(15, 10)) -scatterSeries2.DataPoints.Add(New ScatterDataPoint(18, 22)) -scatterSeries2.DataPoints.Add(New ScatterDataPoint(20, 20)) -scatterSeries2.Shape = New RoundRectShape(1) -scatterSeries2.PointSize = New SizeF(8, 8) -Me.radChartView1.Series.Add(scatterSeries2) - -```` - -{{endregion}} + + + + >caption Figure 1: Initial Setup ![WinForms RadChartView ScatterLine Initial Setup](images/chartview-series-scatterline001.png) @@ -72,21 +31,10 @@ __ScatterLineSeries__ inherit from __ScatterSeries__ thus all important properti #### Spline Settings -{{source=..\SamplesCS\ChartView\Series\ScatterLineSeriesForm.cs region=scatterLineSpline}} -{{source=..\SamplesVB\ChartView\Series\ScatterLineSeriesForm.vb region=scatterLineSpline}} - -````C# -scatterSeries.Spline = true; -scatterSeries.SplineTension = 0.8f; - -```` -````VB.NET -scatterLine.Spline = True -scatterLine.SplineTension = 0.8F + + -```` -{{endregion}} >caption Figire 2: Spline Settings ![WinForms RadChartView ScatterLine Spline Settings](images/chartview-series-scatterline002.png) diff --git a/controls/chartview/series-types/stepline.md b/controls/chartview/series-types/stepline.md index 0717c2f7c..72836cf2e 100644 --- a/controls/chartview/series-types/stepline.md +++ b/controls/chartview/series-types/stepline.md @@ -15,41 +15,10 @@ __SteplineSeries__ plot their Categorical data points on Cartesian Area using on #### Initial Setup -{{source=..\SamplesCS\ChartView\Series\SteplineSeriesForm.cs region=Initialize}} -{{source=..\SamplesVB\ChartView\Series\SteplineSeriesForm.vb region=Initialize}} + + -````C# -SteplineSeries lineSeries = new SteplineSeries(); -lineSeries.DataPoints.Add(new CategoricalDataPoint(20, "Jan")); -lineSeries.DataPoints.Add(new CategoricalDataPoint(22, "Apr")); -lineSeries.DataPoints.Add(new CategoricalDataPoint(12, "Jul")); -lineSeries.DataPoints.Add(new CategoricalDataPoint(19, "Oct")); -this.radChartView1.Series.Add(lineSeries); -SteplineSeries lineSeries2 = new SteplineSeries(); -lineSeries2.DataPoints.Add(new CategoricalDataPoint(18, "Jan")); -lineSeries2.DataPoints.Add(new CategoricalDataPoint(15, "Apr")); -lineSeries2.DataPoints.Add(new CategoricalDataPoint(17, "Jul")); -lineSeries2.DataPoints.Add(new CategoricalDataPoint(22, "Oct")); -this.radChartView1.Series.Add(lineSeries2); -```` -````VB.NET -Dim lineSeries As New SteplineSeries() -lineSeries.DataPoints.Add(New CategoricalDataPoint(20, "Jan")) -lineSeries.DataPoints.Add(New CategoricalDataPoint(22, "Apr")) -lineSeries.DataPoints.Add(New CategoricalDataPoint(12, "Jul")) -lineSeries.DataPoints.Add(New CategoricalDataPoint(19, "Oct")) -Me.RadChartView1.Series.Add(lineSeries) -Dim lineSeries2 As New SteplineSeries() -lineSeries2.DataPoints.Add(New CategoricalDataPoint(18, "Jan")) -lineSeries2.DataPoints.Add(New CategoricalDataPoint(15, "Apr")) -lineSeries2.DataPoints.Add(New CategoricalDataPoint(17, "Jul")) -lineSeries2.DataPoints.Add(New CategoricalDataPoint(22, "Oct")) -Me.RadChartView1.Series.Add(lineSeries2) - -```` - -{{endregion}} >caption Figure 1: Initial Setup ![WinForms RadChartView Stepline Initial Setup](images/chartview-series-types-stepline001.png) diff --git a/controls/chartview/series-types/watterfall.md b/controls/chartview/series-types/watterfall.md index 10ec6d81e..3fa23db6c 100644 --- a/controls/chartview/series-types/watterfall.md +++ b/controls/chartview/series-types/watterfall.md @@ -22,41 +22,10 @@ The example above can be achieved with the following code snippet: #### Initial Setup -{{source=..\SamplesCS\ChartView\Series\WaterfallSeriesForm.cs region=UnboundMode}} -{{source=..\SamplesVB\ChartView\Series\WaterfallSeriesForm.vb region=UnboundMode}} - -````C# -WaterfallSeries series = new WaterfallSeries(); -series.DataPoints.Add(new WaterfallDataPoint(50000, false, false, "Beginning\nBalance")); -series.DataPoints.Add(new WaterfallDataPoint(17000, false, false, "Jan")); -series.DataPoints.Add(new WaterfallDataPoint(14000, false, false, "Feb")); -series.DataPoints.Add(new WaterfallDataPoint(-12000, false, false, "Mar")); -series.DataPoints.Add(new WaterfallDataPoint(69000, true, false, "Q1")); -series.DataPoints.Add(new WaterfallDataPoint(-22000, false, false, "Apr")); -series.DataPoints.Add(new WaterfallDataPoint(-18000, false, false, "May")); -series.DataPoints.Add(new WaterfallDataPoint(10000, false, false, "Jun")); -series.DataPoints.Add(new WaterfallDataPoint(-30000, true, false, "Q2")); -series.DataPoints.Add(new WaterfallDataPoint(39000, false, true, "Ending\nBalance")); -this.radChartView1.Series.Add(series); - -```` -````VB.NET -Dim series As New WaterfallSeries() -series.DataPoints.Add(New WaterfallDataPoint(50000, False, False, "Beginning" & vbLf & "Balance")) -series.DataPoints.Add(New WaterfallDataPoint(17000, False, False, "Jan")) -series.DataPoints.Add(New WaterfallDataPoint(14000, False, False, "Feb")) -series.DataPoints.Add(New WaterfallDataPoint(-12000, False, False, "Mar")) -series.DataPoints.Add(New WaterfallDataPoint(69000, True, False, "Q1")) -series.DataPoints.Add(New WaterfallDataPoint(-22000, False, False, "Apr")) -series.DataPoints.Add(New WaterfallDataPoint(-18000, False, False, "May")) -series.DataPoints.Add(New WaterfallDataPoint(10000, False, False, "Jun")) -series.DataPoints.Add(New WaterfallDataPoint(-30000, True, False, "Q2")) -series.DataPoints.Add(New WaterfallDataPoint(39000, False, True, "Ending" & vbLf & "Balance")) -Me.radChartView1.Series.Add(series) - -```` - -{{endregion}} + + + + To achieve the same chart in a data bound mode you will need appropriate data and once it is in place, you need to set the following properties: @@ -68,61 +37,10 @@ You need to set the standard databinding properties as well ([Binding to Binding #### Data Binding WaterFallSeries -{{source=..\SamplesCS\ChartView\Series\WaterfallSeriesForm.cs region=DataBinding}} -{{source=..\SamplesVB\ChartView\Series\WaterfallSeriesForm.vb region=DataBinding}} - -````C# -DataTable table = new DataTable(); -table.Columns.Add("Category", typeof(string)); -table.Columns.Add("Value", typeof(double)); -table.Columns.Add("Summary", typeof(bool)); -table.Columns.Add("Total", typeof(bool)); -table.Rows.Add("Beginning\nBalance", 50000, false, false); -table.Rows.Add("Jan", 17000, false, false); -table.Rows.Add("Feb", 14000, false, false); -table.Rows.Add("Mar", -12000, false, false); -table.Rows.Add("Q1", 69000, true, false); -table.Rows.Add("Apr", -22000, false, false); -table.Rows.Add("May", -18000, false, false); -table.Rows.Add("Jun", 10000, false, false); -table.Rows.Add("Q2", -30000, true, false); -table.Rows.Add("Ending\nBalance", 39000, false, true); -WaterfallSeries series = new WaterfallSeries(); -series.ValueMember = "Value"; -series.CategoryMember = "Category"; -series.SummaryMember = "Summary"; -series.TotalMember = "Total"; -series.DataSource = table; -this.radChartView1.Series.Add(series); - -```` -````VB.NET -Dim table As New DataTable() -table.Columns.Add("Category", GetType(String)) -table.Columns.Add("Value", GetType(Double)) -table.Columns.Add("Summary", GetType(Boolean)) -table.Columns.Add("Total", GetType(Boolean)) -table.Rows.Add("Beginning" & vbLf & "Balance", 50000, False, False) -table.Rows.Add("Jan", 17000, False, False) -table.Rows.Add("Feb", 14000, False, False) -table.Rows.Add("Mar", -12000, False, False) -table.Rows.Add("Q1", 69000, True, False) -table.Rows.Add("Apr", -22000, False, False) -table.Rows.Add("May", -18000, False, False) -table.Rows.Add("Jun", 10000, False, False) -table.Rows.Add("Q2", -30000, True, False) -table.Rows.Add("Ending" & vbLf & "Balance", 39000, False, True) -Dim series As New WaterfallSeries() -series.ValueMember = "Value" -series.CategoryMember = "Category" -series.SummaryMember = "Summary" -series.TotalMember = "Total" -series.DataSource = table -Me.radChartView1.Series.Add(series) - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/chat/chat-items/cards.md b/controls/chat/chat-items/cards.md index 68aea31e7..b9966fb61 100644 --- a/controls/chat/chat-items/cards.md +++ b/controls/chat/chat-items/cards.md @@ -26,31 +26,10 @@ Depending on the information that is presented, the cards can be one of the foll #### Adding a ChatImageCardElement programmatically -{{source=..\SamplesCS\Chat\ChatCards.cs region=ImageCard}} -{{source=..\SamplesVB\Chat\ChatCards.vb region=ImageCard}} + + -````C# -Telerik.WinControls.UI.ChatImageCardDataItem imageCard = new ChatImageCardDataItem(Properties.Resources.architect, "Benjamin Vilanders", "Senior Architect", - "As a Senior Architect his experience in the industry allows him to take on increased responsibility. Like other architects, he design buildings " + - "and makes sure they are structurally sound. Due to his track record of quality performance, Benjamin also serves as a manager, a mentor, an advisor and coordinator.", - null, null); -Author author = new Author(Properties.Resources.architect, "Ben"); -ChatCardMessage message = new ChatCardMessage(imageCard, author, DateTime.Now); -this.radChat1.AddMessage(message); -```` -````VB.NET -Dim imageCard As Telerik.WinControls.UI.ChatImageCardDataItem = New ChatImageCardDataItem(My.Resources.architect, "Benjamin Vilanders", _ - "Senior Architect", "As a Senior Architect his experience in the industry allows him to take on increased responsibility. Like other architects, he design buildings " & _ - "and makes sure they are structurally sound. Due to his track record of quality performance, Benjamin also serves as a manager, a mentor, an advisor and coordinator.", Nothing, Nothing) -Dim author As Author = New Author(My.Resources.architect, "Ben") -Dim message As ChatCardMessage = New ChatCardMessage(imageCard, author, DateTime.Now) -Me.radChat1.AddMessage(message) - -```` - - -{{endregion}} ## Chat Product Card Element @@ -62,31 +41,11 @@ Me.radChat1.AddMessage(message) #### Adding a ChatProductCardElement programmatically -{{source=..\SamplesCS\Chat\ChatCards.cs region=ProductCard}} -{{source=..\SamplesVB\Chat\ChatCards.vb region=ProductCard}} - -````C# -ChatProductCardDataItem productCard = new ChatProductCardDataItem(Properties.Resources.TV_car1, "Arrive & Drive", "Rating 7/10", - "With our Arrive & Drive Packages, the only thing you will have to think about is driving. We make it simple for you to get more of what you love. We streamline the " + - "entire process and have everything ready for you when you arrive at the track so you can get straight to racing.", "Packages from $340", null, null); -Author author = new Author(Properties.Resources.architect, "Ben"); -ChatCardMessage message = new ChatCardMessage(productCard, author, DateTime.Now); -this.radChat1.AddMessage(message); - -```` -````VB.NET -Dim productCard As ChatProductCardDataItem = New ChatProductCardDataItem(My.Resources.TV_car1, "Arrive & Drive", "Rating 7/10", _ - "With our Arrive & Drive Packages, the only thing you will have to think about is driving. We make it simple for you to get more of what you love. We streamline the " & _ - "entire process and have everything ready for you when you arrive at the track so you can get straight to racing.", "Packages from $340", Nothing, Nothing) -Dim author As Author = New Author(My.Resources.architect, "Ben") -Dim message As ChatCardMessage = New ChatCardMessage(productCard, author, DateTime.Now) -Me.radChat1.AddMessage(message) + + -```` -{{endregion}} - ## ChatWeatherCardElement **ChatWeatherCardElement** illustrates a simple weather forecast. @@ -97,27 +56,10 @@ Me.radChat1.AddMessage(message) #### Adding a ChatWeatherCardElement programmatically -{{source=..\SamplesCS\Chat\ChatCards.cs region=WeatherCard}} -{{source=..\SamplesVB\Chat\ChatCards.vb region=WeatherCard}} - -````C# -ChatWeatherCardDataItem weatherCard = new ChatWeatherCardDataItem("Florence", Properties.Resources.sunny, "33°C", "Humidity: 76%", "Dew: 31°C", - "Pressure: 1031 mb", "Wind Speed: 15 km/h NW"); -Author author = new Author(Properties.Resources.nancy1, "Nancy"); -ChatCardMessage message = new ChatCardMessage(weatherCard, author, DateTime.Now); -this.radChat1.AddMessage(message); - -```` -````VB.NET -Dim weatherCard As ChatWeatherCardDataItem = New ChatWeatherCardDataItem("Florence", My.Resources.sunny, "33°C", "Humidity: 76%", "Dew: 31°C", "Pressure: 1031 mb", "Wind Speed: 15 km/h NW") -Dim author As Author = New Author(My.Resources.nancy1, "Nancy") -Dim message As ChatCardMessage = New ChatCardMessage(weatherCard, author, DateTime.Now) -Me.radChat1.AddMessage(message) - -```` + + -{{endregion}} ## ChatFlightCardElement @@ -129,32 +71,10 @@ Me.radChat1.AddMessage(message) #### Adding a ChatFlightCardElement programmatically -{{source=..\SamplesCS\Chat\ChatCards.cs region=FlightCard}} -{{source=..\SamplesVB\Chat\ChatCards.vb region=FlightCard}} + + -````C# -List flights = new List(); -flights.Add(new FlightInfo("Los Angelis", "LAX", DateTime.Now.AddDays(7), "New York", "JFK", DateTime.Now.AddDays(7).AddHours(5.5))); -flights.Add(new FlightInfo("New York", "JFK", DateTime.Now.AddDays(14).AddHours(3), "Los Angelis", "LAX", DateTime.Now.AddDays(14).AddHours(9.1))); -ChatFlightCardDataItem flightCard = new ChatFlightCardDataItem("Andrew Fuller", flights, Properties.Resources.CardPlane, "$341", null); -Author author = new Author(Properties.Resources.nancy1, "Nancy"); -ChatCardMessage message = new ChatCardMessage(flightCard, author, DateTime.Now); -this.radChat1.AddMessage(message); -```` -````VB.NET -Dim flights As List(Of FlightInfo) = New List(Of FlightInfo)() -flights.Add(New FlightInfo("Los Angelis", "LAX", DateTime.Now.AddDays(7), "New York", "JFK", DateTime.Now.AddDays(7).AddHours(5.5))) -flights.Add(New FlightInfo("New York", "JFK", DateTime.Now.AddDays(14).AddHours(3), "Los Angelis", "LAX", DateTime.Now.AddDays(14).AddHours(9.1))) -Dim flightCard As ChatFlightCardDataItem = New ChatFlightCardDataItem("Andrew Fuller", flights, My.Resources.CardPlane, "$341", Nothing) -Dim author As Author = New Author(My.Resources.nancy1, "Nancy") -Dim message As ChatCardMessage = New ChatCardMessage(flightCard, author, DateTime.Now) -Me.radChat1.AddMessage(message) - -```` - - -{{endregion}} The above examples demonstrates how to add the different card types in a simple **ChatCardMessage**. **RadChat** offers **ChatCarouselMessage** which allows adding and visualizing multiple card elements. Additional information is available in the [Messages]({%slug winforms/chat/chat-items/messages%}) help article. @@ -168,70 +88,19 @@ Each card allows you to add a certain action that can be handled: #### Adding ChatCardActions -{{source=..\SamplesCS\Chat\ChatCards.cs region=CardActions}} -{{source=..\SamplesVB\Chat\ChatCards.vb region=CardActions}} - -````C# -List actions = new List(); -actions.Add(new ChatCardAction("IM")); -actions.Add(new ChatCardAction("Call")); -Telerik.WinControls.UI.ChatImageCardDataItem imageCard = new ChatImageCardDataItem(Properties.Resources.architect, "Benjamin Vilanders", "Senior Architect", - "As a Senior Architect his experience in the industry allows him to take on increased responsibility. Like other architects, he design buildings " + - "and makes sure they are structurally sound. Due to his track record of quality performance, Benjamin also serves as a manager, a mentor, an advisor and coordinator.", - actions, null); -Author author = new Author(Properties.Resources.architect, "Ben"); -ChatCardMessage message = new ChatCardMessage(imageCard, author, DateTime.Now); -this.radChat1.AddMessage(message); + + -```` -````VB.NET -Dim actions As List(Of ChatCardAction) = New List(Of ChatCardAction)() -actions.Add(New ChatCardAction("IM")) -actions.Add(New ChatCardAction("Call")) -Dim imageCard As Telerik.WinControls.UI.ChatImageCardDataItem = New ChatImageCardDataItem(My.Resources.architect, "Benjamin Vilanders", "Senior Architect", "As a Senior Architect his experience in the industry allows him to take on increased responsibility. Like other architects, he design buildings " & "and makes sure they are structurally sound. Due to his track record of quality performance, Benjamin also serves as a manager, a mentor, an advisor and coordinator.", actions, Nothing) -Dim author As Author = New Author(My.Resources.architect, "Ben") -Dim message As ChatCardMessage = New ChatCardMessage(imageCard, author, DateTime.Now) -Me.radChat1.AddMessage(message) -```` - - -{{endregion}} The RadChat.**CardActionClicked** event is fired once a user clicks on the action's text. The **CardActionEventArgs** gives you access to the **ChatCardAction** and user's data. #### Handling ChatCardActions -{{source=..\SamplesCS\Chat\ChatCards.cs region=HandleAction}} -{{source=..\SamplesVB\Chat\ChatCards.vb region=HandleAction}} - -````C# -private void radChat1_CardActionClicked(object sender, CardActionEventArgs e) -{ - if (e.Action.Text == "IM") - { - RadMessageBox.Show("IM is clicked."); - } - else if (e.Action.Text == "Call") - { - RadMessageBox.Show("Call is clicked"); - } -} - -```` -````VB.NET -Private Sub radChat1_CardActionClicked(ByVal sender As Object, ByVal e As CardActionEventArgs) - If e.Action.Text = "IM" Then - RadMessageBox.Show("IM is clicked.") - ElseIf e.Action.Text = "Call" Then - RadMessageBox.Show("Call is clicked") - End If -End Sub - -```` - - -{{endregion}} + + + + >caption Figure 6: Handling ChatCardActions diff --git a/controls/chat/chat-items/messages.md b/controls/chat/chat-items/messages.md index a90997fb4..1ba202265 100644 --- a/controls/chat/chat-items/messages.md +++ b/controls/chat/chat-items/messages.md @@ -26,52 +26,20 @@ A **ChatTimeSeparatorMessage** visually separates the messages according to a ce #### Setting TimeSeparatorInterval -{{source=..\SamplesCS\Chat\ChatMessages.cs region=TimeSeparatorInterval}} -{{source=..\SamplesVB\Chat\ChatMessages.vb region=TimeSeparatorInterval}} + + -````C# - -this.radChat1.ChatElement.MessagesViewElement.TimeSeparatorInterval = TimeSpan.FromHours(1); -```` -````VB.NET -Me.radChat1.ChatElement.MessagesViewElement.TimeSeparatorInterval = TimeSpan.FromHours(1) - -```` - - -{{endregion}} When a new message is added, the **TimeSeparatorAdding** event is fired. It gives you the opportunity to control whether to add a time separator or not no matter the already specified **TimeSeparatorInterval**. The following example adds a time separator if the interval between messages is more than 20 seconds: #### Handling TimeSeparatorAdding -{{source=..\SamplesCS\Chat\ChatMessages.cs region=TimeSeparatorAdding}} -{{source=..\SamplesVB\Chat\ChatMessages.vb region=TimeSeparatorAdding}} - -````C# - -private void radChat1_TimeSeparatorAdding(object sender, TimeSeparatorEventArgs e) -{ - if (e.Item != null && e.PreviousItem != null) - { - e.ShouldAddSeparator = e.Item.Message.TimeStamp - e.PreviousItem.Message.TimeStamp > new TimeSpan(0, 0, 20); - } -} - -```` -````VB.NET -Private Sub radChat1_TimeSeparatorAdding(ByVal sender As Object, ByVal e As TimeSeparatorEventArgs) - If e.Item IsNot Nothing AndAlso e.PreviousItem IsNot Nothing Then - e.ShouldAddSeparator = e.Item.Message.TimeStamp - e.PreviousItem.Message.TimeStamp > New TimeSpan(0, 0, 20) - End If -End Sub + + -```` -{{endregion}} - >caption Figure 2: ChatTimeSeparatorMessage ![WinForms RadChat Separator Message](images/chat-items-messages003.png) @@ -87,39 +55,11 @@ A **ChatTextMessage** represents a single text message by a certain author and s #### Adding Text Messages -{{source=..\SamplesCS\Chat\ChatMessages.cs region=AddTextMessage}} -{{source=..\SamplesVB\Chat\ChatMessages.vb region=AddTextMessage}} - -````C# - -this.radChat1.Author = new Author(Properties.Resources.nancy1, "Nancy"); -Author author2 = new Author(Properties.Resources.andrew1, "Andrew"); - -ChatTextMessage message1 = new ChatTextMessage("Hello", author2, DateTime.Now.AddHours(1)); -this.radChat1.AddMessage(message1); - -ChatTextMessage message2 = new ChatTextMessage("Hi", this.radChat1.Author, DateTime.Now.AddHours(1).AddMinutes(10)); -this.radChat1.AddMessage(message2); - -ChatTextMessage message3 = new ChatTextMessage("How are you?", author2, DateTime.Now.AddHours(3)); -this.radChat1.AddMessage(message3); - -```` -````VB.NET -Me.radChat1.Author = New Author(My.Resources.nancy1, "Nancy") -Dim author2 As Author = New Author(My.Resources.andrew1, "Andrew") -Dim message1 As ChatTextMessage = New ChatTextMessage("Hello", author2, DateTime.Now.AddHours(1)) -Me.radChat1.AddMessage(message1) -Dim message2 As ChatTextMessage = New ChatTextMessage("Hi", Me.radChat1.Author, DateTime.Now.AddHours(1).AddMinutes(10)) -Me.radChat1.AddMessage(message2) -Dim message3 As ChatTextMessage = New ChatTextMessage("How are you?", author2, DateTime.Now.AddHours(3)) -Me.radChat1.AddMessage(message3) + + -```` -{{endregion}} - ## ChatMediaMessage A **ChatMediaMessage** represents an image message by a certain author and sent at certain time. @@ -132,24 +72,11 @@ A **ChatMediaMessage** represents an image message by a certain author and sent #### Adding Media Message -{{source=..\SamplesCS\Chat\ChatMessages.cs region=AddMediaMessage}} -{{source=..\SamplesVB\Chat\ChatMessages.vb region=AddMediaMessage}} - -````C# - -ChatMediaMessage mediaMessage = new ChatMediaMessage(Properties.Resources.TV_car1, new Size(300, 200), this.radChat1.Author, DateTime.Now, null); -this.radChat1.AddMessage(mediaMessage); - -```` -````VB.NET -Dim mediaMessage As ChatMediaMessage = New ChatMediaMessage(My.Resources.TV_car1, New Size(300, 200), Me.radChat1.Author, DateTime.Now, Nothing) -Me.radChat1.AddMessage(mediaMessage) + + -```` -{{endregion}} - ## ChatCardMessage A **ChatCardMessage** stores a message that visualizes a card element, a descendant of **BaseChatCardElement**. In the [Cards]({%slug winforms/chat/chat-items/cards%}) help article you can find additional information about the different card types and how to add card messages. @@ -165,60 +92,10 @@ A **ChatCarouselMessage** allows adding and visualizing multiple [card elements] #### Adding Carousel Message with Cards -{{source=..\SamplesCS\Chat\ChatMessages.cs region=AddCarouselMessage}} -{{source=..\SamplesVB\Chat\ChatMessages.vb region=AddCarouselMessage}} - -````C# - -Telerik.WinControls.UI.ChatImageCardDataItem imageCard = new ChatImageCardDataItem(Properties.Resources.architect, "Benjamin Vilanders", "Senior Architect", - "As a Senior Architect his experience in the industry allows him to take on increased responsibility. Like other architects, he design buildings " + - "and makes sure they are structurally sound. Due to his track record of quality performance, Benjamin also serves as a manager, a mentor, an advisor and coordinator.", - null , null); - -ChatProductCardDataItem productCard = new ChatProductCardDataItem(Properties.Resources.TV_car1,"Arrive & Drive","Rating 7/10", - "With our Arrive & Drive Packages, the only thing you will have to think about is driving. We make it simple for you to get more of what you love. We streamline the " + - "entire process and have everything ready for you when you arrive at the track so you can get straight to racing.", "Packages from $340", null, null); - -ChatWeatherCardDataItem weatherCard = new ChatWeatherCardDataItem("Florence", Properties.Resources.sunny , "33°C", "Humidity: 76%", "Dew: 31°C", - "Pressure: 1031 mb", "Wind Speed: 15 km/h NW"); - -List flights = new List(); -flights.Add(new FlightInfo("Los Angelis", "LAX", DateTime.Now.AddDays(7), "New York", "JFK", DateTime.Now.AddDays(7).AddHours(5.5))); -flights.Add(new FlightInfo("New York", "JFK", DateTime.Now.AddDays(14).AddHours(3), "Los Angelis", "LAX", DateTime.Now.AddDays(14).AddHours(9.1))); -ChatFlightCardDataItem flightCard = new ChatFlightCardDataItem("Andrew Fuller", flights, Properties.Resources.CardPlane, "$341", null); - -List cards = new List(); -cards.Add(imageCard); -cards.Add(productCard); -cards.Add(weatherCard); -cards.Add(flightCard); -Author author = new Author(Properties.Resources.architect, "Ben"); - -ChatCarouselMessage carouselMessage = new ChatCarouselMessage(cards, author, DateTime.Now); -this.radChat1.AddMessage(carouselMessage); - -```` -````VB.NET -Dim imageCard As Telerik.WinControls.UI.ChatImageCardDataItem = New ChatImageCardDataItem(My.Resources.architect, "Benjamin Vilanders", "Senior Architect", "As a Senior Architect his experience in the industry allows him to take on increased responsibility. Like other architects, he design buildings " & "and makes sure they are structurally sound. Due to his track record of quality performance, Benjamin also serves as a manager, a mentor, an advisor and coordinator.", Nothing, Nothing) -Dim productCard As ChatProductCardDataItem = New ChatProductCardDataItem(My.Resources.TV_car1, "Arrive & Drive", "Rating 7/10", "With our Arrive & Drive Packages, the only thing you will have to think about is driving. We make it simple for you to get more of what you love. We streamline the " & "entire process and have everything ready for you when you arrive at the track so you can get straight to racing.", "Packages from $340", Nothing, Nothing) -Dim weatherCard As ChatWeatherCardDataItem = New ChatWeatherCardDataItem("Florence", My.Resources.sunny, "33°C", "Humidity: 76%", "Dew: 31°C", "Pressure: 1031 mb", "Wind Speed: 15 km/h NW") -Dim flights As List(Of FlightInfo) = New List(Of FlightInfo)() -flights.Add(New FlightInfo("Los Angelis", "LAX", DateTime.Now.AddDays(7), "New York", "JFK", DateTime.Now.AddDays(7).AddHours(5.5))) -flights.Add(New FlightInfo("New York", "JFK", DateTime.Now.AddDays(14).AddHours(3), "Los Angelis", "LAX", DateTime.Now.AddDays(14).AddHours(9.1))) -Dim flightCard As ChatFlightCardDataItem = New ChatFlightCardDataItem("Andrew Fuller", flights, My.Resources.CardPlane, "$341", Nothing) -Dim cards As List(Of BaseChatCardDataItem) = New List(Of BaseChatCardDataItem)() -cards.Add(imageCard) -cards.Add(productCard) -cards.Add(weatherCard) -cards.Add(flightCard) -Dim author As Author = New Author(My.Resources.architect, "Ben") -Dim carouselMessage As ChatCarouselMessage = New ChatCarouselMessage(cards, author, DateTime.Now) -Me.radChat1.AddMessage(carouselMessage) - -```` - - -{{endregion}} + + + + ## ChatOverlayMessage @@ -230,36 +107,10 @@ A **ChatOverlayMessage** represents a **ChatMessage** that displays an [overlay #### Adding a ChatListOverlay Message -{{source=..\SamplesCS\Chat\ChatMessages.cs region=AddOverlayMessage}} -{{source=..\SamplesVB\Chat\ChatMessages.vb region=AddOverlayMessage}} - -````C# - -ChatListOverlay chatListOverlay = new ChatListOverlay("List overlay"); -for (int i = 0; i < 10; i++) -{ - chatListOverlay.ListView.Items.Add("Item " + i); -} -bool showAsPopup = false; -Author author = new Author(Properties.Resources.andrew1, "Andrew"); -ChatOverlayMessage overlayMessage = new ChatOverlayMessage(chatListOverlay, showAsPopup, author, DateTime.Now); -this.radChat1.AddMessage(overlayMessage); - -```` -````VB.NET -Dim chatListOverlay As ChatListOverlay = New ChatListOverlay("List overlay") -For i As Integer = 0 To 10 - 1 - chatListOverlay.ListView.Items.Add("Item " & i) -Next -Dim showAsPopup As Boolean = False -Dim author As Author = New Author(My.Resources.andrew1, "Andrew") -Dim overlayMessage As ChatOverlayMessage = New ChatOverlayMessage(chatListOverlay, showAsPopup, author, DateTime.Now) -Me.radChat1.AddMessage(overlayMessage) - -```` - - -{{endregion}} + + + + >caption Figure 7: ChatListOverlay @@ -277,52 +128,10 @@ A **ChatSuggestedActionsMessage** represents a message offering a list of **Sugg #### Adding a ChatSuggestedActionsMessage Message -{{source=..\SamplesCS\Chat\ChatMessages.cs region=AddSuggestedActionsMessage}} -{{source=..\SamplesVB\Chat\ChatMessages.vb region=AddSuggestedActionsMessage}} + + + -````C# - -private void AddSuggestedActions() -{ - this.radChat1.AddMessage(new ChatTextMessage("Hello, here are the choices", this.radChat1.Author, DateTime.Now)); - - List actions = new List(); - for (int i = 0; i < 7; i++) - { - actions.Add(new SuggestedActionDataItem("Option " + (i + 1))); - } - Author author = new Author(Properties.Resources.andrew1, "Andrew"); - ChatSuggestedActionsMessage suggestionActionsMessage = new ChatSuggestedActionsMessage(actions, author, DateTime.Now); - this.radChat1.AddMessage(suggestionActionsMessage); - this.radChat1.SuggestedActionClicked += radChat1_SuggestedActionClicked; -} - -private void radChat1_SuggestedActionClicked(object sender, SuggestedActionEventArgs e) -{ - this.radChat1.AddMessage(new ChatTextMessage("You have chosen " + e.Action.Text, this.radChat1.Author, DateTime.Now)); -} - -```` -````VB.NET -Private Sub AddSuggestedActions() - Me.radChat1.AddMessage(New ChatTextMessage("Hello, here are the choices", Me.radChat1.Author, DateTime.Now)) - Dim actions As List(Of SuggestedActionDataItem) = New List(Of SuggestedActionDataItem)() - For i As Integer = 0 To 7 - 1 - actions.Add(New SuggestedActionDataItem("Option " & (i + 1))) - Next - Dim author As Author = New Author(My.Resources.andrew1, "Andrew") - Dim suggestionActionsMessage As ChatSuggestedActionsMessage = New ChatSuggestedActionsMessage(actions, author, DateTime.Now) - Me.radChat1.AddMessage(suggestionActionsMessage) - AddHandler Me.radChat1.SuggestedActionClicked , AddressOf radChat1_SuggestedActionClicked -End Sub -Private Sub radChat1_SuggestedActionClicked(ByVal sender As Object, ByVal e As SuggestedActionEventArgs) - Me.radChat1.AddMessage(New ChatTextMessage("You have chosen " & e.Action.Text, Me.radChat1.Author, DateTime.Now)) -End Sub - -```` - - -{{endregion}} # See Also diff --git a/controls/chat/chat-items/overlays.md b/controls/chat/chat-items/overlays.md index 7d71c09c3..cffefca7e 100644 --- a/controls/chat/chat-items/overlays.md +++ b/controls/chat/chat-items/overlays.md @@ -28,28 +28,10 @@ When you press the `OK` button, a new message will be automatically added with t #### Adding a ChatCalendarOverlay -{{source=..\SamplesCS\Chat\ChatOverlaysActions.cs region=AddCalendarOverlay}} -{{source=..\SamplesVB\Chat\ChatOverlaysActions.vb region=AddCalendarOverlay}} + + -````C# -ChatCalendarOverlay calendarOverlay = new ChatCalendarOverlay("Select a date"); -bool showAsPopup = false; -Author author = new Author(Properties.Resources.andrew1, "Andrew"); -ChatOverlayMessage overlayMessage = new ChatOverlayMessage(calendarOverlay, showAsPopup, author, DateTime.Now); -this.radChat1.AddMessage(overlayMessage); -```` -````VB.NET -Dim calendarOverlay As ChatCalendarOverlay = New ChatCalendarOverlay("Select a date") -Dim showAsPopup As Boolean = False -Dim author As Author = New Author(My.Resources.andrew1, "Andrew") -Dim overlayMessage As ChatOverlayMessage = New ChatOverlayMessage(calendarOverlay, showAsPopup, author, DateTime.Now) -Me.radChat1.AddMessage(overlayMessage) - -```` - - -{{endregion}} You have access to the calendar itself by the ChatCalendarOverlay.**Calendar** property. @@ -63,28 +45,10 @@ You have access to the calendar itself by the ChatCalendarOverlay.**Calendar** p #### Adding a ChatDateTimeOverlay -{{source=..\SamplesCS\Chat\ChatOverlaysActions.cs region=AddDateTimeOverlay}} -{{source=..\SamplesVB\Chat\ChatOverlaysActions.vb region=AddDateTimeOverlay}} - -````C# -ChatDateTimeOverlay dateTimerOverlay = new ChatDateTimeOverlay("Select a date and time", DateTime.Now); -bool showAsPopup = false; -Author author = new Author(Properties.Resources.andrew1, "Andrew"); -ChatOverlayMessage overlayMessage = new ChatOverlayMessage(dateTimerOverlay, showAsPopup, author, DateTime.Now); -this.radChat1.AddMessage(overlayMessage); - -```` -````VB.NET -Dim dateTimerOverlay As ChatDateTimeOverlay = New ChatDateTimeOverlay("Select a date and time", DateTime.Now) -Dim showAsPopup As Boolean = False -Dim author As Author = New Author(My.Resources.andrew1, "Andrew") -Dim overlayMessage As ChatOverlayMessage = New ChatOverlayMessage(dateTimerOverlay, showAsPopup, author, DateTime.Now) -Me.radChat1.AddMessage(overlayMessage) - -```` + + -{{endregion}} ## ChatListOverlay @@ -96,35 +60,10 @@ Me.radChat1.AddMessage(overlayMessage) #### Adding a ChatListOverlay -{{source=..\SamplesCS\Chat\ChatOverlaysActions.cs region=AddListOverlay}} -{{source=..\SamplesVB\Chat\ChatOverlaysActions.vb region=AddListOverlay}} + + -````C# -ChatListOverlay listOverlay = new ChatListOverlay("List overlay"); -for (int i = 0; i < 10; i++) -{ - listOverlay.ListView.Items.Add("Item " + i); -} -bool showAsPopup = false; -Author author = new Author(Properties.Resources.andrew1, "Andrew"); -ChatOverlayMessage overlayMessage = new ChatOverlayMessage(listOverlay, showAsPopup, author, DateTime.Now); -this.radChat1.AddMessage(overlayMessage); -```` -````VB.NET -Dim listOverlay As ChatListOverlay = New ChatListOverlay("List overlay") -For i As Integer = 0 To 10 - 1 - listOverlay.ListView.Items.Add("Item " & i) -Next -Dim showAsPopup As Boolean = False -Dim author As Author = New Author(My.Resources.andrew1, "Andrew") -Dim overlayMessage As ChatOverlayMessage = New ChatOverlayMessage(listOverlay, showAsPopup, author, DateTime.Now) -Me.radChat1.AddMessage(overlayMessage) - -```` - - -{{endregion}} You have access to the list view by the ChatListOverlay.**ListView** property. @@ -138,28 +77,10 @@ You have access to the list view by the ChatListOverlay.**ListView** property. #### Adding a ChatTimeOverlay -{{source=..\SamplesCS\Chat\ChatOverlaysActions.cs region=AddTimeOverlay}} -{{source=..\SamplesVB\Chat\ChatOverlaysActions.vb region=AddTimeOverlay}} - -````C# -ChatTimeOverlay calendarOverlay = new ChatTimeOverlay("Select a date and time", DateTime.Now); -bool showAsPopup = false; -Author author = new Author(Properties.Resources.andrew1, "Andrew"); -ChatOverlayMessage overlayMessage = new ChatOverlayMessage(calendarOverlay, showAsPopup, author, DateTime.Now); -this.radChat1.AddMessage(overlayMessage); - -```` -````VB.NET -Dim calendarOverlay As ChatTimeOverlay = New ChatTimeOverlay("Select a date and time", DateTime.Now) -Dim showAsPopup As Boolean = False -Dim author As Author = New Author(My.Resources.andrew1, "Andrew") -Dim overlayMessage As ChatOverlayMessage = New ChatOverlayMessage(calendarOverlay, showAsPopup, author, DateTime.Now) -Me.radChat1.AddMessage(overlayMessage) - -```` + + -{{endregion}} # See Also diff --git a/controls/chat/chat-items/suggested-actions.md b/controls/chat/chat-items/suggested-actions.md index e14ed84b2..bfdf07e74 100644 --- a/controls/chat/chat-items/suggested-actions.md +++ b/controls/chat/chat-items/suggested-actions.md @@ -21,48 +21,11 @@ position: 4 #### Adding a SuggestedActionDataItem -{{source=..\SamplesCS\Chat\ChatOverlaysActions.cs region=AddSuggestedActions}} -{{source=..\SamplesVB\Chat\ChatOverlaysActions.vb region=AddSuggestedActions}} + + -````C# -private void AddSuggstedActions() -{ - this.radChat1.AddMessage(new ChatTextMessage("Hello, what kind of a vacation do you need?", this.radChat1.Author, DateTime.Now)); - List actions = new List(); - actions.Add(new SuggestedActionDataItem("Family trip")); - actions.Add(new SuggestedActionDataItem("Summer holiday with friends")); - actions.Add(new SuggestedActionDataItem("Business trip")); - Author author = new Author(Properties.Resources.andrew1, "Andrew"); - ChatSuggestedActionsMessage suggestionActionsMessage = new ChatSuggestedActionsMessage(actions, author, DateTime.Now); - this.radChat1.AddMessage(suggestionActionsMessage); - this.radChat1.SuggestedActionClicked += radChat1_SuggestedActionClicked; -} -private void radChat1_SuggestedActionClicked(object sender, SuggestedActionEventArgs e) -{ - this.radChat1.AddMessage(new ChatTextMessage("You have chosen " + e.Action.Text, this.radChat1.Author, DateTime.Now)); -} -```` -````VB.NET -Private Sub AddSuggstedActions() - Me.radChat1.AddMessage(New ChatTextMessage("Hello, what kind of a vacation do you need?", Me.radChat1.Author, DateTime.Now)) - Dim actions As List(Of SuggestedActionDataItem) = New List(Of SuggestedActionDataItem)() - actions.Add(New SuggestedActionDataItem("Family trip")) - actions.Add(New SuggestedActionDataItem("Summer holiday with friends")) - actions.Add(New SuggestedActionDataItem("Business trip")) - Dim author As Author = New Author(My.Resources.andrew1, "Andrew") - Dim suggestionActionsMessage As ChatSuggestedActionsMessage = New ChatSuggestedActionsMessage(actions, author, DateTime.Now) - Me.radChat1.AddMessage(suggestionActionsMessage) - AddHandler Me.radChat1.SuggestedActionClicked, AddressOf radChat1_SuggestedActionClicked -End Sub -Private Sub radChat1_SuggestedActionClicked(ByVal sender As Object, ByVal e As SuggestedActionEventArgs) - Me.radChat1.AddMessage(New ChatTextMessage("You have chosen " & e.Action.Text, Me.radChat1.Author, DateTime.Now)) -End Sub -```` - - -{{endregion}} # See Also diff --git a/controls/chat/chatelementfactory.md b/controls/chat/chatelementfactory.md index 9f244f0fb..87bcc7d8d 100644 --- a/controls/chat/chatelementfactory.md +++ b/controls/chat/chatelementfactory.md @@ -37,158 +37,10 @@ The following example demonstrates how to create a custom **ChatFactory**, overr #### Creating a custom ChatFactory -{{source=..\SamplesCS\Chat\ChatItemFactory.cs region=CustomFactory}} -{{source=..\SamplesVB\Chat\ChatItemFactory.vb region=CustomFactory}} + + -````C# -public void SetCustomFactory() -{ - this.radChat1.ChatElement.ChatFactory = new CustomChatFactory(); -} -public class CustomChatFactory : ChatFactory -{ - public override BaseChatItemElement CreateItemElement(BaseChatDataItem item) - { - if (item.GetType() == typeof(TextMessageDataItem)) - { - return new TextMessageItemElement(); - } - else if (item.GetType() == typeof(CardMessageDataItem)) - { - return new CardMessageItemElement(); - } - else if (item.GetType() == typeof(CarouselMessageDataItem)) - { - return new CarouselMessageItemElement(); - } - else if (item.GetType() == typeof(MediaMessageDataItem)) - { - return new MediaMessageItemElement(); - } - else if (item.GetType() == typeof(ChatTimeSeparatorDataItem)) - { - return new ChatTimeSeparatorItemElement(); - } - return base.CreateItemElement(item); - } - public override BaseChatCardElement CreateCardElement(BaseChatCardDataItem cardDataItem) - { - if (cardDataItem.GetType() == typeof(ChatFlightCardDataItem)) - { - return new ChatFlightCardElement(cardDataItem as ChatFlightCardDataItem); - } - else if (cardDataItem.GetType() == typeof(ChatImageCardDataItem)) - { - return new ChatImageCardElement(cardDataItem as ChatImageCardDataItem); - } - else if (cardDataItem.GetType() == typeof(ChatProductCardDataItem)) - { - return new ChatProductCardElement(cardDataItem as ChatProductCardDataItem); - } - else if (cardDataItem.GetType() == typeof(ChatWeatherCardDataItem)) - { - return new ChatWeatherCardElement(cardDataItem as ChatWeatherCardDataItem); - } - return base.CreateCardElement(cardDataItem); - } - public override ToolbarActionElement CreateToolbarActionElement(ToolbarActionDataItem item) - { - return new ToolbarActionElement(item); - } - public override SuggestedActionElement CreateSuggestedActionElement(SuggestedActionDataItem item) - { - return new SuggestedActionElement(item); - } - public override BaseChatDataItem CreateDataItem(ChatMessage message) - { - ChatTextMessage textMessage = message as ChatTextMessage; - if (textMessage != null) - { - return new TextMessageDataItem(textMessage); - } - ChatMediaMessage mediaMessage = message as ChatMediaMessage; - if (mediaMessage != null) - { - return new MediaMessageDataItem(mediaMessage); - } - ChatCardMessage cardMessage = message as ChatCardMessage; - if (cardMessage != null) - { - return new CardMessageDataItem(cardMessage); - } - ChatCarouselMessage carouselMessage = message as ChatCarouselMessage; - if (carouselMessage != null) - { - return new CarouselMessageDataItem(carouselMessage); - } - return base.CreateDataItem(message); - } -} -```` -````VB.NET -Public Sub SetCustomFactory() - Me.radChat1.ChatElement.ChatFactory = New CustomChatFactory() -End Sub -Public Class CustomChatFactory - Inherits ChatFactory - Public Overrides Function CreateItemElement(ByVal item As BaseChatDataItem) As BaseChatItemElement - If item.[GetType]() = GetType(TextMessageDataItem) Then - Return New TextMessageItemElement() - ElseIf item.[GetType]() = GetType(CardMessageDataItem) Then - Return New CardMessageItemElement() - ElseIf item.[GetType]() = GetType(CarouselMessageDataItem) Then - Return New CarouselMessageItemElement() - ElseIf item.[GetType]() = GetType(MediaMessageDataItem) Then - Return New MediaMessageItemElement() - ElseIf item.[GetType]() = GetType(ChatTimeSeparatorDataItem) Then - Return New ChatTimeSeparatorItemElement() - End If - Return MyBase.CreateItemElement(item) - End Function - Public Overrides Function CreateCardElement(ByVal cardDataItem As BaseChatCardDataItem) As BaseChatCardElement - If cardDataItem.[GetType]() = GetType(ChatFlightCardDataItem) Then - Return New ChatFlightCardElement(TryCast(cardDataItem, ChatFlightCardDataItem)) - ElseIf cardDataItem.[GetType]() = GetType(ChatImageCardDataItem) Then - Return New ChatImageCardElement(TryCast(cardDataItem, ChatImageCardDataItem)) - ElseIf cardDataItem.[GetType]() = GetType(ChatProductCardDataItem) Then - Return New ChatProductCardElement(TryCast(cardDataItem, ChatProductCardDataItem)) - ElseIf cardDataItem.[GetType]() = GetType(ChatWeatherCardDataItem) Then - Return New ChatWeatherCardElement(TryCast(cardDataItem, ChatWeatherCardDataItem)) - End If - Return MyBase.CreateCardElement(cardDataItem) - End Function - Public Overrides Function CreateToolbarActionElement(ByVal item As ToolbarActionDataItem) As ToolbarActionElement - Return New ToolbarActionElement(item) - End Function - Public Overrides Function CreateSuggestedActionElement(ByVal item As SuggestedActionDataItem) As SuggestedActionElement - Return New SuggestedActionElement(item) - End Function - Public Overrides Function CreateDataItem(ByVal message As ChatMessage) As BaseChatDataItem - Dim textMessage As ChatTextMessage = TryCast(message, ChatTextMessage) - If textMessage IsNot Nothing Then - Return New TextMessageDataItem(textMessage) - End If - Dim mediaMessage As ChatMediaMessage = TryCast(message, ChatMediaMessage) - If mediaMessage IsNot Nothing Then - Return New MediaMessageDataItem(mediaMessage) - End If - Dim cardMessage As ChatCardMessage = TryCast(message, ChatCardMessage) - If cardMessage IsNot Nothing Then - Return New CardMessageDataItem(cardMessage) - End If - Dim carouselMessage As ChatCarouselMessage = TryCast(message, ChatCarouselMessage) - If carouselMessage IsNot Nothing Then - Return New CarouselMessageDataItem(carouselMessage) - End If - Return MyBase.CreateDataItem(message) - End Function -End Class - -```` - - -{{endregion}} ## See Also diff --git a/controls/chat/customizing-appearance/accessing-and-customizing-elements.md b/controls/chat/customizing-appearance/accessing-and-customizing-elements.md index 66069455f..c5104d4ec 100644 --- a/controls/chat/customizing-appearance/accessing-and-customizing-elements.md +++ b/controls/chat/customizing-appearance/accessing-and-customizing-elements.md @@ -43,84 +43,10 @@ The **ItemFormatting** event can be used to access and change the styling of the #### Customizing The Main Item Elements -{{source=..\SamplesCS\Chat\ChatFormatting.cs region=RadChatItemFormatting}} -{{source=..\SamplesVB\Chat\ChatFormatting.vb region=RadChatItemFormatting}} -````C# -private void RadChat1_ItemFormatting(object sender, ChatItemElementEventArgs e) -{ - if (e.ItemElement is TextMessageItemElement) - { - e.ItemElement.DrawBorder = true; - e.ItemElement.BorderBoxStyle = Telerik.WinControls.BorderBoxStyle.FourBorders; - e.ItemElement.BorderLeftColor = Color.Transparent; - e.ItemElement.BorderTopColor = Color.Transparent; - e.ItemElement.BorderRightColor = Color.Transparent; - e.ItemElement.BorderBottomColor = Color.LightBlue; - } - else if (e.ItemElement is MediaMessageItemElement) - { - e.ItemElement.DrawFill = true; - e.ItemElement.BackColor = Color.LightGreen; - } - else if (e.ItemElement is CardMessageItemElement) - { - e.ItemElement.DrawFill = true; - e.ItemElement.BackColor = Color.LightBlue; - } - else if (e.ItemElement is CarouselMessageItemElement) - { - e.ItemElement.DrawFill = true; - e.ItemElement.BackColor = Color.LightCoral; - } - else - { - e.ItemElement.ResetValue(LightVisualElement.DrawBorderProperty, Telerik.WinControls.ValueResetFlags.Local); - e.ItemElement.ResetValue(LightVisualElement.BorderBoxStyleProperty, Telerik.WinControls.ValueResetFlags.Local); - e.ItemElement.ResetValue(LightVisualElement.BorderLeftColorProperty, Telerik.WinControls.ValueResetFlags.Local); - e.ItemElement.ResetValue(LightVisualElement.BorderRightColorProperty, Telerik.WinControls.ValueResetFlags.Local); - e.ItemElement.ResetValue(LightVisualElement.BorderTopColorProperty, Telerik.WinControls.ValueResetFlags.Local); - e.ItemElement.ResetValue(LightVisualElement.BorderBottomColorProperty, Telerik.WinControls.ValueResetFlags.Local); - e.ItemElement.ResetValue(LightVisualElement.DrawFillProperty, Telerik.WinControls.ValueResetFlags.Local); - e.ItemElement.ResetValue(LightVisualElement.BackColorProperty, Telerik.WinControls.ValueResetFlags.Local); - } -} - -```` -````VB.NET -Private Sub RadChat1_ItemFormatting(ByVal sender As Object, ByVal e As ChatItemElementEventArgs) - If TypeOf e.ItemElement Is TextMessageItemElement Then - e.ItemElement.DrawBorder = True - e.ItemElement.BorderBoxStyle = Telerik.WinControls.BorderBoxStyle.FourBorders - e.ItemElement.BorderLeftColor = Color.Transparent - e.ItemElement.BorderTopColor = Color.Transparent - e.ItemElement.BorderRightColor = Color.Transparent - e.ItemElement.BorderBottomColor = Color.LightBlue - ElseIf TypeOf e.ItemElement Is MediaMessageItemElement Then - e.ItemElement.DrawFill = True - e.ItemElement.BackColor = Color.LightGreen - ElseIf TypeOf e.ItemElement Is CardMessageItemElement Then - e.ItemElement.DrawFill = True - e.ItemElement.BackColor = Color.LightBlue - ElseIf TypeOf e.ItemElement Is CarouselMessageItemElement Then - e.ItemElement.DrawFill = True - e.ItemElement.BackColor = Color.LightCoral - Else - e.ItemElement.ResetValue(LightVisualElement.DrawBorderProperty, Telerik.WinControls.ValueResetFlags.Local) - e.ItemElement.ResetValue(LightVisualElement.BorderBoxStyleProperty, Telerik.WinControls.ValueResetFlags.Local) - e.ItemElement.ResetValue(LightVisualElement.BorderLeftColorProperty, Telerik.WinControls.ValueResetFlags.Local) - e.ItemElement.ResetValue(LightVisualElement.BorderRightColorProperty, Telerik.WinControls.ValueResetFlags.Local) - e.ItemElement.ResetValue(LightVisualElement.BorderTopColorProperty, Telerik.WinControls.ValueResetFlags.Local) - e.ItemElement.ResetValue(LightVisualElement.BorderBottomColorProperty, Telerik.WinControls.ValueResetFlags.Local) - e.ItemElement.ResetValue(LightVisualElement.DrawFillProperty, Telerik.WinControls.ValueResetFlags.Local) - e.ItemElement.ResetValue(LightVisualElement.BackColorProperty, Telerik.WinControls.ValueResetFlags.Local) - End If -End Sub - -```` - - - -{{endregion}} + + + + >caption Figure 1: Text and Media Items @@ -136,68 +62,10 @@ End Sub #### Customizing the Child Items -{{source=..\SamplesCS\Chat\ChatFormatting.cs region=ItemFormattingCildren}} -{{source=..\SamplesVB\Chat\ChatFormatting.vb region=ItemFormattingCildren}} -````C# -Font f = new Font("Calibri", 12f, FontStyle.Bold); -private void RadChat1_ItemFormattingCildren(object sender, ChatItemElementEventArgs e) -{ - ChatMessageAvatarElement avatar = e.ItemElement.AvatarPictureElement; - ChatMessageNameElement name = e.ItemElement.NameLabelElement; - ChatMessageStatusElement status = e.ItemElement.StatusLabelElement; - LightVisualElement bubble = e.ItemElement.MainMessageElement; - if (!e.ItemElement.IsOwnMessage && e.ItemElement is TextMessageItemElement) - { - avatar.DrawImage = false; - name.Font = f; - bubble.DrawFill = true; - bubble.BackColor = Color.LightGreen; - bubble.ShadowDepth = 3; - bubble.ShadowColor = Color.Green; - } - else - { - avatar.ResetValue(LightVisualElement.ImageProperty, Telerik.WinControls.ValueResetFlags.Local); - name.ResetValue(LightVisualElement.FontProperty, Telerik.WinControls.ValueResetFlags.All); - status.ResetValue(LightVisualElement.VisibilityProperty, Telerik.WinControls.ValueResetFlags.Local); - bubble.ResetValue(LightVisualElement.DrawFillProperty, Telerik.WinControls.ValueResetFlags.Local); - bubble.ResetValue(LightVisualElement.BackColorProperty, Telerik.WinControls.ValueResetFlags.Local); - bubble.ResetValue(LightVisualElement.ShadowDepthProperty, Telerik.WinControls.ValueResetFlags.Local); - bubble.ResetValue(LightVisualElement.ShadowColorProperty, Telerik.WinControls.ValueResetFlags.Local); - } -} - -```` -````VB.NET -Private f As Font = New Font("Calibri", 12.0F, FontStyle.Bold) -Private Sub RadChat1_ItemFormattingCildren(ByVal sender As Object, ByVal e As ChatItemElementEventArgs) - Dim avatar As ChatMessageAvatarElement = e.ItemElement.AvatarPictureElement - Dim name As ChatMessageNameElement = e.ItemElement.NameLabelElement - Dim status As ChatMessageStatusElement = e.ItemElement.StatusLabelElement - Dim bubble As LightVisualElement = e.ItemElement.MainMessageElement - If Not e.ItemElement.IsOwnMessage AndAlso TypeOf e.ItemElement Is TextMessageItemElement Then - avatar.DrawImage = False - name.Font = f - bubble.DrawFill = True - bubble.BackColor = Color.LightGreen - bubble.ShadowDepth = 3 - bubble.ShadowColor = Color.Green - Else - avatar.ResetValue(LightVisualElement.ImageProperty, Telerik.WinControls.ValueResetFlags.Local) - name.ResetValue(LightVisualElement.FontProperty, Telerik.WinControls.ValueResetFlags.All) - status.ResetValue(LightVisualElement.VisibilityProperty, Telerik.WinControls.ValueResetFlags.Local) - bubble.ResetValue(LightVisualElement.DrawFillProperty, Telerik.WinControls.ValueResetFlags.Local) - bubble.ResetValue(LightVisualElement.BackColorProperty, Telerik.WinControls.ValueResetFlags.Local) - bubble.ResetValue(LightVisualElement.ShadowDepthProperty, Telerik.WinControls.ValueResetFlags.Local) - bubble.ResetValue(LightVisualElement.ShadowColorProperty, Telerik.WinControls.ValueResetFlags.Local) - End If -End Sub - -```` - - - -{{endregion}} + + + + >caption Figure 4: Customizing the Child Elements diff --git a/controls/chat/customizing-appearance/custom-items.md b/controls/chat/customizing-appearance/custom-items.md index b1460e900..246368535 100644 --- a/controls/chat/customizing-appearance/custom-items.md +++ b/controls/chat/customizing-appearance/custom-items.md @@ -28,187 +28,10 @@ The following example demonstrates a sample code snippet how to add a button ele #### Creating a custom message -{{source=..\SamplesCS\Chat\ChatItemFactory.cs region=CustomMessage}} -{{source=..\SamplesVB\Chat\ChatItemFactory.vb region=CustomMessage}} + + -````C# -private void CustomMessage() -{ - this.radChat1.ChatElement.ChatFactory = new MyChatFactory(); - this.radChat1.Author = new Author(Properties.Resources.nancy1, "Nancy"); - Author author2 = new Author(Properties.Resources.andrew1,"Andrew"); - ChatTextMessage message1 = new ChatTextMessage("Hello", author2,DateTime.Now.AddHours(1)); - this.radChat1.AddMessage(message1); - ChatTextMessage message2 = new ChatTextMessage("Hi", this.radChat1.Author,DateTime.Now.AddHours(1).AddMinutes(10)); - this.radChat1.AddMessage(message2); - ChatTextMessage message3 = new ChatTextMessage("We would like to announce that in the R2 2018 release we introduced Conversational UI", author2,DateTime.Now.AddHours(3)); - this.radChat1.AddMessage(message3); -} -public class MyChatFactory : ChatFactory -{ - public override BaseChatItemElement CreateItemElement(BaseChatDataItem item) - { - if (item.GetType() == typeof(TextMessageDataItem)) - { - return new MyTextMessageItemElement(); - } - return base.CreateItemElement(item); - } -} -public class MyTextMessageItemElement : TextMessageItemElement -{ - LightVisualButtonElement likeButton = new LightVisualButtonElement(); - protected override void CreateChildElements() - { - base.CreateChildElements(); - likeButton.NotifyParentOnMouseInput = true; - likeButton.Image = Properties.Resources.heart_empty; - likeButton.Click += likeButton_Click; - likeButton.EnableElementShadow = false; - likeButton.Margin = new Padding(10, 0, 10, 0); - this.Children.Add(likeButton); - } - private void likeButton_Click(object sender, EventArgs e) - { - if (this.Data.Tag == null) - { - this.Data.Tag = true; - } - else - { - bool isLiked = (bool)this.Data.Tag; - this.Data.Tag = !isLiked; - } - } - public override void Synchronize() - { - base.Synchronize(); - if (this.Data.Tag != null && (bool)this.Data.Tag == true) - { - this.likeButton.Image = Properties.Resources.heart_filled; - } - else - { - this.likeButton.Image = Properties.Resources.heart_empty; - } - } - protected override SizeF ArrangeOverride(SizeF finalSize) - { - SizeF baseSize = base.ArrangeOverride(finalSize); - RectangleF likeButtonRect; - RectangleF clientRect = this.GetClientRectangle(finalSize); - if (this.Data.ChatMessagesViewElement.ShowAvatars) - { - if (this.Data.ChatMessagesViewElement.ShowMessagesOnOneSide || !this.Data.IsOwnMessage) - { - likeButtonRect = new RectangleF(clientRect.X+this.AvatarPictureElement.DesiredSize.Width + this.MainMessageElement.DesiredSize.Width, - clientRect.Y + this.NameLabelElement.DesiredSize.Height+this.MainMessageElement.DesiredSize.Height/3, - this.likeButton.Image.Width, this.likeButton.Image.Height); - } - else - { - likeButtonRect = new RectangleF(clientRect.Right - likeButton.DesiredSize.Width - this.AvatarPictureElement.DesiredSize.Width - this.MainMessageElement.DesiredSize.Width, - clientRect.Y + this.NameLabelElement.DesiredSize.Height+this.MainMessageElement.DesiredSize.Height/3, - this.likeButton.Image.Width, this.likeButton.Image.Height); - } - } - else - { - if (this.Data.ChatMessagesViewElement.ShowMessagesOnOneSide || !this.Data.IsOwnMessage) - { - likeButtonRect = new RectangleF(clientRect.X+ this.MainMessageElement.DesiredSize.Width, - clientRect.Y + this.NameLabelElement.DesiredSize.Height+this.MainMessageElement.DesiredSize.Height/3, - this.likeButton.Image.Width, this.likeButton.Image.Height); - } - else - { - likeButtonRect = new RectangleF(clientRect.Right - likeButton.DesiredSize.Width - this.MainMessageElement.DesiredSize.Width, - clientRect.Y + this.NameLabelElement.DesiredSize.Height+this.MainMessageElement.DesiredSize.Height/3, - this.likeButton.Image.Width, this.likeButton.Image.Height); - } - } - this.likeButton.Arrange(likeButtonRect); - return baseSize; - } -} -```` -````VB.NET -Private Sub CustomMessage() - Me.radChat1.ChatElement.ChatFactory = New MyChatFactory() - Me.radChat1.Author = New Author(My.Resources.nancy1, "Nancy") - Dim author2 As Author = New Author(My.Resources.andrew1, "Andrew") - Dim message1 As ChatTextMessage = New ChatTextMessage("Hello", author2, DateTime.Now.AddHours(1)) - Me.radChat1.AddMessage(message1) - Dim message2 As ChatTextMessage = New ChatTextMessage("Hi", Me.radChat1.Author, DateTime.Now.AddHours(1).AddMinutes(10)) - Me.radChat1.AddMessage(message2) - Dim message3 As ChatTextMessage = New ChatTextMessage("We would like to announce that in the R2 2018 release we introduced Conversational UI", author2, DateTime.Now.AddHours(3)) - Me.radChat1.AddMessage(message3) -End Sub -Public Class MyChatFactory - Inherits ChatFactory - Public Overrides Function CreateItemElement(ByVal item As BaseChatDataItem) As BaseChatItemElement - If item.[GetType]() = GetType(TextMessageDataItem) Then - Return New MyTextMessageItemElement() - End If - Return MyBase.CreateItemElement(item) - End Function -End Class -Public Class MyTextMessageItemElement - Inherits TextMessageItemElement - Private likeButton As LightVisualButtonElement - Protected Overrides Sub CreateChildElements() - MyBase.CreateChildElements() - likeButton = New LightVisualButtonElement() - likeButton.NotifyParentOnMouseInput = True - likeButton.Image = My.Resources.heart_empty - AddHandler likeButton.Click, AddressOf likeButton_Click - likeButton.EnableElementShadow = False - likeButton.Margin = New Padding(10, 0, 10, 0) - Me.Children.Add(likeButton) - End Sub - Private Sub likeButton_Click(ByVal sender As Object, ByVal e As EventArgs) - If Me.Data.Tag Is Nothing Then - Me.Data.Tag = True - Else - Dim isLiked As Boolean = CBool(Me.Data.Tag) - Me.Data.Tag = Not isLiked - End If - End Sub - Public Overrides Sub Synchronize() - MyBase.Synchronize() - If Me.Data.Tag IsNot Nothing AndAlso CBool(Me.Data.Tag) = True Then - Me.likeButton.Image = My.Resources.heart_filled - Else - Me.likeButton.Image = My.Resources.heart_empty - End If - End Sub - Protected Overrides Function ArrangeOverride(ByVal finalSize As SizeF) As SizeF - Dim baseSize As SizeF = MyBase.ArrangeOverride(finalSize) - Dim likeButtonRect As RectangleF - Dim clientRect As RectangleF = Me.GetClientRectangle(finalSize) - If Me.Data.ChatMessagesViewElement.ShowAvatars Then - If Me.Data.ChatMessagesViewElement.ShowMessagesOnOneSide OrElse Not Me.Data.IsOwnMessage Then - likeButtonRect = New RectangleF(clientRect.X + Me.AvatarPictureElement.DesiredSize.Width + Me.MainMessageElement.DesiredSize.Width, clientRect.Y + Me.NameLabelElement.DesiredSize.Height + Me.MainMessageElement.DesiredSize.Height / 3, Me.likeButton.Image.Width, Me.likeButton.Image.Height) - Else - likeButtonRect = New RectangleF(clientRect.Right - likeButton.DesiredSize.Width - Me.AvatarPictureElement.DesiredSize.Width - Me.MainMessageElement.DesiredSize.Width, clientRect.Y + Me.NameLabelElement.DesiredSize.Height + Me.MainMessageElement.DesiredSize.Height / 3, Me.likeButton.Image.Width, Me.likeButton.Image.Height) - End If - Else - If Me.Data.ChatMessagesViewElement.ShowMessagesOnOneSide OrElse Not Me.Data.IsOwnMessage Then - likeButtonRect = New RectangleF(clientRect.X + Me.MainMessageElement.DesiredSize.Width, clientRect.Y + Me.NameLabelElement.DesiredSize.Height + Me.MainMessageElement.DesiredSize.Height / 3, Me.likeButton.Image.Width, Me.likeButton.Image.Height) - Else - likeButtonRect = New RectangleF(clientRect.Right - likeButton.DesiredSize.Width - Me.MainMessageElement.DesiredSize.Width, clientRect.Y + Me.NameLabelElement.DesiredSize.Height + Me.MainMessageElement.DesiredSize.Height / 3, Me.likeButton.Image.Width, Me.likeButton.Image.Height) - End If - End If - Me.likeButton.Arrange(likeButtonRect) - Return baseSize - End Function -End Class - -```` - - -{{endregion}} ## See Also diff --git a/controls/chat/customizing-appearance/custom-overlays.md b/controls/chat/customizing-appearance/custom-overlays.md index 003f154ae..2ada70909 100644 --- a/controls/chat/customizing-appearance/custom-overlays.md +++ b/controls/chat/customizing-appearance/custom-overlays.md @@ -22,125 +22,19 @@ To achieve this goal, you need to create a derivative of the **BaseChatItemOverl #### Constructing a custom overlay with RadMultiColumnComboBox -{{source=..\SamplesCS\Chat\ChatOverlaysActions.cs region=CustomOverlay}} -{{source=..\SamplesVB\Chat\ChatOverlaysActions.vb region=CustomOverlay}} - -````C# -public class CustomBaseChatItemOverlay : BaseChatItemOverlay -{ - public CustomBaseChatItemOverlay(string title) - : base(title) - { - this.mccb.SelectedValueChanged += mccb_SelectedValueChanged; - } - public RadMultiColumnComboBox Mccb - { - get - { - return this.mccb; - } - } - private void mccb_SelectedValueChanged(object sender, EventArgs e) - { - if (this.mccb.SelectedItem != null) - { - this.CurrentValue = this.mccb.SelectedValue; - } - } - RadMultiColumnComboBox mccb; - protected override Telerik.WinControls.RadElement CreateMainElement() - { - mccb = new RadMultiColumnComboBox(); - return new RadHostItem(this.mccb); - } - protected override void DisposeManagedResources() - { - this.mccb.SelectedValueChanged -= mccb_SelectedValueChanged; - base.DisposeManagedResources(); - } -} - -```` -````VB.NET -Public Class CustomBaseChatItemOverlay - Inherits BaseChatItemOverlay - Public Sub New(ByVal title As String) - MyBase.New(title) - AddHandler Me.Mccb.SelectedValueChanged, AddressOf mccb_SelectedValueChanged - End Sub - Public ReadOnly Property Mccb As RadMultiColumnComboBox - Get - Return Me._mccb - End Get - End Property - Private Sub mccb_SelectedValueChanged(ByVal sender As Object, ByVal e As EventArgs) - If Me.Mccb.SelectedItem IsNot Nothing Then - Me.CurrentValue = Me.Mccb.SelectedValue - End If - End Sub - Private _mccb As RadMultiColumnComboBox - Protected Overrides Function CreateMainElement() As Telerik.WinControls.RadElement - Me._mccb = New RadMultiColumnComboBox() - Return New RadHostItem(Me._mccb) - End Function - Protected Overrides Sub DisposeManagedResources() - RemoveHandler Me.Mccb.SelectedValueChanged, AddressOf mccb_SelectedValueChanged - MyBase.DisposeManagedResources() - End Sub -End Class - -```` - - -{{endregion}} + + + + Then, you just need to add your overlay to the **Chat UI** when it is necessary to present the user the options from which to choose: #### Adding a custom overlay to the Chat UI -{{source=..\SamplesCS\Chat\ChatOverlaysActions.cs region=UseOverlay}} -{{source=..\SamplesVB\Chat\ChatOverlaysActions.vb region=UseOverlay}} - -````C# -CustomBaseChatItemOverlay customOverlay = new CustomBaseChatItemOverlay("Custom overlay"); -DataTable dt = new DataTable(); -dt.Columns.Add("Id", typeof(int)); -dt.Columns.Add("Name", typeof(string)); -for (int i = 0; i < 10; i++) -{ - dt.Rows.Add(i, "Item" + i); -} -customOverlay.Mccb.DisplayMember = "Name"; -customOverlay.Mccb.ValueMember = "Id"; -customOverlay.Mccb.DataSource = dt; -bool showAsPopup = false; -Author author = new Author(Properties.Resources.andrew1, "Andrew"); -this.radChat1.Author = author; -ChatOverlayMessage overlayMessage = new ChatOverlayMessage(customOverlay, showAsPopup, author, DateTime.Now); -this.radChat1.AddMessage(overlayMessage); - -```` -````VB.NET -Dim customOverlay As CustomBaseChatItemOverlay = New CustomBaseChatItemOverlay("Custom overlay") -Dim dt As DataTable = New DataTable() -dt.Columns.Add("Id", GetType(Integer)) -dt.Columns.Add("Name", GetType(String)) -For i As Integer = 0 To 10 - 1 - dt.Rows.Add(i, "Item" & i) -Next -customOverlay.Mccb.DisplayMember = "Name" -customOverlay.Mccb.ValueMember = "Id" -customOverlay.Mccb.DataSource = dt -Dim showAsPopup As Boolean = False -Dim author As Author = New Author(My.Resources.andrew1, "Andrew") -Me.radChat1.Author = author -Dim overlayMessage As ChatOverlayMessage = New ChatOverlayMessage(customOverlay, showAsPopup, author, DateTime.Now) -Me.radChat1.AddMessage(overlayMessage) - -```` - - -{{endregion}} + + + + # See Also diff --git a/controls/chat/getting-started.md b/controls/chat/getting-started.md index 8492beef6..82164b2e5 100644 --- a/controls/chat/getting-started.md +++ b/controls/chat/getting-started.md @@ -41,21 +41,10 @@ The Telerik UI for WinForms assemblies can be install by using one of the availa #### Setting default author -{{source=..\SamplesCS\Chat\ChatGettingStarted.cs region=SetAuthor}} -{{source=..\SamplesVB\Chat\ChatGettingStarted.vb region=SetAuthor}} + + -````C# -this.radChat1.Author = new Author(Properties.Resources.architect, "Ben"); -```` -````VB.NET -Me.radChat1.Author = New Author(My.Resources.architect, "Ben") - -```` - - - -{{endregion}} Now, you are ready to start sending messages: @@ -67,40 +56,10 @@ If the RadChat.**AutoAddUserMessages** property is set to *false* the message fr #### Adding message programmatically -{{source=..\SamplesCS\Chat\ChatGettingStarted.cs region=AddMessage}} -{{source=..\SamplesVB\Chat\ChatGettingStarted.vb region=AddMessage}} + + + -````C# - -private void AddMessageProgrammatically() -{ - this.radChat1.AutoAddUserMessages = false; - this.radChat1.SendMessage += radChat1_SendMessage; -} - -private void radChat1_SendMessage(object sender, SendMessageEventArgs e) -{ - ChatTextMessage textMessage = e.Message as ChatTextMessage; - textMessage.Message = "[Slightly changed message] " + textMessage.Message; - this.radChat1.AddMessage(textMessage); -} - -```` -````VB.NET -Private Sub AddMessageProgrammatically() - Me.radChat1.AutoAddUserMessages = False - AddHandler Me.radChat1.SendMessage, AddressOf radChat1_SendMessage -End Sub -Private Sub radChat1_SendMessage(ByVal sender As Object, ByVal e As SendMessageEventArgs) - Dim textMessage As ChatTextMessage = TryCast(e.Message, ChatTextMessage) - textMessage.Message = "[Slightly changed message] " & textMessage.Message - Me.radChat1.AddMessage(textMessage) -End Sub - -```` - - -{{endregion}} ![WinForms RadChat Adding Message Programmatically](images/chat-items-getting-started003.gif) diff --git a/controls/chat/how-to/scroll-to-item.md b/controls/chat/how-to/scroll-to-item.md index 21a9979b8..aacbe8ca7 100644 --- a/controls/chat/how-to/scroll-to-item.md +++ b/controls/chat/how-to/scroll-to-item.md @@ -16,10 +16,8 @@ In R3 2019 the we have introduced the __ScrollToItem__ method. It allows you to #### ScrollToItem method -{{source=..\SamplesCS\Chat\ChatItemFactory.cs region=Scroll}} -{{source=..\SamplesVB\Chat\ChatItemFactory.vb region=Scroll}} + + -{{endregion}} - diff --git a/controls/chat/localization/localization.md b/controls/chat/localization/localization.md index ed8e28370..a6f1de5fc 100644 --- a/controls/chat/localization/localization.md +++ b/controls/chat/localization/localization.md @@ -22,83 +22,19 @@ Below is a sample implementation of an English localization provider: #### Localizing RadChat Strings -{{source=..\SamplesCS\Chat\ChatLocalization.cs region=myEnglishLocalizationProvider}} -{{source=..\SamplesVB\Chat\ChatLocalization.vb region=myEnglishLocalizationProvider}} - -````C# -public class MyEnglishChatLocalizationProvider : Telerik.WinControls.Localization.ChatLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case ChatStringId.TypeAMessage: return "Type a message"; - case ChatStringId.OverlayOK: return "OK"; - case ChatStringId.OverlayCancel: return "Cancel"; - case ChatStringId.FlightCardDeparture: return "Departure"; - case ChatStringId.FlightCardArrival: return "Arrival"; - case ChatStringId.FlightCardPassenger: return "Passenger"; - case ChatStringId.FlightCardTotal: return "Total"; - case ChatStringId.TodayStamp: return "TODAY"; - case ChatStringId.YesterdayStamp: return "YESTERDAY"; - default: - break; - } - return base.GetLocalizedString(id); - } -} - -```` -````VB.NET -Public Class MyEnglishChatLocalizationProvider - Inherits Telerik.WinControls.Localization.ChatLocalizationProvider - Public Overrides Function GetLocalizedString(ByVal id As String) As String - Select Case id - Case ChatStringId.TypeAMessage - Return "Type a message" - Case ChatStringId.OverlayOK - Return "OK" - Case ChatStringId.OverlayCancel - Return "Cancel" - Case ChatStringId.FlightCardDeparture - Return "Departure" - Case ChatStringId.FlightCardArrival - Return "Arrival" - Case ChatStringId.FlightCardPassenger - Return "Passenger" - Case ChatStringId.FlightCardTotal - Return "Total" - Case ChatStringId.TodayStamp - Return "TODAY" - Case ChatStringId.YesterdayStamp - Return "YESTERDAY" - Case Else - End Select - Return MyBase.GetLocalizedString(id) - End Function -End Class - -```` - -{{endregion}} + + + + To apply the custom localization provider, instantiate and assign it to the current localization provider: #### Assigning the Current Localization Provider -{{source=..\SamplesCS\Chat\ChatLocalization.cs region=localizeChat}} -{{source=..\SamplesVB\Chat\ChatLocalization.vb region=localizeChat}} - -````C# -ChatLocalizationProvider.CurrentProvider = new MyEnglishChatLocalizationProvider(); - -```` -````VB.NET -ChatLocalizationProvider.CurrentProvider = New MyEnglishChatLocalizationProvider() + + -```` -{{endregion}} The code provided above illustrates the approach to be used to localize the **RadChat** and is not intended as a full translation. diff --git a/controls/chat/toolbar.md b/controls/chat/toolbar.md index 4ddcdb72a..17cd57480 100644 --- a/controls/chat/toolbar.md +++ b/controls/chat/toolbar.md @@ -20,62 +20,10 @@ The below sample code demonstrates how to add a toolbar action that inserts an i #### Adding ToolbarActionDataItem -{{source=..\SamplesCS\Chat\ChatGettingStarted.cs region=Toolbar}} -{{source=..\SamplesVB\Chat\ChatGettingStarted.vb region=Toolbar}} + + -````C# - -private void Toolbar() -{ - ToolbarActionDataItem imageAction = new ToolbarActionDataItem(Properties.Resources.file,"image"); - this.radChat1.ChatElement.ToolbarElement.AddToolbarAction(imageAction); - this.radChat1.ToolbarActionClicked += radChat1_ToolbarActionClicked; -} - -private void radChat1_ToolbarActionClicked(object sender, ToolbarActionEventArgs e) -{ - ToolbarActionDataItem action = e.DataItem; - if (action.UserData + "" == "image") - { - OpenFileDialog dlg = new OpenFileDialog(); - dlg.Title = "Open Image"; - dlg.Filter = "png files (*.png)|*.png"; - if (dlg.ShowDialog() == DialogResult.OK) - { - Image img = Image.FromFile(dlg.FileName); - ChatMediaMessage mediaMessage = new ChatMediaMessage(img, new Size(300, 200), this.radChat1.Author, DateTime.Now, null); - this.radChat1.AddMessage(mediaMessage); - } - dlg.Dispose(); - } -} -```` -````VB.NET -Private Sub Toolbar() - Dim imageAction As ToolbarActionDataItem = New ToolbarActionDataItem(My.Resources.file, "image") - Me.radChat1.ChatElement.ToolbarElement.AddToolbarAction(imageAction) - AddHandler Me.radChat1.ToolbarActionClicked, AddressOf radChat1_ToolbarActionClicked -End Sub -Private Sub radChat1_ToolbarActionClicked(ByVal sender As Object, ByVal e As ToolbarActionEventArgs) - Dim action As ToolbarActionDataItem = e.DataItem - If action.UserData & "" = "image" Then - Dim dlg As OpenFileDialog = New OpenFileDialog() - dlg.Title = "Open Image" - dlg.Filter = "png files (*.png)|*.png" - If dlg.ShowDialog() = Windows.Forms.DialogResult.OK Then - Dim img As Image = Image.FromFile(dlg.FileName) - Dim mediaMessage As ChatMediaMessage = New ChatMediaMessage(img, New Size(300, 200), Me.radChat1.Author, DateTime.Now, Nothing) - Me.radChat1.AddMessage(mediaMessage) - End If - dlg.Dispose() - End If -End Sub - -```` - - -{{endregion}} >caption Figure 2. Inserting an image from a toolbar action diff --git a/controls/checkedlistbox/data-biniding.md b/controls/checkedlistbox/data-biniding.md index 55ea02e64..e190f6773 100644 --- a/controls/checkedlistbox/data-biniding.md +++ b/controls/checkedlistbox/data-biniding.md @@ -51,151 +51,21 @@ The following example demonstrates how you can bind the control by using the __C 1\. Initially let’s create a collection of objects. -{{source=..\SamplesCS\ListView\CheckedListBox\CheckedListBoxDataBinding.cs region=SimpleObject}} -{{source=..\SamplesVB\ListView\CheckedListBox\CheckedListBoxDataBinding.vb region=SimpleObject}} - -````C# -public class SimpleObject -{ - public int Id { get; set; } - public string Name { get; set; } - public CheckState CheckState { get; set; } -} - -```` -````VB.NET -Public Class SimpleObject - Public Property Id() As Integer - Get - Return m_Id - End Get - Set(value As Integer) - m_Id = value - End Set - End Property - Private m_Id As Integer - Public Property Name() As String - Get - Return m_Name - End Get - Set(value As String) - m_Name = value - End Set - End Property - Private m_Name As String - Public Property CheckState() As CheckState - Get - Return m_CheckState - End Get - Set(value As CheckState) - m_CheckState = value - End Set - End Property - Private m_CheckState As CheckState -End Class - -```` - -{{endregion}} - -{{source=..\SamplesCS\ListView\CheckedListBox\CheckedListBoxDataBinding.cs region=CreateSimpleObjects}} -{{source=..\SamplesVB\ListView\CheckedListBox\CheckedListBoxDataBinding.vb region=CreateSimpleObjects}} - -````C# -private IEnumerable CreateSimpleObjects() -{ - List data = new List() - { - new SimpleObject() { Id = 1, Name = "Item1", CheckState = CheckState.Unchecked }, - new SimpleObject() { Id = 2, Name = "Item2", CheckState = CheckState.Checked }, - new SimpleObject() { Id = 3, Name = "Item3", CheckState = CheckState.Indeterminate }, - new SimpleObject() { Id = 4, Name = "Item4", CheckState = CheckState.Unchecked }, - new SimpleObject() { Id = 5, Name = "Item5", CheckState = CheckState.Unchecked }, - new SimpleObject() { Id = 6, Name = "Item6", CheckState = CheckState.Checked } - }; - return data; -} - -```` -````VB.NET -Private Function CreateSimpleObjects() As IEnumerable(Of SimpleObject) - Dim data As New List(Of SimpleObject)() From { _ - New SimpleObject() With { _ - .Id = 1, _ - .Name = "Item1", _ - .CheckState = CheckState.Unchecked _ - }, _ - New SimpleObject() With { _ - .Id = 2, _ - .Name = "Item2", _ - .CheckState = CheckState.Checked _ - }, _ - New SimpleObject() With { _ - .Id = 3, _ - .Name = "Item3", _ - .CheckState = CheckState.Indeterminate _ - }, _ - New SimpleObject() With { _ - .Id = 4, _ - .Name = "Item4", _ - .CheckState = CheckState.Unchecked _ - }, _ - New SimpleObject() With { _ - .Id = 5, _ - .Name = "Item5", _ - .CheckState = CheckState.Unchecked _ - }, _ - New SimpleObject() With { _ - .Id = 6, _ - .Name = "Item6", _ - .CheckState = CheckState.Checked _ - } _ - } - Return data -End Function - -```` - -{{endregion}} + + + + + 2\. To support three state check boxes we need to set the __ThreeStateMode__ property: -{{source=..\SamplesCS\ListView\CheckedListBox\CheckedListBoxDataBinding.cs region=ThreeStateMode}} -{{source=..\SamplesVB\ListView\CheckedListBox\CheckedListBoxDataBinding.vb region=ThreeStateMode}} - -````C# -this.radCheckedListBox1.ThreeStateMode = true; - -```` -````VB.NET -Me.RadCheckedListBox1.ThreeStateMode = True + + -```` - -{{endregion}} - 3\. And finally set programmatically the DataSource, DisplayMember, ValueMember and __CheckedMember__ properties. -{{source=..\SamplesCS\ListView\CheckedListBox\CheckedListBoxDataBinding.cs region=ProgramaticallyDatabind}} -{{source=..\SamplesVB\ListView\CheckedListBox\CheckedListBoxDataBinding.vb region=ProgramaticallyDatabind}} - -````C# -this.radCheckedListBox1.DataSource = this.CreateSimpleObjects(); -this.radCheckedListBox1.DisplayMember = "Name"; -this.radCheckedListBox1.ValueMember = "Id"; -this.radCheckedListBox1.CheckedMember = "CheckState"; - -```` -````VB.NET -Me.RadCheckedListBox1.DataSource = Me.CreateSimpleObjects() -Me.RadCheckedListBox1.DisplayMember = "Name" -Me.RadCheckedListBox1.ValueMember = "Id" -Me.RadCheckedListBox1.CheckedMember = "CheckState" - -```` - -{{endregion}} - + + ![WinForms RadCheckedListBox Programmatically DataSource DisplayMember ValueMember CheckedMember](images/checkedlistbox-data-binding003.png) diff --git a/controls/checkedlistbox/getting-started.md b/controls/checkedlistbox/getting-started.md index 2d21c4661..9e48c8a68 100644 --- a/controls/checkedlistbox/getting-started.md +++ b/controls/checkedlistbox/getting-started.md @@ -49,26 +49,8 @@ To programmatically add a __RadCheckedListBox__ to a form, create a new instanc #### Adding a RadCheckedListBox at runtime -{{source=..\SamplesCS\ListView\CheckedListBox\CheckedListBoxGettingStarted.cs region=CreatingControl}} -{{source=..\SamplesVB\ListView\CheckedListBox\CheckedListBoxGettingStarted.vb region=CreatingControl}} - -````C# -RadCheckedListBox checkedListBox = new RadCheckedListBox(); -this.Controls.Add(checkedListBox); -checkedListBox.Items.Add("Coffee"); -checkedListBox.Items.Add("Tea"); - -```` -````VB.NET -Dim checkedListBox As New RadCheckedListBox() -Me.Controls.Add(checkedListBox) -checkedListBox.Items.Add("Coffee") -checkedListBox.Items.Add("Tea") - -```` - -{{endregion}} - + + The bellow example demonstrates the main capabilities of __RadCheckedListBox__. @@ -84,292 +66,29 @@ The bellow example demonstrates the main capabilities of __RadCheckedListBox__. 4\. Now you are ready to bind the control. Open the code behind and add the following: -{{source=..\SamplesCS\ListView\CheckedListBox\CheckedListBoxGettingStarted.cs region=Initialization}} -{{source=..\SamplesVB\ListView\CheckedListBox\CheckedListBoxGettingStarted.vb region=Initialization}} - -````C# -this.radCheckedListBox1.DataSource = this.CreatePhoneBookEntries(); -this.radCheckedListBox1.VisualItemFormatting += radCheckedListBox1_VisualItemFormatting; -ListViewDetailColumn nameColumn = new ListViewDetailColumn("Name"); -nameColumn.Width = 150; -this.radCheckedListBox2.Columns.Add(nameColumn); -ListViewDetailColumn phoneColumn = new ListViewDetailColumn("Phone"); -phoneColumn.Width = 100; -this.radCheckedListBox2.Columns.Add(phoneColumn); -this.radButtonAddToContacts.Click += radButtonAddToContacts_Click; -this.radButtonRemoveFromContacts.Click += radButtonRemoveFromContacts_Click; - -```` -````VB.NET -Me.RadCheckedListBox1.DataSource = Me.CreatePhoneBookEntries() -AddHandler Me.RadCheckedListBox1.VisualItemFormatting, AddressOf radCheckedListBox1_VisualItemFormatting -Dim nameColumn As New ListViewDetailColumn("Name") -nameColumn.Width = 150 -Me.RadCheckedListBox2.Columns.Add(nameColumn) -Dim phoneColumn As New ListViewDetailColumn("Phone") -phoneColumn.Width = 100 -Me.RadCheckedListBox2.Columns.Add(phoneColumn) -AddHandler Me.radButtonAddToContacts.Click, AddressOf radButtonAddToContacts_Click -AddHandler Me.radButtonRemoveFromContacts.Click, AddressOf radButtonRemoveFromContacts_Click - -```` - -{{endregion}} - + + 5\. The example uses the following sample business object: -{{source=..\SamplesCS\ListView\CheckedListBox\CheckedListBoxGettingStarted.cs region=PhonebookEntry}} -{{source=..\SamplesVB\ListView\CheckedListBox\CheckedListBoxGettingStarted.vb region=PhonebookEntry}} - -````C# -public class PhonebookEntry -{ - public string FirstName { get; set; } - public string LastName { get; set; } - public string PhoneNumber { get; set; } - public string Address { get; set; } - public Image Image { get; set; } -} - -```` -````VB.NET -Public Class PhonebookEntry - Public Property FirstName() As String - Get - Return m_FirstName - End Get - Set(value As String) - m_FirstName = value - End Set - End Property - Private m_FirstName As String - Public Property LastName() As String - Get - Return m_LastName - End Get - Set(value As String) - m_LastName = value - End Set - End Property - Private m_LastName As String - Public Property PhoneNumber() As String - Get - Return m_PhoneNumber - End Get - Set(value As String) - m_PhoneNumber = value - End Set - End Property - Private m_PhoneNumber As String - Public Property Address() As String - Get - Return m_Address - End Get - Set(value As String) - m_Address = value - End Set - End Property - Private m_Address As String - Public Property Image() As Image - Get - Return m_Image - End Get - Set(value As Image) - m_Image = value - End Set - End Property - Private m_Image As Image -End Class - -```` - -{{endregion}} - + + 6\. Now you can create a collection of PhonebookEntry business objects: -{{source=..\SamplesCS\ListView\CheckedListBox\CheckedListBoxGettingStarted.cs region=CreatePhonebookEntries}} -{{source=..\SamplesVB\ListView\CheckedListBox\CheckedListBoxGettingStarted.vb region=CreatePhonebookEntries}} - -````C# -private IEnumerable CreatePhoneBookEntries() -{ - List entries = new List() - { - new PhonebookEntry() { FirstName = "Anne", LastName = "Dodsworth", PhoneNumber = "(71) 555-4444", Address = "7 Houndstooth Rd.", Image = Resources.anne}, - new PhonebookEntry() { FirstName = "Laura", LastName = "Callahan", PhoneNumber = "(206) 555-1189", Address = "4726 - 11th Ave. N.E.", Image = Resources.laura }, - new PhonebookEntry() { FirstName = "Robert", LastName = "King", PhoneNumber = "(71) 555-5598", Address = "Edgeham Hollow Winchester Way", Image = Resources.robert }, - new PhonebookEntry() { FirstName = "Michael", LastName = "Suyama", PhoneNumber = "(71) 555-7773", Address = "Coventry House Miner Rd.", Image = Resources.michael}, - new PhonebookEntry() { FirstName = "Steven", LastName = "Buchanan", PhoneNumber = "(71) 555-4848", Address = "14 Garrett Hill", Image = Resources.steven }, - new PhonebookEntry() { FirstName = "Margaret", LastName = "Peacock", PhoneNumber = "(206) 555-8122", Address = "4110 Old Redmond Rd.", Image = Resources.margaret1 }, - new PhonebookEntry() { FirstName = "Janet", LastName = "Leverling", PhoneNumber = "(206) 555-3412", Address = "722 Moss Bay Blvd.", Image = Resources.janet1 }, - new PhonebookEntry() { FirstName = "Andrew", LastName = "Fuller", PhoneNumber = "(206) 555-9482", Address = "908 W. Capital Way", Image = Resources.andrew1 }, - new PhonebookEntry() { FirstName = "Nancy", LastName = "Davolio", PhoneNumber = "(206) 555-9857", Address = "507 - 20th Ave. E. Apt. 2A", Image = Resources.nancy1 } - }; - return entries; -} - -```` -````VB.NET -Private Function CreatePhoneBookEntries() As IEnumerable(Of PhonebookEntry) - Dim entries As New List(Of PhonebookEntry)() From { _ - New PhonebookEntry() With { _ - .FirstName = "Anne", _ - .LastName = "Dodsworth", _ - .PhoneNumber = "(71) 555-4444", _ - .Address = "7 Houndstooth Rd.", _ - .Image = My.Resources.anne _ - }, _ - New PhonebookEntry() With { _ - .FirstName = "Laura", _ - .LastName = "Callahan", _ - .PhoneNumber = "(206) 555-1189", _ - .Address = "4726 - 11th Ave. N.E.", _ - .Image = My.Resources.laura _ - }, _ - New PhonebookEntry() With { _ - .FirstName = "Robert", _ - .LastName = "King", _ - .PhoneNumber = "(71) 555-5598", _ - .Address = "Edgeham Hollow Winchester Way", _ - .Image = My.Resources.robert _ - }, _ - New PhonebookEntry() With { _ - .FirstName = "Michael", _ - .LastName = "Suyama", _ - .PhoneNumber = "(71) 555-7773", _ - .Address = "Coventry House Miner Rd.", _ - .Image = My.Resources.michael _ - }, _ - New PhonebookEntry() With { _ - .FirstName = "Steven", _ - .LastName = "Buchanan", _ - .PhoneNumber = "(71) 555-4848", _ - .Address = "14 Garrett Hill", _ - .Image = My.Resources.steven _ - }, _ - New PhonebookEntry() With { _ - .FirstName = "Margaret", _ - .LastName = "Peacock", _ - .PhoneNumber = "(206) 555-8122", _ - .Address = "4110 Old Redmond Rd.", _ - .Image = My.Resources.Margaret _ - }, _ - New PhonebookEntry() With { _ - .FirstName = "Janet", _ - .LastName = "Leverling", _ - .PhoneNumber = "(206) 555-3412", _ - .Address = "722 Moss Bay Blvd.", _ - .Image = My.Resources.Janet _ - }, _ - New PhonebookEntry() With { _ - .FirstName = "Andrew", _ - .LastName = "Fuller", _ - .PhoneNumber = "(206) 555-9482", _ - .Address = "908 W. Capital Way", _ - .Image = My.Resources.Andrew _ - }, _ - New PhonebookEntry() With { _ - .FirstName = "Nancy", _ - .LastName = "Davolio", _ - .PhoneNumber = "(206) 555-9857", _ - .Address = "507 - 20th Ave. E. Apt. 2A", _ - .Image = My.Resources.nancy _ - } _ - } - Return entries -End Function - -```` - -{{endregion}} - + + 7\. The next step is to create click event handlers for the buttons: -{{source=..\SamplesCS\ListView\CheckedListBox\CheckedListBoxGettingStarted.cs region=ClickEvents}} -{{source=..\SamplesVB\ListView\CheckedListBox\CheckedListBoxGettingStarted.vb region=ClickEvents}} - -````C# -void radButtonAddToContacts_Click(object sender, EventArgs e) -{ - foreach (ListViewDataItem item in this.radCheckedListBox1.CheckedItems) - { - ListViewDataItem contactItem = new ListViewDataItem(); - this.radCheckedListBox2.Items.Add(contactItem); - //here you can add logic to avoid duplicating contacts - PhonebookEntry entry = item.Value as PhonebookEntry; - contactItem["Name"] = entry.FirstName + " " + entry.LastName; - contactItem["Phone"] = entry.PhoneNumber; - } -} -void radButtonRemoveFromContacts_Click(object sender, EventArgs e) -{ - while (this.radCheckedListBox2.CheckedItems.Count > 0) - { - this.radCheckedListBox2.Items.Remove(this.radCheckedListBox2.CheckedItems[0]); - } -} - -```` -````VB.NET -Private Sub radButtonAddToContacts_Click(sender As Object, e As EventArgs) - For Each item As ListViewDataItem In Me.RadCheckedListBox1.CheckedItems - Dim contactItem As New ListViewDataItem() - Me.RadCheckedListBox2.Items.Add(contactItem) - 'here you can add logic to avoid duplicating contacts - Dim entry As PhonebookEntry = TryCast(item.Value, PhonebookEntry) - contactItem("Name") = entry.FirstName & " " & entry.LastName - contactItem("Phone") = entry.PhoneNumber - Next -End Sub -Private Sub radButtonRemoveFromContacts_Click(sender As Object, e As EventArgs) - While Me.RadCheckedListBox2.CheckedItems.Count > 0 - Me.RadCheckedListBox2.Items.Remove(Me.RadCheckedListBox2.CheckedItems(0)) - End While -End Sub - -```` - -{{endregion}} - + + 8\. The final step is to use the __VisualItemFormatting__ event to style the items in the first __RadCheckedListBox__. Please note that the checkbox position is changed. -{{source=..\SamplesCS\ListView\CheckedListBox\CheckedListBoxGettingStarted.cs region=VisualItemFormatting}} -{{source=..\SamplesVB\ListView\CheckedListBox\CheckedListBoxGettingStarted.vb region=VisualItemFormatting}} - -````C# -BaseListViewVisualItem item = e.VisualItem; -PhonebookEntry entry = item.Data.Value as PhonebookEntry; -item.Image = entry.Image.GetThumbnailImage(80, 80, null, IntPtr.Zero); -item.Text = "" + - "" + entry.FirstName + " " + entry.LastName + "" + - "

Address: " + entry.Address + "" + - "
Phone: " + entry.PhoneNumber + "
"; -if (item.Children.Count > 0) -{ - ListViewItemCheckbox checkBoxItem = item.Children[0] as ListViewItemCheckbox; - checkBoxItem.Margin = new Padding(2); -} - -```` -````VB.NET -Dim item As BaseListViewVisualItem = e.VisualItem -Dim entry As PhonebookEntry = TryCast(item.Data.Value, PhonebookEntry) -item.Image = entry.Image.GetThumbnailImage(80, 80, Nothing, IntPtr.Zero) -item.Text = "" & entry.FirstName & " " & entry.LastName & "

Address: " & entry.Address & "
Phone: " & entry.PhoneNumber + "
" -If item.Children.Count > 0 Then - Dim checkBoxItem As ListViewItemCheckbox = TryCast(item.Children(0), ListViewItemCheckbox) - checkBoxItem.Margin = New Padding(2) -End If - -```` - -{{endregion}} - + + ![WinForms RadCheckedListBox VisualItemFormatting](images/checkedlistbox-getting-started002.png) diff --git a/controls/clock/customizing-appearance/accessing-and-customizing-elements.md b/controls/clock/customizing-appearance/accessing-and-customizing-elements.md index 2bd7331e3..afb8c930b 100644 --- a/controls/clock/customizing-appearance/accessing-and-customizing-elements.md +++ b/controls/clock/customizing-appearance/accessing-and-customizing-elements.md @@ -32,17 +32,8 @@ You can customize the nested elements at run time as well: #### Customize elements -{{source=..\SamplesCS\Clock\ClockGettingStarted.cs region=AccessingCustomizingElements}} -{{source=..\SamplesVB\Clock\ClockGettingStarted.vb region=AccessingCustomizingElements}} + + -````C# -radClock1.ClockElement.SecondsArrow.Image = Properties.Resources.telerikLogo1; - -```` -````VB.NET -radClock1.ClockElement.SecondsArrow.Image = My.Resources.telerikLogo1 - -```` - -{{endregion}} + diff --git a/controls/clock/getting-started.md b/controls/clock/getting-started.md index e6dfd4b2f..b7d25be81 100644 --- a/controls/clock/getting-started.md +++ b/controls/clock/getting-started.md @@ -40,21 +40,10 @@ The Telerik UI for WinForms assemblies can be install by using one of the availa #### Adding a RadClock at runtime -{{source=..\SamplesCS\Clock\ClockGettingStarted.cs region=CreatingControl}} -{{source=..\SamplesVB\Clock\ClockGettingStarted.vb region=CreatingControl}} + + -````C# -RadClock clock = new RadClock(); -this.Controls.Add(clock); - -```` -````VB.NET -Dim clock As New RadClock() -Me.Controls.Add(clock) - -```` - -{{endregion}} + The control has three important properties: @@ -74,25 +63,10 @@ Now let's create a simple application. 3\. In the code behind, set the __ShowSystemTime__ property of the first clock (assuming that your system time show the time in Sofia). 4\. For the rest of the clocks, set their __Offset__ properties to: *-2*, *-6*, *+7*: -{{source=..\SamplesCS\Clock\ClockGettingStarted.cs region=gettingStarted}} -{{source=..\SamplesVB\Clock\ClockGettingStarted.vb region=gettingStarted}} - -````C# -sofiaClock.ShowSystemTime = true; -londonClock.Offset = new TimeSpan(-2, 0, 0); -newYorkClock.Offset = new TimeSpan(-6, 0, 0); -tokyoClock.Offset = new TimeSpan(7, 0, 0); - -```` -````VB.NET -sofiaClock.ShowSystemTime = True -londonClock.Offset = New TimeSpan(-2, 0, 0) -newYorkClock.Offset = New TimeSpan(7, 0, 0) -tokyoClock.Offset = New TimeSpan(-6, 0, 0) - -```` + + -{{endregion}} + Here is the result: diff --git a/controls/clock/tooltips.md b/controls/clock/tooltips.md index 7c00c6bb9..56860e109 100644 --- a/controls/clock/tooltips.md +++ b/controls/clock/tooltips.md @@ -14,42 +14,19 @@ There are two ways to assign tooltips to __RadClock__, namely setting the __Tool #### Setting the ToolTipText property -{{source=..\SamplesCS\Clock\ClockGettingStarted.cs region=SetToolTipText}} -{{source=..\SamplesVB\Clock\ClockGettingStarted.vb region=SetToolTipText}} + + -````C# -radClock1.ClockElement.ToolTipText = DateTime.Now.ToLongTimeString(); - -```` -````VB.NET -radClock1.ClockElement.ToolTipText = DateTime.Now.ToLongTimeString() - -```` - -{{endregion}} + ![WinForms RadClock ToolTips](images/clock-tooltips001.png) #### Setting tool tips in the ToolTipTextNeeded event -{{source=..\SamplesCS\Clock\ClockGettingStarted.cs region=ToolTipTextNeeded}} -{{source=..\SamplesVB\Clock\ClockGettingStarted.vb region=ToolTipTextNeeded}} + + -````C# -private void RadClock1_ToolTipTextNeeded(object sender, Telerik.WinControls.ToolTipTextNeededEventArgs e) -{ - e.ToolTipText = DateTime.Now.ToLongTimeString(); -} - -```` -````VB.NET -Private Sub RadClock1_ToolTipTextNeeded(sender As Object, e As Telerik.WinControls.ToolTipTextNeededEventArgs) - e.ToolTipText = DateTime.Now.ToLongTimeString() -End Sub - -```` - -{{endregion}} + ![WinForms RadClock ToolTipTextNeeded](images/clock-tooltips002.png) diff --git a/controls/commandbar/customizing-appearance/accessing-and-customizing-elements.md b/controls/commandbar/customizing-appearance/accessing-and-customizing-elements.md index 708718659..e11d4944e 100644 --- a/controls/commandbar/customizing-appearance/accessing-and-customizing-elements.md +++ b/controls/commandbar/customizing-appearance/accessing-and-customizing-elements.md @@ -25,25 +25,9 @@ You can customize the elements at run time as well: #### Customize elements at run time -{{source=..\SamplesCS\CommandBar\FloatingStrips.cs region=AccessingCustomizingElements}} -{{source=..\SamplesVB\CommandBar\FloatingStrips.vb region=AccessingCustomizingElements}} - -````C# -this.radCommandBar1.Rows[0].BackColor = Color.Lime; -this.radCommandBar1.Rows[0].DrawFill = true; -this.radCommandBar1.Rows[0].GradientStyle = Telerik.WinControls.GradientStyles.Solid; -this.radCommandBar1.Rows[0].Strips[0].BackColor = Color.Yellow; -this.radCommandBar1.Rows[0].Strips[0].BorderColor = Color.Red; - -```` -````VB.NET -Me.RadCommandBar1.Rows(0).BackColor = Color.Lime -Me.RadCommandBar1.Rows(0).DrawFill = True -Me.RadCommandBar1.Rows(0).GradientStyle = Telerik.WinControls.GradientStyles.Solid -Me.RadCommandBar1.Rows(0).Strips(0).BackColor = Color.Yellow -Me.RadCommandBar1.Rows(0).Strips(0).BorderColor = Color.Red - -```` - -{{endregion}} + + + + + diff --git a/controls/commandbar/floating-strips.md b/controls/commandbar/floating-strips.md index c29bc6538..8b8e31165 100644 --- a/controls/commandbar/floating-strips.md +++ b/controls/commandbar/floating-strips.md @@ -29,113 +29,38 @@ There are some events that provide you with control over the floating/docking pr * __FloatingStripCreating__ event is fired when a strip is about to be made floating. The following example shows how to prevent the strip “OptionsStrip” from becoming floating. -{{source=..\SamplesCS\CommandBar\FloatingStrips.cs region=floatingStripCreating}} -{{source=..\SamplesVB\CommandBar\FloatingStrips.vb region=floatingStripCreating}} - -````C# - -void radCommandBar1_FloatingStripCreating(object sender, CancelEventArgs e) -{ - if ((sender as CommandBarStripElement).Name == "OptionsStrip") - { - e.Cancel = true; - } -} - -```` -````VB.NET -Private Sub radCommandBar1_FloatingStripCreating(ByVal sender As Object, ByVal e As CancelEventArgs) - If TryCast(sender, CommandBarStripElement).Name = "OptionsStrip" Then - e.Cancel = True - End If -End Sub - -```` - -{{endregion}} + + + + * __FloatingStripCreated__ event is fired when the floating form is shown. The following example shows how to set the caption text of the floating form: -{{source=..\SamplesCS\CommandBar\FloatingStrips.cs region=floatingStripCreated}} -{{source=..\SamplesVB\CommandBar\FloatingStrips.vb region=floatingStripCreated}} - -````C# -void radCommandBar1_FloatingStripCreated(object sender, EventArgs e) -{ - (sender as CommandBarStripElement).FloatingForm.Text = "Just a floating form"; -} - -```` -````VB.NET -Private Sub radCommandBar1_FloatingStripCreated(ByVal sender As Object, ByVal e As EventArgs) - TryCast(sender, CommandBarStripElement).FloatingForm.Text = "Just a floating form" -End Sub - -```` + + -{{endregion}} + * __FloatingStripDocking__ event is fired when a floating strip is about to be docked to a __RadCommandBar__ control. The following example shows how to prevent the strip with name “OptionsStrip” from being docked. -{{source=..\SamplesCS\CommandBar\FloatingStrips.cs region=floatingStripDocking}} -{{source=..\SamplesVB\CommandBar\FloatingStrips.vb region=floatingStripDocking}} - -````C# -void radCommandBar1_FloatingStripDocking(object sender, CancelEventArgs e) -{ - if ((sender as CommandBarStripElement).Name == "OptionsStrip") - { - e.Cancel = true; - } -} - -```` -````VB.NET -Private Sub radCommandBar1_FloatingStripDocking(ByVal sender As Object, ByVal e As CancelEventArgs) - If TryCast(sender, CommandBarStripElement).Name = "OptionsStrip" Then - e.Cancel = True - End If -End Sub - -```` - -{{endregion}} + + + + * __FloatingStripDocked__ event is fired when a floating strip has docked to a __RadCommandBar__ control. The following example shows a sample usage of this event. -{{source=..\SamplesCS\CommandBar\FloatingStrips.cs region=floatingStripDocked}} -{{source=..\SamplesVB\CommandBar\FloatingStrips.vb region=floatingStripDocked}} - -````C# - -void radCommandBar1_FloatingStripDocked(object sender, EventArgs e) -{ - CommandBarStripElement dockedStrip = sender as CommandBarStripElement; - if (dockedStrip != null) - { - MessageBox.Show(dockedStrip.Name + " has docked to " + dockedStrip.ElementTree.Control.Name); - } -} - -```` -````VB.NET -Private Sub radCommandBar1_FloatingStripDocked(ByVal sender As Object, ByVal e As EventArgs) - Dim dockedStrip As CommandBarStripElement = TryCast(sender, CommandBarStripElement) - If dockedStrip IsNot Nothing Then - MessageBox.Show(dockedStrip.Name & " has docked to " & dockedStrip.ElementTree.Control.Name) - End If -End Sub - -```` - -{{endregion}} + + + + diff --git a/controls/commandbar/getting-started.md b/controls/commandbar/getting-started.md index 34ceaeac7..d8b1e62cf 100644 --- a/controls/commandbar/getting-started.md +++ b/controls/commandbar/getting-started.md @@ -49,36 +49,10 @@ To programmatically add a __RadCommandBar__ to a form, create a new instance of #### Adding a RadCommandBar at runtime -{{source=..\SamplesCS\CommandBar\FloatingStrips.cs region=CreatingControl}} -{{source=..\SamplesVB\CommandBar\FloatingStrips.vb region=CreatingControl}} - -````C# - -RadCommandBar radCommandBar = new RadCommandBar(); -this.Controls.Add(radCommandBar); -radCommandBar.Dock = DockStyle.Top; -CommandBarRowElement row1 = new CommandBarRowElement(); -radCommandBar.Rows.Add(row1); -CommandBarStripElement strip1 = new CommandBarStripElement(); -row1.Strips.Add(strip1); -CommandBarButton button1 = new CommandBarButton(); -strip1.Items.Add(button1); - -```` -````VB.NET -Dim radCommandBar As New RadCommandBar() -Me.Controls.Add(radCommandBar) -radCommandBar.Dock = DockStyle.Top -Dim row1 As New CommandBarRowElement() -radCommandBar.Rows.Add(row1) -Dim strip1 As New CommandBarStripElement() -row1.Strips.Add(strip1) -Dim button1 As New CommandBarButton() -strip1.Items.Add(button1) - -```` - -{{endregion}} + + + + ## Telerik UI for WinForms Learning Resources * [Telerik UI for WinForms CommandBar Component](https://www.telerik.com/products/winforms/commandbar.aspx) diff --git a/controls/commandbar/how-to/customize-the-control-context-menu.md b/controls/commandbar/how-to/customize-the-control-context-menu.md index 1a8fc53c3..b3b3022cc 100644 --- a/controls/commandbar/how-to/customize-the-control-context-menu.md +++ b/controls/commandbar/how-to/customize-the-control-context-menu.md @@ -13,56 +13,16 @@ previous_url: commandbar-howto-customize-the-control-context-menu When the __RadCommandBar__ control is right clicked, a context menu enlisting the strips in the control together with __Customize__ menu option (allowing to customize the strips) is being shown. This context menu is being populated by the time of its opening and in order to customize its items, you should do that from within the __DropDownOpening__ event of this context menu. Here is how to subscribe to this event and how add your custom item and how to remove the __Customize__ option: -{{source=..\SamplesCS\CommandBar\SaveAndLoadLayout1.cs region=subscribeToContextMenuOpening}} -{{source=..\SamplesVB\CommandBar\SaveAndLoadLayout.vb region=subscribeToContextMenuOpening}} -````C# -radCommandBar1.CustomizeContextMenu.DropDownOpening += new CancelEventHandler(CustomizeContextMenu_DropDownOpening); + + -```` -````VB.NET -AddHandler RadCommandBar1.CustomizeContextMenu.DropDownOpening, AddressOf CustomizeContextMenu_DropDownOpening -```` -{{endregion}} + + -{{source=..\SamplesCS\CommandBar\SaveAndLoadLayout1.cs region=CustomizeTheContextMenu}} -{{source=..\SamplesVB\CommandBar\SaveAndLoadLayout.vb region=CustomizeTheContextMenu}} - -````C# -void CustomizeContextMenu_DropDownOpening(object sender, CancelEventArgs e) -{ - //add custom item - RadMenuItem myItem = new RadMenuItem("MyItem"); - radCommandBar1.CustomizeContextMenu.Items.Add(myItem); - //remove the customize menu option - for (int i = 0; i < radCommandBar1.CustomizeContextMenu.Items.Count; i++) - { - if ( radCommandBar1.CustomizeContextMenu.Items[i].Text == "Customize...") - { - radCommandBar1.CustomizeContextMenu.Items.RemoveAt(i); - } - } -} - -```` -````VB.NET -Private Sub CustomizeContextMenu_DropDownOpening(sender As Object, e As System.ComponentModel.CancelEventArgs) - 'add custom item - Dim myItem As New RadMenuItem("MyItem") - RadCommandBar1.CustomizeContextMenu.Items.Add(myItem) - 'remove the customize menu option - For i As Integer = 0 To RadCommandBar1.CustomizeContextMenu.Items.Count - 1 - If RadCommandBar1.CustomizeContextMenu.Items(i).Text = "Customize..." Then - RadCommandBar1.CustomizeContextMenu.Items.RemoveAt(i) - End If - Next -End Sub - -```` - -{{endregion}} + >caption Figure 1: CustomizeContextMenu > diff --git a/controls/commandbar/how-to/customize-the-overflow-button.md b/controls/commandbar/how-to/customize-the-overflow-button.md index cc9d0696e..8458e4c53 100644 --- a/controls/commandbar/how-to/customize-the-overflow-button.md +++ b/controls/commandbar/how-to/customize-the-overflow-button.md @@ -21,41 +21,10 @@ Each [CommandBarStripElement]({%slug winforms/commandbar/structure%}) has its ow The following example, demonstrates how to access the __RadMenuItems__ of the __Overflow__ button. For your convenience we have exposed the __CustomizeButtonMenuItem__ and the __AddRemoveButtonsMenuItem__. -{{source=..\SamplesCS\CommandBar\SaveAndLoadLayout1.cs region=HideMenuItems}} -{{source=..\SamplesVB\CommandBar\SaveAndLoadLayout.vb region=HideMenuItems}} + + -````C# -//Change the font of the AddRemoveButtonMenuItem -radCommandBarStripElement1.OverflowButton.AddRemoveButtonsMenuItem.Font = new System.Drawing.Font("Arial", 12f); -//Change the font of the CustomizeButtonMenuItem -radCommandBarStripElement1.OverflowButton.CustomizeButtonMenuItem.Font = new System.Drawing.Font("Segoe UI", 10f, FontStyle.Bold); -//hide the separators -foreach (var item in radCommandBarStripElement1.OverflowButton.DropDownMenu.Items) -{ - RadMenuSeparatorItem separator = item as RadMenuSeparatorItem; - if (separator != null) - { - separator.Visibility = Telerik.WinControls.ElementVisibility.Collapsed; - } -} - -```` -````VB.NET -'Change the font of the AddRemoveButtonMenuItem -CommandBarStripElement1.OverflowButton.AddRemoveButtonsMenuItem.Font = New System.Drawing.Font("Arial", 12.0F) -'Change the font of the CustomizeButtonMenuItem -CommandBarStripElement1.OverflowButton.CustomizeButtonMenuItem.Font = New System.Drawing.Font("Segoe UI", 10.0F, FontStyle.Bold) -'hide the separators -For Each item In CommandBarStripElement1.OverflowButton.DropDownMenu.Items - Dim separator As RadMenuSeparatorItem = TryCast(item, RadMenuSeparatorItem) - If separator IsNot Nothing Then - separator.Visibility = Telerik.WinControls.ElementVisibility.Collapsed - End If -Next - -```` - -{{endregion}} + ![WinForms RadCommandBar Customize the Overflow Button Result](images/commandbar-howto-customize-the-overflow-button003.png) @@ -63,19 +32,10 @@ Next Alternatively, if you need to hide the whole __Overflow__ button, simply set its Visibility property to *Collapsed* -{{source=..\SamplesCS\CommandBar\SaveAndLoadLayout1.cs region=HideTheOverFlowButton}} -{{source=..\SamplesVB\CommandBar\SaveAndLoadLayout.vb region=HideTheOverFlowButton}} + + -````C# -radCommandBarStripElement1.OverflowButton.Visibility = Telerik.WinControls.ElementVisibility.Collapsed; - -```` -````VB.NET -CommandBarStripElement1.OverflowButton.Visibility = Telerik.WinControls.ElementVisibility.Collapsed - -```` - -{{endregion}} + ![WinForms RadCommandBar Customize the Overflow Button Hide](images/commandbar-howto-customize-the-overflow-button004.png) diff --git a/controls/commandbar/how-to/prevent-the-control-from-gaining-focus.md b/controls/commandbar/how-to/prevent-the-control-from-gaining-focus.md index 96011bd48..4b5c842b3 100644 --- a/controls/commandbar/how-to/prevent-the-control-from-gaining-focus.md +++ b/controls/commandbar/how-to/prevent-the-control-from-gaining-focus.md @@ -21,44 +21,10 @@ Currently, __RadCommandBar__ receives the focus. One can easily override this be 1. Override the ProcessFocusRequested method and return false. -{{source=..\SamplesCS\CommandBar\HowTo\MakeRadCommandBarUnfocusable.cs region=ForbidFocus}} -{{source=..\SamplesVB\CommandBar\HowTo\MakeRadCommandBarUnfocusable.vb region=ForbidFocus}} + + -````C# -class MyCommandBar : RadCommandBar -{ - public override string ThemeClassName - { - get - { - return typeof(RadCommandBar).FullName; - } - } - protected override bool ProcessFocusRequested(RadElement element) - { - return false; - } -} - -```` -````VB.NET -Class MyCommandBar - Inherits RadCommandBar - Public Overrides Property ThemeClassName() As String - Get - Return GetType(RadButton).FullName - End Get - Set(ByVal value As String) - End Set - End Property - Protected Overrides Function ProcessFocusRequested(element As RadElement) As Boolean - Return False - End Function -End Class - -```` - -{{endregion}} + diff --git a/controls/commandbar/localization/localization.md b/controls/commandbar/localization/localization.md index 9c98cb1b7..cc7496728 100644 --- a/controls/commandbar/localization/localization.md +++ b/controls/commandbar/localization/localization.md @@ -25,78 +25,20 @@ To localize RadCommandBar to display control text and messages in a specific lan Below is a sample implementation of an English localization provider: -{{source=..\SamplesCS\CommandBar\MyEnglishCommandBarLocalizationProvider.cs region=provider}} -{{source=..\SamplesVB\CommandBar\MyEnglishCommandBarLocalizationProvider.vb region=provider}} + + -````C# -public class MyEnglishCommandBarLocalizationProvider : CommandBarLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case CommandBarStringId.CustomizeDialogChooseToolstripLabelText: return "Choose a toolstrip to rearrange:"; - case CommandBarStringId.CustomizeDialogCloseButtonText: return "Close"; - case CommandBarStringId.CustomizeDialogItemsPageTitle: return "Items"; - case CommandBarStringId.CustomizeDialogMoveDownButtonText: return "Move Down"; - case CommandBarStringId.CustomizeDialogMoveUpButtonText: return "Move Up"; - case CommandBarStringId.CustomizeDialogResetButtonText: return "Reset"; - case CommandBarStringId.CustomizeDialogTitle: return "Customize1"; - case CommandBarStringId.CustomizeDialogToolstripsPageTitle: return "Toolstrips"; - case CommandBarStringId.OverflowMenuAddOrRemoveButtonsText: return "Add or Remove Buttons"; - case CommandBarStringId.OverflowMenuCustomizeText: return "Customize..."; - case CommandBarStringId.ContextMenuCustomizeText: return "Customize..."; - default: return base.GetLocalizedString(id); - } - } -} - -```` -````VB.NET -Public Class MyEnglishCommandBarLocalizationProvider - Inherits CommandBarLocalizationProvider - Public Overrides Function GetLocalizedString(ByVal id As String) As String - Select Case id - Case CommandBarStringId.CustomizeDialogChooseToolstripLabelText : Return "Choose a toolstrip to rearrange:" - Case CommandBarStringId.CustomizeDialogCloseButtonText : Return "Close" - Case CommandBarStringId.CustomizeDialogItemsPageTitle : Return "Items" - Case CommandBarStringId.CustomizeDialogMoveDownButtonText : Return "Move Down" - Case CommandBarStringId.CustomizeDialogMoveUpButtonText : Return "Move Up" - Case CommandBarStringId.CustomizeDialogResetButtonText : Return "Reset" - Case CommandBarStringId.CustomizeDialogTitle : Return "Customize1" - Case CommandBarStringId.CustomizeDialogToolstripsPageTitle : Return "Toolstrips" - Case CommandBarStringId.OverflowMenuAddOrRemoveButtonsText : Return "Add or Remove Buttons" - Case CommandBarStringId.OverflowMenuCustomizeText : Return "Customize..." - Case CommandBarStringId.ContextMenuCustomizeText : Return "Customize..." - Case Else : Return MyBase.GetLocalizedString(id) - End Select - Return String.Empty - End Function -End Class - -```` - -{{endregion}} + To apply the custom localization provider, instantiate and assign it to the current localization provider: #### Assigning the Current Localization Provider -{{source=..\SamplesCS\CommandBar\FloatingStrips.cs region=usingProvider}} -{{source=..\SamplesVB\CommandBar\FloatingStrips.vb region=usingProvider}} + + -````C# - -CommandBarLocalizationProvider.CurrentProvider = new MyEnglishCommandBarLocalizationProvider(); - -```` -````VB.NET -CommandBarLocalizationProvider.CurrentProvider = New MyEnglishCommandBarLocalizationProvider() - -```` - -{{endregion}} + The code provided above illustrates the approach to be used to localize the __RadCommandBar__ and is not intended as a full translation. diff --git a/controls/commandbar/localization/right-to-left-support.md b/controls/commandbar/localization/right-to-left-support.md index 0889625b0..a48ef9afd 100644 --- a/controls/commandbar/localization/right-to-left-support.md +++ b/controls/commandbar/localization/right-to-left-support.md @@ -17,20 +17,10 @@ previous_url: commandbar-localization-rtl You can present the content of your commandbar instance in a right-to-left direction by setting the __RightToLeft__ property to *Yes*: -{{source=..\SamplesCS\CommandBar\FloatingStrips.cs region=rtl}} -{{source=..\SamplesVB\CommandBar\FloatingStrips.vb region=rtl}} + + -````C# - -this.radCommandBar1.RightToLeft = RightToLeft.Yes; - -```` -````VB.NET -Me.RadCommandBar1.RightToLeft = Windows.Forms.RightToLeft.Yes - -```` - -{{endregion}} + ![WinForms RadCommandBar Right-to-Left Support](images/commandbar-localization-right-to-left-support001.png) diff --git a/controls/commandbar/save-and-load-layout.md b/controls/commandbar/save-and-load-layout.md index b5952a667..dfd43d1e7 100644 --- a/controls/commandbar/save-and-load-layout.md +++ b/controls/commandbar/save-and-load-layout.md @@ -21,79 +21,19 @@ Initially the layout looks like this: ![WinForms RadCommandBar command-bar-save-and-load-layout 001](images/command-bar-save-and-load-layout001.png) -{{source=..\SamplesCS\CommandBar\SaveAndLoadLayout1.cs region=saveLayout}} -{{source=..\SamplesVB\CommandBar\SaveAndLoadLayout.vb region=saveLayout}} - -````C# -private void radButton1_Click(object sender, EventArgs e) -{ - string s = "default.xml"; - SaveFileDialog dialog = new SaveFileDialog(); - dialog.Filter = - "xml files (*.xml)|*.xml|All files (*.*)|*.*"; - dialog.Title = "Select a xml file"; - if (dialog.ShowDialog() == DialogResult.OK) - { - s = dialog.FileName; - } - this.radCommandBar1.CommandBarElement.SaveLayout(s); -} - -```` -````VB.NET -Private Sub RadButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadButton1.Click - Dim s As String = "default.xml" - Dim dialog As New SaveFileDialog() - dialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*" - dialog.Title = "Select a xml file" - If dialog.ShowDialog() = DialogResult.OK Then - s = dialog.FileName - End If - Me.RadCommandBar1.CommandBarElement.SaveLayout(s) -End Sub - -```` - -{{endregion}} + + + + Now we are going to set some of the items __VisibleInStrip__ properties to *false*![WinForms RadCommandBar command-bar-save-and-load-layout 002](images/command-bar-save-and-load-layout002.png) The code snippets below demonstrate how you can implement a *Load Layout* button event handler: -{{source=..\SamplesCS\CommandBar\SaveAndLoadLayout1.cs region=loadLayout}} -{{source=..\SamplesVB\CommandBar\SaveAndLoadLayout.vb region=loadLayout}} - -````C# -private void radButton2_Click(object sender, EventArgs e) -{ - string s = "default.xml"; - OpenFileDialog dialog = new OpenFileDialog(); - dialog.Filter = - "xml files (*.xml)|*.xml|All files (*.*)|*.*"; - dialog.Title = "Select a xml file"; - if (dialog.ShowDialog() == DialogResult.OK) - { - s = dialog.FileName; - } - this.radCommandBar1.CommandBarElement.LoadLayout(s); -} - -```` -````VB.NET -Private Sub RadButton2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadButton2.Click - Dim s As String = "default.xml" - Dim dialog As New OpenFileDialog() - dialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*" - dialog.Title = "Select a xml file" - If dialog.ShowDialog() = DialogResult.OK Then - s = dialog.FileName - End If - Me.RadCommandBar1.CommandBarElement.LoadLayout(s) -End Sub - -```` - -{{endregion}} + + + + After loading the layout it will reload the initial settings of the existing items:![WinForms RadCommandBar Save Load Layout](images/command-bar-save-and-load-layout001.png) @@ -104,29 +44,10 @@ __Sample save/load scenario__ The following example demonstrates how you can save the layout settings of a __RadCommandBar__ when the parent form of this command bar is closed and how you can load these settings when the form is reopened. Basically, you need to handle the __Load__ and __FormClosing__ events of the form. -{{source=..\SamplesCS\CommandBar\SaveAndLoadLayout1.cs region=autoLoadLayoutOnFormLoad}} -{{source=..\SamplesVB\CommandBar\SaveAndLoadLayout.vb region=autoLoadLayoutOnFormLoad}} - -````C# -private void SaveAndLoadLayout1_Load(object sender, EventArgs e) -{ - if (File.Exists("MyLayout.xml")) - { - this.radCommandBar1.CommandBarElement.LoadLayout("MyLayout.xml"); - } -} - -```` -````VB.NET -Private Sub SaveAndLoadLayout_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load - If File.Exists("MyLayout.xml") Then - Me.RadCommandBar1.CommandBarElement.LoadLayout("MyLayout.xml") - End If -End Sub - -```` - -{{endregion}} + + + + diff --git a/controls/dataentry/customizing-appearance/customizing-appearance.md b/controls/dataentry/customizing-appearance/customizing-appearance.md index 0e8b57064..1b74a37f0 100644 --- a/controls/dataentry/customizing-appearance/customizing-appearance.md +++ b/controls/dataentry/customizing-appearance/customizing-appearance.md @@ -26,18 +26,10 @@ The following snippet show how you can customize the RadDataEntry styles at runt #### Change Border Color -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadDataEntryHowTo.cs region=SetBorderColor}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadDataEntryHowTo.vb region=SetBorderColor}} -````C# -radDataEntry1.DataEntryElement.Border.ForeColor = ColorTranslator.FromHtml("#e83737"); + + -```` -````VB.NET -radDataEntry1.DataEntryElement.Border.ForeColor = ColorTranslator.FromHtml("#e83737") -```` - -{{endregion}} >caption Figure 2: The changed border. @@ -49,34 +41,10 @@ The following snippet shows how you access the underlying controls and change th #### Set Labels ForeColor -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadDataEntryHowTo.cs region=LabelColor}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadDataEntryHowTo.vb region=LabelColor}} -````C# -foreach (RadPanel item in radDataEntry1.PanelContainer.Controls) -{ - foreach (RadControl control in item.Controls) - { - if (control is RadLabel) - { - control.ForeColor = ColorTranslator.FromHtml("#e83737"); - } - } -} - -```` -````VB.NET -For Each item As RadPanel In radDataEntry1.PanelContainer.Controls - For Each control As RadControl In item.Controls - If TypeOf control Is RadLabel Then - control.ForeColor = ColorTranslator.FromHtml("#e83737") - End If - Next control -Next item - -```` - - -{{endregion}} + + + + >caption Figure 3: Set Labels ForeColor. @@ -88,18 +56,10 @@ The following code snippets represent how to change the BackColor property of Va ### Change Back Color -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadDataEntryHowTo.cs region=ChangeBackColor}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadDataEntryHowTo.vb region=ChangeBackColor}} -````C# -this.radDataEntry1.ValidationPanel.PanelElement.Fill.BackColor = Color.PapayaWhip; - -```` -````VB.NET -Me.radDataEntry1.ValidationPanel.PanelElement.Fill.BackColor = Color.PapayaWhip + + -```` -{{endregion}} >caption Figure 4: Set Validaton Panel BackColor. diff --git a/controls/dataentry/getting-started.md b/controls/dataentry/getting-started.md index ed4dd7082..c603ec88d 100644 --- a/controls/dataentry/getting-started.md +++ b/controls/dataentry/getting-started.md @@ -43,162 +43,18 @@ The Telerik UI for WinForms assemblies can be install by using one of the availa 2\. For the purpose of this tutorial, we will create a new class Employee with a couple of exposed properties -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadDataEntryGettingStarted.cs region=empl1}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadDataEntryGettingStarted.vb region=empl1}} - -````C# -private class Employee -{ - public string FirstName - { - get; - set; - } - public string LastName - { - get; - set; - } - public string Occupation - { - get; - set; - } - public DateTime StartingDate - { - get; - set; - } - public bool IsMarried - { - get; - set; - } - public int Salary - { - get; - set; - } - public Gender Gender - { - get; - set; - } -} -private enum Gender -{ - Female, - Male -} - -```` -````VB.NET -Private Class Employee - Public Property FirstName() As String - Get - Return m_FirstName - End Get - Set(value As String) - m_FirstName = Value - End Set - End Property - Private m_FirstName As String - Public Property LastName() As String - Get - Return m_LastName - End Get - Set(value As String) - m_LastName = Value - End Set - End Property - Private m_LastName As String - Public Property Occupation() As String - Get - Return m_Occupation - End Get - Set(value As String) - m_Occupation = Value - End Set - End Property - Private m_Occupation As String - Public Property StartingDate() As DateTime - Get - Return m_StartingDate - End Get - Set(value As DateTime) - m_StartingDate = Value - End Set - End Property - Private m_StartingDate As DateTime - Public Property IsMarried() As Boolean - Get - Return m_IsMarried - End Get - Set(value As Boolean) - m_IsMarried = Value - End Set - End Property - Private m_IsMarried As Boolean - Public Property Salary() As Integer - Get - Return m_Salary - End Get - Set(value As Integer) - m_Salary = Value - End Set - End Property - Private m_Salary As Integer - Public Property Gender() As Gender - Get - Return m_Gender - End Get - Set(value As Gender) - m_Gender = Value - End Set - End Property - Private m_Gender As Gender -End Class -Private Enum Gender - Female - Male -End Enum - -```` - -{{endregion}} + + + + 3\. Once the class Employee is defined, you may use it for creating an object of this type and bind it to the RadDataEntry control: -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadDataEntryGettingStarted.cs region=bind1}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadDataEntryGettingStarted.vb region=bind1}} - -````C# -this.radDataEntry1.DataSource = new Employee() -{ - FirstName = "Sarah", - LastName = "Blake", - Occupation = "Supplied Manager", - StartingDate = new DateTime(2005, 04, 12), - IsMarried = true, - Salary = 3500, Gender = Gender.Female -}; - -```` -````VB.NET -Me.radDataEntry1.DataSource = New Employee() With { _ - .FirstName = "Sarah", _ - .LastName = "Blake", _ - .Occupation = "Supplied Manager", _ - .StartingDate = New DateTime(2005, 4, 12), _ - .IsMarried = True, _ - .Salary = 3500, _ - .Gender = Gender.Female _ - } - -```` - -{{endregion}} + + + + 4\. Press F5 to run the project and you should see the following: @@ -218,80 +74,18 @@ The following tutorial will demonstrate how to bind __RadDataEntry__ to a collec 2\. Create List of business objects and set it as data source of BindingSource. -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadDataEntryGettingStarted2.cs region=bind2}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadDataEntryGettingStarted2.vb region=bind2}} - -````C# -List employees = new List(); -employees.Add(new Employee() { FirstName = "Sarah", LastName = "Blake", Occupation = "Supplied Manager", StartingDate = new DateTime(2005, 04, 12), IsMarried = true, Salary = 3500, Gender = Gender.Female }); -employees.Add(new Employee() { FirstName = "Jane", LastName = "Simpson", Occupation = "Security", StartingDate = new DateTime(2008, 12, 03), IsMarried = true, Salary = 2000, Gender = Gender.Female }); -employees.Add(new Employee() { FirstName = "John", LastName = "Peterson", Occupation = "Consultant", StartingDate = new DateTime(2005, 04, 12), IsMarried = false, Salary = 2600, Gender = Gender.Male }); -employees.Add(new Employee() { FirstName = "Peter", LastName = "Bush", Occupation = "Cashier", StartingDate = new DateTime(2005, 04, 12), IsMarried = true, Salary = 2300, Gender = Gender.Male }); -this.bindingSource1.DataSource = employees; - -```` -````VB.NET -Dim employees As New List(Of Employee)() -employees.Add(New Employee() With { _ - .FirstName = "Sarah", _ - .LastName = "Blake", _ - .Occupation = "Supplied Manager", _ - .StartingDate = New DateTime(2005, 4, 12), _ - .IsMarried = True, _ - .Salary = 3500, _ - .Gender = Gender.Female _ -}) -employees.Add(New Employee() With { _ - .FirstName = "Jane", _ - .LastName = "Simpson", _ - .Occupation = "Security", _ - .StartingDate = New DateTime(2008, 12, 3), _ - .IsMarried = True, _ - .Salary = 2000, _ - .Gender = Gender.Female _ -}) -employees.Add(New Employee() With { _ - .FirstName = "John", _ - .LastName = "Peterson", _ - .Occupation = "Consultant", _ - .StartingDate = New DateTime(2005, 4, 12), _ - .IsMarried = False, _ - .Salary = 2600, _ - .Gender = Gender.Male _ -}) -employees.Add(New Employee() With { _ - .FirstName = "Peter", _ - .LastName = "Bush", _ - .Occupation = "Cashier", _ - .StartingDate = New DateTime(2005, 4, 12), _ - .IsMarried = True, _ - .Salary = 2300, _ - .Gender = Gender.Male _ -}) -Me.bindingSource1.DataSource = employees - -```` - -{{endregion}} + + + + 3\. Set this __BindingSource__ to __RadBindingNavigator__ and __RadDataEntry__. -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadDataEntryGettingStarted2.cs region=bind3}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadDataEntryGettingStarted2.vb region=bind3}} - -````C# -this.radDataEntry1.DataSource = this.bindingSource1; -this.radBindingNavigator1.BindingSource = this.bindingSource1; - -```` -````VB.NET -Me.radDataEntry1.DataSource = Me.bindingSource1 -Me.radBindingNavigator1.BindingSource = Me.bindingSource1 + + -```` - -{{endregion}} + 4\. Press __F5__ to run the project and you should see the following: diff --git a/controls/dataentry/how-to/change-auto-generated-editor.md b/controls/dataentry/how-to/change-auto-generated-editor.md index b3194fbfb..c842eec00 100644 --- a/controls/dataentry/how-to/change-auto-generated-editor.md +++ b/controls/dataentry/how-to/change-auto-generated-editor.md @@ -30,161 +30,17 @@ In the following example it will be demonstrated how to change default editor wi #### Data Object -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadDataEntryGettingStarted.cs region=empl1}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadDataEntryGettingStarted.vb region=empl1}} - -````C# -private class Employee -{ - public string FirstName - { - get; - set; - } - public string LastName - { - get; - set; - } - public string Occupation - { - get; - set; - } - public DateTime StartingDate - { - get; - set; - } - public bool IsMarried - { - get; - set; - } - public int Salary - { - get; - set; - } - public Gender Gender - { - get; - set; - } -} -private enum Gender -{ - Female, - Male -} - -```` -````VB.NET -Private Class Employee - Public Property FirstName() As String - Get - Return m_FirstName - End Get - Set(value As String) - m_FirstName = Value - End Set - End Property - Private m_FirstName As String - Public Property LastName() As String - Get - Return m_LastName - End Get - Set(value As String) - m_LastName = Value - End Set - End Property - Private m_LastName As String - Public Property Occupation() As String - Get - Return m_Occupation - End Get - Set(value As String) - m_Occupation = Value - End Set - End Property - Private m_Occupation As String - Public Property StartingDate() As DateTime - Get - Return m_StartingDate - End Get - Set(value As DateTime) - m_StartingDate = Value - End Set - End Property - Private m_StartingDate As DateTime - Public Property IsMarried() As Boolean - Get - Return m_IsMarried - End Get - Set(value As Boolean) - m_IsMarried = Value - End Set - End Property - Private m_IsMarried As Boolean - Public Property Salary() As Integer - Get - Return m_Salary - End Get - Set(value As Integer) - m_Salary = Value - End Set - End Property - Private m_Salary As Integer - Public Property Gender() As Gender - Get - Return m_Gender - End Get - Set(value As Gender) - m_Gender = Value - End Set - End Property - Private m_Gender As Gender -End Class -Private Enum Gender - Female - Male -End Enum - -```` - -{{endregion}} + + + + #### Data Binding -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadDataEntryGettingStarted.cs region=bind1}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadDataEntryGettingStarted.vb region=bind1}} - -````C# -this.radDataEntry1.DataSource = new Employee() -{ - FirstName = "Sarah", - LastName = "Blake", - Occupation = "Supplied Manager", - StartingDate = new DateTime(2005, 04, 12), - IsMarried = true, - Salary = 3500, Gender = Gender.Female -}; - -```` -````VB.NET -Me.radDataEntry1.DataSource = New Employee() With { _ - .FirstName = "Sarah", _ - .LastName = "Blake", _ - .Occupation = "Supplied Manager", _ - .StartingDate = New DateTime(2005, 4, 12), _ - .IsMarried = True, _ - .Salary = 3500, _ - .Gender = Gender.Female _ - } - -```` - -{{endregion}} + + + + >caption Figure 1: RadDataEntry Initializing. @@ -192,72 +48,19 @@ Me.radDataEntry1.DataSource = New Employee() With { _ 2\. To change the default __RadTextBox__ editor of the “Salary” property with __RadMaskedEditBox__ we will subscribe to *EditorInitializing* event of __RadDataEntry__. -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadDataEntryHowTo.cs region=EditorInitializing}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadDataEntryHowTo.vb region=EditorInitializing}} - -````C# -void radDataEntry1_EditorInitializing(object sender, Telerik.WinControls.UI.EditorInitializingEventArgs e) -{ - if (e.Property.Name == "Salary") - { - RadMaskedEditBox radMaskedEditBox = new RadMaskedEditBox(); - radMaskedEditBox.MaskType = MaskType.Numeric; - radMaskedEditBox.MaskedEditBoxElement.StretchVertically = true; - e.Editor = radMaskedEditBox; - } -} - -```` -````VB.NET -Private Sub radDataEntry1_EditorInitializing(sender As Object, e As Telerik.WinControls.UI.EditorInitializingEventArgs) - If e.[Property].Name = "Salary" Then - Dim radMaskedEditBox As New RadMaskedEditBox() - radMaskedEditBox.MaskType = MaskType.Numeric - radMaskedEditBox.MaskedEditBoxElement.StretchVertically = True - e.Editor = radMaskedEditBox - End If -End Sub - -```` - -{{endregion}} + + + + 3\. To achieve working binding for this new editor we should subscribe to the *BindingCreated* event where we will subscribe to the *Parse* event of the Binding object. You can read more about *Format* and *Parse* events of Binding object and why we should use them [here](http://msdn.microsoft.com/en-us/library/system.windows.forms.binding_events%28v=vs.110%29.aspx). #### Subscribe to Parse Event -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadDataEntryHowTo.cs region=BindingCreated}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadDataEntryHowTo.vb region=BindingCreated}} - -````C# -void radDataEntry1_BindingCreated(object sender, BindingCreatedEventArgs e) -{ - if (e.DataMember == "Salary") - { - e.Binding.Parse += new ConvertEventHandler(Binding_Parse); - } -} -void Binding_Parse(object sender, ConvertEventArgs e) -{ - int salary = int.Parse(e.Value.ToString(), NumberStyles.Currency); - e.Value = salary; -} - -```` -````VB.NET -Private Sub radDataEntry1_BindingCreated(sender As Object, e As BindingCreatedEventArgs) - If e.DataMember = "Salary" Then - AddHandler e.Binding.Parse, AddressOf Binding_Parse - End If -End Sub -Private Sub Binding_Parse(sender As Object, e As ConvertEventArgs) - Dim salary As Integer = Integer.Parse(e.Value.ToString(), NumberStyles.Currency) - e.Value = salary -End Sub - -```` - -{{endregion}} + + + + >caption Figure 2: RadDataEntry MaskedEditBox. @@ -267,35 +70,10 @@ End Sub The spin editor is created with the default settings for __Minimum/Maximum, DecimalPlaces, and Step__. If a case, you are using fractional numbers, the decimal part will be lost so we need to change the above properties. You can do that in the __EditorInitializing__. -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadDataEntryHowTo.cs region=SpinEditorDefaultValues}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadDataEntryHowTo.vb region=SpinEditorDefaultValues}} - -````C# -void radDataEntry_EditorInitializing(object sender, EditorInitializingEventArgs e) -{ - var spinEditor = e.Editor as RadSpinEditor; - - if (spinEditor == null) - return; - - spinEditor.Step = 0.01m; - spinEditor.DecimalPlaces = 2; - spinEditor.Maximum = Decimal.MaxValue; -} - -```` -````VB.NET -Private Sub radDataEntry_EditorInitializing(ByVal sender As Object, ByVal e As EditorInitializingEventArgs) - Dim spinEditor = TryCast(e.Editor, RadSpinEditor) - If spinEditor Is Nothing Then Return - spinEditor.[Step] = 0.01D - spinEditor.DecimalPlaces = 2 - spinEditor.Maximum = Decimal.MaxValue -End Sub + + -```` -{{endregion}} # See Also diff --git a/controls/dataentry/how-to/change-the-editor-to-a-bound-raddropdownlist.md b/controls/dataentry/how-to/change-the-editor-to-a-bound-raddropdownlist.md index 46297b569..9a128a68d 100644 --- a/controls/dataentry/how-to/change-the-editor-to-a-bound-raddropdownlist.md +++ b/controls/dataentry/how-to/change-the-editor-to-a-bound-raddropdownlist.md @@ -21,332 +21,57 @@ This article will walk you through the process of changing the default editor to #### Subscribe to Events -{{source=..\SamplesCS\DataEntryAndBindingNavigator\DataEntryHowTo\ChangeEditorToDropDownList.cs region=subscribe}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\DataEntryHowTo\ChangeEditorToDropDownList.vb region=subscribe}} + + -````C# -radDataEntry1.EditorInitializing += radDataEntry1_EditorInitializing; -radDataEntry1.BindingCreating += radDataEntry1_BindingCreating; -radDataEntry1.BindingCreated += radDataEntry1_BindingCreated; - -radDataEntry1.DataSource = productsBinding; - -```` -````VB.NET -AddHandler radDataEntry1.EditorInitializing, AddressOf radDataEntry1_EditorInitializing -AddHandler radDataEntry1.BindingCreating, AddressOf radDataEntry1_BindingCreating -AddHandler radDataEntry1.BindingCreated, AddressOf radDataEntry1_BindingCreated -radDataEntry1.DataSource = productsBinding -```` - -{{endregion}} 2\. In the __EditorInitializing__ event handler, you will be able to change the automatically generated editor with RadDropDownList. In addition, you should set it up as needed. In this case we will set the __DataSource__, __DisplayMember__ and __ValueMenber__ properties. #### Change Default Editor -{{source=..\SamplesCS\DataEntryAndBindingNavigator\DataEntryHowTo\ChangeEditorToDropDownList.cs region=editor}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\DataEntryHowTo\ChangeEditorToDropDownList.vb region=editor}} - -````C# -RadDropDownList radDropDownList1; -void radDataEntry1_EditorInitializing(object sender, Telerik.WinControls.UI.EditorInitializingEventArgs e) -{ - if (e.Property.Name == "SupplierID") - { - radDropDownList1 = new RadDropDownList(); - radDropDownList1.DataSource = suplierList; - radDropDownList1.ValueMember = "SupplierID"; - radDropDownList1.DisplayMember = "CompanyName"; - e.Editor = radDropDownList1; - } -} - -```` -````VB.NET -Private radDropDownList1 As RadDropDownList -Private Sub radDataEntry1_EditorInitializing(sender As Object, e As Telerik.WinControls.UI.EditorInitializingEventArgs) - If e.[Property].Name = "SupplierID" Then - radDropDownList1 = New RadDropDownList() - radDropDownList1.DataSource = suplierList - radDropDownList1.ValueMember = "SupplierID" - radDropDownList1.DisplayMember = "CompanyName" - e.Editor = radDropDownList1 - End If -End Sub - -```` - -{{endregion}} + + -3\. In order the values to be synchronized correctly, the bound property should be set in the __BindingCreating__ event handler. In this case it should be set to the __SelectedValue__ property. -#### Map Property -{{source=..\SamplesCS\DataEntryAndBindingNavigator\DataEntryHowTo\ChangeEditorToDropDownList.cs region=creating}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\DataEntryHowTo\ChangeEditorToDropDownList.vb region=creating}} +3\. In order the values to be synchronized correctly, the bound property should be set in the __BindingCreating__ event handler. In this case it should be set to the __SelectedValue__ property. -````C# -void radDataEntry1_BindingCreating(object sender, Telerik.WinControls.UI.BindingCreatingEventArgs e) -{ - if (e.DataMember == "SupplierID") - { - e.PropertyName = "SelectedValue"; - } -} +#### Map Property -```` -````VB.NET -Private Sub radDataEntry1_BindingCreating(sender As Object, e As Telerik.WinControls.UI.BindingCreatingEventArgs) - If e.DataMember = "SupplierID" Then - e.PropertyName = "SelectedValue" - End If -End Sub + + -```` -{{endregion}} 4\. When the data source is using nullable values in order the user to be able to change the current value via the drop down list, the result value should be manually parsed. This can be done in the binding's __Parse__ event. You can subscribe to this event in the __BindingCreated__ event handler (in order this event to fire the formatting should be enabled). #### Enable Formatting -{{source=..\SamplesCS\DataEntryAndBindingNavigator\DataEntryHowTo\ChangeEditorToDropDownList.cs region=created}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\DataEntryHowTo\ChangeEditorToDropDownList.vb region=created}} - -````C# -void radDataEntry1_BindingCreated(object sender, BindingCreatedEventArgs e) -{ - if (e.DataMember == "SupplierID") - { - e.Binding.FormattingEnabled = true; - e.Binding.Parse += new ConvertEventHandler(Binding_Parse); - } -} - -private void Binding_Parse(object sender, ConvertEventArgs e) -{ - int tmpvalue; - int? result = int.TryParse(e.Value.ToString(), out tmpvalue) ? tmpvalue : (int?)null; - e.Value = result; -} - -```` -````VB.NET -Private Sub radDataEntry1_BindingCreated(sender As Object, e As BindingCreatedEventArgs) - If e.DataMember = "SupplierID" Then - e.Binding.FormattingEnabled = True - AddHandler e.Binding.Parse, AddressOf Binding_Parse - End If -End Sub -Private Sub Binding_Parse(sender As Object, e As ConvertEventArgs) - Dim tmpvalue As Integer - Dim result As System.Nullable(Of Integer) = If(Integer.TryParse(e.Value.ToString(), tmpvalue), tmpvalue, DirectCast(Nothing, System.Nullable(Of Integer))) - e.Value = result -End Sub - -```` - -{{endregion}} + + + + + To make the example complete you can use the following classes. #### Data Models -{{source=..\SamplesCS\DataEntryAndBindingNavigator\DataEntryHowTo\ChangeEditorToDropDownList.cs region=data}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\DataEntryHowTo\ChangeEditorToDropDownList.vb region=data}} - -````C# -public class Product -{ - private int? _supplierID; - private string _productName; - public Product(int? supplierID, string productName) - { - this._supplierID = supplierID; - this._productName = productName; - } - public int? SupplierID - { - get - { - return this._supplierID; - } - set - { - this._supplierID = value; - } - } - public string ProductName - { - get - { - return this._productName; - } - set - { - this._productName = value; - } - } -} -public partial class Supplier -{ - private int? _supplierID; - private string _companyName; - public Supplier(int? supplierID, string companyName) - { - this._supplierID = supplierID; - this._companyName = companyName; - } - public int? SupplierID - { - get - { - return this._supplierID; - } - set - { - this._supplierID = value; - } - } - public string CompanyName - { - get - { - return this._companyName; - } - set - { - this._companyName = value; - } - } -} - -```` -````VB.NET -Public Class Product - Private _supplierID As System.Nullable(Of Integer) - Private _productName As String - Public Sub New(supplierID As System.Nullable(Of Integer), productName As String) - Me._supplierID = supplierID - Me._productName = productName - End Sub - Public Property SupplierID() As System.Nullable(Of Integer) - Get - Return Me._supplierID - End Get - Set(value As System.Nullable(Of Integer)) - Me._supplierID = value - End Set - End Property - Public Property ProductName() As String - Get - Return Me._productName - End Get - Set(value As String) - Me._productName = value - End Set - End Property -End Class -Partial Public Class Supplier - Private _supplierID As System.Nullable(Of Integer) - Private _companyName As String - Public Sub New(supplierID As System.Nullable(Of Integer), companyName As String) - Me._supplierID = supplierID - Me._companyName = companyName - End Sub - Public Property SupplierID() As System.Nullable(Of Integer) - Get - Return Me._supplierID - End Get - Set(value As System.Nullable(Of Integer)) - Me._supplierID = value - End Set - End Property - Public Property CompanyName() As String - Get - Return Me._companyName - End Get - Set(value As String) - Me._companyName = value - End Set - End Property -End Class - -```` - -{{endregion}} + + + + You can initialize the data sources in the Form’s constructor. #### Initialize Data -{{source=..\SamplesCS\DataEntryAndBindingNavigator\DataEntryHowTo\ChangeEditorToDropDownList.cs region=init}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\DataEntryHowTo\ChangeEditorToDropDownList.vb region=init}} - -````C# -List productList; -List suplierList; -BindingSource productsBinding; -public ChangeEditorToDropDownList() -{ - InitializeComponent(); - productList = new List(); - suplierList = new List(); - productList.Add(new Product(1, "Chai")); - productList.Add(new Product(2, "Chang")); - productList.Add(new Product(3, "Aniseed Syrup")); - productList.Add(new Product(4, "Chef Anton's Gumbo Mix")); - productList.Add(new Product(5, "Tofu")); - productList.Add(new Product(null, "Sir Rodney's Marmalade")); - productList.Add(new Product(6, "Boston Crab Meat")); - productList.Add(new Product(5, "Chartreuse verte")); - productList.Add(new Product(2, "Ravioli Angelo")); - productList.Add(new Product(4, "Perth Pasties")); - suplierList.Add(new Supplier(1, "Exotic Liquids")); - suplierList.Add(new Supplier(2, "New Orleans Cajun Delights")); - suplierList.Add(new Supplier(3, "Tokyo Traders")); - suplierList.Add(new Supplier(4, "Norske Meierier")); - suplierList.Add(new Supplier(5, "New England Seafood Cannery")); - suplierList.Add(new Supplier(6, "Leka Trading")); - productsBinding = new BindingSource(); - productsBinding.DataSource = productList; -} - -```` -````VB.NET -Private productList As List(Of Product) -Private suplierList As List(Of Supplier) -Private productsBinding As BindingSource -Public Sub New() - InitializeComponent() - productList = New List(Of Product)() - suplierList = New List(Of Supplier)() - productList.Add(New Product(1, "Chai")) - productList.Add(New Product(2, "Chang")) - productList.Add(New Product(3, "Aniseed Syrup")) - productList.Add(New Product(4, "Chef Anton's Gumbo Mix")) - productList.Add(New Product(5, "Tofu")) - productList.Add(New Product(Nothing, "Sir Rodney's Marmalade")) - productList.Add(New Product(6, "Boston Crab Meat")) - productList.Add(New Product(5, "Chartreuse verte")) - productList.Add(New Product(2, "Ravioli Angelo")) - productList.Add(New Product(4, "Perth Pasties")) - suplierList.Add(New Supplier(1, "Exotic Liquids")) - suplierList.Add(New Supplier(2, "New Orleans Cajun Delights")) - suplierList.Add(New Supplier(3, "Tokyo Traders")) - suplierList.Add(New Supplier(4, "Norske Meierier")) - suplierList.Add(New Supplier(5, "New England Seafood Cannery")) - suplierList.Add(New Supplier(6, "Leka Trading")) - productsBinding = New BindingSource() - productsBinding.DataSource = productList -End Sub - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/dataentry/how-to/handle-unsupported-values.md b/controls/dataentry/how-to/handle-unsupported-values.md index 8dba0bfd2..a67ca404e 100644 --- a/controls/dataentry/how-to/handle-unsupported-values.md +++ b/controls/dataentry/how-to/handle-unsupported-values.md @@ -21,89 +21,30 @@ The following example demonstrates how to do that: #### Map Nullable Property -{{source=..\SamplesCS\DataEntryAndBindingNavigator\DataEntryHowTo\HandleUnsupportedValues.cs region=BindingCreating}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\DataEntryHowTo\HandleUnsupportedValues.vb region=BindingCreating}} + + -````C# -void radDataEntry1_BindingCreating(object sender, BindingCreatingEventArgs e) -{ - if (e.DataMember == "DateTime") - { - e.PropertyName = "NullableValue"; - } -} -```` -````VB.NET -Private Sub radDataEntry1_BindingCreating(sender As Object, e As BindingCreatingEventArgs) - If e.DataMember = "DateTime" Then - e.PropertyName = "NullableValue" - End If -End Sub - -```` - -{{endregion}} 2\. Then in the __BindingCreated__ event you will enable the binding formatting and will subscribe to its __Format__ event. #### Enable Formatting -{{source=..\SamplesCS\DataEntryAndBindingNavigator\DataEntryHowTo\HandleUnsupportedValues.cs region=BindingCreated}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\DataEntryHowTo\HandleUnsupportedValues.vb region=BindingCreated}} - -````C# -void radDataEntry1_BindingCreated(object sender, BindingCreatedEventArgs e) -{ - if (e.DataMember == "DateTime") - { - e.Binding.FormattingEnabled = true; - e.Binding.Format += Binding_Format; - } -} + + -```` -````VB.NET -Private Sub radDataEntry1_BindingCreated(sender As Object, e As BindingCreatedEventArgs) - If e.DataMember = "DateTime" Then - e.Binding.FormattingEnabled = True - AddHandler e.Binding.Format, AddressOf Binding_Format - End If -End Sub -```` - -{{endregion}} 3\. At the end we just need to interpret the *DBNull* values as *null* values: #### Evaluate DBNull -{{source=..\SamplesCS\DataEntryAndBindingNavigator\DataEntryHowTo\HandleUnsupportedValues.cs region=Format}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\DataEntryHowTo\HandleUnsupportedValues.vb region=Format}} - -````C# -void Binding_Format(object sender, ConvertEventArgs e) -{ - if (e.Value.Equals(DBNull.Value)) - { - e.Value = null; - } -} - -```` -````VB.NET -Private Sub Binding_Format(sender As Object, e As ConvertEventArgs) - If e.Value.Equals(DBNull.Value) Then - e.Value = Nothing - End If -End Sub - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/dataentry/programmatically-arrange-items-.md b/controls/dataentry/programmatically-arrange-items-.md index 1482be0eb..f86aa9c7f 100644 --- a/controls/dataentry/programmatically-arrange-items-.md +++ b/controls/dataentry/programmatically-arrange-items-.md @@ -17,161 +17,17 @@ Items in __RadDataEntry__ can be arranged both at design time and run time. At d #### Data Object -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadDataEntryGettingStarted.cs region=empl1}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadDataEntryGettingStarted.vb region=empl1}} - -````C# -private class Employee -{ - public string FirstName - { - get; - set; - } - public string LastName - { - get; - set; - } - public string Occupation - { - get; - set; - } - public DateTime StartingDate - { - get; - set; - } - public bool IsMarried - { - get; - set; - } - public int Salary - { - get; - set; - } - public Gender Gender - { - get; - set; - } -} -private enum Gender -{ - Female, - Male -} - -```` -````VB.NET -Private Class Employee - Public Property FirstName() As String - Get - Return m_FirstName - End Get - Set(value As String) - m_FirstName = Value - End Set - End Property - Private m_FirstName As String - Public Property LastName() As String - Get - Return m_LastName - End Get - Set(value As String) - m_LastName = Value - End Set - End Property - Private m_LastName As String - Public Property Occupation() As String - Get - Return m_Occupation - End Get - Set(value As String) - m_Occupation = Value - End Set - End Property - Private m_Occupation As String - Public Property StartingDate() As DateTime - Get - Return m_StartingDate - End Get - Set(value As DateTime) - m_StartingDate = Value - End Set - End Property - Private m_StartingDate As DateTime - Public Property IsMarried() As Boolean - Get - Return m_IsMarried - End Get - Set(value As Boolean) - m_IsMarried = Value - End Set - End Property - Private m_IsMarried As Boolean - Public Property Salary() As Integer - Get - Return m_Salary - End Get - Set(value As Integer) - m_Salary = Value - End Set - End Property - Private m_Salary As Integer - Public Property Gender() As Gender - Get - Return m_Gender - End Get - Set(value As Gender) - m_Gender = Value - End Set - End Property - Private m_Gender As Gender -End Class -Private Enum Gender - Female - Male -End Enum - -```` - -{{endregion}} + + + + #### Data Binding -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadDataEntryGettingStarted.cs region=bind1}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadDataEntryGettingStarted.vb region=bind1}} - -````C# -this.radDataEntry1.DataSource = new Employee() -{ - FirstName = "Sarah", - LastName = "Blake", - Occupation = "Supplied Manager", - StartingDate = new DateTime(2005, 04, 12), - IsMarried = true, - Salary = 3500, Gender = Gender.Female -}; - -```` -````VB.NET -Me.radDataEntry1.DataSource = New Employee() With { _ - .FirstName = "Sarah", _ - .LastName = "Blake", _ - .Occupation = "Supplied Manager", _ - .StartingDate = New DateTime(2005, 4, 12), _ - .IsMarried = True, _ - .Salary = 3500, _ - .Gender = Gender.Female _ - } - -```` - -{{endregion}} + + + + >caption Figure 1: RadDataEntry is initialized. @@ -181,47 +37,10 @@ Me.radDataEntry1.DataSource = New Employee() With { _ #### Special Arrangement -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadDataEntryHowTo.cs region=ItemInitialized}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadDataEntryHowTo.vb region=ItemInitialized}} - -````C# -void radDataEntry1_ItemInitialized(object sender, Telerik.WinControls.UI.ItemInitializedEventArgs e) -{ - if (e.Panel.Controls[1].Text == "FirstName") - { - e.Panel.Size = new Size(150, 25); - e.Panel.Controls[1].Text = "Name"; - } - else if (e.Panel.Controls[1].Text == "LastName") - { - e.Panel.Size = new Size(100, 25); - e.Panel.Controls[1].Visible = false; - e.Panel.Location = new Point(160, radDataEntry1.ItemSpace); - } - else - { - e.Panel.Location = new Point(e.Panel.Location.X, e.Panel.Location.Y - 25); - } -} - -```` -````VB.NET -Private Sub radDataEntry1_ItemInitialized(sender As Object, e As Telerik.WinControls.UI.ItemInitializedEventArgs) - If e.Panel.Controls(1).Text = "FirstName" Then - e.Panel.Size = New Size(150, 25) - e.Panel.Controls(1).Text = "Name" - ElseIf e.Panel.Controls(1).Text = "LastName" Then - e.Panel.Size = New Size(100, 25) - e.Panel.Controls(1).Visible = False - e.Panel.Location = New Point(160, radDataEntry1.ItemSpace) - Else - e.Panel.Location = New Point(e.Panel.Location.X, e.Panel.Location.Y - 25) - End If -End Sub - -```` - -{{endregion}} + + + + >caption Figure 2: The whole name is now displayed in the first row. diff --git a/controls/dataentry/properties-events-and-attributes.md b/controls/dataentry/properties-events-and-attributes.md index 6a0a8e53a..f0175c9c0 100644 --- a/controls/dataentry/properties-events-and-attributes.md +++ b/controls/dataentry/properties-events-and-attributes.md @@ -19,35 +19,10 @@ The main purpose of __RadDataEntry__ is to generate editors according to the obj #### RadDataEntry Binding. -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadDataEntryGettingStarted.cs region=bind1}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadDataEntryGettingStarted.vb region=bind1}} - -````C# -this.radDataEntry1.DataSource = new Employee() -{ - FirstName = "Sarah", - LastName = "Blake", - Occupation = "Supplied Manager", - StartingDate = new DateTime(2005, 04, 12), - IsMarried = true, - Salary = 3500, Gender = Gender.Female -}; - -```` -````VB.NET -Me.radDataEntry1.DataSource = New Employee() With { _ - .FirstName = "Sarah", _ - .LastName = "Blake", _ - .Occupation = "Supplied Manager", _ - .StartingDate = New DateTime(2005, 4, 12), _ - .IsMarried = True, _ - .Salary = 3500, _ - .Gender = Gender.Female _ - } - -```` - -{{endregion}} + + + + >caption> Figure 1: Set The Data Source of RadDataEntry @@ -57,19 +32,10 @@ Me.radDataEntry1.DataSource = New Employee() With { _ #### Set the Columns Count. -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadDataEntryProgram.cs region=NumberOfColumns}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadDataEntryProgram.vb region=NumberOfColumns}} - -````C# -this.radDataEntry1.ColumnCount = 2; - -```` -````VB.NET -Me.radDataEntry1.ColumnCount = 2 - -```` + + -{{endregion}} + >caption Figure 2: Set The Columns Count. @@ -79,19 +45,10 @@ Me.radDataEntry1.ColumnCount = 2 #### Set FitToParentWidth Property. -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadDataEntryProgram.cs region=FitToParentWidth}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadDataEntryProgram.vb region=FitToParentWidth}} - -````C# -this.radDataEntry1.FitToParentWidth = true; - -```` -````VB.NET -Me.radDataEntry1.FitToParentWidth = True + + -```` - -{{endregion}} + >caption Figure 3. Set FitToParentWidth @@ -101,33 +58,10 @@ Me.radDataEntry1.FitToParentWidth = True #### Setup the Validation Panel. -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadDataEntryProgram.cs region=ShowValidationPanel}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadDataEntryProgram.vb region=ShowValidationPanel}} - -````C# -this.radDataEntry1.ShowValidationPanel = true; -RadLabel label = new RadLabel(); -label.Name = "First Name"; -label.Text = "First Name : First Name should be between 2 and 15 chars long."; -label.Dock = DockStyle.Top; -label.AutoSize = false; -label.BackColor = Color.Transparent; -this.radDataEntry1.ValidationPanel.PanelContainer.Controls.Add(label); - -```` -````VB.NET -Me.radDataEntry1.ShowValidationPanel = True -Dim label As New RadLabel() -label.Name = "First Name" -label.Text = "First Name : First Name should be between 2 and 15 chars long." -label.Dock = DockStyle.Top -label.AutoSize = False -label.BackColor = Color.Transparent -Me.radDataEntry1.ValidationPanel.PanelContainer.Controls.Add(label) - -```` - -{{endregion}} + + + + >caption Figure 4: The Validation Panel. @@ -137,21 +71,10 @@ Me.radDataEntry1.ValidationPanel.PanelContainer.Controls.Add(label) ### Set the Flow Direction. -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadDataEntryProgram.cs region=FillingOrder1}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadDataEntryProgram.vb region=FillingOrder1}} - -````C# -this.radDataEntry1.ColumnCount = 2; -this.radDataEntry1.FlowDirection = FlowDirection.BottomUp; - -```` -````VB.NET -Me.radDataEntry1.ColumnCount = 2 -Me.radDataEntry1.FlowDirection = FlowDirection.BottomUp - -```` + + -{{endregion}} + >caption Figure 5: Set the flow direction. @@ -161,19 +84,10 @@ Me.radDataEntry1.FlowDirection = FlowDirection.BottomUp #### Set Space Between The Items. -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadDataEntryProgram.cs region=ItemSpace}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadDataEntryProgram.vb region=ItemSpace}} - -````C# -this.radDataEntry1.ItemSpace = 10; - -```` -````VB.NET -Me.radDataEntry1.ItemSpace = 10 - -```` + + -{{endregion}} + >caption Figure 6 Set the items space. @@ -183,19 +97,10 @@ Me.radDataEntry1.ItemSpace = 10 #### Set items default size. -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadDataEntryProgram.cs region=ItemDefaultSize}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadDataEntryProgram.vb region=ItemDefaultSize}} - -````C# -this.radDataEntry1.ItemDefaultSize = new Size(300, 30); - -```` -````VB.NET -Me.radDataEntry1.ItemDefaultSize = New Size(300, 30) + + -```` - -{{endregion}} + >caption Figure 7. Set items size. @@ -205,19 +110,10 @@ Me.radDataEntry1.ItemDefaultSize = New Size(300, 30) #### Set The AutoSizeLabels Property. -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadDataEntryProgram.cs region=ResizeLabels}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadDataEntryProgram.vb region=ResizeLabels}} + + -````C# -this.radDataEntry1.AutoSizeLabels = true; - -```` -````VB.NET -Me.radDataEntry1.AutoSizeLabels = True - -```` - -{{endregion}} + >caption Figure 8: The Labels are not Auto-Sized. @@ -254,66 +150,20 @@ With the __Browsable__ attribute users can easily control which properties shoul #### Set The Browsable Attribute. -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadDataEntryProgram.cs region=Browsable}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadDataEntryProgram.vb region=Browsable}} - -````C# -[Browsable(false)] -public string PhoneNumber -{ - get; - set; -} + + -```` -````VB.NET - _ -Public Property PhoneNumber() As String - Get - Return m_PhoneNumber - End Get - Set(value As String) - m_PhoneNumber = Value - End Set -End Property -Private m_PhoneNumber As String - -```` - -{{endregion}} + The __DisplayName__ attribute defines what text should be displayed in the label that is associated with the editor. #### Set The DisplayName Attribute. -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadDataEntryProgram.cs region=DisplayName}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadDataEntryProgram.vb region=DisplayName}} - -````C# -[DisplayName("family name")] -public string LastName -{ - get; - set; -} - -```` -````VB.NET - _ -Public Property LastName() As String - Get - Return m_LastName - End Get - Set(value As String) - m_LastName = Value - End Set -End Property -Private m_LastName As String + + -```` - -{{endregion}} + ![WinForms RadDataEntry Set The DisplayName Attribute](images/dataentry-properties-events-and-attributes009.png) @@ -322,33 +172,10 @@ With __RadRange__ attribute users can define range that can be used into validat #### Set The RadRange Attribute -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadDataEntryProgram.cs region=RadRange}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadDataEntryProgram.vb region=RadRange}} - -````C# -[RadRange(1500,2000)] -public int Salary -{ - get; - set; -} - -```` -````VB.NET - _ -Public Property Salary() As Integer - Get - Return m_Salary - End Get - Set(value As Integer) - m_Salary = Value - End Set -End Property -Private m_Salary As Integer - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/dataentry/validation.md b/controls/dataentry/validation.md index 123673a18..5d5f1dbee 100644 --- a/controls/dataentry/validation.md +++ b/controls/dataentry/validation.md @@ -17,162 +17,19 @@ For the need of validation process we made two events (__ItemValidating, ItemVal #### DataObject -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadDataEntryGettingStarted.cs region=empl1}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadDataEntryGettingStarted.vb region=empl1}} + + -````C# -private class Employee -{ - public string FirstName - { - get; - set; - } - public string LastName - { - get; - set; - } - public string Occupation - { - get; - set; - } - public DateTime StartingDate - { - get; - set; - } - public bool IsMarried - { - get; - set; - } - public int Salary - { - get; - set; - } - public Gender Gender - { - get; - set; - } -} -private enum Gender -{ - Female, - Male -} -```` -````VB.NET -Private Class Employee - Public Property FirstName() As String - Get - Return m_FirstName - End Get - Set(value As String) - m_FirstName = Value - End Set - End Property - Private m_FirstName As String - Public Property LastName() As String - Get - Return m_LastName - End Get - Set(value As String) - m_LastName = Value - End Set - End Property - Private m_LastName As String - Public Property Occupation() As String - Get - Return m_Occupation - End Get - Set(value As String) - m_Occupation = Value - End Set - End Property - Private m_Occupation As String - Public Property StartingDate() As DateTime - Get - Return m_StartingDate - End Get - Set(value As DateTime) - m_StartingDate = Value - End Set - End Property - Private m_StartingDate As DateTime - Public Property IsMarried() As Boolean - Get - Return m_IsMarried - End Get - Set(value As Boolean) - m_IsMarried = Value - End Set - End Property - Private m_IsMarried As Boolean - Public Property Salary() As Integer - Get - Return m_Salary - End Get - Set(value As Integer) - m_Salary = Value - End Set - End Property - Private m_Salary As Integer - Public Property Gender() As Gender - Get - Return m_Gender - End Get - Set(value As Gender) - m_Gender = Value - End Set - End Property - Private m_Gender As Gender -End Class -Private Enum Gender - Female - Male -End Enum -```` - -{{endregion}} #### Data Binding -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadDataEntryGettingStarted.cs region=bind1}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadDataEntryGettingStarted.vb region=bind1}} - -````C# -this.radDataEntry1.DataSource = new Employee() -{ - FirstName = "Sarah", - LastName = "Blake", - Occupation = "Supplied Manager", - StartingDate = new DateTime(2005, 04, 12), - IsMarried = true, - Salary = 3500, Gender = Gender.Female -}; - -```` -````VB.NET -Me.radDataEntry1.DataSource = New Employee() With { _ - .FirstName = "Sarah", _ - .LastName = "Blake", _ - .Occupation = "Supplied Manager", _ - .StartingDate = New DateTime(2005, 4, 12), _ - .IsMarried = True, _ - .Salary = 3500, _ - .Gender = Gender.Female _ - } + + -```` -{{endregion}} >caption Figure 1: RadDataEntry is initialized. @@ -181,158 +38,21 @@ Me.radDataEntry1.DataSource = New Employee() With { _ 2\. Set the __ShowValidationPanel__ property to true. This will display the panel below the editors: -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadDataEntryHowTo.cs region=ShowValidationPanel2}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadDataEntryHowTo.vb region=ShowValidationPanel2}} + + -````C# -this.radDataEntry1.ShowValidationPanel = true; -```` -````VB.NET -Me.radDataEntry1.ShowValidationPanel = True -```` - -{{endregion}} 3\. Subscribe to the __ItemValidated__ event of __RadDataEntry__: #### Data Validation -{{source=..\SamplesCS\DataEntryAndBindingNavigator\RadDataEntryHowTo.cs region=ItemValidated}} -{{source=..\SamplesVB\DataEntryAndBindingNavigator\RadDataEntryHowTo.vb region=ItemValidated}} - -````C# -void radDataEntry1_ItemValidated(object sender, ItemValidatedEventArgs e) -{ - Employee employee = this.radDataEntry1.CurrentObject as Employee; - if (e.Label.Text == "FirstName") - { - if (employee.FirstName.Length < 2 || employee.FirstName.Length > 15) - { - e.ErrorProvider.SetError((sender as Control), "First Name should be between 2 and 15 chars long."); - if (!this.radDataEntry1.ValidationPanel.PanelContainer.Controls.ContainsKey("FirstName")) - { - RadLabel label = new RadLabel(); - label.Name = "FirstName"; - label.Text = "FirstName : First Name should be between 2 and 15 chars long."; - label.Dock = DockStyle.Top; - label.AutoSize = false; - label.BackColor = Color.Transparent; - this.radDataEntry1.ValidationPanel.PanelContainer.Controls.Add(label); - } - } - else - { - e.ErrorProvider.Clear(); - this.radDataEntry1.ValidationPanel.PanelContainer.Controls.RemoveByKey("FirstName"); - } - } - else if (e.Label.Text == "LastName") - { - if (employee.LastName.Length < 2 || employee.LastName.Length > 15) - { - e.ErrorProvider.SetError((sender as Control), "Last Name should be between 2 and 15 chars long."); - if (!this.radDataEntry1.ValidationPanel.PanelContainer.Controls.ContainsKey("LastName")) - { - RadLabel label = new RadLabel(); - label.Name = "LastName"; - label.Text = "LastName : Last Name should be between 2 and 15 chars long."; - label.Dock = DockStyle.Top; - label.AutoSize = false; - label.BackColor = Color.Transparent; - this.radDataEntry1.ValidationPanel.PanelContainer.Controls.Add(label); - } - } - else - { - e.ErrorProvider.Clear(); - this.radDataEntry1.ValidationPanel.PanelContainer.Controls.RemoveByKey("LastName"); - } - } - else if (e.Label.Text == "Salary") - { - if (employee.Salary < 1500 || employee.Salary > 1700) - { - e.ErrorProvider.SetError((sender as Control), "Salary should be in range 1500 - 1700."); - if (!this.radDataEntry1.ValidationPanel.PanelContainer.Controls.ContainsKey("Salary")) - { - RadLabel label = new RadLabel(); - label.Name = "Salary"; - label.Text = "Salary : Salary should be in range 1500 - 1700."; - label.Dock = DockStyle.Top; - label.AutoSize = false; - label.BackColor = Color.Transparent; - this.radDataEntry1.ValidationPanel.PanelContainer.Controls.Add(label); - } - } - else - { - e.ErrorProvider.Clear(); - this.radDataEntry1.ValidationPanel.PanelContainer.Controls.RemoveByKey("Salary"); - } - } -} - -```` -````VB.NET -Private Sub radDataEntry1_ItemValidated(sender As Object, e As ItemValidatedEventArgs) - Dim employee As Employee = TryCast(Me.radDataEntry1.CurrentObject, Employee) - If e.Label.Text = "FirstName" Then - If employee.FirstName.Length < 2 OrElse employee.FirstName.Length > 15 Then - e.ErrorProvider.SetError(TryCast(sender, Control), "First Name should be between 2 and 15 chars long.") - If Not Me.radDataEntry1.ValidationPanel.PanelContainer.Controls.ContainsKey("FirstName") Then - Dim label As New RadLabel() - label.Name = "FirstName" - label.Text = "FirstName : First Name should be between 2 and 15 chars long." - label.Dock = DockStyle.Top - label.AutoSize = False - label.BackColor = Color.Transparent - Me.radDataEntry1.ValidationPanel.PanelContainer.Controls.Add(label) - End If - Else - e.ErrorProvider.Clear() - Me.radDataEntry1.ValidationPanel.PanelContainer.Controls.RemoveByKey("FirstName") - End If - ElseIf e.Label.Text = "LastName" Then - If employee.LastName.Length < 2 OrElse employee.LastName.Length > 15 Then - e.ErrorProvider.SetError(TryCast(sender, Control), "Last Name should be between 2 and 15 chars long.") - If Not Me.radDataEntry1.ValidationPanel.PanelContainer.Controls.ContainsKey("LastName") Then - Dim label As New RadLabel() - label.Name = "LastName" - label.Text = "LastName : Last Name should be between 2 and 15 chars long." - label.Dock = DockStyle.Top - label.AutoSize = False - label.BackColor = Color.Transparent - Me.radDataEntry1.ValidationPanel.PanelContainer.Controls.Add(label) - End If - Else - e.ErrorProvider.Clear() - Me.radDataEntry1.ValidationPanel.PanelContainer.Controls.RemoveByKey("LastName") - End If - ElseIf e.Label.Text = "Salary" Then - If employee.Salary < 1500 OrElse employee.Salary > 1700 Then - e.ErrorProvider.SetError(TryCast(sender, Control), "Salary should be in range 1500 - 1700.") - If Not Me.radDataEntry1.ValidationPanel.PanelContainer.Controls.ContainsKey("Salary") Then - Dim label As New RadLabel() - label.Name = "Salary" - label.Text = "Salary : Salary should be in range 1500 - 1700." - label.Dock = DockStyle.Top - label.AutoSize = False - label.BackColor = Color.Transparent - Me.radDataEntry1.ValidationPanel.PanelContainer.Controls.Add(label) - End If - Else - e.ErrorProvider.Clear() - Me.radDataEntry1.ValidationPanel.PanelContainer.Controls.RemoveByKey("Salary") - End If - End If -End Sub + + -```` -{{endregion}} >caption Figure 2. The Validation panels shows the error message. diff --git a/controls/datafilter/customizing-appearance/custom-display-names.md b/controls/datafilter/customizing-appearance/custom-display-names.md index f7cfc49b2..b2998cdc5 100644 --- a/controls/datafilter/customizing-appearance/custom-display-names.md +++ b/controls/datafilter/customizing-appearance/custom-display-names.md @@ -18,30 +18,10 @@ The names behind each of the descriptor items are extracted from the data-bound #### PropertyDisplayNameNeeded Event -{{source=..\SamplesCS\DataFilter\DataFilterWorkingWithNodes.cs region=CustomDisplayNames}} -{{source=..\SamplesVB\DataFilter\DataFilterWorkingWithNodes.vb region=CustomDisplayNames}} -````C# -private void RadDataFilter1_PropertyDisplayNameNeeded(object sender, PropertyDisplayNameNeededEventArgs e) -{ - if (e.FieldName == "BirthDay") - { - e.DisplayName = "Birth Day"; - } -} - -```` -````VB.NET -Private Sub RadDataFilter1_PropertyDisplayNameNeeded(sender As Object, e As PropertyDisplayNameNeededEventArgs) - If e.FieldName = "Birth Day" Then - e.DisplayName = "Birth Day" - End If -End Sub - -```` - - - -{{endregion}} + + + + # See Also diff --git a/controls/datafilter/customizing-appearance/formatting-nodes.md b/controls/datafilter/customizing-appearance/formatting-nodes.md index faa2afbd9..219e238a5 100644 --- a/controls/datafilter/customizing-appearance/formatting-nodes.md +++ b/controls/datafilter/customizing-appearance/formatting-nodes.md @@ -25,38 +25,10 @@ Group nodes can be formatted to handle custom scenarios. The root node in the ex #### Group Nodes -{{source=..\SamplesCS\DataFilter\DataFilterWorkingWithNodes.cs region=GroupNodes}} -{{source=..\SamplesVB\DataFilter\DataFilterWorkingWithNodes.vb region=GroupNodes}} -````C# -private void radDataFilter1_NodeFormatting(object sender, TreeNodeFormattingEventArgs e) -{ - DataFilterGroupElement dataGroupFilterElement = e.NodeElement as DataFilterGroupElement; - if (dataGroupFilterElement != null && dataGroupFilterElement.IsRootNode) - { - dataGroupFilterElement.ExpanderElement.Visibility = ElementVisibility.Collapsed; - } - else - { - e.NodeElement.ResetValue(LightVisualElement.VisibilityProperty, ValueResetFlags.Local); - } -} - -```` -````VB.NET -Private Sub radDataFilter1_NodeFormatting(sender As Object, e As TreeNodeFormattingEventArgs) - Dim dataGroupFilterElement As DataFilterGroupElement = TryCast(e.NodeElement, DataFilterGroupElement) - If dataGroupFilterElement IsNot Nothing AndAlso dataGroupFilterElement.IsRootNode Then - dataGroupFilterElement.ExpanderElement.Visibility = ElementVisibility.Collapsed - Else - e.NodeElement.ResetValue(LightVisualElement.VisibilityProperty, ValueResetFlags.Local) - End If -End Sub - -```` - - - -{{endregion}} + + + + ## Formatting Expression Nodes @@ -68,38 +40,10 @@ The appearance of the expression nodes can also be modified to change their visu #### Expression Nodes -{{source=..\SamplesCS\DataFilter\DataFilterWorkingWithNodes.cs region=ExpressionNodes}} -{{source=..\SamplesVB\DataFilter\DataFilterWorkingWithNodes.vb region=ExpressionNodes}} -````C# -private void radDataFilter1_NodeFormatting1(object sender, TreeNodeFormattingEventArgs e) -{ - DataFilterCriteriaElement dataExpressionFilterElement = e.NodeElement as DataFilterCriteriaElement; - if (dataExpressionFilterElement != null && dataExpressionFilterElement.CriteriaNode.Descriptor.PropertyName == "Name") - { - dataExpressionFilterElement.ContentElement.BackColor = Color.LightBlue; - } - else - { - e.NodeElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local); - } -} - -```` -````VB.NET -Private Sub radDataFilter1_NodeFormatting1(sender As Object, e As TreeNodeFormattingEventArgs) - Dim dataExpressionFilterElement As DataFilterCriteriaElement = TryCast(e.NodeElement, DataFilterCriteriaElement) - If dataExpressionFilterElement IsNot Nothing AndAlso dataExpressionFilterElement.CriteriaNode.Descriptor.PropertyName = "Name" Then - dataExpressionFilterElement.ContentElement.BackColor = Color.LightBlue - Else - e.NodeElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local) - End If -End Sub - -```` - - - -{{endregion}} + + + + ## Formatting Button Nodes @@ -111,38 +55,10 @@ The button responsible for adding a new expression can also be customized in a f #### Button Nodes -{{source=..\SamplesCS\DataFilter\DataFilterWorkingWithNodes.cs region=AddButton}} -{{source=..\SamplesVB\DataFilter\DataFilterWorkingWithNodes.vb region=AddButton}} -````C# -private void radDataFilter1_NodeFormatting2(object sender, TreeNodeFormattingEventArgs e) -{ - DataFilterAddNodeElement dataAddNodeElement = e.NodeElement as DataFilterAddNodeElement; - if (dataAddNodeElement != null && dataAddNodeElement.DropDownButton.Text == "Add") - { - dataAddNodeElement.DropDownButton.Text = "Add Filter"; - } - else - { - e.NodeElement.ResetValue(LightVisualElement.VisibilityProperty, ValueResetFlags.Local); - } -} - -```` -````VB.NET -Private Sub radDataFilter1_NodeFormatting2(sender As Object, e As TreeNodeFormattingEventArgs) - Dim dataAddNodeElement As DataFilterAddNodeElement = TryCast(e.NodeElement, DataFilterAddNodeElement) - If dataAddNodeElement IsNot Nothing AndAlso dataAddNodeElement.DropDownButton.Text = "Add" Then - dataAddNodeElement.DropDownButton.Text = "Add Filter" - Else - e.NodeElement.ResetValue(LightVisualElement.VisibilityProperty, ValueResetFlags.Local) - End If -End Sub - -```` - - - -{{endregion}} + + + + ## Formatting Child Expression Elements @@ -154,69 +70,10 @@ Each of the nodes holding the expressions has three editor elements which can be #### Child Expression Elements -{{source=..\SamplesCS\DataFilter\DataFilterWorkingWithNodes.cs region=ChildExpressionElements}} -{{source=..\SamplesVB\DataFilter\DataFilterWorkingWithNodes.vb region=ChildExpressionElements}} -````C# -private void radDataFilter1_NodeFormatting3(object sender, TreeNodeFormattingEventArgs e) -{ - DataFilterCriteriaElement dataExpressionFilterElement = e.NodeElement as DataFilterCriteriaElement; - if (dataExpressionFilterElement == null) - { - return; - } - if (dataExpressionFilterElement.CriteriaNode.Descriptor.PropertyName == "Id") - { - dataExpressionFilterElement.FieldElement.DrawFill = true; - dataExpressionFilterElement.FieldElement.GradientStyle = GradientStyles.Solid; - dataExpressionFilterElement.FieldElement.BackColor = Color.LightGreen; - dataExpressionFilterElement.OperatorElement.ForeColor = Color.Red; - dataExpressionFilterElement.ValueElement.DrawFill = true; - dataExpressionFilterElement.ValueElement.GradientStyle = GradientStyles.Solid; - dataExpressionFilterElement.ValueElement.BackColor = Color.LightBlue; - } - else - { - dataExpressionFilterElement.FieldElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local); - dataExpressionFilterElement.FieldElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local); - dataExpressionFilterElement.FieldElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local); - dataExpressionFilterElement.OperatorElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local); - dataExpressionFilterElement.ValueElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local); - dataExpressionFilterElement.ValueElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local); - dataExpressionFilterElement.ValueElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local); - } -} - -```` -````VB.NET -Private Sub radDataFilter1_NodeFormatting3(sender As Object, e As TreeNodeFormattingEventArgs) - Dim dataExpressionFilterElement As DataFilterCriteriaElement = TryCast(e.NodeElement, DataFilterCriteriaElement) - If dataExpressionFilterElement Is Nothing Then - Return - End If - If dataExpressionFilterElement.CriteriaNode.Descriptor.PropertyName = "Id" Then - dataExpressionFilterElement.FieldElement.DrawFill = True - dataExpressionFilterElement.FieldElement.GradientStyle = GradientStyles.Solid - dataExpressionFilterElement.FieldElement.BackColor = Color.LightGreen - dataExpressionFilterElement.OperatorElement.ForeColor = Color.Red - dataExpressionFilterElement.ValueElement.DrawFill = True - dataExpressionFilterElement.ValueElement.GradientStyle = GradientStyles.Solid - dataExpressionFilterElement.ValueElement.BackColor = Color.LightBlue - Else - dataExpressionFilterElement.FieldElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local) - dataExpressionFilterElement.FieldElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local) - dataExpressionFilterElement.FieldElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local) - dataExpressionFilterElement.OperatorElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local) - dataExpressionFilterElement.ValueElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local) - dataExpressionFilterElement.ValueElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local) - dataExpressionFilterElement.ValueElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local) - End If -End Sub - -```` - - - -{{endregion}} + + + + # See Also diff --git a/controls/datafilter/datafilter-dialog.md b/controls/datafilter/datafilter-dialog.md index d9d73a50b..1542f371a 100644 --- a/controls/datafilter/datafilter-dialog.md +++ b/controls/datafilter/datafilter-dialog.md @@ -18,27 +18,10 @@ You can find below a sample code snippet how to show the filter dialog and get i #### Showing the RadDataFilterDialog -{{source=..\SamplesCS\DataFilter\DataFilterGettingStarted.cs region=FilterDialog}} -{{source=..\SamplesVB\DataFilter\DataFilterGettingStarted.vb region=FilterDialog}} - -````C# -RadDataFilterDialog dialog = new RadDataFilterDialog(); -dialog.DataSource = this.ordersBindingSource; -dialog.DataFilter.Expression = "[OrderID] > 10300 AND [EmployeeID] = 2"; -dialog.ShowDialog(); -string expression = dialog.DataFilter.Expression; - -```` -````VB.NET -Dim dialog As New RadDataFilterDialog() -dialog.DataSource = Me.ordersBindingSource -dialog.DataFilter.Expression = "[OrderID] > 10300 AND [EmployeeID] = 2" -dialog.ShowDialog() -Dim expression As String = dialog.DataFilter.Expression - -```` - -{{endregion}} + + + + If you need to customize the performed action on one of the buttons in the filter dialog you can create a derivative of the **RadDataFilterDialog** and override the **OnOKButtonClick**, **OnCancelButtonClick** or **OnApplyButtonClick** methods. diff --git a/controls/datafilter/editing/custom-editors.md b/controls/datafilter/editing/custom-editors.md index 14674c3c5..13abe5427 100644 --- a/controls/datafilter/editing/custom-editors.md +++ b/controls/datafilter/editing/custom-editors.md @@ -20,150 +20,10 @@ All editors inherit from **BaseInputEditor**. So, you have to inherit from this #### Custom editor -{{source=..\SamplesCS\DataFilter\DataFilterCustomEditor.cs region=CustomEditor}} -{{source=..\SamplesVB\DataFilter\DataFilterCustomEditor.vb region=CustomEditor}} + + -````C# -public DataFilterCustomEditor() -{ - InitializeComponent(); - this.radDataFilter1.DataSource = this.productsBindingSource; - this.radDataFilter1.EditorRequired += radDataFilter1_EditorRequired; - this.radDataFilter1.EditorInitialized += radDataFilter1_EditorInitialized; - this.radDataFilter1.ItemHeight = 40; -} -private void radDataFilter1_EditorInitialized(object sender, TreeNodeEditorInitializedEventArgs e) -{ - TrackBarEditor editor = e.Editor as TrackBarEditor; - if (editor != null) - { - RadTrackBarElement element = editor.EditorElement as RadTrackBarElement; - element.ShowTicks = true; - element.Maximum = 10; - } -} -private void radDataFilter1_EditorRequired(object sender, TreeNodeEditorRequiredEventArgs e) -{ - DataFilterCriteriaNode filterNode = e.Node as DataFilterCriteriaNode; - if (filterNode != null && filterNode.PropertyName == "ProductID" && sender is DataFilterValueEditorElement) - { - e.EditorType = typeof(TrackBarEditor); - } -} -public class TrackBarEditor : BaseInputEditor -{ - public override object Value - { - get - { - RadTrackBarElement editor = (RadTrackBarElement)this.EditorElement; - return editor.Value; - } - set - { - RadTrackBarElement editor = (RadTrackBarElement)this.EditorElement; - if (value != null && value != DBNull.Value) - { - editor.Value = Convert.ToInt32(value); - } - else - { - editor.Value = 0; - } - } - } - public override void BeginEdit() - { - base.BeginEdit(); - this.EditorElement.Focus(); - ((RadTrackBarElement)this.EditorElement).ValueChanged += new EventHandler(TrackBarEditor_ValueChanged); - } - void TrackBarEditor_ValueChanged(object sender, EventArgs e) - { - this.OnValueChanged(); - } - public override bool EndEdit() - { - ((RadTrackBarElement)this.EditorElement).ValueChanged -= TrackBarEditor_ValueChanged; - return base.EndEdit(); - } - protected override Telerik.WinControls.RadElement CreateEditorElement() - { - return new RadTrackBarElement(); - } - public override Type DataType - { - get - { - return typeof(int); - } - } -} -```` -````VB.NET -Public Sub New() - InitializeComponent() - Me.RadDataFilter1.DataSource = Me.ProductsBindingSource - AddHandler Me.RadDataFilter1.EditorRequired, AddressOf radDataFilter1_EditorRequired - AddHandler Me.RadDataFilter1.EditorInitialized, AddressOf radDataFilter1_EditorInitialized - Me.RadDataFilter1.ItemHeight = 40 -End Sub -Private Sub radDataFilter1_EditorInitialized(sender As Object, e As TreeNodeEditorInitializedEventArgs) - Dim editor As TrackBarEditor = TryCast(e.Editor, TrackBarEditor) - If editor IsNot Nothing Then - Dim element As RadTrackBarElement = TryCast(editor.EditorElement, RadTrackBarElement) - element.ShowTicks = True - element.Maximum = 10 - End If -End Sub -Private Sub radDataFilter1_EditorRequired(sender As Object, e As TreeNodeEditorRequiredEventArgs) - Dim filterNode As DataFilterCriteriaNode = TryCast(e.Node, DataFilterCriteriaNode) - If filterNode IsNot Nothing AndAlso filterNode.PropertyName = "ProductID" AndAlso TypeOf sender Is DataFilterValueEditorElement Then - e.EditorType = GetType(TrackBarEditor) - End If -End Sub -Public Class TrackBarEditor -Inherits BaseInputEditor - Public Overrides Property Value() As Object - Get - Dim editor As RadTrackBarElement = DirectCast(Me.EditorElement, RadTrackBarElement) - Return editor.Value - End Get - Set(value As Object) - Dim editor As RadTrackBarElement = DirectCast(Me.EditorElement, RadTrackBarElement) - If value IsNot Nothing AndAlso Not value.Equals(DBNull.Value) Then - editor.Value = Convert.ToInt32(value) - Else - editor.Value = 0 - End If - End Set - End Property - Public Overrides Sub BeginEdit() - MyBase.BeginEdit() - Me.EditorElement.Focus() - AddHandler DirectCast(Me.EditorElement, RadTrackBarElement).ValueChanged, AddressOf TrackBarEditor_ValueChanged - End Sub - Private Sub TrackBarEditor_ValueChanged(sender As Object, e As EventArgs) - Me.OnValueChanged() - End Sub - Public Overrides Function EndEdit() As Boolean - RemoveHandler DirectCast(Me.EditorElement, RadTrackBarElement).ValueChanged, AddressOf TrackBarEditor_ValueChanged - Return MyBase.EndEdit() - End Function - Protected Overrides Function CreateEditorElement() As Telerik.WinControls.RadElement - Return New RadTrackBarElement() - End Function - Public Overrides ReadOnly Property DataType() As Type - Get - Return GetType(Integer) - End Get - End Property -End Class - -```` - -{{endregion}} # See Also diff --git a/controls/datafilter/editing/events.md b/controls/datafilter/editing/events.md index 0ea781049..606c0adc2 100644 --- a/controls/datafilter/editing/events.md +++ b/controls/datafilter/editing/events.md @@ -47,74 +47,10 @@ The following code snippet demonstrates how to replace the default editor with a #### Replace and customize the default editor -{{source=..\SamplesCS\DataFilter\DataFilterEditing.cs region=CustomizeEditor}} -{{source=..\SamplesVB\DataFilter\DataFilterEditing.vb region=CustomizeEditor}} - -````C# -public DataFilterEditing() -{ - InitializeComponent(); - this.radDataFilter1.DataSource = this.productsBindingSource; - this.radDataFilter1.EditorRequired += radDataFilter1_EditorRequired; - this.radDataFilter1.EditorInitialized += radDataFilter1_EditorInitialized; -} -private void radDataFilter1_EditorInitialized(object sender, TreeNodeEditorInitializedEventArgs e) -{ - TreeViewDropDownListEditor editor = e.Editor as TreeViewDropDownListEditor; - if (editor != null) - { - editor.DropDownStyle = Telerik.WinControls.RadDropDownStyle.DropDown; - editor.DropDownSizingMode = SizingMode.UpDownAndRightBottom; - BaseDropDownListEditorElement el = editor.EditorElement as BaseDropDownListEditorElement; - el.AutoCompleteMode = AutoCompleteMode.Suggest; - } -} -private void radDataFilter1_EditorRequired(object sender, TreeNodeEditorRequiredEventArgs e) -{ - DataFilterCriteriaNode filterNode = e.Node as DataFilterCriteriaNode; - if (filterNode != null && filterNode.PropertyName == "CategoryID" && sender is DataFilterValueEditorElement) - { - TreeViewDropDownListEditor editor = new TreeViewDropDownListEditor(); - BaseDropDownListEditorElement el = editor.EditorElement as BaseDropDownListEditorElement; - el.DataSource = this.categoriesBindingSource; - el.ValueMember = "CategoryID"; - el.DisplayMember = "CategoryName"; - e.Editor = editor; - } -} - -```` -````VB.NET -Public Sub New() - InitializeComponent() - Me.RadDataFilter1.DataSource = Me.ProductsBindingSource - AddHandler Me.RadDataFilter1.EditorRequired, AddressOf radDataFilter1_EditorRequired - AddHandler Me.RadDataFilter1.EditorInitialized, AddressOf radDataFilter1_EditorInitialized -End Sub -Private Sub radDataFilter1_EditorInitialized(sender As Object, e As TreeNodeEditorInitializedEventArgs) - Dim editor As TreeViewDropDownListEditor = TryCast(e.Editor, TreeViewDropDownListEditor) - If editor IsNot Nothing Then - editor.DropDownStyle = Telerik.WinControls.RadDropDownStyle.DropDown - editor.DropDownSizingMode = SizingMode.UpDownAndRightBottom - Dim el As BaseDropDownListEditorElement = TryCast(editor.EditorElement, BaseDropDownListEditorElement) - el.AutoCompleteMode = AutoCompleteMode.Suggest - End If -End Sub -Private Sub radDataFilter1_EditorRequired(sender As Object, e As TreeNodeEditorRequiredEventArgs) - Dim filterNode As DataFilterCriteriaNode = TryCast(e.Node, DataFilterCriteriaNode) - If filterNode IsNot Nothing AndAlso filterNode.PropertyName = "CategoryID" AndAlso TypeOf sender Is DataFilterValueEditorElement Then - Dim editor As New TreeViewDropDownListEditor() - Dim el As BaseDropDownListEditorElement = TryCast(editor.EditorElement, BaseDropDownListEditorElement) - el.DataSource = Me.CategoriesBindingSource - el.ValueMember = "CategoryID" - el.DisplayMember = "CategoryName" - e.Editor = editor - End If -End Sub - -```` - -{{endregion}} + + + + ### Check which element is being edited. @@ -123,45 +59,10 @@ Both editors, field and filter type are TreeViewDropDownListEditor and if you ne #### Determine which item is edited. -{{source=..\SamplesCS\DataFilter\DataFilterEditing.cs region=EditorType}} -{{source=..\SamplesVB\DataFilter\DataFilterEditing.vb region=EditorType}} -````C# -private void radDataFilter1_EditorInitialized1(object sender, TreeNodeEditorInitializedEventArgs e) -{ - TreeViewDropDownListEditor editor = e.Editor as TreeViewDropDownListEditor; - DataFilterCriteriaElement criteriaElement = e.NodeElement as DataFilterCriteriaElement; - if (editor != null && criteriaElement != null) - { - if (criteriaElement.EditingElement is DataFilterFieldEditorElement) - { - //the field is edited - } - if (criteriaElement.EditingElement is DataFilterOperatorEditorElement) - { - // the filter type is edited - } - } -} - -```` -````VB.NET -Private Sub radDataFilter1_EditorInitialized1(ByVal sender As Object, ByVal e As TreeNodeEditorInitializedEventArgs) - Dim editor As TreeViewDropDownListEditor = TryCast(e.Editor, TreeViewDropDownListEditor) - Dim criteriaElement As DataFilterCriteriaElement = TryCast(e.NodeElement, DataFilterCriteriaElement) - If editor IsNot Nothing AndAlso criteriaElement IsNot Nothing Then - If TypeOf criteriaElement.EditingElement Is DataFilterFieldEditorElement Then - 'the field is edited - End If - If TypeOf criteriaElement.EditingElement Is DataFilterOperatorEditorElement Then - ' the filter type is edited - End If - End If -End Sub - -```` - - -{{endregion}} + + + + ## Edited diff --git a/controls/datafilter/getting-started.md b/controls/datafilter/getting-started.md index 5c188b420..298ca6018 100644 --- a/controls/datafilter/getting-started.md +++ b/controls/datafilter/getting-started.md @@ -50,31 +50,10 @@ At this point your form should look like this: 4\. When the user adds his filtering criteria, the control automatically produces a filter expression available in its Expression property. To apply this filter to the underlying BindingSource, the __ApplyFilter__ method should be invoked. We can use the control events to call the method when new filter is added by the user for example when an item is applied and when removed. Since the RadDataFilter control is build on top of RadTreeView we can use the NodeRemoved and the Edited events for the purpose. -{{source=..\SamplesCS\DataFilter\DataFilterGettingStarted.cs region=Events}} -{{source=..\SamplesVB\DataFilter\DataFilterGettingStarted.vb region=Events}} -````C# -private void RadDataFilter1_NodeRemoved(object sender, RadTreeViewEventArgs e) -{ - radDataFilter1.ApplyFilter(); -} -private void RadDataFilter1_Edited(object sender, TreeNodeEditedEventArgs e) -{ - radDataFilter1.ApplyFilter(); -} - -```` -````VB.NET -Private Sub RadDataFilter1_NodeRemoved(ByVal sender As Object, ByVal e As RadTreeViewEventArgs) - RadDataFilter1.ApplyFilter() -End Sub -Private Sub RadDataFilter1_Edited(ByVal sender As Object, ByVal e As TreeNodeEditedEventArgs) - RadDataFilter1.ApplyFilter() -End Sub - -```` - - -{{endregion}} + + + + 5\. Start the application and add some filters. diff --git a/controls/datafilter/localization/localization.md b/controls/datafilter/localization/localization.md index d38c331b4..066b16982 100644 --- a/controls/datafilter/localization/localization.md +++ b/controls/datafilter/localization/localization.md @@ -22,192 +22,19 @@ Below is a sample implementation of an English localization provider: #### Localizing RadDataFilter Strings -{{source=..\SamplesCS\DataFilter\DataFilterLocalization.cs region=MyLocalizationProvider}} -{{source=..\SamplesVB\DataFilter\DataFilterLocalization.vb region=MyLocalizationProvider}} -````C# - -public class EnglishDataFilterLocalizationProvider : Telerik.WinControls.UI.DataFilterLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case DataFilterStringId.LogicalOperatorAnd: - return "All"; - case DataFilterStringId.LogicalOperatorOr: - return "Any"; - case DataFilterStringId.LogicalOperatorDescription: - return " of the following are true"; - - case DataFilterStringId.FieldNullText: - return "Choose field"; - case DataFilterStringId.ValueNullText: - return "Enter a value"; - - case DataFilterStringId.AddNewButtonText: - return "Add"; - case DataFilterStringId.AddNewButtonExpression: - return "Expression"; - case DataFilterStringId.AddNewButtonGroup: - return "Group"; - - case DataFilterStringId.DialogTitle: - return "Data Filter"; - case DataFilterStringId.DialogOKButton: - return "OK"; - case DataFilterStringId.DialogCancelButton: - return "Cancel"; - case DataFilterStringId.DialogApplyButton: - return "Apply"; - - case DataFilterStringId.ErrorAddNodeDialogTitle: - return "RadDataFilter Error"; - case DataFilterStringId.ErrorAddNodeDialogText: - return "Cannot add entries to the control - missing property descriptors. \nDataSource is not set and/or DataFilterDescriptorItems are not added to the Descriptors collection of the control."; - - case DataFilterStringId.FilterFunctionBetween: - return "Between"; - case DataFilterStringId.FilterFunctionContains: - return "Contains"; - case DataFilterStringId.FilterFunctionDoesNotContain: - return "Does not contain"; - case DataFilterStringId.FilterFunctionEndsWith: - return "Ends with"; - case DataFilterStringId.FilterFunctionEqualTo: - return "Equals"; - case DataFilterStringId.FilterFunctionGreaterThan: - return "Greater than"; - case DataFilterStringId.FilterFunctionGreaterThanOrEqualTo: - return "Greater than or equal to"; - case DataFilterStringId.FilterFunctionIsEmpty: - return "Is empty"; - case DataFilterStringId.FilterFunctionIsNull: - return "Is null"; - case DataFilterStringId.FilterFunctionLessThan: - return "Less than"; - case DataFilterStringId.FilterFunctionLessThanOrEqualTo: - return "Less than or equal to"; - case DataFilterStringId.FilterFunctionNoFilter: - return "No filter"; - case DataFilterStringId.FilterFunctionIsContainedIn: - return "Is in list"; - case DataFilterStringId.FilterFunctionIsNotContainedIn: - return "Not in list"; - case DataFilterStringId.FilterFunctionNotBetween: - return "Not between"; - case DataFilterStringId.FilterFunctionNotEqualTo: - return "Not equal to"; - case DataFilterStringId.FilterFunctionNotIsEmpty: - return "Is not empty"; - case DataFilterStringId.FilterFunctionNotIsNull: - return "Is not null"; - case DataFilterStringId.FilterFunctionStartsWith: - return "Starts with"; - case DataFilterStringId.FilterFunctionCustom: - return "Custom"; - } - return base.GetLocalizedString(id); - } - -```` -````VB.NET -Public Class EnglishDataFilterLocalizationProvider -Inherits Telerik.WinControls.UI.DataFilterLocalizationProvider - Public Overrides Function GetLocalizedString(id As String) As String - Select Case id - Case DataFilterStringId.LogicalOperatorAnd - Return "All" - Case DataFilterStringId.LogicalOperatorOr - Return "Any" - Case DataFilterStringId.LogicalOperatorDescription - Return " of the following are true" - Case DataFilterStringId.FieldNullText - Return "Choose field" - Case DataFilterStringId.ValueNullText - Return "Enter a value" - Case DataFilterStringId.AddNewButtonText - Return "Add" - Case DataFilterStringId.AddNewButtonExpression - Return "Expression" - Case DataFilterStringId.AddNewButtonGroup - Return "Group" - Case DataFilterStringId.DialogTitle - Return "Data Filter" - Case DataFilterStringId.DialogOKButton - Return "OK" - Case DataFilterStringId.DialogCancelButton - Return "Cancel" - Case DataFilterStringId.DialogApplyButton - Return "Apply" - Case DataFilterStringId.ErrorAddNodeDialogTitle - Return "RadDataFilter Error" - Case DataFilterStringId.ErrorAddNodeDialogText - Return "Cannot add entries to the control - missing property descriptors. " & vbLf & "DataSource is not set and/or DataFilterDescriptorItems are not added to the Descriptors collection of the control." - Case DataFilterStringId.FilterFunctionBetween - Return "Between" - Case DataFilterStringId.FilterFunctionContains - Return "Contains" - Case DataFilterStringId.FilterFunctionDoesNotContain - Return "Does not contain" - Case DataFilterStringId.FilterFunctionEndsWith - Return "Ends with" - Case DataFilterStringId.FilterFunctionEqualTo - Return "Equals" - Case DataFilterStringId.FilterFunctionGreaterThan - Return "Greater than" - Case DataFilterStringId.FilterFunctionGreaterThanOrEqualTo - Return "Greater than or equal to" - Case DataFilterStringId.FilterFunctionIsEmpty - Return "Is empty" - Case DataFilterStringId.FilterFunctionIsNull - Return "Is null" - Case DataFilterStringId.FilterFunctionLessThan - Return "Less than" - Case DataFilterStringId.FilterFunctionLessThanOrEqualTo - Return "Less than or equal to" - Case DataFilterStringId.FilterFunctionNoFilter - Return "No filter" - Case DataFilterStringId.FilterFunctionIsContainedIn - Return "Is in list" - Case DataFilterStringId.FilterFunctionIsNotContainedIn - Return "Not in list" - Case DataFilterStringId.FilterFunctionNotBetween - Return "Not between" - Case DataFilterStringId.FilterFunctionNotEqualTo - Return "Not equal to" - Case DataFilterStringId.FilterFunctionNotIsEmpty - Return "Is not empty" - Case DataFilterStringId.FilterFunctionNotIsNull - Return "Is not null" - Case DataFilterStringId.FilterFunctionStartsWith - Return "Starts with" - Case DataFilterStringId.FilterFunctionCustom - Return "Custom" - End Select - Return MyBase.GetLocalizedString(id) - End Function - -```` - -{{endregion}} + + + + To apply the custom localization provider, instantiate and assign it to the current localization provider: #### Assigning the Current Localization Provider -{{source=..\SamplesCS\DataFilter\DataFilterLocalization.cs region=ApplyLocalizationProvider}} -{{source=..\SamplesVB\DataFilter\DataFilterLocalization.vb region=ApplyLocalizationProvider}} -````C# - -DataFilterLocalizationProvider.CurrentProvider = new EnglishDataFilterLocalizationProvider(); - -```` -````VB.NET -DataFilterLocalizationProvider.CurrentProvider = New EnglishDataFilterLocalizationProvider() - -```` + + -{{endregion}} + The code provided above illustrates the approach to be used to localize the **RadDataFilter** and is not intended as a full translation. diff --git a/controls/datafilter/save-load-filters.md b/controls/datafilter/save-load-filters.md index 3e912a836..ba1cfdf11 100644 --- a/controls/datafilter/save-load-filters.md +++ b/controls/datafilter/save-load-filters.md @@ -13,48 +13,18 @@ position: 11 You can use the __SaveXML__ and __LoadXml__ methods to save the current expression either in a file or in a stream. The following snippets are showing how you can save or load the current state. #### SaveXML -{{source=..\SamplesCS\DataFilter\DataFilterGettingStarted.cs region=Save}} -{{source=..\SamplesVB\DataFilter\DataFilterGettingStarted.vb region=Save}} -````C# -private void radButton1_Click(object sender, EventArgs e) -{ - radDataFilter1.SaveXML("Test.xml"); -} + + -```` -````VB.NET -Private Sub radButton1_Click(ByVal sender As Object, ByVal e As EventArgs) - RadDataFilter1.SaveXML("Test.xml") -End Sub -```` - - - -{{endregion}} #### LoadXML -{{source=..\SamplesCS\DataFilter\DataFilterGettingStarted.cs region=Load}} -{{source=..\SamplesVB\DataFilter\DataFilterGettingStarted.vb region=Load}} -````C# -private void radButton2_Click(object sender, EventArgs e) -{ - radDataFilter1.LoadXML("Test.xml"); -} - -```` -````VB.NET -Private Sub radButton2_Click(ByVal sender As Object, ByVal e As EventArgs) - RadDataFilter1.LoadXML("Test.xml") -End Sub - -```` - + + -{{endregion}} diff --git a/controls/datafilter/working-with-descriptor-items/data-binding.md b/controls/datafilter/working-with-descriptor-items/data-binding.md index ef95cb04c..eaad998db 100644 --- a/controls/datafilter/working-with-descriptor-items/data-binding.md +++ b/controls/datafilter/working-with-descriptor-items/data-binding.md @@ -38,27 +38,10 @@ It is possible to set the **DataSource** property programmatically as well. #### Setting DataSource at run time -{{source=..\SamplesCS\DataFilter\DataFilterGettingStarted.cs region=BoundMode}} -{{source=..\SamplesVB\DataFilter\DataFilterGettingStarted.vb region=BoundMode}} - -````C# -DataTable dt = new DataTable(); -dt.Columns.Add("Id", typeof(int)); -dt.Columns.Add("Name", typeof(string)); -dt.Columns.Add("IsActive", typeof(bool)); -this.radDataFilter1.DataSource = dt; - -```` -````VB.NET -Dim dt As New DataTable() -dt.Columns.Add("Id", GetType(Integer)) -dt.Columns.Add("Name", GetType(String)) -dt.Columns.Add("IsActive", GetType(Boolean)) -Me.RadDataFilter1.DataSource = dt - -```` - -{{endregion}} + + + + After setting the **DataSource** property, the **Descriptors** collection is filled with the respective fields. Then, you can apply the desired filter either by setting the **Expression** property or by using the UI at run time. diff --git a/controls/datafilter/working-with-descriptor-items/descriptor-items.md b/controls/datafilter/working-with-descriptor-items/descriptor-items.md index fb33364b2..b4ef87952 100644 --- a/controls/datafilter/working-with-descriptor-items/descriptor-items.md +++ b/controls/datafilter/working-with-descriptor-items/descriptor-items.md @@ -63,35 +63,10 @@ The *RadItem Collection Editor* that allows you to edit the items at design time The following snippet shows how you can add __DataFilterComboDescriptorItem__ in the code: -{{source=..\SamplesCS\DataFilter\DataFilterEditing.cs region=AddComboItem}} -{{source=..\SamplesVB\DataFilter\DataFilterEditing.vb region=AddComboItem}} -````C# -DataFilterComboDescriptorItem item1 = new DataFilterComboDescriptorItem(); -item1.DescriptorName = "Item Type"; -item1.DescriptorType = typeof(int); -item1.DataSource = GetTable(); -item1.ValueMember = "ID"; -item1.DisplayMember = "Type"; -item1.DropDownStyle = RadDropDownStyle.DropDown; -item1.AutoCompleteMode = AutoCompleteMode.Suggest; -radDataFilter1.Descriptors.Add(item1); - -```` -````VB.NET -Dim item1 As New DataFilterComboDescriptorItem() -item1.DescriptorName = "Item Type" -item1.DescriptorType = GetType(Integer) -item1.DataSource = GetTable() -item1.ValueMember = "ID" -item1.DisplayMember = "Type" -item1.DropDownStyle = RadDropDownStyle.DropDown -item1.AutoCompleteMode = AutoCompleteMode.Suggest -RadDataFilter1.Descriptors.Add(item1) - -```` - - -{{endregion}} + + + + When this is done you can add new expression item and choose from the list: diff --git a/controls/datafilter/working-with-descriptor-items/unbound-mode.md b/controls/datafilter/working-with-descriptor-items/unbound-mode.md index 71f9bc89c..4061ee5d6 100644 --- a/controls/datafilter/working-with-descriptor-items/unbound-mode.md +++ b/controls/datafilter/working-with-descriptor-items/unbound-mode.md @@ -22,34 +22,10 @@ You can add/remove/modify **DataFilterDescriptorItems** by using the *RadItem Co #### Adding descriptor items programmatically and applying an expression -{{source=..\SamplesCS\DataFilter\DataFilterGettingStarted.cs region=UnboundMode}} -{{source=..\SamplesVB\DataFilter\DataFilterGettingStarted.vb region=UnboundMode}} -````C# -DataFilterDescriptorItem nameDescriptorItem = new DataFilterDescriptorItem(); -nameDescriptorItem.DescriptorName = "ProductName"; -nameDescriptorItem.DescriptorType = typeof(string); -this.radDataFilter1.Descriptors.Add(nameDescriptorItem); -DataFilterDescriptorItem priceDescriptorItem = new DataFilterDescriptorItem(); -priceDescriptorItem.DescriptorName = "UnitPrice"; -priceDescriptorItem.DescriptorType = typeof(decimal); -this.radDataFilter1.Descriptors.Add(priceDescriptorItem); -this.radDataFilter1.Expression = "([ProductName] LIKE '%ch%' OR [UnitPrice] > '15')"; - -```` -````VB.NET -Dim nameDescriptorItem As New DataFilterDescriptorItem() -nameDescriptorItem.DescriptorName = "ProductName" -nameDescriptorItem.DescriptorType = GetType(String) -Me.RadDataFilter1.Descriptors.Add(nameDescriptorItem) -Dim priceDescriptorItem As New DataFilterDescriptorItem() -priceDescriptorItem.DescriptorName = "UnitPrice" -priceDescriptorItem.DescriptorType = GetType(Decimal) -Me.RadDataFilter1.Descriptors.Add(priceDescriptorItem) -Me.RadDataFilter1.Expression = "([ProductName] LIKE '%ch%' OR [UnitPrice] > '15')" - -```` - -{{endregion}} + + + + ![WinForms RadDataFilter Unbound Mode Design Time](images/datafilter-unbound-mode001.png) diff --git a/controls/datalayout/change-the-editor-to-a-bound-raddropdownlist.md b/controls/datalayout/change-the-editor-to-a-bound-raddropdownlist.md index f19427ac2..6a2797532 100644 --- a/controls/datalayout/change-the-editor-to-a-bound-raddropdownlist.md +++ b/controls/datalayout/change-the-editor-to-a-bound-raddropdownlist.md @@ -19,321 +19,45 @@ This article will walk you through the process of changing the default editor to 1\. First you can subscribe to the __BindingCreating__, __BindingCreated__ and __EditorInitializing__ events of __RadDataLayout__ (please note that this should be done before the control has been bound). -{{source=..\SamplesCS\DataLayout\DataLayoutChangeEditor.cs region=subscribe}} -{{source=..\SamplesVB\DataLayout\DataLayoutChangeEditor.vb region=subscribe}} + + -````C# -this.radDataLayout1.EditorInitializing += radDataLayout1_EditorInitializing; -this.radDataLayout1.BindingCreating += radDataLayout1_BindingCreating; -this.radDataLayout1.BindingCreated += radDataLayout1_BindingCreated; -this.radDataLayout1.DataSource = productsBinding; -```` -````VB.NET -AddHandler Me.RadDataLayout1.EditorInitializing, AddressOf radDataLayout1_EditorInitializing -AddHandler Me.RadDataLayout1.BindingCreating, AddressOf radDataLayout1_BindingCreating -AddHandler Me.RadDataLayout1.BindingCreated, AddressOf radDataLayout1_BindingCreated -Me.RadDataLayout1.DataSource = productsBinding - -```` - -{{endregion}} 2\. In the __EditorInitializing__ event handler, you will be able to change the automatically generated editor with a __RadDropDownList__. In addition, you should set it up as needed. In this case we will set the __DataSource__, __DisplayMember__ and __ValueMember__ properties. -{{source=..\SamplesCS\DataLayout\DataLayoutChangeEditor.cs region=editor}} -{{source=..\SamplesVB\DataLayout\DataLayoutChangeEditor.vb region=editor}} - -````C# -RadDropDownList radDropDownList1; -void radDataLayout1_EditorInitializing(object sender, Telerik.WinControls.UI.EditorInitializingEventArgs e) -{ - if (e.Property.Name == "SupplierID") - { - radDropDownList1 = new RadDropDownList(); - radDropDownList1.DataSource = suplierList; - radDropDownList1.ValueMember = "SupplierID"; - radDropDownList1.DisplayMember = "CompanyName"; - e.Editor = radDropDownList1; - } -} - -```` -````VB.NET -Private radDropDownList1 As RadDropDownList -Private Sub radDataLayout1_EditorInitializing(sender As Object, e As Telerik.WinControls.UI.EditorInitializingEventArgs) - If e.[Property].Name = "SupplierID" Then - radDropDownList1 = New RadDropDownList() - radDropDownList1.DataSource = suplierList - radDropDownList1.ValueMember = "SupplierID" - radDropDownList1.DisplayMember = "CompanyName" - e.Editor = radDropDownList1 - End If -End Sub + + -```` - -{{endregion}} 3\. In order the values to be synchronized correctly, the bound property should be set in the __BindingCreating__ event handler. In this case it should be set to the __SelectedValue__ property. -{{source=..\SamplesCS\DataLayout\DataLayoutChangeEditor.cs region=creating}} -{{source=..\SamplesVB\DataLayout\DataLayoutChangeEditor.vb region=creating}} - -````C# -void radDataLayout1_BindingCreating(object sender, Telerik.WinControls.UI.BindingCreatingEventArgs e) -{ - if (e.DataMember == "SupplierID") - { - e.PropertyName = "SelectedValue"; - } -} - -```` -````VB.NET -Private Sub radDataLayout1_BindingCreating(sender As Object, e As Telerik.WinControls.UI.BindingCreatingEventArgs) - If e.DataMember = "SupplierID" Then - e.PropertyName = "SelectedValue" - End If -End Sub + + -```` -{{endregion}} 4\. When the data source is using nullable values in order the user to be able to change the current value via the drop down list, the result value should be manually parsed. This can be done in the binding's __Parse__ event. You can subscribe to this event in the __BindingCreated__ event handler (in order this event to fire the formatting should be enabled). -{{source=..\SamplesCS\DataLayout\DataLayoutChangeEditor.cs region=created}} -{{source=..\SamplesVB\DataLayout\DataLayoutChangeEditor.vb region=created}} + + -````C# -void radDataLayout1_BindingCreated(object sender, BindingCreatedEventArgs e) -{ - if (e.DataMember == "SupplierID") - { - e.Binding.FormattingEnabled = true; - e.Binding.Parse += new ConvertEventHandler(Binding_Parse); - } -} - -private void Binding_Parse(object sender, ConvertEventArgs e) -{ - int tmpvalue; - int? result = int.TryParse(e.Value.ToString(), out tmpvalue) ? tmpvalue : (int?)null; - e.Value = result; -} -```` -````VB.NET -Private Sub radDataLayout1_BindingCreated(sender As Object, e As BindingCreatedEventArgs) - If e.DataMember = "SupplierID" Then - e.Binding.FormattingEnabled = True - AddHandler e.Binding.Parse, AddressOf Binding_Parse - End If -End Sub -Private Sub Binding_Parse(sender As Object, e As ConvertEventArgs) - Dim tmpvalue As Integer - Dim result As System.Nullable(Of Integer) = If(Integer.TryParse(e.Value.ToString(), tmpvalue), tmpvalue, DirectCast(Nothing, System.Nullable(Of Integer))) - e.Value = result -End Sub - -```` - -{{endregion}} To make the example complete you can use the following classes. -{{source=..\SamplesCS\DataLayout\DataLayoutChangeEditor.cs region=data}} -{{source=..\SamplesVB\DataLayout\DataLayoutChangeEditor.vb region=data}} - -````C# -public class ProductModel -{ - private int? _supplierID; - private string _productName; - public ProductModel(int? supplierID, string productName) - { - this._supplierID = supplierID; - this._productName = productName; - } - public int? SupplierID - { - get - { - return this._supplierID; - } - set - { - this._supplierID = value; - } - } - public string ProductName - { - get - { - return this._productName; - } - set - { - this._productName = value; - } - } -} -public partial class SupplierModel -{ - private int? _supplierID; - private string _companyName; - public SupplierModel(int? supplierID, string companyName) - { - this._supplierID = supplierID; - this._companyName = companyName; - } - public int? SupplierID - { - get - { - return this._supplierID; - } - set - { - this._supplierID = value; - } - } - public string CompanyName - { - get - { - return this._companyName; - } - set - { - this._companyName = value; - } - } -} + + -```` -````VB.NET -Public Class ProductModel - Private _supplierID As System.Nullable(Of Integer) - Private _productName As String - Public Sub New(supplierID As System.Nullable(Of Integer), productName As String) - Me._supplierID = supplierID - Me._productName = productName - End Sub - Public Property SupplierID() As System.Nullable(Of Integer) - Get - Return Me._supplierID - End Get - Set(value As System.Nullable(Of Integer)) - Me._supplierID = value - End Set - End Property - Public Property ProductName() As String - Get - Return Me._productName - End Get - Set(value As String) - Me._productName = value - End Set - End Property -End Class -Partial Public Class SupplierModel - Private _supplierID As System.Nullable(Of Integer) - Private _companyName As String - Public Sub New(supplierID As System.Nullable(Of Integer), companyName As String) - Me._supplierID = supplierID - Me._companyName = companyName - End Sub - Public Property SupplierID() As System.Nullable(Of Integer) - Get - Return Me._supplierID - End Get - Set(value As System.Nullable(Of Integer)) - Me._supplierID = value - End Set - End Property - Public Property CompanyName() As String - Get - Return Me._companyName - End Get - Set(value As String) - Me._companyName = value - End Set - End Property -End Class -```` - -{{endregion}} You can initialize the data sources in the Form’s constructor. -{{source=..\SamplesCS\DataLayout\DataLayoutChangeEditor.cs region=init}} -{{source=..\SamplesVB\DataLayout\DataLayoutChangeEditor.vb region=init}} - -````C# -List productList; -List suplierList; -BindingSource productsBinding; -public DataLayoutChangeEditor() -{ - InitializeComponent(); - productList = new List(); - suplierList = new List(); - productList.Add(new ProductModel(1, "Chai")); - productList.Add(new ProductModel(2, "Chang")); - productList.Add(new ProductModel(3, "Aniseed Syrup")); - productList.Add(new ProductModel(4, "Chef Anton's Gumbo Mix")); - productList.Add(new ProductModel(5, "Tofu")); - productList.Add(new ProductModel(null, "Sir Rodney's Marmalade")); - productList.Add(new ProductModel(6, "Boston Crab Meat")); - productList.Add(new ProductModel(5, "Chartreuse verte")); - productList.Add(new ProductModel(2, "Ravioli Angelo")); - productList.Add(new ProductModel(4, "Perth Pasties")); - suplierList.Add(new SupplierModel(1, "Exotic Liquids")); - suplierList.Add(new SupplierModel(2, "New Orleans Cajun Delights")); - suplierList.Add(new SupplierModel(3, "Tokyo Traders")); - suplierList.Add(new SupplierModel(4, "Norske Meierier")); - suplierList.Add(new SupplierModel(5, "New England Seafood Cannery")); - suplierList.Add(new SupplierModel(6, "Leka Trading")); - productsBinding = new BindingSource(); - productsBinding.DataSource = productList; -} - -```` -````VB.NET -Private productList As List(Of ProductModel) -Private suplierList As List(Of SupplierModel) -Private productsBinding As BindingSource -Public Sub New() - InitializeComponent() - productList = New List(Of ProductModel)() - suplierList = New List(Of SupplierModel)() - productList.Add(New ProductModel(1, "Chai")) - productList.Add(New ProductModel(2, "Chang")) - productList.Add(New ProductModel(3, "Aniseed Syrup")) - productList.Add(New ProductModel(4, "Chef Anton's Gumbo Mix")) - productList.Add(New ProductModel(5, "Tofu")) - productList.Add(New ProductModel(Nothing, "Sir Rodney's Marmalade")) - productList.Add(New ProductModel(6, "Boston Crab Meat")) - productList.Add(New ProductModel(5, "Chartreuse verte")) - productList.Add(New ProductModel(2, "Ravioli Angelo")) - productList.Add(New ProductModel(4, "Perth Pasties")) - suplierList.Add(New SupplierModel(1, "Exotic Liquids")) - suplierList.Add(New SupplierModel(2, "New Orleans Cajun Delights")) - suplierList.Add(New SupplierModel(3, "Tokyo Traders")) - suplierList.Add(New SupplierModel(4, "Norske Meierier")) - suplierList.Add(New SupplierModel(5, "New England Seafood Cannery")) - suplierList.Add(New SupplierModel(6, "Leka Trading")) - productsBinding = New BindingSource() - productsBinding.DataSource = productList -End Sub + + -```` -{{endregion}} # See Also diff --git a/controls/datalayout/customizing-appearance/customizing-appearance.md b/controls/datalayout/customizing-appearance/customizing-appearance.md index 3f2abc733..8f3b24085 100644 --- a/controls/datalayout/customizing-appearance/customizing-appearance.md +++ b/controls/datalayout/customizing-appearance/customizing-appearance.md @@ -21,30 +21,10 @@ You can access and modify the style for different elements in __RadDataEntry__ b The following snippet shows how you access the underlying controls and change their style: -{{source=..\SamplesCS\DataLayout\PropertiesEventsAttributesForm.cs region=FormatItems}} -{{source=..\SamplesVB\DataLayout\PropertiesEventsAttributesForm.vb region=FormatItems}} -````C# -foreach (DataLayoutControlItem item in radDataLayout1.LayoutControl.Items) -{ - item.ForeColor = ColorTranslator.FromHtml("#51ab2e"); - if (item.AssociatedControl is RadTextBox) - { - item.AssociatedControl.BackColor = ColorTranslator.FromHtml("#91c930"); - } -} - -```` -````VB.NET -For Each item As DataLayoutControlItem In RadDataLayout1.LayoutControl.Items - item.ForeColor = ColorTranslator.FromHtml("#51ab2e") - If TypeOf item.AssociatedControl Is RadTextBox Then - item.AssociatedControl.BackColor = ColorTranslator.FromHtml("#91c930") - End If -Next item - -```` - -{{endregion}} + + + + >caption Figure 2: Change the items styles diff --git a/controls/datalayout/getting-started.md b/controls/datalayout/getting-started.md index aeeea1950..92160c132 100644 --- a/controls/datalayout/getting-started.md +++ b/controls/datalayout/getting-started.md @@ -44,123 +44,24 @@ The Telerik UI for WinForms assemblies can be install by using one of the availa 2\. Let`s define the layout of our data control. -{{source=..\SamplesCS\DataLayout\GettingStartedForm.cs region=DefineLayout}} -{{source=..\SamplesVB\DataLayout\GettingStartedForm.vb region=DefineLayout}} + + -````C# -this.radDataLayout1.ItemDefaultHeight = 26; -this.radDataLayout1.ColumnCount = 2; -this.radDataLayout1.FlowDirection = FlowDirection.TopDown; -this.radDataLayout1.AutoSizeLabels = true; -```` -````VB.NET -Me.RadDataLayout1.ItemDefaultHeight = 26 -Me.RadDataLayout1.ColumnCount = 2 -Me.RadDataLayout1.FlowDirection = FlowDirection.TopDown -Me.RadDataLayout1.AutoSizeLabels = True -```` +3\. A sample *Employee* class exposing several properties is going to be our model. -{{endregion}} + + -3\. A sample *Employee* class exposing several properties is going to be our model. -{{source=..\SamplesCS\DataLayout\GettingStartedForm.cs region=EmployeeModel}} -{{source=..\SamplesVB\DataLayout\GettingStartedForm.vb region=EmployeeModel}} - -````C# -public class Employee -{ - public string FirstName { get; set; } - public string LastName { get; set; } - public string Occupation { get; set; } - public DateTime StartingDate { get; set; } - public bool IsMarried { get; set; } -} - -```` -````VB.NET -Public Class EmployeeModel - Public Property FirstName() As String - Get - Return m_FirstName - End Get - Set(value As String) - m_FirstName = value - End Set - End Property - Private m_FirstName As String - Public Property LastName() As String - Get - Return m_LastName - End Get - Set(value As String) - m_LastName = value - End Set - End Property - Private m_LastName As String - Public Property Occupation() As String - Get - Return m_Occupation - End Get - Set(value As String) - m_Occupation = value - End Set - End Property - Private m_Occupation As String - Public Property StartingDate() As DateTime - Get - Return m_StartingDate - End Get - Set(value As DateTime) - m_StartingDate = value - End Set - End Property - Private m_StartingDate As DateTime - Public Property IsMarried() As Boolean - Get - Return m_IsMarried - End Get - Set(value As Boolean) - m_IsMarried = value - End Set - End Property - Private m_IsMarried As Boolean -End Class - -```` - -{{endregion}} 4\. Once the **Employee** class is defined, you may use it to create an object of this type and bind it to the __RadDataLayout__ control: -{{source=..\SamplesCS\DataLayout\GettingStartedForm.cs region=BindSingleObject}} -{{source=..\SamplesVB\DataLayout\GettingStartedForm.vb region=BindSingleObject}} - -````C# -this.radDataLayout1.DataSource = new Employee() -{ - FirstName = "Sarah", - LastName = "Blake", - Occupation = "Supplied Manager", - StartingDate = new DateTime(2005, 04, 12), - IsMarried = true -}; - -```` -````VB.NET -Me.RadDataLayout1.DataSource = New EmployeeModel() With { - .FirstName = "Sarah", - .LastName = "Blake", - .Occupation = "Supplied Manager", - .StartingDate = New DateTime(2005, 4, 12), - .IsMarried = True -} - -```` - -{{endregion}} + + + + 5\. Press __F5__ to run the project and you should see the following: @@ -178,85 +79,10 @@ Besides a __RadDataLayout__ we are also going to need a __RadBindingNavigator__ Compared to the previously shown example only the data binding is different. This time we are going to bind the __RadDataLayout__ control to a list of our model objects. The same list will also provide data to the **BindingSource** component. -{{source=..\SamplesCS\DataLayout\GettingStartedForm.cs region=BindMultipleObjects}} -{{source=..\SamplesVB\DataLayout\GettingStartedForm.vb region=BindMultipleObjects}} - -````C# -List employees = new List(); -employees.Add(new Employee() -{ - FirstName = "Sarah", - LastName = "Blake", - Occupation = "Supplied Manager", - StartingDate = new DateTime(2005, 04, 12), - IsMarried = true -}); -employees.Add(new Employee() -{ - FirstName = "Jane", - LastName = "Simpson", - Occupation = "Security", - StartingDate = new DateTime(2008, 12, 03), - IsMarried = true -}); -employees.Add(new Employee() -{ - FirstName = "John", - LastName = "Peterson", - Occupation = "Consultant", - StartingDate = new DateTime(2005, 04, 12), - IsMarried = false -}); -employees.Add(new Employee() -{ - FirstName = "Peter", - LastName = "Bush", - Occupation = "Cashier", - StartingDate = new DateTime(2005, 04, 12), - IsMarried = true -}); -this.bindingSource1.DataSource = employees; -this.radDataLayout1.DataSource = this.bindingSource1; -this.radBindingNavigator1.BindingSource = this.bindingSource1; - -```` -````VB.NET -Dim employees As New List(Of EmployeeModel)() -employees.Add(New EmployeeModel() With { - .FirstName = "Sarah", - .LastName = "Blake", - .Occupation = "Supplied Manager", - .StartingDate = New DateTime(2005, 4, 12), - .IsMarried = True -}) -employees.Add(New EmployeeModel() With { - .FirstName = "Jane", - .LastName = "Simpson", - .Occupation = "Security", - .StartingDate = New DateTime(2008, 12, 3), - .IsMarried = True -}) -employees.Add(New EmployeeModel() With { - .FirstName = "John", - .LastName = "Peterson", - .Occupation = "Consultant", - .StartingDate = New DateTime(2005, 4, 12), - .IsMarried = False -}) -employees.Add(New EmployeeModel() With { - .FirstName = "Peter", - .LastName = "Bush", - .Occupation = "Cashier", - .StartingDate = New DateTime(2005, 4, 12), - .IsMarried = True -}) -Me.BindingSource1.DataSource = employees -Me.RadDataLayout1.DataSource = Me.BindingSource1 -Me.RadBindingNavigator1.BindingSource = Me.BindingSource1 - -```` - -{{endregion}} + + + + Press __F5__ to run the project and you should see the following: diff --git a/controls/datalayout/localization.md b/controls/datalayout/localization.md index ab654fd9a..fd7065cb3 100644 --- a/controls/datalayout/localization.md +++ b/controls/datalayout/localization.md @@ -1,163 +1,45 @@ ---- -title: Localization -page_title: Localization - WinForms DataLayout Control -description: learn how you can localize the string used in WinForms DataLayout. -slug: winforms/datalayout/localization -tags: localization -published: True -position: 8 -previous_url: datalayout-localization ---- - -# Localization - -To localize __RadDataLayout__ to display any text and messages in a specific language: - -* All required classes for localization are defined in __Telerik.WinControls.UI.Localization__ namespace. - -* Start by creating a descendant of the __LayoutControlLocalizationProvider__ class. - -* Override the __GetLocalizedString(string id)__ method and provide a translation for the label and user messages. If a translation is not provided, the default value will be returned. This behavior is guaranteed by the call to the base __GetLocalizedString__ method in the __default__ clause of the __switch__ statement in the example. - -Below is a sample implementation of an English localization provider: - -{{source=..\SamplesCS\DataLayout\DataLayoutLocalization.cs region=Localization}} -{{source=..\SamplesVB\DataLayout\DataLayoutLocalization.vb region=Localization}} - -````C# -public class MyEnglishLayoutControlLocalizationProvider : LayoutControlLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case LayoutControlStringId.CustomizeDialogHiddenItems: - return "Hidden Items ({0})"; - case LayoutControlStringId.CustomizeDialogNewItems: - return "New Items ({0})"; - case LayoutControlStringId.CustomizeDialogPageItems: - return "Items"; - case LayoutControlStringId.CustomizeDialogPageStructure: - return "Structure"; - case LayoutControlStringId.CustomizeDialogRootItem: - return "Root"; - case LayoutControlStringId.CustomizeDialogSaveLayout: - return "Save Layout"; - case LayoutControlStringId.CustomizeDialogLoadLayout: - return "Load Layout"; - case LayoutControlStringId.NewGroupDefaultText: - return "Item Group"; - case LayoutControlStringId.NewLabelDefaultText: - return "Label Item"; - case LayoutControlStringId.CustomizeDialogNewItemsEmptySpace: - return "Empty Space"; - case LayoutControlStringId.CustomizeDialogNewItemsLabel: - return "Label"; - case LayoutControlStringId.CustomizeDialogNewItemsSeparator: - return "Separator"; - case LayoutControlStringId.CustomizeDialogNewItemsSplitter: - return "Splitter"; - case LayoutControlStringId.CustomizeDialogNewItemsGroup: - return "Group"; - case LayoutControlStringId.CustomizeDialogNewItemsTabbedGroup: - return "Tabbed Group"; - case LayoutControlStringId.ContextMenuCustomize: - return "Customize"; - case LayoutControlStringId.ContextMenuHideItem: - return "Hide"; - case LayoutControlStringId.CustomizeDialogTitle: - return "Customize"; - case LayoutControlStringId.ErrorBoxTitle: - return "Error!"; - case LayoutControlStringId.ErrorFileNotFoundMessage: - return "File not found!"; - case LayoutControlStringId.ErrorLoadingLayoutMessage: - return "Error loading layout!"; - } - return base.GetLocalizedString(id); - } -} - -```` -````VB.NET -Public Class MyEnglishLayoutControlLocalizationProvider - Inherits LayoutControlLocalizationProvider - Public Overrides Function GetLocalizedString(id As String) As String - Select Case id - Case LayoutControlStringId.CustomizeDialogHiddenItems - Return "Hidden Items ({0})" - Case LayoutControlStringId.CustomizeDialogNewItems - Return "New Items ({0})" - Case LayoutControlStringId.CustomizeDialogPageItems - Return "Items" - Case LayoutControlStringId.CustomizeDialogPageStructure - Return "Structure" - Case LayoutControlStringId.CustomizeDialogRootItem - Return "Root" - Case LayoutControlStringId.CustomizeDialogSaveLayout - Return "Save Layout" - Case LayoutControlStringId.CustomizeDialogLoadLayout - Return "Load Layout" - Case LayoutControlStringId.NewGroupDefaultText - Return "Item Group" - Case LayoutControlStringId.NewLabelDefaultText - Return "Label Item" - Case LayoutControlStringId.CustomizeDialogNewItemsEmptySpace - Return "Empty Space" - Case LayoutControlStringId.CustomizeDialogNewItemsLabel - Return "Label" - Case LayoutControlStringId.CustomizeDialogNewItemsSeparator - Return "Separator" - Case LayoutControlStringId.CustomizeDialogNewItemsSplitter - Return "Splitter" - Case LayoutControlStringId.CustomizeDialogNewItemsGroup - Return "Group" - Case LayoutControlStringId.CustomizeDialogNewItemsTabbedGroup - Return "Tabbed Group" - Case LayoutControlStringId.ContextMenuCustomize - Return "Customize" - Case LayoutControlStringId.ContextMenuHideItem - Return "Hide" - Case LayoutControlStringId.CustomizeDialogTitle - Return "Customize" - Case LayoutControlStringId.ErrorBoxTitle - Return "Error!" - Case LayoutControlStringId.ErrorFileNotFoundMessage - Return "File not found!" - Case LayoutControlStringId.ErrorLoadingLayoutMessage - Return "Error loading layout!" - End Select - Return MyBase.GetLocalizedString(id) - End Function -End Class - -```` - -{{endregion}} - -To apply the custom localization provider, instantiate and assign it to the current localization provider: - -#### Assigning the Current Localization Provider - -{{source=..\SamplesCS\DataLayout\DataLayoutLocalization.cs region=SetProvider}} -{{source=..\SamplesVB\DataLayout\DataLayoutLocalization.vb region=SetProvider}} - -````C# -LayoutControlLocalizationProvider.CurrentProvider = new MyEnglishLayoutControlLocalizationProvider(); - -```` -````VB.NET -LayoutControlLocalizationProvider.CurrentProvider = New MyEnglishLayoutControlLocalizationProvider() - -```` - -{{endregion}} - -# See Also - - * [Structure]({%slug winforms/datalayout/control-element-structure%}) - * [Getting Started]({%slug winforms/datalayout/getting-started%}) - * [Properties, events and attributes]({%slug winforms/datalayout/properties,-events-and-attributes%}) - * [Validation]({%slug winforms/datalayout/validation%}) - * [Change the editor to RadDropDownList]({%slug winforms/dataentry/how-to/change-the-editor-to-a-bound-raddropdownlist%}) - * [Customizing Appearance ]({%slug winforms/raddatalayout/customizing-appearance%}) +--- +title: Localization +page_title: Localization - WinForms DataLayout Control +description: learn how you can localize the string used in WinForms DataLayout. +slug: winforms/datalayout/localization +tags: localization +published: True +position: 8 +previous_url: datalayout-localization +--- + +# Localization + +To localize __RadDataLayout__ to display any text and messages in a specific language: + +* All required classes for localization are defined in __Telerik.WinControls.UI.Localization__ namespace. + +* Start by creating a descendant of the __LayoutControlLocalizationProvider__ class. + +* Override the __GetLocalizedString(string id)__ method and provide a translation for the label and user messages. If a translation is not provided, the default value will be returned. This behavior is guaranteed by the call to the base __GetLocalizedString__ method in the __default__ clause of the __switch__ statement in the example. + +Below is a sample implementation of an English localization provider: + + + + + + +To apply the custom localization provider, instantiate and assign it to the current localization provider: + +#### Assigning the Current Localization Provider + + + + + + +# See Also + + * [Structure]({%slug winforms/datalayout/control-element-structure%}) + * [Getting Started]({%slug winforms/datalayout/getting-started%}) + * [Properties, events and attributes]({%slug winforms/datalayout/properties,-events-and-attributes%}) + * [Validation]({%slug winforms/datalayout/validation%}) + * [Change the editor to RadDropDownList]({%slug winforms/dataentry/how-to/change-the-editor-to-a-bound-raddropdownlist%}) + * [Customizing Appearance ]({%slug winforms/raddatalayout/customizing-appearance%}) diff --git a/controls/datalayout/properties-events-and-attributes.md b/controls/datalayout/properties-events-and-attributes.md index 6e9d4dc0c..5a5797d76 100644 --- a/controls/datalayout/properties-events-and-attributes.md +++ b/controls/datalayout/properties-events-and-attributes.md @@ -60,78 +60,10 @@ __RadDataLayout__ has support for several attributes that can be used to change #### Using attributes. -{{source=..\SamplesCS\DataLayout\PropertiesEventsAttributesForm.cs region=ModelWithAttributes}} -{{source=..\SamplesVB\DataLayout\PropertiesEventsAttributesForm.vb region=ModelWithAttributes}} - -````C# -public class Employee -{ - public string FirstName { get; set; } - [DisplayName("Family Name")] - public string LastName { get; set; } - [Browsable(false)] - public string Occupation { get; set; } - [RadRange(2000, 3000)] - public int Salary { get; set; } - public DateTime StartingDate { get; set; } -} - -```` -````VB.NET -Public Class Employee - Public Property FirstName() As String - Get - Return m_FirstName - End Get - Set(value As String) - m_FirstName = value - End Set - End Property - Private m_FirstName As String - _ - Public Property LastName() As String - Get - Return m_LastName - End Get - Set(value As String) - m_LastName = value - End Set - End Property - Private m_LastName As String - _ - Public Property Occupation() As String - Get - Return m_Occupation - End Get - Set(value As String) - m_Occupation = value - End Set - End Property - Private m_Occupation As String - _ - Public Property Salary() As Integer - Get - Return m_Salary - End Get - Set(value As Integer) - m_Salary = value - End Set - End Property - Private m_Salary As Integer - Public Property StartingDate() As DateTime - Get - Return m_StartingDate - End Get - Set(value As DateTime) - m_StartingDate = value - End Set - End Property - Private m_StartingDate As DateTime -End Class - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/datalayout/save-load-layout.md b/controls/datalayout/save-load-layout.md index 959b858f3..2a37840fc 100644 --- a/controls/datalayout/save-load-layout.md +++ b/controls/datalayout/save-load-layout.md @@ -14,73 +14,18 @@ previous_url: datalayout-save-load-layout __RadDataLayout__ allows changes at runtime. The control can export/import its layout which is stored in Xml format. This funtionality can be utilized by calling the __SaveLayout__ and __LoadLayout__ methods. #### Save the layout. -{{source=..\SamplesCS\DataLayout\LoadSaveLayout.cs region=SaveLayout}} -{{source=..\SamplesVB\DataLayout\LoadSaveLayout.vb region=SaveLayout}} -````C# -private void SaveLayout() -{ - using (SaveFileDialog sfd = new SaveFileDialog()) - { - sfd.DefaultExt = ".xml"; - sfd.Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.*"; - if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK) - { - this.radDataLayout1.LayoutControl.SaveLayout(sfd.FileName); - } - } -} + + -```` -````VB.NET -Private Sub SaveLayout() - Using sfd As New SaveFileDialog() - sfd.DefaultExt = ".xml" - sfd.Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.*" - If sfd.ShowDialog() = System.Windows.Forms.DialogResult.OK Then - Me.RadDataLayout1.LayoutControl.SaveLayout(sfd.FileName) - End If - End Using -End Sub -```` - -{{endregion}} #### Load the Layout -{{source=..\SamplesCS\DataLayout\LoadSaveLayout.cs region=LoadLayout}} -{{source=..\SamplesVB\DataLayout\LoadSaveLayout.vb region=LoadLayout}} - -````C# -private void LoadLayout() -{ - using (OpenFileDialog ofd = new OpenFileDialog()) - { - ofd.DefaultExt = ".xml"; - ofd.Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.*"; - if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) - { - this.radDataLayout1.LayoutControl.LoadLayout(ofd.FileName); - } - } -} - -```` -````VB.NET -Private Sub LoadLayout() - Using ofd As New OpenFileDialog() - ofd.DefaultExt = ".xml" - ofd.Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.*" - If ofd.ShowDialog() = System.Windows.Forms.DialogResult.OK Then - Me.RadDataLayout1.LayoutControl.LoadLayout(ofd.FileName) - End If - End Using -End Sub + + -```` -{{endregion}} The layout can be saved/loaded with the [customize dialog]({%slug winforms/datalayout/customize-layout-mode%}) as well. diff --git a/controls/datalayout/validation.md b/controls/datalayout/validation.md index 3c1f63f73..205258c20 100644 --- a/controls/datalayout/validation.md +++ b/controls/datalayout/validation.md @@ -15,291 +15,39 @@ For the need of the validation process we made two events (__ItemValidating, Ite 1\. For the purpose of this tutorial, we will create a new class **Employee** with a couple of exposed properties. By binding __RadDataLayout__ to object from this type we will generate several items: -{{source=..\SamplesCS\DataLayout\DataLayoutValidation.cs region=DataLayoutEmployee}} -{{source=..\SamplesVB\DataLayout\DataLayoutValidation.vb region=DataLayoutEmployee}} + + -````C# -public class Employee -{ - [DisplayName("First Name")] - public string FirstName { get; set; } - [DisplayName("Family Name")] - public string LastName { get; set; } - public string Occupation { get; set; } - public int Salary { get; set; } - public DateTime StartingDate { get; set; } - public bool IsMarried { get; set; } -} -```` -````VB.NET -Public Class Employee - _ - Public Property FirstName() As String - Get - Return m_FirstName - End Get - Set(value As String) - m_FirstName = value - End Set - End Property - Private m_FirstName As String - _ - Public Property LastName() As String - Get - Return m_LastName - End Get - Set(value As String) - m_LastName = value - End Set - End Property - Private m_LastName As String - Public Property Occupation() As String - Get - Return m_Occupation - End Get - Set(value As String) - m_Occupation = value - End Set - End Property - Private m_Occupation As String - Public Property Salary() As Integer - Get - Return m_Salary - End Get - Set(value As Integer) - m_Salary = value - End Set - End Property - Private m_Salary As Integer - Public Property StartingDate() As DateTime - Get - Return m_StartingDate - End Get - Set(value As DateTime) - m_StartingDate = value - End Set - End Property - Private m_StartingDate As DateTime - Public Property IsMarried() As Boolean - Get - Return m_IsMarried - End Get - Set(value As Boolean) - m_IsMarried = value - End Set - End Property - Private m_IsMarried As Boolean -End Class -```` + + -{{endregion}} -{{source=..\SamplesCS\DataLayout\DataLayoutValidation.cs region=DataLayoutBinding}} -{{source=..\SamplesVB\DataLayout\DataLayoutValidation.vb region=DataLayoutBinding}} - -````C# -this.radDataLayout1.DataSource = new Employee() -{ - FirstName = "Sarah", - LastName = "Blake", - Occupation = "Supplied Manager", - StartingDate = new DateTime(2005, 04, 12), - Salary = 1500, - IsMarried = true -}; - -```` -````VB.NET -Me.RadDataLayout1.DataSource = New Employee() With { - .FirstName = "Sarah", - .LastName = "Blake", - .Occupation = "Supplied Manager", - .StartingDate = New DateTime(2005, 4, 12), - .Salary = 1500, - .IsMarried = True -} - -```` - -{{endregion}} >caption Figure 1: RadDataLayout Initialized ![WinForms RadDataLayout Initialized](images/datalayout-validation001.png) 2\. Set the __ShowValidationPanel__ property to *true*. This will display the panel below the editors: -{{source=..\SamplesCS\DataLayout\DataLayoutValidation.cs region=DataLayoutShowPanel}} -{{source=..\SamplesVB\DataLayout\DataLayoutValidation.vb region=DataLayoutShowPanel}} - -````C# -this.radDataLayout1.ShowValidationPanel = true; + + -```` -````VB.NET -Me.RadDataLayout1.ShowValidationPanel = True -```` - -{{endregion}} 3\. Set a padding to the __LayoutControlContainerElement__ so that the error icons are visible. A suitable place to perform this operation is the handler of the __BindingCreated__. -{{source=..\SamplesCS\DataLayout\DataLayoutValidation.cs region=DataLayoutSetPadding}} -{{source=..\SamplesVB\DataLayout\DataLayoutValidation.vb region=DataLayoutSetPadding}} - -````C# -private void radDataLayout1_BindingCreated(object sender, Telerik.WinControls.UI.BindingCreatedEventArgs e) -{ - this.radDataLayout1.LayoutControl.ContainerElement.Padding = new Padding(0, 0, 20, 0); -} - -```` -````VB.NET -Private Sub RadDataLayout1_BindingCreated(sender As Object, e As BindingCreatedEventArgs) - Me.RadDataLayout1.LayoutControl.ContainerElement.Padding = New Padding(0, 0, 20, 0) -End Sub + + -```` -{{endregion}} 4\. Subscribe to the __ItemValidated__ event of __RadDataEntry__: -{{source=..\SamplesCS\DataLayout\DataLayoutValidation.cs region=DataLayoutItemValidated}} -{{source=..\SamplesVB\DataLayout\DataLayoutValidation.vb region=DataLayoutItemValidated}} - -````C# -private void radDataLayout1_ItemValidated(object sender, Telerik.WinControls.UI.DataLayoutItemValidatedEventArgs e) -{ - Employee employee = this.radDataLayout1.CurrentObject as Employee; - if (e.Item.Text == "First Name") - { - if (employee.FirstName.Length < 2 || employee.FirstName.Length > 15) - { - e.ErrorProvider.SetError((sender as Control), "First Name should be between 2 and 15 chars long."); - if (!this.radDataLayout1.ValidationPanel.PanelContainer.Controls.ContainsKey("FirstName")) - { - RadLabel label = new RadLabel(); - label.Name = "FirstName"; - label.Text = "FirstName : First Name should be between 2 and 15 chars long."; - label.Dock = DockStyle.Top; - label.AutoSize = false; - label.BackColor = Color.Transparent; - this.radDataLayout1.ValidationPanel.PanelContainer.Controls.Add(label); - } - } - else - { - e.ErrorProvider.Clear(); - this.radDataLayout1.ValidationPanel.PanelContainer.Controls.RemoveByKey("FirstName"); - } - } - else if (e.Item.Text == "Family Name") - { - if (employee.LastName.Length < 2 || employee.LastName.Length > 15) - { - e.ErrorProvider.SetError((sender as Control), "Last Name should be between 2 and 15 chars long."); - if (!this.radDataLayout1.ValidationPanel.PanelContainer.Controls.ContainsKey("LastName")) - { - RadLabel label = new RadLabel(); - label.Name = "LastName"; - label.Text = "LastName : Last Name should be between 2 and 15 chars long."; - label.Dock = DockStyle.Top; - label.AutoSize = false; - label.BackColor = Color.Transparent; - this.radDataLayout1.ValidationPanel.PanelContainer.Controls.Add(label); - } - } - else - { - e.ErrorProvider.Clear(); - this.radDataLayout1.ValidationPanel.PanelContainer.Controls.RemoveByKey("LastName"); - } - } - else if (e.Item.Text == "Salary") - { - if (employee.Salary < 1400 || employee.Salary > 1800) - { - e.ErrorProvider.SetError((sender as Control), "Salary should be in range 1500 - 1700."); - if (!this.radDataLayout1.ValidationPanel.PanelContainer.Controls.ContainsKey("Salary")) - { - RadLabel label = new RadLabel(); - label.Name = "Salary"; - label.Text = "Salary : Salary should be in range 1500 - 1700."; - label.Dock = DockStyle.Top; - label.AutoSize = false; - label.BackColor = Color.Transparent; - this.radDataLayout1.ValidationPanel.PanelContainer.Controls.Add(label); - } - } - else - { - e.ErrorProvider.Clear(); - this.radDataLayout1.ValidationPanel.PanelContainer.Controls.RemoveByKey("Salary"); - } - } -} - -```` -````VB.NET -Private Sub radDataLayout1_ItemValidated(sender As Object, e As Telerik.WinControls.UI.DataLayoutItemValidatedEventArgs) - Dim employee As Employee = TryCast(Me.RadDataLayout1.CurrentObject, Employee) - If e.Item.Text = "First Name" Then - If employee.FirstName.Length < 2 OrElse employee.FirstName.Length > 15 Then - e.ErrorProvider.SetError(TryCast(sender, Control), "First Name should be between 2 and 15 chars long.") - If Not Me.RadDataLayout1.ValidationPanel.PanelContainer.Controls.ContainsKey("FirstName") Then - Dim label As New RadLabel() - label.Name = "FirstName" - label.Text = "FirstName : First Name should be between 2 and 15 chars long." - label.Dock = DockStyle.Top - label.AutoSize = False - label.BackColor = Color.Transparent - Me.RadDataLayout1.ValidationPanel.PanelContainer.Controls.Add(label) - End If - Else - e.ErrorProvider.Clear() - Me.RadDataLayout1.ValidationPanel.PanelContainer.Controls.RemoveByKey("FirstName") - End If - ElseIf e.Item.Text = "Family Name" Then - If employee.LastName.Length < 2 OrElse employee.LastName.Length > 15 Then - e.ErrorProvider.SetError(TryCast(sender, Control), "Last Name should be between 2 and 15 chars long.") - If Not Me.RadDataLayout1.ValidationPanel.PanelContainer.Controls.ContainsKey("LastName") Then - Dim label As New RadLabel() - label.Name = "LastName" - label.Text = "LastName : Last Name should be between 2 and 15 chars long." - label.Dock = DockStyle.Top - label.AutoSize = False - label.BackColor = Color.Transparent - Me.RadDataLayout1.ValidationPanel.PanelContainer.Controls.Add(label) - End If - Else - e.ErrorProvider.Clear() - Me.RadDataLayout1.ValidationPanel.PanelContainer.Controls.RemoveByKey("LastName") - End If - ElseIf e.Item.Text = "Salary" Then - If employee.Salary < 1400 OrElse employee.Salary > 1800 Then - e.ErrorProvider.SetError(TryCast(sender, Control), "Salary should be in range 1500 - 1700.") - If Not Me.RadDataLayout1.ValidationPanel.PanelContainer.Controls.ContainsKey("Salary") Then - Dim label As New RadLabel() - label.Name = "Salary" - label.Text = "Salary : Salary should be in range 1500 - 1700." - label.Dock = DockStyle.Top - label.AutoSize = False - label.BackColor = Color.Transparent - Me.RadDataLayout1.ValidationPanel.PanelContainer.Controls.Add(label) - End If - Else - e.ErrorProvider.Clear() - Me.RadDataLayout1.ValidationPanel.PanelContainer.Controls.RemoveByKey("Salary") - End If - End If -End Sub + + -```` -{{endregion}} >caption Figure 2: Validaton Errors ![WinForms RadDataLayout Validaton Errors](images/datalayout-validation002.png) diff --git a/controls/desktopalert/button-items.md b/controls/desktopalert/button-items.md index 23eb36009..9cfcf15f9 100644 --- a/controls/desktopalert/button-items.md +++ b/controls/desktopalert/button-items.md @@ -18,50 +18,7 @@ __RadDesktopAlert__ supports adding custom items to the pop up by using the __Bu #### Adding elements to the ButtonItems collection -{{source=..\SamplesCS\DesktopAlert\DesktopAlert1.cs region=ButtonItems}} -{{source=..\SamplesVB\DesktopAlert\DesktopAlert1.vb region=ButtonItems}} + + -````C# - -public void AddButtonItems() -{ - RadLabelElement labelElement = new RadLabelElement(); - labelElement.Text = "Recipients count: "; - labelElement.Padding = new System.Windows.Forms.Padding(0, 5, 0, 0); - RadButtonElement buttonElement = new RadButtonElement(); - buttonElement.Text = "Send"; - buttonElement.Click += ButtonElement_Click; - RadSpinEditorElement spinElement = new RadSpinEditorElement(); - spinElement.MinSize = new Size(50, 20); - this.radDesktopAlert1.ButtonItems.Add(labelElement); - this.radDesktopAlert1.ButtonItems.Add(spinElement); - this.radDesktopAlert1.ButtonItems.Add(buttonElement); -} - -private void ButtonElement_Click(object sender, EventArgs e) -{ - //TODO -} - -```` -````VB.NET -Public Sub AddButtonItems() - Dim labelElement As New RadLabelElement() - labelElement.Text = "Recipients count: " - labelElement.Padding = New System.Windows.Forms.Padding(0, 5, 0, 0) - Dim buttonElement As New RadButtonElement() - buttonElement.Text = "Send" - AddHandler buttonElement.Click, AddressOf ButtonElement_Click - Dim spinElement As New RadSpinEditorElement() - spinElement.MinSize = New Size(50, 20) - Me.radDesktopAlert1.ButtonItems.Add(labelElement) - Me.radDesktopAlert1.ButtonItems.Add(spinElement) - Me.radDesktopAlert1.ButtonItems.Add(buttonElement) -End Sub -Private Sub ButtonElement_Click(sender As Object, e As EventArgs) -'TODO -End Sub - -```` - -{{endregion}} + diff --git a/controls/desktopalert/customizing-appearance/accessing-and-customizing-elements.md b/controls/desktopalert/customizing-appearance/accessing-and-customizing-elements.md index 1ff4d8035..5c96bcd11 100644 --- a/controls/desktopalert/customizing-appearance/accessing-and-customizing-elements.md +++ b/controls/desktopalert/customizing-appearance/accessing-and-customizing-elements.md @@ -20,40 +20,7 @@ The following code example demonstrates how to customize the nested elements at #### Customize elements -{{source=..\SamplesCS\DesktopAlert\DesktopAlert1.cs region=AccessingCustomizingElements}} -{{source=..\SamplesVB\DesktopAlert\DesktopAlert1.vb region=AccessingCustomizingElements}} + + -````C# - -this.radDesktopAlert1.Popup.AlertElement.CaptionElement.TextAndButtonsElement.TextElement.ForeColor = Color.Red; -this.radDesktopAlert1.Popup.AlertElement.CaptionElement.CaptionGrip.BackColor = Color.Red; -this.radDesktopAlert1.Popup.AlertElement.CaptionElement.CaptionGrip.GradientStyle = GradientStyles.Solid; -this.radDesktopAlert1.Popup.AlertElement.ContentElement.Font = new Font("Arial", 8f,FontStyle.Italic); -this.radDesktopAlert1.Popup.AlertElement.ContentElement.TextImageRelation = TextImageRelation.TextBeforeImage; -this.radDesktopAlert1.Popup.AlertElement.BackColor = Color.Yellow; -this.radDesktopAlert1.Popup.AlertElement.GradientStyle = GradientStyles.Solid; -this.radDesktopAlert1.Popup.AlertElement.BorderColor = Color.Red; - -```` -````VB.NET -Me.radDesktopAlert1.Popup.AlertElement.CaptionElement.TextAndButtonsElement.TextElement.ForeColor = Color.Red -Me.radDesktopAlert1.Popup.AlertElement.CaptionElement.CaptionGrip.BackColor = Color.Red -Me.radDesktopAlert1.Popup.AlertElement.CaptionElement.CaptionGrip.GradientStyle = GradientStyles.Solid -Me.radDesktopAlert1.Popup.AlertElement.ContentElement.Font = New Font("Arial", 8.0F, FontStyle.Italic) -Me.radDesktopAlert1.Popup.AlertElement.ContentElement.TextImageRelation = TextImageRelation.TextBeforeImage -Me.radDesktopAlert1.Popup.AlertElement.BackColor = Color.Yellow -Me.radDesktopAlert1.Popup.AlertElement.GradientStyle = GradientStyles.Solid -Me.radDesktopAlert1.Popup.AlertElement.BorderColor = Color.Red -'#End Region -End Sub -'#region showingAlert -Private Sub radButton1_Click(ByVal sender As Object, ByVal e As EventArgs) -Me.radDesktopAlert1.ContentImage = envelopeImage -Me.radDesktopAlert1.CaptionText = "New E-mail Notification" -Me.radDesktopAlert1.ContentText = "Hello Jack, I am writing to inform you " & "that the planning meeting scheduled for Wednesday has been postponed and" & "it will eventually be rescheduled, possibly for the next Tuesday" -Me.radDesktopAlert1.Show() -End Sub - -```` - -{{endregion}} + diff --git a/controls/desktopalert/gettingstarted.md b/controls/desktopalert/gettingstarted.md index a397cee23..672fafed2 100644 --- a/controls/desktopalert/gettingstarted.md +++ b/controls/desktopalert/gettingstarted.md @@ -48,33 +48,10 @@ Follow the described steps below: #### Setting up RadDesktopAlert -{{source=..\SamplesCS\DesktopAlert\DesktopAlert1.cs region=showingAlert}} -{{source=..\SamplesVB\DesktopAlert\DesktopAlert1.vb region=showingAlert}} - -````C# - -void radButton1_Click(object sender, EventArgs e) -{ - this.radDesktopAlert1.ContentImage = envelopeImage; - this.radDesktopAlert1.CaptionText = "New E-mail Notification"; - this.radDesktopAlert1.ContentText = "Hello Jack, I am writing to inform you " + - "that the planning meeting scheduled for Wednesday has been postponed and" + - "it will eventually be rescheduled, possibly for the next Tuesday"; - this.radDesktopAlert1.Show(); -} - -```` -````VB.NET -Private Sub radButton1_Click(ByVal sender As Object, ByVal e As EventArgs) - Me.radDesktopAlert1.ContentImage = envelopeImage - Me.radDesktopAlert1.CaptionText = "New E-mail Notification" - Me.radDesktopAlert1.ContentText = "Hello Jack, I am writing to inform you " & "that the planning meeting scheduled for Wednesday has been postponed and" & "it will eventually be rescheduled, possibly for the next Tuesday" - Me.radDesktopAlert1.Show() -End Sub - -```` - -{{endregion}} + + + + This way you will display an alert window at the bottom right part of the screen just the same way Microsoft Outlook does. diff --git a/controls/diagram/background-grid.md b/controls/diagram/background-grid.md index 813fee514..8661586f8 100644 --- a/controls/diagram/background-grid.md +++ b/controls/diagram/background-grid.md @@ -18,21 +18,10 @@ You can control the background settings of the diagramming surface through the f #### Set IsBackgroundSurfaceVisible -{{source=..\SamplesCS\Diagram\DiagramBackgroundGrid.cs region=IsBackgroundSurfaceVisible}} -{{source=..\SamplesVB\Diagram\DiagramBackgroundGrid.vb region=IsBackgroundSurfaceVisible}} + + -````C# - -this.radDiagram1.DiagramElement.IsBackgroundSurfaceVisible = true; - -```` -````VB.NET -Me.RadDiagram1.DiagramElement.IsBackgroundSurfaceVisible = True -```` - -{{endregion}} - | __IsBackgroundSurfaceVisible__ = *true* | __IsBackgroundSurfaceVisible__ = *false* | |----|----| @@ -42,21 +31,11 @@ Me.RadDiagram1.DiagramElement.IsBackgroundSurfaceVisible = True #### Set Background -{{source=..\SamplesCS\Diagram\DiagramBackgroundGrid.cs region=Background}} -{{source=..\SamplesVB\Diagram\DiagramBackgroundGrid.vb region=Background}} + + -````C# - -this.radDiagram1.DiagramElement.BackgroundGrid.Background = new System.Drawing.SolidBrush(Color.LightYellow); - -```` -````VB.NET -Me.RadDiagram1.DiagramElement.BackgroundGrid.Background = New System.Drawing.SolidBrush(Color.LightYellow) -```` -{{endregion}} - >caption Figure 1: Background ![WinForms RadDiagram Background](images/diagram-backgroundgrid003.png) @@ -71,20 +50,10 @@ You can access the __BackgroundGrid__ properties: #### Set CellSize -{{source=..\SamplesCS\Diagram\DiagramBackgroundGrid.cs region=CellSize}} -{{source=..\SamplesVB\Diagram\DiagramBackgroundGrid.vb region=CellSize}} + + -````C# - -this.radDiagram1.DiagramElement.BackgroundGrid.CellSize = new Telerik.Windows.Diagrams.Core.Size(40, 40); -```` -````VB.NET -Me.RadDiagram1.DiagramElement.BackgroundGrid.CellSize = New Telerik.Windows.Diagrams.Core.Size(40, 40) - -```` - -{{endregion}} * __LineStroke__: this property is of type *Brush* and it specifies how the cells outline is painted. @@ -95,20 +64,11 @@ Me.RadDiagram1.DiagramElement.BackgroundGrid.CellSize = New Telerik.Windows.Diag #### Set LineStroke -{{source=..\SamplesCS\Diagram\DiagramBackgroundGrid.cs region=LineStroke}} -{{source=..\SamplesVB\Diagram\DiagramBackgroundGrid.vb region=LineStroke}} - -````C# - -this.radDiagram1.DiagramElement.BackgroundGrid.LineStroke = new System.Drawing.SolidBrush(Color.Red); + + -```` -````VB.NET -Me.RadDiagram1.DiagramElement.BackgroundGrid.LineStroke = New System.Drawing.SolidBrush(Color.Red) -```` -{{endregion}} * __LineStrokeThickness__: this property is of type *double* and it gets or sets the thickness of the __RadDiagram__ background grid lines. @@ -118,20 +78,10 @@ Me.RadDiagram1.DiagramElement.BackgroundGrid.LineStroke = New System.Drawing.Sol #### Set LineStrokeThickness -{{source=..\SamplesCS\Diagram\DiagramBackgroundGrid.cs region=LineStrokeThickness}} -{{source=..\SamplesVB\Diagram\DiagramBackgroundGrid.vb region=LineStrokeThickness}} - -````C# - -this.radDiagram1.DiagramElement.BackgroundGrid.LineStrokeThickness = 5; - -```` -````VB.NET -Me.RadDiagram1.DiagramElement.BackgroundGrid.LineStrokeThickness = 5 + + -```` -{{endregion}} # See Also diff --git a/controls/diagram/custom-shapes.md b/controls/diagram/custom-shapes.md index 3f1301bb6..946fe1068 100644 --- a/controls/diagram/custom-shapes.md +++ b/controls/diagram/custom-shapes.md @@ -17,75 +17,14 @@ This tutorial will guide you through the task of creating a custom shape. In order to create a custom shape, you need to define a custom shape class deriving from the __ElementShape__ class. Overriding its __CreatePath__ method you can define the desired shape. Afterwards, you need to apply your shape implementation to the RadDiagramShape.__ElementShape__ property: -{{source=..\SamplesCS\Diagram\DiagramCustomShapes.cs region=MyShape}} -{{source=..\SamplesVB\Diagram\DiagramCustomShapes.vb region=MyShape}} - -````C# - -public class MyShape : ElementShape -{ - public override GraphicsPath CreatePath(System.Drawing.Rectangle bounds) - { - GraphicsPath path = new GraphicsPath(); - path.AddString("Custom", new System.Drawing.FontFamily("Arial"), 0, bounds.Width, Point.Empty, StringFormat.GenericTypographic); - return path; - } -} - -```` -````VB.NET -Public Class MyShape -Inherits ElementShape - Public Overrides Function CreatePath(bounds As System.Drawing.Rectangle) As GraphicsPath - Dim path As New GraphicsPath() - path.AddString("Custom", New System.Drawing.FontFamily("Arial"), 0, bounds.Width, Point.Empty, StringFormat.GenericTypographic) - Return path - End Function -End Class - -```` - -{{endregion}} - - -{{source=..\SamplesCS\Diagram\DiagramCustomShapes.cs region=ApplyCustomShape}} -{{source=..\SamplesVB\Diagram\DiagramCustomShapes.vb region=ApplyCustomShape}} - -````C# - -RadDiagramShape shape1 = new RadDiagramShape() -{ - Text = "", - ElementShape = new MyShape(), - BackColor = System.Drawing.Color.LightBlue -}; -shape1.Position = new Telerik.Windows.Diagrams.Core.Point(100, 80); -radDiagram1.AddShape(shape1); - -```` -````VB.NET -Dim shape1 As New RadDiagramShape() With { _ - .Text = "", _ - .ElementShape = New MyShape(), _ - .BackColor = System.Drawing.Color.LightBlue _ -} -shape1.Position = New Telerik.Windows.Diagrams.Core.Point(100, 80) -'#Region "" -RadDiagram1.AddShape(shape1) -End Sub -'#Region "MyShape" -Public Class MyShape -Inherits ElementShape -Public Overrides Function CreatePath(bounds As System.Drawing.Rectangle) As GraphicsPath - Dim path As New GraphicsPath() - path.AddString("Custom", New System.Drawing.FontFamily("Arial"), 0, bounds.Width, Point.Empty, StringFormat.GenericTypographic) - Return path -End Function -End Class - -```` - -{{endregion}} + + + + + + + + ![WinForms RadDiagram Custom Shapes](images/diagram-custom-shapes001.png) diff --git a/controls/diagram/data-binding/binding-to-custom-objects.md b/controls/diagram/data-binding/binding-to-custom-objects.md index f56a26279..91449832d 100644 --- a/controls/diagram/data-binding/binding-to-custom-objects.md +++ b/controls/diagram/data-binding/binding-to-custom-objects.md @@ -20,636 +20,16 @@ The data source should contain columns/fields that represent the shapes/connecti Consider the following classes: -{{source=..\SamplesCS\Diagram\DiagramDataBinding.cs region=CustomObjects}} -{{source=..\SamplesVB\Diagram\DiagramDataBinding.vb region=CustomObjects}} + + -````C# - -public class Task : INotifyPropertyChanged -{ - private string id; - private string text; - private string type; - private double x; - private double y; - private double width; - private double height; - - public string Id - { - get - { - return this.id; - } - set - { - this.id = value; - if (this.id != value) - { - this.id = value; - OnPropertyChanged("Id"); - } - } - } - - public string Text - { - get - { - return this.text; - } - set - { - this.text = value; - if (this.text != value) - { - this.text = value; - OnPropertyChanged("Text"); - } - } - } - - public string Type - { - get - { - return this.type; - } - set - { - if (this.type != value) - { - this.type = value; - OnPropertyChanged("Type"); - } - } - } - - public double X - { - get - { - return this.x; - } - set - { - if (this.x != value) - { - this.x = value; - OnPropertyChanged("X"); - } - } - } - - public double Y - { - get - { - return this.y; - } - set - { - this.y = value; - if (this.y != value) - { - this.y = value; - OnPropertyChanged("Y"); - } - } - } - - public double Height - { - get - { - return this.height; - } - set - { - if (this.height != value) - { - this.height = value; - OnPropertyChanged("Height"); - } - } - } - - public double Width - { - get - { - return this.width; - } - set - { - if (this.width != value) - { - this.width = value; - OnPropertyChanged("Width"); - } - } - } - - private void OnPropertyChanged(string propertyName) - { - if (PropertyChanged != null) - PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); - } - - public event PropertyChangedEventHandler PropertyChanged; -} - -public class Relation : INotifyPropertyChanged -{ - private string sourceTaskId; - private string sourceConnector; - private string targetTaskId; - private string targetConnector; - private string startCapField; - private string endCapField; - public string EndCapField - { - get - { - return this.endCapField; - } - set - { - this.endCapField = value; - if (this.endCapField != value) - { - this.endCapField = value; - OnPropertyChanged("EndCapField"); - } - } - } - public string StartCapField - { - get - { - return this.startCapField; - } - set - { - this.startCapField = value; - if (this.startCapField != value) - { - this.startCapField = value; - OnPropertyChanged("StartCapField"); - } - } - } - public string TargetConnector - { - get - { - return this.targetConnector; - } - set - { - this.targetConnector = value; - if (this.targetConnector != value) - { - this.targetConnector = value; - OnPropertyChanged("TargetConnector"); - } - } - } - public string TargetTaskId - { - get - { - return this.targetTaskId; - } - set - { - this.targetTaskId = value; - if (this.targetTaskId != value) - { - this.targetTaskId = value; - OnPropertyChanged("TargetTaskId"); - } - } - } - public string SourceConnector - { - get - { - return this.sourceConnector; - } - set - { - this.sourceConnector = value; - if (this.sourceConnector != value) - { - this.sourceConnector = value; - OnPropertyChanged("SourceConnector"); - } - } - } - public string SourceTaskId - { - get - { - return this.sourceTaskId; - } - set - { - this.sourceTaskId = value; - if (this.sourceTaskId != value) - { - this.sourceTaskId = value; - OnPropertyChanged("SourceTaskId"); - } - } - } - private void OnPropertyChanged(string propertyName) - { - if (PropertyChanged != null) - PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); - } - public event PropertyChangedEventHandler PropertyChanged; -} - -public class Source -{ - public BindingList Tasks - { - get - { - return GetTasks(); - } - } - - public BindingList Relations - { - get - { - return GetRelations(); - } - } - - private BindingList GetTasks() - { - return new BindingList() - { - new Task() { Id = "Task1", Text = "Task 1", Type = "circle", X = 100, Y = 300, Width = 50, Height = 50 }, - new Task() { Id = "Task2", Text = "Task 2", Type = "rectangle", X = 200, Y = 100, Width = 100, Height = 100 }, - new Task() { Id = "Task3", Text = "Task 3", Type = "circle", X = 300, Y = 300, Width = 50, Height = 50 }, - new Task() { Id = "Task4", Text = "Task 4", Type = "rectangle", X = 400, Y = 100, Width = 100, Height = 100 }, - new Task() { Id = "Task5", Text = "Task 5", Type = "circle", X = 500, Y = 300, Width = 50, Height = 50 } - }; - } - - private BindingList GetRelations() - { - return new BindingList() - { - new Relation() - { - SourceTaskId = "Task2", SourceConnector = "Left", TargetTaskId = "Task1", - TargetConnector = "Auto", StartCapField = "Arrow5Filled", EndCapField = "Arrow1" - }, - new Relation() - { - SourceTaskId = "Task2", SourceConnector = "Auto", TargetTaskId = "Task3", - TargetConnector = "Auto", StartCapField = "Arrow4Filled", EndCapField = "Arrow1Filled" - }, - new Relation() - { - SourceTaskId = "Task4", SourceConnector = "Auto", TargetTaskId = "Task5", - TargetConnector = "Auto", StartCapField = "Arrow2Filled", EndCapField = "Arrow2" - } - }; - } -} - -```` -````VB.NET -Public Class Task -Implements INotifyPropertyChanged - Private m_id As String - Private m_text As String - Private m_type As String - Private m_x As Double - Private m_y As Double - Private m_width As Double - Private m_height As Double - Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged - Public Property Id() As String - Get - Return Me.m_id - End Get - Set(value As String) - Me.m_id = value - If Me.m_id <> value Then - Me.m_id = value - OnPropertyChanged("Id") - End If - End Set - End Property - Public Property Text() As String - Get - Return Me.m_text - End Get - Set(value As String) - Me.m_text = value - If Me.m_text <> value Then - Me.m_text = value - OnPropertyChanged("Text") - End If - End Set - End Property - Public Property Type() As String - Get - Return Me.m_type - End Get - Set(value As String) - If Me.m_type <> value Then - Me.m_type = value - OnPropertyChanged("Type") - End If - End Set - End Property - Public Property X() As Double - Get - Return Me.m_x - End Get - Set(value As Double) - If Me.m_x <> value Then - Me.m_x = value - OnPropertyChanged("X") - End If - End Set - End Property - Public Property Y() As Double - Get - Return Me.m_y - End Get - Set(value As Double) - Me.m_y = value - If Me.m_y <> value Then - Me.m_y = value - OnPropertyChanged("Y") - End If - End Set - End Property - Public Property Height() As Double - Get - Return Me.m_height - End Get - Set(value As Double) - If Me.m_height <> value Then - Me.m_height = value - OnPropertyChanged("Height") - End If - End Set - End Property - Public Property Width() As Double - Get - Return Me.m_width - End Get - Set(value As Double) - If Me.m_width <> value Then - Me.m_width = value - OnPropertyChanged("Width") - End If - End Set - End Property - Private Sub OnPropertyChanged(propertyName As String) - RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName)) - End Sub -End Class -Public Class Relation -Implements INotifyPropertyChanged - Private m_sourceTaskId As String - Private m_sourceConnector As String - Private m_targetTaskId As String - Private m_targetConnector As String - Private m_startCapField As String - Private m_endCapField As String - Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged - Public Property EndCapField() As String - Get - Return Me.m_endCapField - End Get - Set(value As String) - Me.m_endCapField = value - If Me.m_endCapField <> value Then - Me.m_endCapField = value - OnPropertyChanged("EndCapField") - End If - End Set - End Property - Public Property StartCapField() As String - Get - Return Me.m_startCapField - End Get - Set(value As String) - Me.m_startCapField = value - If Me.m_startCapField <> value Then - Me.m_startCapField = value - OnPropertyChanged("StartCapField") - End If - End Set - End Property - Public Property TargetConnector() As String - Get - Return Me.m_targetConnector - End Get - Set(value As String) - Me.m_targetConnector = value - If Me.m_targetConnector <> value Then - Me.m_targetConnector = value - OnPropertyChanged("TargetConnector") - End If - End Set - End Property - Public Property TargetTaskId() As String - Get - Return Me.m_targetTaskId - End Get - Set(value As String) - Me.m_targetTaskId = value - If Me.m_targetTaskId <> value Then - Me.m_targetTaskId = value - OnPropertyChanged("TargetTaskId") - End If - End Set - End Property - Public Property SourceConnector() As String - Get - Return Me.m_sourceConnector - End Get - Set(value As String) - Me.m_sourceConnector = value - If Me.m_sourceConnector <> value Then - Me.m_sourceConnector = value - OnPropertyChanged("SourceConnector") - End If - End Set - End Property - Public Property SourceTaskId() As String - Get - Return Me.m_sourceTaskId - End Get - Set(value As String) - Me.m_sourceTaskId = value - If Me.m_sourceTaskId <> value Then - Me.m_sourceTaskId = value - OnPropertyChanged("SourceTaskId") - End If - End Set - End Property - Private Sub OnPropertyChanged(propertyName As String) - RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName)) - End Sub - -End Class - -Public Class Source - Public ReadOnly Property Tasks() As BindingList(Of Task) - Get - Return GetTasks() - End Get - End Property - Public ReadOnly Property Relations() As BindingList(Of Relation) - Get - Return GetRelations() - End Get - End Property - Private Function GetTasks() As BindingList(Of Task) - Return New BindingList(Of Task)() From { _ - New Task() With { _ - .Id = "Task1", _ - .Text = "Task 1", _ - .Type = "circle", _ - .X = 100, _ - .Y = 300, _ - .Width = 50, _ - .Height = 50 _ - }, _ - New Task() With { _ - .Id = "Task2", _ - .Text = "Task 2", _ - .Type = "rectangle", _ - .X = 200, _ - .Y = 100, _ - .Width = 100, _ - .Height = 100 _ - }, _ - New Task() With { _ - .Id = "Task3", _ - .Text = "Task 3", _ - .Type = "circle", _ - .X = 300, _ - .Y = 300, _ - .Width = 50, _ - .Height = 50 _ - }, _ - New Task() With { _ - .Id = "Task4", _ - .Text = "Task 4", _ - .Type = "rectangle", _ - .X = 400, _ - .Y = 100, _ - .Width = 100, _ - .Height = 100 _ - }, _ - New Task() With { _ - .Id = "Task5", _ - .Text = "Task 5", _ - .Type = "circle", _ - .X = 500, _ - .Y = 300, _ - .Width = 50, _ - .Height = 50 _ - } _ - } - End Function - Private Function GetRelations() As BindingList(Of Relation) - Return New BindingList(Of Relation)() From { _ - New Relation() With { _ - .SourceTaskId = "Task2", _ - .SourceConnector = "Left", _ - .TargetTaskId = "Task1", _ - .TargetConnector = "Auto", _ - .StartCapField = "Arrow5Filled", _ - .EndCapField = "Arrow1" _ - }, _ - New Relation() With { _ - .SourceTaskId = "Task2", _ - .SourceConnector = "Auto", _ - .TargetTaskId = "Task3", _ - .TargetConnector = "Auto", _ - .StartCapField = "Arrow4Filled", _ - .EndCapField = "Arrow1Filled" _ - }, _ - New Relation() With { _ - .SourceTaskId = "Task4", _ - .SourceConnector = "Auto", _ - .TargetTaskId = "Task5", _ - .TargetConnector = "Auto", _ - .StartCapField = "Arrow2Filled", _ - .EndCapField = "Arrow2" _ - } _ - } - End Function -End Class -```` -{{endregion}} - The __Task__ class will represent a single shape in __RadDiagram__, while the __Relation__ class will represent a connection. Note that the __Source__ class contains two properties, __Tasks__ and __Relations__ which will be specified as __ConnectionDataMember__ and __ShapeDataMember__ for __RadDiagram__. To make data binding work, you should specify the member properties as well: -{{source=..\SamplesCS\Diagram\DiagramDataBinding.cs region=SetupMembers}} -{{source=..\SamplesVB\Diagram\DiagramDataBinding.vb region=SetupMembers}} - -````C# - -this.radDiagram1.DataSource = new Source(); - -this.radDiagram1.ConnectionDataMember = "Relations"; -this.radDiagram1.ShapeDataMember = "Tasks"; -this.radDiagram1.ShapeIdMember = "Id"; -this.radDiagram1.ShapeTextMember = "Text"; -this.radDiagram1.ShapeTypeMember = "Type"; -this.radDiagram1.ShapeXMember = "X"; -this.radDiagram1.ShapeYMember = "Y"; -this.radDiagram1.ShapeWidthMember = "Width"; -this.radDiagram1.ShapeHeightMember = "Height"; - -this.radDiagram1.ConnectionSourceShapeIdMember = "SourceTaskId"; -this.radDiagram1.ConnectionTargetShapeIdMember = "TargetTaskId"; -this.radDiagram1.ConnectionSourceCapTypeMember = "StartCapField"; -this.radDiagram1.ConnectionTargetCapTypeMember = "EndCapField"; - -this.radDiagram1.ConnectionSourceConnectorMember = "SourceConnector"; -this.radDiagram1.ConnectionTargetConnectorMember = "TargetConnector"; - -```` -````VB.NET -Me.radDiagram1.DataSource = New Source() -Me.radDiagram1.ConnectionDataMember = "Relations" -Me.radDiagram1.ShapeDataMember = "Tasks" -Me.radDiagram1.ShapeIdMember = "Id" -Me.radDiagram1.ShapeTextMember = "Text" -Me.radDiagram1.ShapeTypeMember = "Type" -Me.radDiagram1.ShapeXMember = "X" -Me.radDiagram1.ShapeYMember = "Y" -Me.radDiagram1.ShapeWidthMember = "Width" -Me.radDiagram1.ShapeHeightMember = "Height" -Me.radDiagram1.ConnectionSourceShapeIdMember = "SourceTaskId" -Me.radDiagram1.ConnectionTargetShapeIdMember = "TargetTaskId" -Me.radDiagram1.ConnectionSourceCapTypeMember = "StartCapField" -Me.radDiagram1.ConnectionTargetCapTypeMember = "EndCapField" -Me.radDiagram1.ConnectionSourceConnectorMember = "SourceConnector" -Me.radDiagram1.ConnectionTargetConnectorMember = "TargetConnector" - -```` + + -{{endregion}} ![WinForms RadDiagram DataBinding Custom Objects](images/diagram-data-binding-binding-to-custom-objects001.png) diff --git a/controls/diagram/data-binding/data-binding-basics.md b/controls/diagram/data-binding/data-binding-basics.md index 6fb591089..facb5411f 100644 --- a/controls/diagram/data-binding/data-binding-basics.md +++ b/controls/diagram/data-binding/data-binding-basics.md @@ -58,108 +58,9 @@ In this article you can check how to data bind __RadDiagram__. To make data bind * __ConnectionTargetConnectorMember__ – set this to the name of the field that will be used as connector for the target shape for a connection. -{{source=..\SamplesCS\Diagram\DiagramDataBinding.cs region=DataTable}} -{{source=..\SamplesVB\Diagram\DiagramDataBinding.vb region=DataTable}} + + -````C# - -DataTable tasksTable = new DataTable("Tasks"); -tasksTable.Columns.Add("Id"); -tasksTable.Columns.Add("Text"); -tasksTable.Columns.Add("Type"); -tasksTable.Columns.Add("X"); -tasksTable.Columns.Add("Y"); -tasksTable.Columns.Add("Width"); -tasksTable.Columns.Add("Height"); -tasksTable.Rows.Add("Task1", "Task 1", "circle", 100, 300, 50, 50); -tasksTable.Rows.Add("Task2", "Task 2", "rectangle", 200, 100, 100, 100); -tasksTable.Rows.Add("Task3", "Task 3", "circle", 300, 300, 50, 50); -tasksTable.Rows.Add("Task4", "Task 4", "rectangle", 400, 100, 100, 100); -tasksTable.Rows.Add("Task5", "Task 5", "circle", 500, 300, 50, 50); - -DataTable relationsTable = new DataTable("Relations"); -relationsTable.Columns.Add("SourceTaskId"); -relationsTable.Columns.Add("SourceConnector"); -relationsTable.Columns.Add("TargetTaskId"); -relationsTable.Columns.Add("TargetConnector"); -relationsTable.Columns.Add("StartCapField"); -relationsTable.Columns.Add("EndCapField"); -relationsTable.Rows.Add("Task2", "Left", "Task1", "Auto", "Arrow5Filled", "Arrow1"); -relationsTable.Rows.Add("Task2", "Auto", "Task3", "Auto", "Arrow4Filled", "Arrow1Filled"); -relationsTable.Rows.Add("Task4", "Auto", "Task5", "Auto", "Arrow2Filled", "Arrow2"); - -DataSet ds = new DataSet(); -ds.Tables.Add(tasksTable); -ds.Tables.Add(relationsTable); - -this.radDiagram1.DataSource = ds; - -this.radDiagram1.ConnectionDataMember = "Relations"; -this.radDiagram1.ShapeDataMember = "Tasks"; -this.radDiagram1.ShapeIdMember = "Id"; -this.radDiagram1.ShapeTextMember = "Text"; -this.radDiagram1.ShapeTypeMember = "Type"; -this.radDiagram1.ShapeXMember = "X"; -this.radDiagram1.ShapeYMember = "Y"; -this.radDiagram1.ShapeWidthMember = "Width"; -this.radDiagram1.ShapeHeightMember = "Height"; - -this.radDiagram1.ConnectionSourceShapeIdMember = "SourceTaskId"; -this.radDiagram1.ConnectionTargetShapeIdMember = "TargetTaskId"; -this.radDiagram1.ConnectionSourceCapTypeMember = "StartCapField"; -this.radDiagram1.ConnectionTargetCapTypeMember = "EndCapField"; - -this.radDiagram1.ConnectionSourceConnectorMember = "SourceConnector"; -this.radDiagram1.ConnectionTargetConnectorMember = "TargetConnector"; - -```` -````VB.NET -Dim tasksTable As New DataTable("Tasks") -tasksTable.Columns.Add("Id") -tasksTable.Columns.Add("Text") -tasksTable.Columns.Add("Type") -tasksTable.Columns.Add("X") -tasksTable.Columns.Add("Y") -tasksTable.Columns.Add("Width") -tasksTable.Columns.Add("Height") -tasksTable.Rows.Add("Task1", "Task 1", "circle", 100, 300, 50, 50) -tasksTable.Rows.Add("Task2", "Task 2", "rectangle", 200, 100, 100, 100) -tasksTable.Rows.Add("Task3", "Task 3", "circle", 300, 300, 50, 50) -tasksTable.Rows.Add("Task4", "Task 4", "rectangle", 400, 100, 100, 100) -tasksTable.Rows.Add("Task5", "Task 5", "circle", 500, 300, 50, 50) -Dim relationsTable As New DataTable("Relations") -relationsTable.Columns.Add("SourceTaskId") -relationsTable.Columns.Add("SourceConnector") -relationsTable.Columns.Add("TargetTaskId") -relationsTable.Columns.Add("TargetConnector") -relationsTable.Columns.Add("StartCapField") -relationsTable.Columns.Add("EndCapField") -relationsTable.Rows.Add("Task2", "Left", "Task1", "Auto", "Arrow5Filled", "Arrow1") -relationsTable.Rows.Add("Task2", "Auto", "Task3", "Auto", "Arrow4Filled", "Arrow1Filled") -relationsTable.Rows.Add("Task4", "Auto", "Task5", "Auto", "Arrow2Filled", "Arrow2") -Dim ds As New DataSet() -ds.Tables.Add(tasksTable) -ds.Tables.Add(relationsTable) -Me.RadDiagram1.DataSource = ds -Me.RadDiagram1.ConnectionDataMember = "Relations" -Me.RadDiagram1.ShapeDataMember = "Tasks" -Me.RadDiagram1.ShapeIdMember = "Id" -Me.RadDiagram1.ShapeTextMember = "Text" -Me.RadDiagram1.ShapeTypeMember = "Type" -Me.RadDiagram1.ShapeXMember = "X" -Me.RadDiagram1.ShapeYMember = "Y" -Me.RadDiagram1.ShapeWidthMember = "Width" -Me.RadDiagram1.ShapeHeightMember = "Height" -Me.RadDiagram1.ConnectionSourceShapeIdMember = "SourceTaskId" -Me.RadDiagram1.ConnectionTargetShapeIdMember = "TargetTaskId" -Me.RadDiagram1.ConnectionSourceCapTypeMember = "StartCapField" -Me.RadDiagram1.ConnectionTargetCapTypeMember = "EndCapField" -Me.RadDiagram1.ConnectionSourceConnectorMember = "SourceConnector" -Me.RadDiagram1.ConnectionTargetConnectorMember = "TargetConnector" - -```` - -{{endregion}} ![WinForms RadDiagram Data Binding Basics](images/diagram-data-binding-basics001.png) diff --git a/controls/diagram/diagram-factory.md b/controls/diagram/diagram-factory.md index 25fa93642..a03937e4c 100644 --- a/controls/diagram/diagram-factory.md +++ b/controls/diagram/diagram-factory.md @@ -14,203 +14,11 @@ Since **R2 2018 SP1** **RadDiagram** provides means for changing the default sha If you need to customize any of the **RadDiagram** shapes/connections you can use the **DiagramDataLayerElementProvider** class. It allows you to replace the default elements with custom ones. This can be achieved by creating a **DiagramDataLayerElementProvider** descendant class and overriding the **CreateShape** and **CreateConnection** methods. Then, set the DiagramElement.DataLayer.ElementFactory property before data binding. -{{source=..\SamplesCS\Diagram\DiagramCustomFactory.cs region=CustomElementProvider}} -{{source=..\SamplesVB\Diagram\DiagramCustomFactory.vb region=CustomElementProvider}} + + -````C# - -public partial class DiagramCustomFactory : Form -{ - public DiagramCustomFactory() - { - InitializeComponent(); - - this.radDiagram1.DiagramElement.DataLayer.ElementFactory = new CustomDiagramDataLayerElementProvider(); - - Bind(); - - foreach (MyCustomShape shape in this.radDiagram1.Shapes) - { - Console.WriteLine(shape.CreatedOn); - } - - foreach (MyCustomRadDiagramConnection connection in this.radDiagram1.Connections) - { - Console.WriteLine(connection.CreatedOn); - } - } - - private void Bind() - { - DataTable tasksTable = new DataTable("Tasks"); - tasksTable.Columns.Add("Id"); - tasksTable.Columns.Add("Text"); - tasksTable.Columns.Add("Type"); - tasksTable.Columns.Add("X"); - tasksTable.Columns.Add("Y"); - tasksTable.Columns.Add("Width"); - tasksTable.Columns.Add("Height"); - tasksTable.Rows.Add("Task1", "Task 1", "circle", 100, 300, 50, 50); - tasksTable.Rows.Add("Task2", "Task 2", "rectangle", 200, 100, 100, 100); - tasksTable.Rows.Add("Task3", "Task 3", "circle", 300, 300, 50, 50); - tasksTable.Rows.Add("Task4", "Task 4", "rectangle", 400, 100, 100, 100); - tasksTable.Rows.Add("Task5", "Task 5", "circle", 500, 300, 50, 50); - - DataTable relationsTable = new DataTable("Relations"); - relationsTable.Columns.Add("SourceTaskId"); - relationsTable.Columns.Add("SourceConnector"); - relationsTable.Columns.Add("TargetTaskId"); - relationsTable.Columns.Add("TargetConnector"); - relationsTable.Columns.Add("StartCapField"); - relationsTable.Columns.Add("EndCapField"); - relationsTable.Rows.Add("Task2", "Left", "Task1", "Auto", "Arrow5Filled", "Arrow1"); - relationsTable.Rows.Add("Task2", "Auto", "Task3", "Auto", "Arrow4Filled", "Arrow1Filled"); - relationsTable.Rows.Add("Task4", "Auto", "Task5", "Auto", "Arrow2Filled", "Arrow2"); - - DataSet ds = new DataSet(); - ds.Tables.Add(tasksTable); - ds.Tables.Add(relationsTable); - - this.radDiagram1.DataSource = ds; - - this.radDiagram1.ConnectionDataMember = "Relations"; - this.radDiagram1.ShapeDataMember = "Tasks"; - this.radDiagram1.ShapeIdMember = "Id"; - this.radDiagram1.ShapeTextMember = "Text"; - this.radDiagram1.ShapeTypeMember = "Type"; - this.radDiagram1.ShapeXMember = "X"; - this.radDiagram1.ShapeYMember = "Y"; - this.radDiagram1.ShapeWidthMember = "Width"; - this.radDiagram1.ShapeHeightMember = "Height"; - - this.radDiagram1.ConnectionSourceShapeIdMember = "SourceTaskId"; - this.radDiagram1.ConnectionTargetShapeIdMember = "TargetTaskId"; - this.radDiagram1.ConnectionSourceCapTypeMember = "StartCapField"; - this.radDiagram1.ConnectionTargetCapTypeMember = "EndCapField"; - - this.radDiagram1.ConnectionSourceConnectorMember = "SourceConnector"; - this.radDiagram1.ConnectionTargetConnectorMember = "TargetConnector"; - } -} - -public class MyCustomShape : RadDiagramShape -{ - public DateTime CreatedOn { get; set; } - - public MyCustomShape() - { - this.CreatedOn = DateTime.Now; - } -} - -public class MyCustomRadDiagramConnection : RadDiagramConnection -{ - public DateTime CreatedOn { get; set; } - - public MyCustomRadDiagramConnection() - { - this.CreatedOn = DateTime.Now; - } -} - -public class CustomDiagramDataLayerElementProvider : DiagramDataLayerElementProvider -{ - public override RadDiagramShape CreateShape() - { - return new MyCustomShape(); - } - - public override RadDiagramConnection CreateConnection() - { - return new MyCustomRadDiagramConnection(); - } -} -```` -````VB.NET -Sub New() - InitializeComponent() - Me.RadDiagram1.DiagramElement.DataLayer.ElementFactory = New CustomDiagramDataLayerElementProvider() - Bind() - For Each shape As MyCustomShape In Me.RadDiagram1.Shapes - Console.WriteLine(shape.CreatedOn) - Next - For Each connection As MyCustomRadDiagramConnection In Me.RadDiagram1.Connections - Console.WriteLine(connection.CreatedOn) - Next -End Sub -Private Sub Bind() - Dim tasksTable As DataTable = New DataTable("Tasks") - tasksTable.Columns.Add("Id") - tasksTable.Columns.Add("Text") - tasksTable.Columns.Add("Type") - tasksTable.Columns.Add("X") - tasksTable.Columns.Add("Y") - tasksTable.Columns.Add("Width") - tasksTable.Columns.Add("Height") - tasksTable.Rows.Add("Task1", "Task 1", "circle", 100, 300, 50, 50) - tasksTable.Rows.Add("Task2", "Task 2", "rectangle", 200, 100, 100, 100) - tasksTable.Rows.Add("Task3", "Task 3", "circle", 300, 300, 50, 50) - tasksTable.Rows.Add("Task4", "Task 4", "rectangle", 400, 100, 100, 100) - tasksTable.Rows.Add("Task5", "Task 5", "circle", 500, 300, 50, 50) - Dim relationsTable As DataTable = New DataTable("Relations") - relationsTable.Columns.Add("SourceTaskId") - relationsTable.Columns.Add("SourceConnector") - relationsTable.Columns.Add("TargetTaskId") - relationsTable.Columns.Add("TargetConnector") - relationsTable.Columns.Add("StartCapField") - relationsTable.Columns.Add("EndCapField") - relationsTable.Rows.Add("Task2", "Left", "Task1", "Auto", "Arrow5Filled", "Arrow1") - relationsTable.Rows.Add("Task2", "Auto", "Task3", "Auto", "Arrow4Filled", "Arrow1Filled") - relationsTable.Rows.Add("Task4", "Auto", "Task5", "Auto", "Arrow2Filled", "Arrow2") - Dim ds As DataSet = New DataSet() - ds.Tables.Add(tasksTable) - ds.Tables.Add(relationsTable) - Me.RadDiagram1.DataSource = ds - Me.RadDiagram1.ConnectionDataMember = "Relations" - Me.RadDiagram1.ShapeDataMember = "Tasks" - Me.RadDiagram1.ShapeIdMember = "Id" - Me.RadDiagram1.ShapeTextMember = "Text" - Me.RadDiagram1.ShapeTypeMember = "Type" - Me.RadDiagram1.ShapeXMember = "X" - Me.RadDiagram1.ShapeYMember = "Y" - Me.RadDiagram1.ShapeWidthMember = "Width" - Me.RadDiagram1.ShapeHeightMember = "Height" - Me.RadDiagram1.ConnectionSourceShapeIdMember = "SourceTaskId" - Me.RadDiagram1.ConnectionTargetShapeIdMember = "TargetTaskId" - Me.RadDiagram1.ConnectionSourceCapTypeMember = "StartCapField" - Me.RadDiagram1.ConnectionTargetCapTypeMember = "EndCapField" - Me.RadDiagram1.ConnectionSourceConnectorMember = "SourceConnector" - Me.RadDiagram1.ConnectionTargetConnectorMember = "TargetConnector" -End Sub -Class -ic Class MyCustomShape -rits RadDiagramShape -Public Property CreatedOn As DateTime -Public Sub New() - Me.CreatedOn = DateTime.Now -End Sub -Class -ic Class MyCustomRadDiagramConnection -rits RadDiagramConnection -Public Property CreatedOn As DateTime -Public Sub New() - Me.CreatedOn = DateTime.Now -End Sub -Class -ic Class CustomDiagramDataLayerElementProvider -rits DiagramDataLayerElementProvider -Public Overrides Function CreateShape() As RadDiagramShape - Return New MyCustomShape() -End Function -Public Overrides Function CreateConnection() As RadDiagramConnection - Return New MyCustomRadDiagramConnection() -End Function -Class -```` - -{{endregion}} # See Also diff --git a/controls/diagram/diagram-items/connections/cap-types.md b/controls/diagram/diagram-items/connections/cap-types.md index 69b635b78..ac82747ca 100644 --- a/controls/diagram/diagram-items/connections/cap-types.md +++ b/controls/diagram/diagram-items/connections/cap-types.md @@ -16,22 +16,10 @@ __CapType__ enumeration members: ![WinForms RadDiagram CapType Enumeration Members](images/diagram-diagram-items-connections012.png) -{{source=..\SamplesCS\Diagram\DiagramItems.cs region=CapTypeNone}} -{{source=..\SamplesVB\Diagram\DiagramItems.vb region=CapTypeNone}} + + -````C# - -connection1.SourceCapType = Telerik.Windows.Diagrams.Core.CapType.None; -connection1.TargetCapType = Telerik.Windows.Diagrams.Core.CapType.None; -```` -````VB.NET -connection1.SourceCapType = Telerik.Windows.Diagrams.Core.CapType.None -connection1.TargetCapType = Telerik.Windows.Diagrams.Core.CapType.None - -```` - -{{endregion}} @@ -40,21 +28,10 @@ connection1.TargetCapType = Telerik.Windows.Diagrams.Core.CapType.None ![WinForms RadDiagram Arrow1](images/diagram-diagram-items-connections013.png) -{{source=..\SamplesCS\Diagram\DiagramItems.cs region=CapTypeArrow1}} -{{source=..\SamplesVB\Diagram\DiagramItems.vb region=CapTypeArrow1}} - -````C# -connection1.SourceCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow1; -connection1.TargetCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow1; + + -```` -````VB.NET -connection1.SourceCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow1 -connection1.TargetCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow1 -```` - -{{endregion}} * __Arrow1Filled__: @@ -62,109 +39,52 @@ connection1.TargetCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow1 ![WinForms RadDiagram Arrow1Filled](images/diagram-diagram-items-connections014.png) -{{source=..\SamplesCS\Diagram\DiagramItems.cs region=CapTypeArrow1Filled}} -{{source=..\SamplesVB\Diagram\DiagramItems.vb region=CapTypeArrow1Filled}} - -````C# - -connection1.SourceCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow1Filled; -connection1.TargetCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow1Filled; - -```` -````VB.NET -connection1.SourceCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow1Filled -connection1.TargetCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow1Filled + + -```` -{{endregion}} * __Arrow2__: ![WinForms RadDiagram Arrow2](images/diagram-diagram-items-connections015.png) -{{source=..\SamplesCS\Diagram\DiagramItems.cs region=CapTypeArrow2}} -{{source=..\SamplesVB\Diagram\DiagramItems.vb region=CapTypeArrow2}} + + -````C# - -connection1.SourceCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow2; -connection1.TargetCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow2; -```` -````VB.NET -connection1.SourceCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow2 -connection1.TargetCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow2 - -```` - -{{endregion}} * __Arrow2Filled__: ![WinForms RadDiagram Arrow2Filled](images/diagram-diagram-items-connections016.png) -{{source=..\SamplesCS\Diagram\DiagramItems.cs region=CapTypeArrow2Filled}} -{{source=..\SamplesVB\Diagram\DiagramItems.vb region=CapTypeArrow2Filled}} - -````C# -connection1.SourceCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow2Filled; -connection1.TargetCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow2Filled; + + -```` -````VB.NET -connection1.SourceCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow2Filled -connection1.TargetCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow2Filled -```` -{{endregion}} * __Arrow3__: ![WinForms RadDiagram Arrow3](images/diagram-diagram-items-connections017.png) -{{source=..\SamplesCS\Diagram\DiagramItems.cs region=CapTypeArrow3}} -{{source=..\SamplesVB\Diagram\DiagramItems.vb region=CapTypeArrow3}} + + -````C# - -connection1.SourceCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow3; -connection1.TargetCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow3; -```` -````VB.NET -connection1.SourceCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow3 -connection1.TargetCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow3 -```` - -{{endregion}} * __Arrow4__: ![WinForms RadDiagram Arrow4](images/diagram-diagram-items-connections018.png) -{{source=..\SamplesCS\Diagram\DiagramItems.cs region=CapTypeArrow4}} -{{source=..\SamplesVB\Diagram\DiagramItems.vb region=CapTypeArrow4}} - -````C# - -connection1.SourceCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow4; -connection1.TargetCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow4; + + -```` -````VB.NET -connection1.SourceCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow4 -connection1.TargetCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow4 -```` - -{{endregion}} * __Arrow4Filled__: @@ -172,87 +92,39 @@ connection1.TargetCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow4 ![WinForms RadDiagram Arrow4Filled](images/diagram-diagram-items-connections019.png) -{{source=..\SamplesCS\Diagram\DiagramItems.cs region=CapTypeArrow4Filled}} -{{source=..\SamplesVB\Diagram\DiagramItems.vb region=CapTypeArrow4Filled}} - -````C# - -connection1.SourceCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow4Filled; -connection1.TargetCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow4Filled; - -```` -````VB.NET -connection1.SourceCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow4Filled -connection1.TargetCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow4Filled + + -```` -{{endregion}} * __Arrow5__: ![WinForms RadDiagram Arrow5](images/diagram-diagram-items-connections020.png) -{{source=..\SamplesCS\Diagram\DiagramItems.cs region=CapTypeArrow5}} -{{source=..\SamplesVB\Diagram\DiagramItems.vb region=CapTypeArrow5}} + + -````C# - -connection1.SourceCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow5; -connection1.TargetCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow5; -```` -````VB.NET -connection1.SourceCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow5 -connection1.TargetCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow5 - -```` - -{{endregion}} * __Arrow5Filled__: ![WinForms RadDiagram Arrow5Filled](images/diagram-diagram-items-connections021.png) -{{source=..\SamplesCS\Diagram\DiagramItems.cs region=CapTypeArrow5Filled}} -{{source=..\SamplesVB\Diagram\DiagramItems.vb region=CapTypeArrow5Filled}} - -````C# - -connection1.SourceCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow5Filled; -connection1.TargetCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow5Filled; + + -```` -````VB.NET -connection1.SourceCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow5Filled -connection1.TargetCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow5Filled -```` - -{{endregion}} * __Arrow6__: ![WinForms RadDiagram Arrow6](images/diagram-diagram-items-connections022.png) -{{source=..\SamplesCS\Diagram\DiagramItems.cs region=CapTypeArrow6}} -{{source=..\SamplesVB\Diagram\DiagramItems.vb region=CapTypeArrow6}} - -````C# - -connection1.SourceCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow6; -connection1.TargetCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow6; - -```` -````VB.NET -connection1.SourceCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow6 -connection1.TargetCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow6 + + -```` -{{endregion}} @@ -261,19 +133,7 @@ connection1.TargetCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow6 ![WinForms RadDiagram Arrow6Filled](images/diagram-diagram-items-connections023.png) -{{source=..\SamplesCS\Diagram\DiagramItems.cs region=CapTypeArrow6Filled}} -{{source=..\SamplesVB\Diagram\DiagramItems.vb region=CapTypeArrow6Filled}} - -````C# - -connection1.SourceCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow6Filled; -connection1.TargetCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow6Filled; - -```` -````VB.NET -connection1.SourceCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow6Filled -connection1.TargetCapType = Telerik.Windows.Diagrams.Core.CapType.Arrow6Filled + + -```` -{{endregion}} diff --git a/controls/diagram/diagram-items/connections/connection-types.md b/controls/diagram/diagram-items/connections/connection-types.md index 1ace18278..bc1d423ca 100644 --- a/controls/diagram/diagram-items/connections/connection-types.md +++ b/controls/diagram/diagram-items/connections/connection-types.md @@ -12,31 +12,10 @@ position: 1 * __ConnectionPoints__ - if you want to change the route of the connection, you can add connection points in code-behind through the RadDiagramConnection.__ConnectionPoints__ property. You can populate the __ConnectionPoints__ collection with objects of type *Point*: -{{source=..\SamplesCS\Diagram\DiagramItems.cs region=AddConnection}} -{{source=..\SamplesVB\Diagram\DiagramItems.vb region=AddConnection}} + + -````C# - -RadDiagramConnection connection1 = new RadDiagramConnection() { Name = "connection1" }; - -connection1.Source = shape1; -connection1.Target = starShape; -connection1.ConnectionPoints.Add(new Point(200, 30)); -radDiagram1.Items.Add(connection1); - -```` -````VB.NET -Dim connection1 As New RadDiagramConnection() With { _ - .Name = "connection1" _ -} -connection1.Source = shape1 -connection1.Target = starShape -connection1.ConnectionPoints.Add(New Point(200, 30)) -RadDiagram1.Items.Add(connection1) -```` - -{{endregion}} ![WinForms RadDiagram Connection Types](images/diagram-diagram-items-connections002.png) @@ -53,86 +32,19 @@ RadDiagram1.Items.Add(connection1) ![WinForms RadDiagram Polyline](images/diagram-diagram-items-connections003.png) -{{source=..\SamplesCS\Diagram\DiagramItems.cs region=PolylineConnection}} -{{source=..\SamplesVB\Diagram\DiagramItems.vb region=PolylineConnection}} + + -````C# - -RadDiagramShape sourceShape = new RadDiagramShape() -{ - Text = "source", - Shape = new RoundRectShape(5), - BackColor = Color.Red -}; - -sourceShape.Position = new Telerik.Windows.Diagrams.Core.Point(150, 100); -radDiagram1.AddShape(sourceShape); - -RadDiagramShape targetShape = new RadDiagramShape() -{ - Text = "target", - Shape = new RoundRectShape(5), - BackColor = Color.Red -}; - -targetShape.Position = new Telerik.Windows.Diagrams.Core.Point(400, 300); -radDiagram1.AddShape(targetShape); - -RadDiagramConnection polylineConnection = new RadDiagramConnection() { Name = "connection1" }; - -polylineConnection.Source = sourceShape; -polylineConnection.Target = targetShape; -polylineConnection.ConnectionType = Telerik.Windows.Diagrams.Core.ConnectionType.Polyline; -radDiagram1.AddShape(polylineConnection); - -```` -````VB.NET -Dim sourceShape As New RadDiagramShape() With { _ - .Text = "source", _ - .Shape = New RoundRectShape(5), _ - .BackColor = Color.Red _ -} -sourceShape.Position = New Telerik.Windows.Diagrams.Core.Point(150, 100) -RadDiagram1.AddShape(sourceShape) -Dim targetShape As New RadDiagramShape() With { _ - .Text = "target", _ - .Shape = New RoundRectShape(5), _ - .BackColor = Color.Red _ -} -targetShape.Position = New Telerik.Windows.Diagrams.Core.Point(400, 300) -RadDiagram1.AddShape(targetShape) -Dim polylineConnection As New RadDiagramConnection() With { _ - .Name = "connection1" _ -} -polylineConnection.Source = sourceShape -polylineConnection.Target = targetShape -polylineConnection.ConnectionType = Telerik.Windows.Diagrams.Core.ConnectionType.Polyline -RadDiagram1.Items.Add(polylineConnection) - -```` - -{{endregion}} -If you want to change the route of the connection, you can add connection points in code-behind through the RadDiagramConnection.__ConnectionPoints__ property. You can populate the __ConnectionPoints__ collection with objects of type Point: +If you want to change the route of the connection, you can add connection points in code-behind through the RadDiagramConnection.__ConnectionPoints__ property. You can populate the __ConnectionPoints__ collection with objects of type Point: -{{source=..\SamplesCS\Diagram\DiagramItems.cs region=ConnectionPolylineWithPoints}} -{{source=..\SamplesVB\Diagram\DiagramItems.vb region=ConnectionPolylineWithPoints}} - -````C# - -polylineConnection.ConnectionPoints.Add(new Point(300, 140)); -polylineConnection.ConnectionPoints.Add(new Point(330, 280)); -```` -````VB.NET -polylineConnection.ConnectionPoints.Add(New Point(300, 140)) -polylineConnection.ConnectionPoints.Add(New Point(330, 280)) + + -```` -{{endregion}} Sample of a curved Polyline connection: @@ -145,33 +57,10 @@ Sample of a curved Polyline connection: ![WinForms RadDiagram BezierTension Option](images/diagram-diagram-items-connections006.png) -{{source=..\SamplesCS\Diagram\DiagramItems.cs region=BezierConnection}} -{{source=..\SamplesVB\Diagram\DiagramItems.vb region=BezierConnection}} - -````C# - -RadDiagramConnection bezierConnection = new RadDiagramConnection() { Name = "connection1" }; - -bezierConnection.Source = sourceShape; -bezierConnection.Target = targetShape; -bezierConnection.BezierTension = 16; -bezierConnection.ConnectionType = Telerik.Windows.Diagrams.Core.ConnectionType.Bezier; -radDiagram1.Items.Add(bezierConnection); - -```` -````VB.NET -Dim bezierConnection As New RadDiagramConnection() With { _ - .Name = "connection1" _ -} -bezierConnection.Source = sourceShape -bezierConnection.Target = targetShape -bezierConnection.BezierTension = 16 -bezierConnection.ConnectionType = Telerik.Windows.Diagrams.Core.ConnectionType.Bezier -RadDiagram1.Items.Add(bezierConnection) + + -```` -{{endregion}} By default, when you create a Bezier connection and attach its endpoints to __RadDiagramShapes__, the position of the handle points of the connection will be calculated based on the connector positions. Both handle points will be added to the RadDiagramConnection.__ConnectionPoints__ collection. The following snapshot illustrates the default direction of the Bezier connection handles based on the position of the connector to which the connection is attached. @@ -193,34 +82,7 @@ The offset between a Bezier connection handle point and its corresponding endpoi ![WinForms RadDiagram Spline Connection Type](images/diagram-diagram-items-connections008.png) -{{source=..\SamplesCS\Diagram\DiagramItems.cs region=SplineConnection}} -{{source=..\SamplesVB\Diagram\DiagramItems.vb region=SplineConnection}} + + + -````C# - -RadDiagramConnection splineConnection = new RadDiagramConnection() { Name = "connection1" }; - -splineConnection.Source = sourceShape; -splineConnection.Target = targetShape; -splineConnection.ConnectionType = Telerik.Windows.Diagrams.Core.ConnectionType.Spline; -splineConnection.ConnectionPoints.Add(new Point(140, 20)); -splineConnection.ConnectionPoints.Add(new Point(250, 150)); -splineConnection.ConnectionPoints.Add(new Point(350, 50)); -radDiagram1.Items.Add(splineConnection); - -```` -````VB.NET -Dim splineConnection As New RadDiagramConnection() With { _ - .Name = "connection1" _ -} -splineConnection.Source = sourceShape -splineConnection.Target = targetShape -splineConnection.ConnectionType = Telerik.Windows.Diagrams.Core.ConnectionType.Spline -splineConnection.ConnectionPoints.Add(New Point(140, 20)) -splineConnection.ConnectionPoints.Add(New Point(250, 150)) -splineConnection.ConnectionPoints.Add(New Point(350, 50)) -RadDiagram1.Items.Add(splineConnection) - -```` - -{{endregion}} diff --git a/controls/diagram/diagram-items/connections/connections.md b/controls/diagram/diagram-items/connections/connections.md index b2edd162c..e9cce2c98 100644 --- a/controls/diagram/diagram-items/connections/connections.md +++ b/controls/diagram/diagram-items/connections/connections.md @@ -69,20 +69,10 @@ You can label a connection by setting its __Content__ property. ![WinForms RadDiagram Set Content](images/diagram-diagram-items-connections024.png) -{{source=..\SamplesCS\Diagram\DiagramItems.cs region=Content}} -{{source=..\SamplesVB\Diagram\DiagramItems.vb region=Content}} + + -````C# - -connection1.Content = "connection label"; - -```` -````VB.NET -connection1.Content = "connection label" -```` - -{{endregion}} ## Customize the Connection Appearance @@ -93,39 +83,20 @@ You can easily customize the visual appearance of the __RadDiagramConnection__ b ![WinForms RadDiagram Connection BackColor](images/diagram-diagram-items-connections025.png) -{{source=..\SamplesCS\Diagram\DiagramItems.cs region=ConnectionBackColor}} -{{source=..\SamplesVB\Diagram\DiagramItems.vb region=ConnectionBackColor}} + + -````C# - -connection1.BackColor = Color.Red; -```` -````VB.NET -connection1.BackColor = Color.Red - -```` - -{{endregion}} * __StrokeThickness__: gets or sets the width of the __RadDiagramConnection__ outline. ![WinForms RadDiagram Connection StrokeThickness](images/diagram-diagram-items-connections026.png) -{{source=..\SamplesCS\Diagram\DiagramItems.cs region=StrokeThickness}} -{{source=..\SamplesVB\Diagram\DiagramItems.vb region=StrokeThickness}} - -````C# -connection1.StrokeThickness = 5; + + -```` -````VB.NET -connection1.StrokeThickness = 5 -```` - -{{endregion}} @@ -134,43 +105,19 @@ connection1.StrokeThickness = 5 ![WinForms RadDiagram Connection ForeColor](images/diagram-diagram-items-connections027.png) -{{source=..\SamplesCS\Diagram\DiagramItems.cs region=ConnectionForeColor}} -{{source=..\SamplesVB\Diagram\DiagramItems.vb region=ConnectionForeColor}} - -````C# - -connection1.ForeColor = Color.Blue; - -```` -````VB.NET -connection1.ForeColor = Color.Blue + + -```` -{{endregion}} * __StrokeDashArray__: gets or sets a collection of Double values that indicate the pattern of dashes and gaps that is used to outline the __RadDiagramConnection__. -{{source=..\SamplesCS\Diagram\DiagramItems.cs region=StrokeDashArray}} -{{source=..\SamplesVB\Diagram\DiagramItems.vb region=StrokeDashArray}} - -````C# -connection1.StrokeDashArray = new Telerik.WinControls.UI.Diagrams.DoubleCollection(new List { 2, 2, 2, 2 }); - -```` -````VB.NET -connection1.StrokeDashArray = New Telerik.WinControls.UI.Diagrams.DoubleCollection(New List(Of Single)() From { _ - 2, _ - 2, _ - 2, _ - 2 _ -}) + + -```` -{{endregion}} ![WinForms RadDiagram Connection StrokeDashArray](images/diagram-diagram-items-connections029.png) diff --git a/controls/diagram/diagram-items/containershapes.md b/controls/diagram/diagram-items/containershapes.md index 1e043d9ae..e59d3cf86 100644 --- a/controls/diagram/diagram-items/containershapes.md +++ b/controls/diagram/diagram-items/containershapes.md @@ -32,24 +32,10 @@ A container can be connected and handled like other shapes. __RadDiagramContainerShape__ header is controlled via the __Content__ property: -{{source=..\SamplesCS\Diagram\DiagramItems.cs region=ContainersContent}} -{{source=..\SamplesVB\Diagram\DiagramItems.vb region=ContainersContent}} + + -````C# - -RadDiagramContainerShape container = new RadDiagramContainerShape(); -container.Content = "Container header"; -this.radDiagram1.Items.Add(container); - -```` -````VB.NET -Dim container As New RadDiagramContainerShape() -container.Content = "Container header" -Me.RadDiagram1.Items.Add(container) - -```` -{{endregion}} @@ -70,44 +56,10 @@ The main purpose of the __RadDiagramContainerShape__ is to allow you to drop sha You can also populate it manually in code-behind: -{{source=..\SamplesCS\Diagram\DiagramItems.cs region=ContainerItems}} -{{source=..\SamplesVB\Diagram\DiagramItems.vb region=ContainerItems}} + + + -````C# - -RadDiagramShape shape = new RadDiagramShape() -{ - Text = "Shape1", - Shape = new RoundRectShape(4), - BackColor = Color.LimeGreen -}; -shape.Position = new Telerik.Windows.Diagrams.Core.Point(100, 100); - -RadDiagramContainerShape containerShape = new RadDiagramContainerShape(); -containerShape.Content = "Container header"; -containerShape.Location = new Point(10,10); -containerShape.DrawBorder = true; -this.radDiagram1.Items.Add(containerShape); -containerShape.Items.Add(shape); - -```` -````VB.NET -Dim shape As New RadDiagramShape() With { _ - .Text = "Shape1", _ - .Shape = New RoundRectShape(4), _ - .BackColor = Color.LimeGreen _ -} -shape.Position = New Telerik.Windows.Diagrams.Core.Point(100, 100) -Dim containerShape As New RadDiagramContainerShape() -containerShape.Content = "Container header" -containerShape.Location = New Point(10, 10) -containerShape.DrawBorder = True -Me.RadDiagram1.Items.Add(containerShape) -containerShape.Items.Add(shape) - -```` - -{{endregion}} >caption Figure 3: RadDiagramContainerShape.Items @@ -168,24 +120,10 @@ You can easily customize the visual appearance of the __RadDiagramContainerShape #### RadDiagramContainerShape's appearance -{{source=..\SamplesCS\Diagram\DiagramItems.cs region=ContainerAppearance}} -{{source=..\SamplesVB\Diagram\DiagramItems.vb region=ContainerAppearance}} - -````C# - -container.BackColor = Color.Yellow; -container.BorderThickness = new Padding(3); -container.BorderBrush = new System.Drawing.SolidBrush(Color.Fuchsia); - -```` -````VB.NET -container.BackColor = Color.Yellow -container.BorderThickness = New System.Windows.Forms.Padding(3) -container.BorderBrush = New System.Drawing.SolidBrush(Color.Fuchsia) + + -```` -{{endregion}} diff --git a/controls/diagram/diagram-items/shapes.md b/controls/diagram/diagram-items/shapes.md index dfaaabb62..f5e052b43 100644 --- a/controls/diagram/diagram-items/shapes.md +++ b/controls/diagram/diagram-items/shapes.md @@ -23,63 +23,15 @@ __RadDiagramShape__ is an object that describes the nodes of the diagram. You ca ![WinForms RadDiagram Shape](images/diagram-diagram-items-shapes001.png) -{{source=..\SamplesCS\Diagram\DiagramItems.cs region=SetAShape}} -{{source=..\SamplesVB\Diagram\DiagramItems.vb region=SetAShape}} + + + + + + + + -````C# - -RadDiagramShape shape1 = new RadDiagramShape() -{ - Text = "", - Shape = new AShape(), - BackColor = Color.LimeGreen -}; -shape1.Position = new Telerik.Windows.Diagrams.Core.Point(100, 100); -radDiagram1.AddShape(shape1); - -```` -````VB.NET -Dim shape1 As New RadDiagramShape() With { _ - .Text = "", _ - .Shape = New AShape(), _ - .BackColor = Color.LimeGreen _ -} -shape1.Position = New Telerik.Windows.Diagrams.Core.Point(100, 100) -RadDiagram1.AddShape(shape1) - -```` - -{{endregion}} - -{{source=..\SamplesCS\Diagram\DiagramItems.cs region=AShape}} -{{source=..\SamplesVB\Diagram\DiagramItems.vb region=AShape}} - -````C# - -public class AShape : ElementShape -{ - public override GraphicsPath CreatePath(Rectangle bounds) - { - GraphicsPath path = new GraphicsPath(); - path.AddString("A", new FontFamily("Arial"), 0, 122, Point.Empty, StringFormat.GenericTypographic); - return path; - } -} - -```` -````VB.NET -Public Class AShape -Inherits ElementShape - Public Overrides Function CreatePath(bounds As Rectangle) As GraphicsPath - Dim path As New GraphicsPath() - path.AddString("A", New FontFamily("Arial"), 0, 122, Point.Empty, StringFormat.GenericTypographic) - Return path - End Function -End Class - -```` - -{{endregion}} @@ -88,33 +40,10 @@ or to use one of the pre-defined shapes: ![WinForms RadDiagram Pre-defined Shapes](images/diagram-diagram-items-shapes002.png) -{{source=..\SamplesCS\Diagram\DiagramItems.cs region=StarShape}} -{{source=..\SamplesVB\Diagram\DiagramItems.vb region=StarShape}} + + + -````C# - -RadDiagramShape starShape = new RadDiagramShape() -{ - Text = "", - Shape = new StarShape(), - BackColor = Color.LimeGreen -}; -starShape.Position = new Telerik.Windows.Diagrams.Core.Point(400, 100); -radDiagram1.AddShape(starShape); - -```` -````VB.NET -Dim starShape As New RadDiagramShape() With { _ - .Text = "", _ - .Shape = New StarShape(), _ - .BackColor = Color.LimeGreen _ -} -starShape.Position = New Telerik.Windows.Diagrams.Core.Point(100, 100) -RadDiagram1.AddShape(starShape) - -```` - -{{endregion}} >note A list of pre-defined shapes is available here: [Shapes](https://docs.telerik.com/devtools/winforms/controls/diagram/diagram-items/shapes) @@ -194,22 +123,10 @@ You can easily customize the visual appearance of the __RadDiagramShape__ by usi * __BorderBrush__- gets or sets the brush that specifies the __RadDiagramShape__ border color if the __DrawBorder__ property is set to *true*. -{{source=..\SamplesCS\Diagram\DiagramItems.cs region=ShapeBorder}} -{{source=..\SamplesVB\Diagram\DiagramItems.vb region=ShapeBorder}} + + -````C# - -shape1.BorderBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Red); -shape1.DrawBorder = true; - -```` -````VB.NET -shape1.BorderBrush = New System.Drawing.SolidBrush(System.Drawing.Color.Red) -shape1.DrawBorder = True -```` - -{{endregion}} @@ -219,26 +136,10 @@ shape1.DrawBorder = True * __StrokeDashArray__ - gets or sets a collection of Double values that indicate the pattern of dashes and gaps that is used to outline the __RadDiagramShape__. -{{source=..\SamplesCS\Diagram\DiagramItems.cs region=BorderStroke}} -{{source=..\SamplesVB\Diagram\DiagramItems.vb region=BorderStroke}} - -````C# - -shape.StrokeDashArray = new Telerik.WinControls.UI.Diagrams.DoubleCollection(new List { 2, 2, 2, 2 }); - -```` -````VB.NET - -shape.StrokeDashArray = New Telerik.WinControls.UI.Diagrams.DoubleCollection(New List(Of Single)() From { _ - 2, _ - 2, _ - 2, _ - 2 _ -}) + + -```` -{{endregion}} >caption Figure 6: StrokeDashArray diff --git a/controls/diagram/diagram-tools/text-tool.md b/controls/diagram/diagram-tools/text-tool.md index 55e48c889..57ae7aa5c 100644 --- a/controls/diagram/diagram-tools/text-tool.md +++ b/controls/diagram/diagram-tools/text-tool.md @@ -15,20 +15,9 @@ The __TextTool__ allows you to enter the edit mode of a __RadDiagramItem__ as so #### Active Tool -{{source=..\SamplesCS\Diagram\DiagramPopulatingWithData.cs region=ActiveTool}} -{{source=..\SamplesVB\Diagram\DiagramPopulatingWithData.vb region=ActiveTool}} + + -````C# - -this.radDiagram1.ActiveTool = Telerik.Windows.Diagrams.Core.MouseTool.TextTool; - -```` -````VB.NET -Me.RadDiagram1.ActiveTool = Telerik.Windows.Diagrams.Core.MouseTool.TextTool - -```` - -{{endregion}} Let's consider we already have a shape in __RadDiagram__. As soon as you click on the shape, you will enter its edit mode. This way you can easily modify its content. diff --git a/controls/diagram/drag-and-drop/drag-and-drop-from-another-control.md b/controls/diagram/drag-and-drop/drag-and-drop-from-another-control.md index 51f86e96c..e760812c8 100644 --- a/controls/diagram/drag-and-drop/drag-and-drop-from-another-control.md +++ b/controls/diagram/drag-and-drop/drag-and-drop-from-another-control.md @@ -22,319 +22,30 @@ The drag and drop behavior in __RadGridView__ is controlled by a service class. #### Setup RadGridView -{{source=..\SamplesCS\Diagram\DiagramDragAndDropGrid.cs region=SetupGrid}} -{{source=..\SamplesVB\Diagram\DiagramDragAndDropGrid.vb region=SetupGrid}} -````C# -public DiagramDragAndDropGrid() -{ - InitializeComponent(); - BaseGridBehavior gridBehavior = this.radGridView1.GridBehavior as BaseGridBehavior; - gridBehavior.UnregisterBehavior(typeof(GridViewDataRowInfo)); - gridBehavior.RegisterBehavior(typeof(GridViewDataRowInfo), new CustomRowGridBehavior()); - this.radGridView1.DataSource = this.GetData(); - this.radGridView1.AutoSizeColumnsMode = Telerik.WinControls.UI.GridViewAutoSizeColumnsMode.Fill; - RadGridViewDragDropService svc = this.radGridView1.GridViewElement.GetService(); - svc.PreviewDragDrop += svc_PreviewDragDrop; - svc.PreviewDragOver += svc_PreviewDragOver; - svc.PreviewDragStart += svc_PreviewDragStart; -} -private BindingList GetData() -{ - Color[] colors = new Color[] { Color.LightBlue, Color.LightGreen, Color.LightYellow, Color.LightCoral, Color.LightGray, Color.LightCyan }; - string[] shapes = new string[] { "RoundRect", "Diamond", "Star", "Heart", "Media", "Donut" }; - BindingList data = new BindingList(); - for (int i = 0; i < shapes.Length; i++) - { - data.Add(new GridModel - { - Id = i + 1, - Color = colors[i], - Shape = shapes[i] - }); - } - return data; -} + + -```` -````VB.NET -Sub New() - InitializeComponent() - Dim gridBehavior As BaseGridBehavior = TryCast(Me.RadGridView1.GridBehavior, BaseGridBehavior) - gridBehavior.UnregisterBehavior(GetType(GridViewDataRowInfo)) - gridBehavior.RegisterBehavior(GetType(GridViewDataRowInfo), New CustomRowGridBehavior()) - Me.RadGridView1.DataSource = Me.GetData() - Me.RadGridView1.AutoSizeColumnsMode = Telerik.WinControls.UI.GridViewAutoSizeColumnsMode.Fill - Dim svc As RadGridViewDragDropService = Me.RadGridView1.GridViewElement.GetService(Of RadGridViewDragDropService)() - AddHandler svc.PreviewDragDrop, AddressOf svc_PreviewDragDrop - AddHandler svc.PreviewDragOver, AddressOf svc_PreviewDragOver - AddHandler svc.PreviewDragStart, AddressOf svc_PreviewDragStart -End Sub -Private Function GetData() As BindingList(Of GridModel) - Dim colors As Color() = New Color() {Color.LightBlue, Color.LightGreen, Color.LightYellow, Color.LightCoral, Color.LightGray, Color.LightCyan} - Dim shapes As String() = New String() {"RoundRect", "Diamond", "Star", "Heart", "Media", "Donut"} - Dim data As New BindingList(Of GridModel)() - For i As Integer = 0 To shapes.Length - 1 - data.Add(New GridModel() With { - .Id = i + 1, - .Color = colors(i), - .Shape = shapes(i) - }) - Next - Return data -End Function -```` - - - -{{endregion}} For the purpose of the example we will define a grid model object storing information about the shapes. #### Grid Helpers -{{source=..\SamplesCS\Diagram\DiagramDragAndDropGrid.cs region=HelperClasses}} -{{source=..\SamplesVB\Diagram\DiagramDragAndDropGrid.vb region=HelperClasses}} -````C# -public class GridModel -{ - public int Id { get; set; } - public Color Color { get; set; } - public string Shape { get; set; } -} -public class CustomRowGridBehavior : GridDataRowBehavior -{ - protected override bool OnMouseDownLeft(MouseEventArgs e) - { - GridDataRowElement row = this.GetRowAtPoint(e.Location) as GridDataRowElement; - if (row != null) - { - RadGridViewDragDropService svc = this.GridViewElement.GetService(); - svc.Start(row); - } - return base.OnMouseDownLeft(e); - } -} - -```` -````VB.NET -Public Class GridModel - Public Property Id() As Integer - Get - Return m_Id - End Get - Set(value As Integer) - m_Id = value - End Set - End Property - Private m_Id As Integer - Public Property Color() As Color - Get - Return m_Color - End Get - Set(value As Color) - m_Color = value - End Set - End Property - Private m_Color As Color - Public Property Shape() As String - Get - Return m_Shape - End Get - Set(value As String) - m_Shape = value - End Set - End Property - Private m_Shape As String -End Class -Public Class CustomRowGridBehavior - Inherits GridDataRowBehavior - Protected Overrides Function OnMouseDownLeft(e As MouseEventArgs) As Boolean - Dim row As GridDataRowElement = TryCast(Me.GetRowAtPoint(e.Location), GridDataRowElement) - If row IsNot Nothing Then - Dim svc As RadGridViewDragDropService = Me.GridViewElement.GetService(Of RadGridViewDragDropService)() - svc.Start(row) - End If - Return MyBase.OnMouseDownLeft(e) - End Function -End Class - -```` + + -{{endregion}} - ## Handling Events __RadDiagram__ will accept the dragged data only if it is dropped on the diagram element. The __PreviewDragDrop__ event handler will be responsible for reading the data and transforming it to a shape. #### Drag and Drop Events -{{source=..\SamplesCS\Diagram\DiagramDragAndDropGrid.cs region=HandleEvents}} -{{source=..\SamplesVB\Diagram\DiagramDragAndDropGrid.vb region=HandleEvents}} -````C# -private void svc_PreviewDragStart(object sender, PreviewDragStartEventArgs e) -{ - e.CanStart = true; -} -private void svc_PreviewDragOver(object sender, RadDragOverEventArgs e) -{ - if (e.DragInstance is GridDataRowElement) - { - e.CanDrop = e.HitTarget is RadDiagramElement; - } -} -private void svc_PreviewDragDrop(object sender, RadDropEventArgs e) -{ - RadDiagramElement targetElement = e.HitTarget as RadDiagramElement; - GridDataRowElement draggedRow = e.DragInstance as GridDataRowElement; - if (draggedRow == null) - { - return; - } - GridModel data = (GridModel)draggedRow.Data.DataBoundItem; - RadDiagramShape shape = new RadDiagramShape() - { - Text = data.Shape, - ElementShape = this.GetShapeFromModel(data), - BackColor = data.Color - }; - shape.Position = e.DropLocation; - this.radDiagram1.AddShape(shape); -} -private ElementShape GetShapeFromModel(GridModel data) -{ - ElementShape shape = null; - switch (data.Shape) - { - case "RoundRect": - shape = new RoundRectShape(); - break; - case "Diamond": - shape = new DiamondShape(); - break; - case "Star": - shape = new StarShape(); - break; - case "Heart": - shape = new HeartShape(); - break; - case "Media": - shape = new MediaShape(); - break; - case "Donut": - shape = new DonutShape(); - break; - default: - shape = new CustomShape(); - break; - } - return shape; -} - -```` -````VB.NET -Private Sub svc_PreviewDragStart(sender As Object, e As PreviewDragStartEventArgs) - e.CanStart = True -End Sub -Private Sub svc_PreviewDragOver(sender As Object, e As RadDragOverEventArgs) - If TypeOf e.DragInstance Is GridDataRowElement Then - e.CanDrop = TypeOf e.HitTarget Is RadDiagramElement - End If -End Sub -Private Sub svc_PreviewDragDrop(sender As Object, e As RadDropEventArgs) - Dim targetElement As RadDiagramElement = TryCast(e.HitTarget, RadDiagramElement) - Dim draggedRow As GridDataRowElement = TryCast(e.DragInstance, GridDataRowElement) - If draggedRow Is Nothing Then - Return - End If - Dim data As GridModel = DirectCast(draggedRow.Data.DataBoundItem, GridModel) - Dim shape As New RadDiagramShape() With { - .Text = data.Shape, - .ElementShape = Me.GetShapeFromModel(data), - .BackColor = data.Color - } - shape.Position = e.DropLocation - Me.RadDiagram1.AddShape(shape) -End Sub -Private Function GetShapeFromModel(data As GridModel) As ElementShape - Dim shape As ElementShape = Nothing - Select Case data.Shape - Case "RoundRect" - shape = New RoundRectShape() - Exit Select - Case "Diamond" - shape = New DiamondShape() - Exit Select - Case "Star" - shape = New StarShape() - Exit Select - Case "Heart" - shape = New HeartShape() - Exit Select - Case "Media" - shape = New MediaShape() - Exit Select - Case "Donut" - shape = New DonutShape() - Exit Select - Case Else - shape = New CustomShape() - Exit Select - End Select - Return shape -End Function - -'endregion -Class -gion HelperClasses -ic Class GridModel -Public Property Id() As Integer - Get - Return m_Id - End Get - Set(value As Integer) - m_Id = value - End Set -End Property -Private m_Id As Integer -Public Property Color() As Color - Get - Return m_Color - End Get - Set(value As Color) - m_Color = value - End Set -End Property -Private m_Color As Color -Public Property Shape() As String - Get - Return m_Shape - End Get - Set(value As String) - m_Shape = value - End Set -End Property -Private m_Shape As String -Class -ic Class CustomRowGridBehavior -Inherits GridDataRowBehavior -Protected Overrides Function OnMouseDownLeft(e As MouseEventArgs) As Boolean - Dim row As GridDataRowElement = TryCast(Me.GetRowAtPoint(e.Location), GridDataRowElement) - If row IsNot Nothing Then - Dim svc As RadGridViewDragDropService = Me.GridViewElement.GetService(Of RadGridViewDragDropService)() - svc.Start(row) - End If - Return MyBase.OnMouseDownLeft(e) -End Function -Class - -```` - + + -{{endregion}} # See Also diff --git a/controls/diagram/drag-and-drop/ole-drag-and-drop.md b/controls/diagram/drag-and-drop/ole-drag-and-drop.md index 4ee4fb3ab..494f76af0 100644 --- a/controls/diagram/drag-and-drop/ole-drag-and-drop.md +++ b/controls/diagram/drag-and-drop/ole-drag-and-drop.md @@ -20,39 +20,10 @@ In order to achieve the desired result the MouseDown, MouseMove and MouseUp even #### Subscribe to Events -{{source=..\SamplesCS\Diagram\OleDragAndDropForm.cs region=SubscribeEvents}} -{{source=..\SamplesVB\Diagram\OleDragAndDropForm.vb region=SubscribeEvents}} -````C# -public OleDragAndDropForm() -{ - InitializeComponent(); - this.radDiagram2.AllowDrop = true; - this.radDiagram1.IsDraggingEnabled = false; - this.radDiagram1.MouseMove += radDiagram1_MouseMove; - this.radDiagram1.MouseDown += radDiagram1_MouseDown; - this.radDiagram1.MouseUp += radDiagram1_MouseUp; - this.radDiagram2.DragEnter += radDiagram2_DragEnter; - this.radDiagram2.DragDrop += radDiagram2_DragDrop; -} - -```` -````VB.NET -Public Sub New() - InitializeComponent() - Me.RadDiagram2.AllowDrop = True - Me.RadDiagram1.IsDraggingEnabled = False - AddHandler Me.RadDiagram1.MouseMove, AddressOf radDiagram1_MouseMove - AddHandler Me.RadDiagram1.MouseDown, AddressOf radDiagram1_MouseDown - AddHandler Me.RadDiagram1.MouseUp, AddressOf radDiagram1_MouseUp - AddHandler Me.RadDiagram2.DragEnter, AddressOf radDiagram2_DragEnter - AddHandler Me.RadDiagram2.DragDrop, AddressOf radDiagram2_DragDrop -End Sub - -```` - - - -{{endregion}} + + + + For the purpose of the example we will define a grid model object storing information about the shapes. @@ -62,98 +33,10 @@ __RadDiagram__ will accept the dragged data only if it is dropped on the diagram #### Drag and Drop Events -{{source=..\SamplesCS\Diagram\OleDragAndDropForm.cs region=HandleEvents}} -{{source=..\SamplesVB\Diagram\OleDragAndDropForm.vb region=HandleEvents}} -````C# -private void radDiagram2_DragDrop(object sender, DragEventArgs e) -{ - Telerik.WinControls.UI.RadDiagram diagram = sender as Telerik.WinControls.UI.RadDiagram; - Point point = diagram.PointToClient(new Point(e.X, e.Y)); - RadDiagramShape draggedItem = e.Data.GetData(typeof(RadDiagramShape)) as RadDiagramShape; - this.radDiagram1.RemoveShape(draggedItem); - draggedItem.Position = point; - diagram.AddShape(draggedItem); - this.mouseDownPosition = Point.Empty; -} -private void radDiagram2_DragEnter(object sender, DragEventArgs e) -{ - e.Effect = DragDropEffects.Copy; -} -private Point mouseDownPosition; -private void radDiagram1_MouseDown(object sender, MouseEventArgs e) -{ - this.mouseDownPosition = e.Location; -} -private void radDiagram1_MouseUp(object sender, MouseEventArgs e) -{ - this.mouseDownPosition = Point.Empty; -} -private void radDiagram1_MouseMove(object sender, MouseEventArgs e) -{ - if (!(e.Button == MouseButtons.Left)) - { - return; - } - if (this.ShouldBeginDrag(this.mouseDownPosition, e.Location)) - { - RadDiagramShape draggedItem = this.radDiagram1.ElementTree.GetElementAtPoint(this.mouseDownPosition).Parent as RadDiagramShape; - if (draggedItem != null) - { - ((Telerik.WinControls.UI.RadDiagram)sender).DoDragDrop(draggedItem, DragDropEffects.Copy); - } - } -} -private bool ShouldBeginDrag(Point current, Point capture) -{ - Size dragSize = SystemInformation.DragSize; - Rectangle dragRect = new Rectangle(capture.X - dragSize.Width / 2, - capture.Y - dragSize.Height / 2, dragSize.Width, dragSize.Height); - return !dragRect.Contains(current); -} - -```` -````VB.NET -Private Sub radDiagram2_DragDrop(sender As Object, e As DragEventArgs) - Dim diagram As Telerik.WinControls.UI.RadDiagram = TryCast(sender, Telerik.WinControls.UI.RadDiagram) - Dim point As Point = diagram.PointToClient(New Point(e.X, e.Y)) - Dim draggedItem As RadDiagramShape = TryCast(e.Data.GetData(GetType(RadDiagramShape)), RadDiagramShape) - Me.RadDiagram1.RemoveShape(draggedItem) - draggedItem.Position = point - diagram.AddShape(draggedItem) - Me.mouseDownPosition = point.Empty -End Sub -Private Sub radDiagram2_DragEnter(sender As Object, e As DragEventArgs) - e.Effect = DragDropEffects.Copy -End Sub -Private mouseDownPosition As Point -Private Sub radDiagram1_MouseDown(sender As Object, e As MouseEventArgs) - Me.mouseDownPosition = e.Location -End Sub -Private Sub radDiagram1_MouseUp(sender As Object, e As MouseEventArgs) - Me.mouseDownPosition = Point.Empty -End Sub -Private Sub radDiagram1_MouseMove(sender As Object, e As MouseEventArgs) - If Not (e.Button = MouseButtons.Left) Then - Return - End If - If Me.ShouldBeginDrag(Me.mouseDownPosition, e.Location) Then - Dim draggedItem As RadDiagramShape = TryCast(Me.RadDiagram1.ElementTree.GetElementAtPoint(Me.mouseDownPosition).Parent, RadDiagramShape) - If draggedItem IsNot Nothing Then - DirectCast(sender, Telerik.WinControls.UI.RadDiagram).DoDragDrop(draggedItem, DragDropEffects.Copy) - End If - End If -End Sub -Private Function ShouldBeginDrag(current As Point, capture As Point) As Boolean - Dim dragSize As Size = SystemInformation.DragSize - Dim dragRect As New Rectangle(capture.X - dragSize.Width / 2, capture.Y - dragSize.Height / 2, dragSize.Width, dragSize.Height) - Return Not dragRect.Contains(current) -End Function - -```` - - - -{{endregion}} + + + + # See Also diff --git a/controls/diagram/features/commands.md b/controls/diagram/features/commands.md index d8c90488e..3101217ef 100644 --- a/controls/diagram/features/commands.md +++ b/controls/diagram/features/commands.md @@ -104,40 +104,10 @@ The static __DiagramCommands__ class defines the following __RoutedUICommands__: Below is shown a sample code snippet how you can use some of the Diagram Commands in an application by using the DiagramElement.__TryExecuteCommand__ method: -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=CommandsExample}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=CommandsExample}} - -````C# - -private void radButton1_Click(object sender, EventArgs e) -{ - this.radDiagram1.DiagramElement.TryExecuteCommand(Telerik.WinControls.UI.Diagrams.DiagramCommands.Copy); -} - -private void radButton2_Click(object sender, EventArgs e) -{ - this.radDiagram1.DiagramElement.TryExecuteCommand(Telerik.WinControls.UI.Diagrams.DiagramCommands.Paste); -} -private void radButton3_Click(object sender, EventArgs e) -{ - this.radDiagram1.DiagramElement.TryExecuteCommand(Telerik.WinControls.UI.Diagrams.DiagramCommands.Nudge, "Left"); -} - -```` -````VB.NET -Private Sub RadButton1_Click(sender As Object, e As EventArgs) Handles RadButton1.Click - Me.RadDiagram1.DiagramElement.TryExecuteCommand(Telerik.WinControls.UI.Diagrams.DiagramCommands.Copy) -End Sub -Private Sub RadButton2_Click(sender As Object, e As EventArgs) Handles RadButton2.Click - Me.RadDiagram1.DiagramElement.TryExecuteCommand(Telerik.WinControls.UI.Diagrams.DiagramCommands.Paste) -End Sub -Private Sub RadButton3_Click(sender As Object, e As EventArgs) Handles RadButton3.Click - Me.RadDiagram1.DiagramElement.TryExecuteCommand(Telerik.WinControls.UI.Diagrams.DiagramCommands.Nudge, "Left") -End Sub - -```` - -{{endregion}} + + + + ![WinForms RadDiagram Commands](images/diagram-features-commands001.gif) diff --git a/controls/diagram/features/export.md b/controls/diagram/features/export.md index 82e96d87c..04dca4191 100644 --- a/controls/diagram/features/export.md +++ b/controls/diagram/features/export.md @@ -19,23 +19,10 @@ The __RadDiagram__ framework provides a method for exporting its current state t The RadDiagram.__ExportToImage()__ method allows you to export the diagram to an image. It returns an Image which can be saved in the desired type. -{{source=..\SamplesCS\Diagram\DiagramItems.cs region=Export}} -{{source=..\SamplesVB\Diagram\DiagramItems.vb region=Export}} + + -````C# -Image img1 = this.radDiagram1.ExportToImage(); -string imagePath1 = @"..\..\img1.png"; -img1.Save(imagePath1); -```` -````VB.NET -Dim img1 As Image = Me.RadDiagram1.ExportToImage() -Dim imagePath1 As String = "..\..\img1.png" -img1.Save(imagePath1) - -```` - -{{endregion}} Alternatively, you can use the __RadDiagramRibbonBar__ and its *Export* button: diff --git a/controls/diagram/features/grouping.md b/controls/diagram/features/grouping.md index bb26c98b5..388c61595 100644 --- a/controls/diagram/features/grouping.md +++ b/controls/diagram/features/grouping.md @@ -74,63 +74,18 @@ In the next example we will create 20 shapes with contents - "1", "2",... "20" a Let's first create some random shapes: -{{source=..\SamplesCS\Diagram\DiagramGrouping.cs region=AddShapes}} -{{source=..\SamplesVB\Diagram\DiagramGrouping.vb region=AddShapes}} + + -````C# - -Random random = new Random(); -for (int i = 0; i < 21; i++) -{ - RadDiagramShape s = new RadDiagramShape() { Width = 30, Height = 30, Content = i }; - s.Shape = new Telerik.WinControls.RoundRectShape(5); - s.BackColor = System.Drawing.Color.CadetBlue; - s.Position = new Telerik.Windows.Diagrams.Core.Point(random.Next(0, 900), random.Next(0, 200)); - this.radDiagram1.Items.Add(s); -} - -```` -````VB.NET -Dim random As New Random() -For i As Integer = 0 To 20 - Dim s As New RadDiagramShape() With { _ - .Width = 30, _ - .Height = 30, _ - .Content = i _ - } - s.Shape = New Telerik.WinControls.RoundRectShape(5) - s.BackColor = Color.CadetBlue - s.Position = New Telerik.Windows.Diagrams.Core.Point(random.[Next](0, 900), random.[Next](0, 200)) - Me.RadDiagram1.Items.Add(s) -Next - -```` - -{{endregion}} + Now let's implement some grouping logic: -{{source=..\SamplesCS\Diagram\DiagramGrouping.cs region=Group}} -{{source=..\SamplesVB\Diagram\DiagramGrouping.vb region=Group}} - -````C# - -IShape[] evenShapes = this.radDiagram1.Shapes.Where(x => int.Parse(x.Content.ToString()) % 2 == 0).ToArray(); -IShape[] oddShapes = this.radDiagram1.Shapes.Where(x => int.Parse(x.Content.ToString()) % 2 == 1).ToArray(); -this.radDiagram1.Group("Even", evenShapes); -this.radDiagram1.Group("Odd", oddShapes); - -```` -````VB.NET -Dim evenShapes As IShape() = Me.RadDiagram1.Shapes.Where(Function(x) Integer.Parse(x.Content.ToString()) Mod 2 = 0).ToArray() -Dim oddShapes As IShape() = Me.RadDiagram1.Shapes.Where(Function(x) Integer.Parse(x.Content.ToString()) Mod 2 = 1).ToArray() -Me.RadDiagram1.Group("Even", evenShapes) -Me.RadDiagram1.Group("Odd", oddShapes) + + -```` - -{{endregion}} + @@ -146,23 +101,10 @@ Below you can see how the grouping works: Now let's play with grouping and upgrouping. Below are some code examples and the result of the code execution: -{{source=..\SamplesCS\Diagram\DiagramGrouping.cs region=NewGroups}} -{{source=..\SamplesVB\Diagram\DiagramGrouping.vb region=NewGroups}} + + -````C# - -this.radDiagram1.Group("123", this.radDiagram1.Shapes[1], this.radDiagram1.Shapes[2], this.radDiagram1.Shapes[3]); -this.radDiagram1.Group("345", this.radDiagram1.Shapes[3], this.radDiagram1.Shapes[4], this.radDiagram1.Shapes[5]); - -```` -````VB.NET - -Me.RadDiagram1.Group("123", Me.RadDiagram1.Shapes(1), Me.RadDiagram1.Shapes(2), Me.RadDiagram1.Shapes(3)) -Me.RadDiagram1.Group("345", Me.RadDiagram1.Shapes(3), Me.RadDiagram1.Shapes(4), Me.RadDiagram1.Shapes(5)) - -```` - -{{endregion}} + This makes group "123" with items {Shapes[1],Shapes[2]} and "345" with items {Shapes[3], Shapes[4], Shapes[5]}. The creation of the second group excludes Shapes[3] from group "123". @@ -170,22 +112,10 @@ This makes group "123" with items {Shapes[1],Shapes[2]} and "345" with items {Sh Alternatively if we use one name in the method: -{{source=..\SamplesCS\Diagram\DiagramGrouping.cs region=ReplaceGroup}} -{{source=..\SamplesVB\Diagram\DiagramGrouping.vb region=ReplaceGroup}} - -````C# - -this.radDiagram1.Group("123", this.radDiagram1.Shapes[1], this.radDiagram1.Shapes[2], this.radDiagram1.Shapes[3]); -this.radDiagram1.Group("123", this.radDiagram1.Shapes[3], this.radDiagram1.Shapes[4], this.radDiagram1.Shapes[5]); + + -```` -````VB.NET -Me.RadDiagram1.Group("123", Me.RadDiagram1.Shapes(1), Me.RadDiagram1.Shapes(2), Me.RadDiagram1.Shapes(3)) -Me.RadDiagram1.Group("123", Me.RadDiagram1.Shapes(3), Me.RadDiagram1.Shapes(4), Me.RadDiagram1.Shapes(5)) - -```` - -{{endregion}} + This produces a single group "123" with the 5 elements Shapes[1]-Shapes[5]. @@ -196,25 +126,10 @@ Subgrouping must be done from subgroups to parent groups. In other words, creati Below is an example of creating a subgroups and a parent group. -{{source=..\SamplesCS\Diagram\DiagramGrouping.cs region=Subgroups}} -{{source=..\SamplesVB\Diagram\DiagramGrouping.vb region=Subgroups}} - -````C# - -IGroup groupA = this.radDiagram1.Group("1-2", this.radDiagram1.Shapes[1], this.radDiagram1.Shapes[2]); -IGroup groupB = this.radDiagram1.Group("3-4", this.radDiagram1.Shapes[3], this.radDiagram1.Shapes[4]); -IGroup parentGroup = this.radDiagram1.Group("1-2-3-4", groupA, groupB); - -```` -````VB.NET - -Dim groupA As IGroup = Me.RadDiagram1.Group("1-2", Me.RadDiagram1.Shapes(1), Me.RadDiagram1.Shapes(2)) -Dim groupB As IGroup = Me.RadDiagram1.Group("3-4", Me.RadDiagram1.Shapes(3), Me.RadDiagram1.Shapes(4)) -Dim parentGroup As IGroup = Me.RadDiagram1.Group("1-2-3-4", groupA, groupB) + + -```` - -{{endregion}} + @@ -231,22 +146,10 @@ Below you can see how consecutive clicks on a shape reflects the selection of gr What will happen if we try to create parent group then create subgroups? -{{source=..\SamplesCS\Diagram\DiagramGrouping.cs region=ParentToSubgroups}} -{{source=..\SamplesVB\Diagram\DiagramGrouping.vb region=ParentToSubgroups}} + + -````C# - -this.radDiagram1.Group("1-2-3-4", this.radDiagram1.Shapes[1], this.radDiagram1.Shapes[2], this.radDiagram1.Shapes[3], this.radDiagram1.Shapes[4]); -this.radDiagram1.Group("1-2", this.radDiagram1.Shapes[1], this.radDiagram1.Shapes[2]); - -```` -````VB.NET -Me.RadDiagram1.Group("1-2-3-4", Me.RadDiagram1.Shapes(1), Me.RadDiagram1.Shapes(2), Me.RadDiagram1.Shapes(3), Me.RadDiagram1.Shapes(4)) -Me.RadDiagram1.Group("1-2", Me.RadDiagram1.Shapes(1), Me.RadDiagram1.Shapes(2)) - -```` - -{{endregion}} + This will create two separate groups - "1-2-3-4" with items {Shapes[3], Shapes[4]} and "1-2" with items {Shapes[1], Shapes[2]}. @@ -258,45 +161,20 @@ __Ungrouping__ You can Ungroup one or several groups with the __Ungroup__ method of __RadDiagram__: -{{source=..\SamplesCS\Diagram\DiagramGrouping.cs region=Ungroup}} -{{source=..\SamplesVB\Diagram\DiagramGrouping.vb region=Ungroup}} + + -````C# - -this.radDiagram1.Ungroup(groupA, groupB); -this.radDiagram1.Ungroup(this.radDiagram1.Groups.ToArray()); - -```` -````VB.NET -Me.RadDiagram1.Ungroup(groupA, groupB) -Me.RadDiagram1.Ungroup(Me.RadDiagram1.Groups.ToArray()) - -```` - -{{endregion}} + ## Grouping With Commands Using the DiagramCommands __Group__ and __Ungroup__ is straightforward. __Group__ applies to the selected __IGroupables__ and __Ungroup__ applies to the selected __IGroups__. -{{source=..\SamplesCS\Diagram\DiagramGrouping.cs region=CommandsGrouping}} -{{source=..\SamplesVB\Diagram\DiagramGrouping.vb region=CommandsGrouping}} + + -````C# -this.radDiagram1.DiagramElement.ServiceLocator.GetService>().SelectItem(this.radDiagram1.Shapes[1],true); -this.radDiagram1.DiagramElement.ServiceLocator.GetService>().SelectItem(this.radDiagram1.Shapes[5],true); -this.radDiagram1.DiagramElement.TryExecuteCommand(Telerik.WinControls.UI.Diagrams.DiagramCommands.Group); - -```` -````VB.NET -Me.RadDiagram1.DiagramElement.ServiceLocator.GetService(Of ISelectionService(Of IDiagramItem))().SelectItem(Me.RadDiagram1.Shapes(1), True) -Me.RadDiagram1.DiagramElement.ServiceLocator.GetService(Of ISelectionService(Of IDiagramItem))().SelectItem(Me.RadDiagram1.Shapes(5), True) -Me.RadDiagram1.DiagramElement.TryExecuteCommand(Telerik.WinControls.UI.Diagrams.DiagramCommands.Group) - -```` - -{{endregion}} + diff --git a/controls/diagram/features/layout.md b/controls/diagram/features/layout.md index 71a4cfe1d..84d5e9dbd 100644 --- a/controls/diagram/features/layout.md +++ b/controls/diagram/features/layout.md @@ -21,67 +21,25 @@ Sugiyama is the default layout algorithm in __RadDiagram__. Using it is straight * use the RadDiagram.__SetLayout__ method: -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=SetLayout}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=SetLayout}} + + -````C# -this.radDiagram1.SetLayout(Telerik.Windows.Diagrams.Core.LayoutType.Sugiyama); - -```` -````VB.NET -Me.RadDiagram1.SetLayout(Telerik.Windows.Diagrams.Core.LayoutType.Sugiyama) - -```` - -{{endregion}} + * use the DiagramCommands.__Layout__: -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=LayoutCommand}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=LayoutCommand}} - -````C# -this.radDiagram1.DiagramElement.TryExecuteCommand(Telerik.WinControls.UI.Diagrams.DiagramCommands.Layout); - -```` -````VB.NET -Me.RadDiagram1.DiagramElement.TryExecuteCommand(Telerik.WinControls.UI.Diagrams.DiagramCommands.Layout) - -```` + + -{{endregion}} + The __SetLayout__ method provides two optional parameters - the type of the Layout (Sugiyama or Tree) and the corresponding layout settings (SugiyamaSettings or TreeLayoutSettings): -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=SugiyamaSettings}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=SugiyamaSettings}} - -````C# -Telerik.Windows.Diagrams.Core.SugiyamaSettings settings = new Telerik.Windows.Diagrams.Core.SugiyamaSettings() -{ - HorizontalDistance = 50, - VerticalDistance = 20, - Orientation = Telerik.Windows.Diagrams.Core.Orientation.Horizontal, - TotalMargin = new Telerik.Windows.Diagrams.Core.Size(20, 20), - ShapeMargin = new Telerik.Windows.Diagrams.Core.Size(10, 10), -}; -this.radDiagram1.SetLayout(Telerik.Windows.Diagrams.Core.LayoutType.Sugiyama, settings); - -```` -````VB.NET -Dim settings As New Telerik.Windows.Diagrams.Core.SugiyamaSettings() With { _ - .HorizontalDistance = 50, _ - .VerticalDistance = 20, _ - .Orientation = Telerik.Windows.Diagrams.Core.Orientation.Horizontal, _ - .TotalMargin = New Telerik.Windows.Diagrams.Core.Size(20, 20), _ - .ShapeMargin = New Telerik.Windows.Diagrams.Core.Size(10, 10) _ -} -Me.RadDiagram1.SetLayout(Telerik.Windows.Diagrams.Core.LayoutType.Sugiyama, Settings) - -```` + + -{{endregion}} + @@ -158,31 +116,10 @@ Below you can see a snapshots of random diagrams laid out with Tree Layout types Here is how this could be achieved in code behind. -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=TreeLayoutSettings}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=TreeLayoutSettings}} + + -````C# - -Telerik.Windows.Diagrams.Core.TreeLayoutSettings settings = new Telerik.Windows.Diagrams.Core.TreeLayoutSettings() -{ - TreeLayoutType = Telerik.Windows.Diagrams.Core.TreeLayoutType.RadialTree, - VerticalDistance = 20, -}; -settings.Roots.Add(this.radDiagram1.Shapes[0]); -this.radDiagram1.SetLayout(Telerik.Windows.Diagrams.Core.LayoutType.Tree, settings); - -```` -````VB.NET -Dim settings As New Telerik.Windows.Diagrams.Core.TreeLayoutSettings() With { _ - .TreeLayoutType = Telerik.Windows.Diagrams.Core.TreeLayoutType.RadialTree, _ - .VerticalDistance = 20 _ -} -Settings.Roots.Add(Me.RadDiagram1.Shapes(0)) -Me.RadDiagram1.SetLayout(Telerik.Windows.Diagrams.Core.LayoutType.Tree, Settings) - -```` - -{{endregion}} + ## Layout Settings diff --git a/controls/diagram/features/pan-and-zoom.md b/controls/diagram/features/pan-and-zoom.md index 498c7300e..921ad942f 100644 --- a/controls/diagram/features/pan-and-zoom.md +++ b/controls/diagram/features/pan-and-zoom.md @@ -21,21 +21,10 @@ __RadDiagram__ exposes an __IsPanEnabled__ property which defines whether the pa You can also activate the Pan [MouseTool]({%slug winforms/diagram-(beta)/diagram-tools/mouse-tools%}) to start a pan operation simply by dragging the current view port with the mouse. -{{source=..\SamplesCS\Diagram\DiagramPanZoom.cs region=IsPanEnabled}} -{{source=..\SamplesVB\Diagram\DiagramPanZoom.vb region=IsPanEnabled}} -````C# - -this.radDiagram1.IsPanEnabled = true; - -```` -````VB.NET -Me.RadDiagram1.IsPanEnabled = True - -```` - - + + -{{endregion}} + @@ -47,20 +36,10 @@ Me.RadDiagram1.IsPanEnabled = True ## Pan Methods You can use the __PanToPosition__ method in order to programmatically pan to a specific position: -{{source=..\SamplesCS\Diagram\DiagramPanZoom.cs region=PanMethod}} -{{source=..\SamplesVB\Diagram\DiagramPanZoom.vb region=PanMethod}} -````C# -this.radDiagram1.PanToPosition(new Telerik.Windows.Diagrams.Core.Point(200, 300)); - -```` -````VB.NET -Me.RadDiagram1.PanToPosition(New Point(200, 300)) - -```` - + + - -{{endregion}} + ## Pan events @@ -89,20 +68,10 @@ __RadDiagram__ exposes two panning events: __RadDiagram__ supports zooming out-of-the-box. The feature is controlled through the RadDiagram. __IsZoomEnabled__ property which default value is *true*. The user can initiate a zoom using the mouse wheel. -{{source=..\SamplesCS\Diagram\DiagramPanZoom.cs region=IsZoomEnabled}} -{{source=..\SamplesVB\Diagram\DiagramPanZoom.vb region=IsZoomEnabled}} -````C# -this.radDiagram1.IsZoomEnabled = true; - -```` -````VB.NET -Me.RadDiagram1.IsZoomEnabled = True - -```` + + - - -{{endregion}} + @@ -117,22 +86,10 @@ The zoom range is controlled through two __DiagramConstants__: * __MaximumZoom__: a double value which indicates the maximum zoom level. Its default value is 5. -{{source=..\SamplesCS\Diagram\DiagramPanZoom.cs region=MinMaxZoom}} -{{source=..\SamplesVB\Diagram\DiagramPanZoom.vb region=MinMaxZoom}} -````C# - -Telerik.Windows.Diagrams.Core.DiagramConstants.MinimumZoom = 0.5; -Telerik.Windows.Diagrams.Core.DiagramConstants.MaximumZoom = 10; + + -```` -````VB.NET -Telerik.Windows.Diagrams.Core.DiagramConstants.MinimumZoom = 0.5 -Telerik.Windows.Diagrams.Core.DiagramConstants.MaximumZoom = 10 - -```` - - -{{endregion}} + The current zoom value in a __RadDiagram__ instance is controlled through the __Zoom__ property. It represents a double value which cannot be null, infinity or NaN. Additionally, this value is coerced to be within the range defined by the __MinimumZoom__ and __MaximumZoom__ constants. The default __Zoom__ value is 1. @@ -156,20 +113,10 @@ If you need to initiate a zoom through code-behind, __RadDiagram__ provides two >note Please note that both of the parameters described above are optional. > -{{source=..\SamplesCS\Diagram\DiagramPanZoom.cs region=ZoomIn}} -{{source=..\SamplesVB\Diagram\DiagramPanZoom.vb region=ZoomIn}} - -````C# - -this.radDiagram1.DiagramElement.ZoomIn(1.5); - -```` -````VB.NET -Me.RadDiagram1.DiagramElement.ZoomIn(1.5) - -```` + + -{{endregion}} + * __ZoomOut__: this method performs an incremental zoom out taking into account the previous zoom operations. It can take up to 2 parameters: @@ -181,44 +128,16 @@ Me.RadDiagram1.DiagramElement.ZoomIn(1.5) >note Please note that both of the parameters described above are optional. > -{{source=..\SamplesCS\Diagram\DiagramPanZoom.cs region=ZoomOut}} -{{source=..\SamplesVB\Diagram\DiagramPanZoom.vb region=ZoomOut}} - -````C# - -this.radDiagram1.DiagramElement.ZoomOut(3.5); - -```` -````VB.NET -Me.RadDiagram1.DiagramElement.ZoomOut(3.5) + + -```` - -{{endregion}} + * __BringIntoView__: This method allows you to center the currently occupied space: -{{source=..\SamplesCS\Diagram\DiagramPanZoom.cs region=BringIntoView}} -{{source=..\SamplesVB\Diagram\DiagramPanZoom.vb region=BringIntoView}} -````C# -private void radButton1_Click(object sender, EventArgs e) -{ - var enclosingBounds = ((IGraph)this.radDiagram1.DiagramElement).CalculateEnclosingBoundsWithoutTransform(); - this.radDiagram1.DiagramElement.BringIntoView(enclosingBounds, false); - this.radDiagram1.Zoom = 1; -} - -```` -````VB.NET -Private Sub radButton1_Click(ByVal sender As Object, ByVal e As EventArgs) - Dim enclosingBounds = DirectCast(Me.RadDiagram1.DiagramElement, IGraph).CalculateEnclosingBoundsWithoutTransform() - Me.RadDiagram1.DiagramElement.BringIntoView(enclosingBounds, False) - Me.RadDiagram1.Zoom = 1 -End Sub - -```` - - -{{endregion}} + + + + ## Zoom events diff --git a/controls/diagram/features/printing-support.md b/controls/diagram/features/printing-support.md index dbea50661..0df005164 100644 --- a/controls/diagram/features/printing-support.md +++ b/controls/diagram/features/printing-support.md @@ -18,38 +18,18 @@ __RadDiagram__ provides options to print its content by using a [RadPrintDocumen __RadDiagram__ has two public methods available for printing - __Print()__ and __PrintPreview()__. The first method will directly send a print job to the default printer with the settings currently saved in the __PrintStyle__ property. This method has one overload available which can show a system PrintDialog with the available printers and their options. -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=Print}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=Print}} + + -````C# -this.radDiagram1.Print(); -this.radDiagram1.Print(true); - -```` -````VB.NET -Me.RadDiagram1.Print() -Me.RadDiagram1.Print(True) - -```` - -{{endregion}} + The other available method is __PrintPreview()__, which opens [RadPrintPreviewDialog]({%slug winforms/telerik-presentation-framework/printing-support/end-user-functionality/print-preview-dialog%}). -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=PrintPreview}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=PrintPreview}} - -````C# -this.radDiagram1.PrintPreview(); + + -```` -````VB.NET -Me.RadDiagram1.PrintPreview() - -```` - -{{endregion}} + diff --git a/controls/diagram/features/routing.md b/controls/diagram/features/routing.md index 509c523c0..db0ee780b 100644 --- a/controls/diagram/features/routing.md +++ b/controls/diagram/features/routing.md @@ -38,29 +38,10 @@ The __OrgTreeRouter__ is a __LayoutType__ - based router that performs a hierarc In order to use the __OrgTreeRouter__, you have to instantiate an __OrgTreeRouter__ object and set it as current __Router__ of the __RadDiagram__ via the __RoutingService__: -{{source=..\SamplesCS\Diagram\DiagramRouting.cs region=OrgTreeRouter}} -{{source=..\SamplesVB\Diagram\DiagramRouting.vb region=OrgTreeRouter}} + + -````C# - -Telerik.Windows.Diagrams.Core.OrgTreeRouter router = new Telerik.Windows.Diagrams.Core.OrgTreeRouter() -{ - TreeLayoutType = Telerik.Windows.Diagrams.Core.TreeLayoutType.TreeDown, - ConnectionOuterSpacing = 20, -}; -this.radDiagram1.RoutingService.Router = router; - -```` -````VB.NET -Dim router As New Telerik.Windows.Diagrams.Core.OrgTreeRouter() With { _ - .TreeLayoutType = Telerik.Windows.Diagrams.Core.TreeLayoutType.TreeDown, _ - .ConnectionOuterSpacing = 20 _ -} -Me.RadDiagram1.RoutingService.Router = router - -```` - -{{endregion}} + @@ -79,48 +60,10 @@ When the __TreeLayoutType__ is set to *TipOverTree*, the __OrgTreeRouter__ uses Here is a sample code snippet demonstrating how to create and configure __TreeLayoutSettings__ and create and assign a __Router__ to be the default one. -{{source=..\SamplesCS\Diagram\DiagramRouting.cs region=TipOverTreeRouter}} -{{source=..\SamplesVB\Diagram\DiagramRouting.vb region=TipOverTreeRouter}} - -````C# - -Telerik.Windows.Diagrams.Core.TreeLayoutSettings settings = new Telerik.Windows.Diagrams.Core.TreeLayoutSettings() -{ - TreeLayoutType = Telerik.Windows.Diagrams.Core.TreeLayoutType.TipOverTree, - UnderneathVerticalSeparation = 50, - VerticalDistance = 50, - UnderneathHorizontalOffset = 50, - UnderneathVerticalTopOffset = 50 -}; -settings.Roots.Add(this.radDiagram1.Shapes[0]); -Telerik.Windows.Diagrams.Core.OrgTreeRouter router = new Telerik.Windows.Diagrams.Core.OrgTreeRouter() -{ - TreeLayoutType = Telerik.Windows.Diagrams.Core.TreeLayoutType.TipOverTree, - ConnectionOuterSpacing = 10 -}; -this.radDiagram1.RoutingService.Router = router; -this.radDiagram1.SetLayout(Telerik.Windows.Diagrams.Core.LayoutType.Tree, settings); - -```` -````VB.NET -Dim settings As New Telerik.Windows.Diagrams.Core.TreeLayoutSettings() With { _ - .TreeLayoutType = Telerik.Windows.Diagrams.Core.TreeLayoutType.TipOverTree, _ - .UnderneathVerticalSeparation = 50, _ - .VerticalDistance = 50, _ - .UnderneathHorizontalOffset = 50, _ - .UnderneathVerticalTopOffset = 50 _ -} -settings.Roots.Add(Me.RadDiagram1.Shapes(0)) -Dim router As New Telerik.Windows.Diagrams.Core.OrgTreeRouter() With { _ - .TreeLayoutType = Telerik.Windows.Diagrams.Core.TreeLayoutType.TipOverTree, _ - .ConnectionOuterSpacing = 10 _ -} -Me.RadDiagram1.RoutingService.Router = router -Me.RadDiagram1.SetLayout(Telerik.Windows.Diagrams.Core.LayoutType.Tree, settings) - -```` - -{{endregion}} + + + + @@ -200,127 +143,27 @@ In the following section we will create a custom Router. This way we will be abl Let's first create some items: -{{source=..\SamplesCS\Diagram\DiagramRouting.cs region=PopulateItems}} -{{source=..\SamplesVB\Diagram\DiagramRouting.vb region=PopulateItems}} - -````C# - -RadDiagramShape shapeA = new RadDiagramShape() -{ - Text = "ShapeA", - ElementShape = new RoundRectShape(4), - BackColor = Color.CadetBlue -}; -shapeA.Position = new Telerik.Windows.Diagrams.Core.Point(100, 100); -this.radDiagram1.Items.Add(shapeA); - -RadDiagramShape shapeB = new RadDiagramShape() -{ - Text = "ShapeB", - ElementShape = new RoundRectShape(4), - BackColor = Color.CadetBlue -}; -shapeB.Position = new Telerik.Windows.Diagrams.Core.Point(300, 100); -this.radDiagram1.Items.Add(shapeB); - -RadDiagramConnection connection = new RadDiagramConnection() -{ - Source = shapeA, - Target = shapeB -}; -this.radDiagram1.Items.Add(connection); - -```` -````VB.NET -Dim shapeA As New RadDiagramShape() With { _ - .Text = "ShapeA", _ - .ElementShape = New RoundRectShape(4), _ - .BackColor = Color.CadetBlue _ -} -shapeA.Position = New Telerik.Windows.Diagrams.Core.Point(100, 100) -Me.RadDiagram1.Items.Add(shapeA) -Dim shapeB As New RadDiagramShape() With { _ - .Text = "ShapeB", _ - .ElementShape = New RoundRectShape(4), _ - .BackColor = Color.CadetBlue _ -} -shapeB.Position = New Telerik.Windows.Diagrams.Core.Point(300, 100) -Me.RadDiagram1.Items.Add(shapeB) -Dim connection As New RadDiagramConnection() With { _ - .Source = shapeA, _ - .Target = shapeB _ -} -Me.RadDiagram1.Items.Add(connection) - -```` - -{{endregion}} + + + + Now we have to create class that implements the __IRouter__ interface and override the GetRoutePoints() method: -{{source=..\SamplesCS\Diagram\DiagramRouting.cs region=CustomRouter}} -{{source=..\SamplesVB\Diagram\DiagramRouting.vb region=CustomRouter}} + + -````C# - -public class CustomRouter : Telerik.Windows.Diagrams.Core.IRouter -{ - public System.Collections.Generic.IList GetRoutePoints(Telerik.Windows.Diagrams.Core.IConnection connection, bool showLastLine) - { - List pointList = new List(); - Telerik.Windows.Diagrams.Core.Point start = connection.StartPoint; - Telerik.Windows.Diagrams.Core.Point end = connection.EndPoint; - - pointList.Add(new Telerik.Windows.Diagrams.Core.Point(start.X + (end.X - start.X) * 0.45, start.Y)); - pointList.Add(new Telerik.Windows.Diagrams.Core.Point((start.X + end.X) / 2, (start.Y + end.Y) / 2 - 50)); - pointList.Add(new Telerik.Windows.Diagrams.Core.Point((start.X + end.X) / 2, (start.Y + end.Y) / 2 + 50)); - pointList.Add(new Telerik.Windows.Diagrams.Core.Point(start.X + (end.X - start.X) * 0.55, end.Y)); - - return pointList; - } -} - -```` -````VB.NET -Public Class CustomRouter -Implements Telerik.Windows.Diagrams.Core.IRouter - Public Function GetRoutePoints1(connection As Telerik.Windows.Diagrams.Core.IConnection, showLastLine As Boolean) As IList(Of Telerik.Windows.Diagrams.Core.Point) Implements Telerik.Windows.Diagrams.Core.IRouter.GetRoutePoints - Dim pointList As New List(Of Telerik.Windows.Diagrams.Core.Point)() - Dim start As Telerik.Windows.Diagrams.Core.Point = connection.StartPoint - Dim [end] As Telerik.Windows.Diagrams.Core.Point = connection.EndPoint - pointList.Add(New Telerik.Windows.Diagrams.Core.Point(start.X + ([end].X - start.X) * 0.45, start.Y)) - pointList.Add(New Telerik.Windows.Diagrams.Core.Point((start.X + [end].X) / 2, (start.Y + [end].Y) / 2 - 50)) - pointList.Add(New Telerik.Windows.Diagrams.Core.Point((start.X + [end].X) / 2, (start.Y + [end].Y) / 2 + 50)) - pointList.Add(New Telerik.Windows.Diagrams.Core.Point(start.X + ([end].X - start.X) * 0.55, [end].Y)) - Return pointList - End Function -End Class - -```` - -{{endregion}} + Please note that we only have to add in the list the route points, no need to add the start and the end point of the connection. The final step is to make our router the current one of the __RadDiagram__. This is done via Diagram's Routing Service: -{{source=..\SamplesCS\Diagram\DiagramRouting.cs region=SetCustomRouter}} -{{source=..\SamplesVB\Diagram\DiagramRouting.vb region=SetCustomRouter}} - -````C# - -this.radDiagram1.RouteConnections = true; -this.radDiagram1.RoutingService.Router = new CustomRouter(); + + -```` -````VB.NET -Me.RadDiagram1.RouteConnections = True -Me.RadDiagram1.RoutingService.Router = New CustomRouter() - -```` - -{{endregion}} + diff --git a/controls/diagram/features/save-and-load-layout.md b/controls/diagram/features/save-and-load-layout.md index ba592379a..4a2e17085 100644 --- a/controls/diagram/features/save-and-load-layout.md +++ b/controls/diagram/features/save-and-load-layout.md @@ -18,35 +18,10 @@ Here is a sample demonstrating how you can save the layout to a file: #### Save Layout -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=SaveLayout}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=SaveLayout}} + + -````C# - -string s = "default.xml"; -System.Windows.Forms.SaveFileDialog dialog = new System.Windows.Forms.SaveFileDialog(); -dialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*"; -dialog.Title = "Select a xml file"; -if (dialog.ShowDialog() == DialogResult.OK) -{ - s = dialog.FileName; -} -this.radDiagram1.SaveToFile(s); - -```` -````VB.NET -Dim s As String = "default.xml" -Dim dialog As New System.Windows.Forms.SaveFileDialog() -dialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*" -dialog.Title = "Select a xml file" -If dialog.ShowDialog() = DialogResult.OK Then - s = dialog.FileName -End If -Me.radDiagram1.SaveToFile(s) - -```` - -{{endregion}} + >note You can use the RadDiagram.**Save** method in case you need just the string representation of the XML data. @@ -56,33 +31,9 @@ Here is a sample demonstrating how you can load the layout from a file: #### Load Layout -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=LoadLayout}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=LoadLayout}} - -````C# -string s = "default.xml"; -System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog(); -dialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*"; -dialog.Title = "Select a xml file"; -if (dialog.ShowDialog() == DialogResult.OK) -{ - s = dialog.FileName; -} -this.radDiagram1.LoadFromFile(s); - -```` -````VB.NET -Dim s As String = "default.xml" -Dim dialog As New System.Windows.Forms.OpenFileDialog() -dialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*" -dialog.Title = "Select a xml file" -If dialog.ShowDialog() = DialogResult.OK Then - s = dialog.FileName -End If -Me.radDiagram1.LoadFromFile(s) - -```` + + -{{endregion}} + >note You can use the RadDiagram.**Load** method in order to load data from a string representation of the XML data. diff --git a/controls/diagram/features/undo-and-redo.md b/controls/diagram/features/undo-and-redo.md index 436571baf..4d166abca 100644 --- a/controls/diagram/features/undo-and-redo.md +++ b/controls/diagram/features/undo-and-redo.md @@ -23,33 +23,10 @@ __RadDiagram__ class exposes two methods that allow you to take advantage of the * __Redo()__: this method reapplies the last operation that was undone in the __RadDiagram__. -{{source=..\SamplesCS\Diagram\DiagramUndoRedo.cs region=UndoRedo}} -{{source=..\SamplesVB\Diagram\DiagramUndoRedo.vb region=UndoRedo}} + + -````C# - -private void radButtonUndo_Click(object sender, EventArgs e) -{ - this.radDiagram1.Undo(); -} - -private void radButtonRedo_Click(object sender, EventArgs e) -{ - this.radDiagram1.Redo(); -} - -```` -````VB.NET -Private Sub RadButtonUndo_Click(sender As Object, e As EventArgs) Handles RadButtonUndo.Click - Me.RadDiagram1.Undo() -End Sub -Private Sub RadButtonRedo_Click(sender As Object, e As EventArgs) Handles RadButtonRedo.Click - Me.RadDiagram1.Redo() -End Sub - -```` - -{{endregion}} + @@ -65,21 +42,10 @@ Telerik Diagramming Framework exposes a set of commands that allow you to easily > -{{source=..\SamplesCS\Diagram\DiagramUndoRedo.cs region=CommandsUndoRedo}} -{{source=..\SamplesVB\Diagram\DiagramUndoRedo.vb region=CommandsUndoRedo}} + + -````C# -this.radDiagram1.DiagramElement.TryExecuteCommand(Telerik.WinControls.UI.Diagrams.DiagramCommands.Undo); -this.radDiagram1.DiagramElement.TryExecuteCommand(Telerik.WinControls.UI.Diagrams.DiagramCommands.Redo); - -```` -````VB.NET -Me.RadDiagram1.DiagramElement.TryExecuteCommand(Telerik.WinControls.UI.Diagrams.DiagramCommands.Undo) -Me.RadDiagram1.DiagramElement.TryExecuteCommand(Telerik.WinControls.UI.Diagrams.DiagramCommands.Redo) - -```` - -{{endregion}} + diff --git a/controls/diagram/information-adorner.md b/controls/diagram/information-adorner.md index 40fb6b449..e92f70229 100644 --- a/controls/diagram/information-adorner.md +++ b/controls/diagram/information-adorner.md @@ -15,19 +15,10 @@ __RadDiagram__ shows information tool-tips that appear below the manipulation ad __RadDiagram__ uses the __ItemInformationAdorner__ to visualize information regarding the position, size and rotation angle of its shapes. -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=EnableInformationAdorner}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=EnableInformationAdorner}} + + -````C# -this.radDiagram1.IsInformationAdornerVisible = true; - -```` -````VB.NET -Me.RadDiagram1.IsInformationAdornerVisible = True - -```` - -{{endregion}} + @@ -41,88 +32,20 @@ Fig.1 visualizes the X and Y component of the current position of the shape when __ItemInformationAdorner__ can be customized in order to display additional elements, e.g. a button. To achieve it, you should create a derivative of the __Telerik.WinControls.UI.Diagrams.Primitives.ItemInformationAdorner__ class and override its __CreateChildElements__ method. Here is demonstrated a sample code snippet: -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=CustomItemInformationAdorner}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=CustomItemInformationAdorner}} - -````C# - -class MyItemInformationAdorner : Telerik.WinControls.UI.Diagrams.Primitives.ItemInformationAdorner -{ - public MyItemInformationAdorner(RadDiagramElement diagram) - { - this.Diagram = diagram; - } - - protected override void CreateChildElements() - { - base.CreateChildElements(); - RadButtonElement button = new RadButtonElement() { Text = "Click me!", AutoSize = true, TextAlignment = ContentAlignment.MiddleRight }; - this.InformationTipPanel.Children.First().Visibility = ElementVisibility.Collapsed; - this.InformationTipPanel.Children.Add(button); - button.ButtonFillElement.BackColor = System.Drawing.Color.Red; - button.ButtonFillElement.GradientStyle = GradientStyles.Solid; - button.Click += button_Click; - } - void button_Click(object sender, EventArgs e) - { - MessageBox.Show("Hello"); - } -} - -```` -````VB.NET -Class MyItemInformationAdorner -Inherits Telerik.WinControls.UI.Diagrams.Primitives.ItemInformationAdorner - Public Sub New(diagram As RadDiagramElement) - Me.Diagram = diagram - End Sub - - Protected Overrides Sub CreateChildElements() - MyBase.CreateChildElements() - Dim button As New RadButtonElement() With { _ - .Text = "Click me!", _ - .AutoSize = True, _ - .TextAlignment = ContentAlignment.MiddleRight _ - } - Me.InformationTipPanel.Children.First().Visibility = ElementVisibility.Collapsed - Me.InformationTipPanel.Children.Add(Button) - Button.ButtonFillElement.BackColor = System.Drawing.Color.Red - Button.ButtonFillElement.GradientStyle = GradientStyles.Solid - AddHandler Button.Click, AddressOf button_Click - End Sub - Private Sub button_Click(sender As Object, e As EventArgs) - MessageBox.Show("Hello") - End Sub -End Class - -```` + + -{{endregion}} + Now, you should apply the custom __ItemInformationAdorner__ to __DiagramElement__: -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=AssignCustomItemInformationAdorner}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=AssignCustomItemInformationAdorner}} - -````C# -this.radDiagram1.DiagramElement.ItemInformationAdorner = new MyItemInformationAdorner(this.radDiagram1.DiagramElement); -Telerik.WinControls.UI.Diagrams.Primitives.ItemInformationAdorner item = this.radDiagram1.DiagramElement.ItemInformationAdorner; -item.Width = 100; -item.Height = 20; - -```` -````VB.NET -Me.RadDiagram1.DiagramElement.ItemInformationAdorner = New MyItemInformationAdorner(Me.RadDiagram1.DiagramElement) -Dim item As Telerik.WinControls.UI.Diagrams.Primitives.ItemInformationAdorner = Me.RadDiagram1.DiagramElement.ItemInformationAdorner -item.Width = 100 -item.Height = 20 + + -```` - -{{endregion}} + diff --git a/controls/diagram/items-manipulation/clipboard-operations.md b/controls/diagram/items-manipulation/clipboard-operations.md index 824c0edc9..f0e927932 100644 --- a/controls/diagram/items-manipulation/clipboard-operations.md +++ b/controls/diagram/items-manipulation/clipboard-operations.md @@ -34,29 +34,10 @@ You can perform these operations in a single form, but you can also copy/cut and You can use the __DiagramCommands__ "Cut", "Copy" and "Paste" in order to perform the standard clipboard operations. -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=ClipboardCommands}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=ClipboardCommands}} - -````C# -this.radDiagram1.SelectedItem = shape1; -this.radDiagram1.DiagramElement.TryExecuteCommand(DiagramCommands.Copy, ""); -this.radDiagram2.DiagramElement.TryExecuteCommand(DiagramCommands.Paste, ""); -this.radDiagram1.SelectedItem = shape2; -this.radDiagram1.DiagramElement.TryExecuteCommand(DiagramCommands.Cut, ""); -this.radDiagram2.DiagramElement.TryExecuteCommand(DiagramCommands.Paste, ""); - -```` -````VB.NET -Me.RadDiagram1.SelectedItem = shape1 -Me.RadDiagram1.DiagramElement.TryExecuteCommand(DiagramCommands.Copy, "") -Me.RadDiagram2.DiagramElement.TryExecuteCommand(DiagramCommands.Paste, "") -Me.RadDiagram1.SelectedItem = shape2 -Me.RadDiagram1.DiagramElement.TryExecuteCommand(DiagramCommands.Cut, "") -Me.RadDiagram2.DiagramElement.TryExecuteCommand(DiagramCommands.Paste, "") - -```` - -{{endregion}} + + + + diff --git a/controls/diagram/items-manipulation/editing.md b/controls/diagram/items-manipulation/editing.md index 2eb32739f..43c84de32 100644 --- a/controls/diagram/items-manipulation/editing.md +++ b/controls/diagram/items-manipulation/editing.md @@ -21,19 +21,10 @@ By default, the __RadDiagramItems__ are enabled for editing. In order to disable ![WinForms RadDiagram Fig IsEditable](images/diagram-items-manipulation-editing001.png) -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=IsEditable}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=IsEditable}} + + -````C# -this.radDiagram1.IsEditable = true; - -```` -````VB.NET -Me.RadDiagram1.IsEditable = True - -```` - -{{endregion}} + ## Start Editing By Using Keyboard @@ -56,27 +47,10 @@ In the code snippet below it is demonstrated how to access the editor element: #### Access editor element -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=GetEditor}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=GetEditor}} + + -````C# - -private void shape_BeginEdit(object sender, EventArgs e) -{ - RadDiagramShape shape = sender as RadDiagramShape; - RadTextBoxControlElement editorElement = shape.FindDescendant(); -} - -```` -````VB.NET -Private Sub shape_BeginEdit(sender As Object, e As EventArgs) - Dim shape As RadDiagramShape = TryCast(sender, RadDiagramShape) - Dim editorElement As RadTextBoxControlElement = shape.FindDescendant(Of RadTextBoxControlElement)() -End Sub - -```` - -{{endregion}} + * __PreviewEndEdit__: fires when a __RadDiagramItem__ is about to leave the edit mode. It is cancelable. @@ -93,40 +67,10 @@ __RadDiagram__ provides three predefined commands for editing the selected item ![WinForms RadDiagram Editing by commands](images/diagram-items-manipulation-editing002.gif) -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=EditCommands}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=EditCommands}} + + -````C# - -private void radButtonEdit_Click(object sender, EventArgs e) -{ - this.radDiagram1.DiagramElement.TryExecuteCommand(Telerik.WinControls.UI.Diagrams.DiagramCommands.BeginEdit); -} - -private void radButtonConfirm_Click(object sender, EventArgs e) -{ - this.radDiagram1.DiagramElement.TryExecuteCommand(Telerik.WinControls.UI.Diagrams.DiagramCommands.CommitEdit); -} -private void radButtonCancel_Click(object sender, EventArgs e) -{ - this.radDiagram1.DiagramElement.TryExecuteCommand(Telerik.WinControls.UI.Diagrams.DiagramCommands.CancelEdit); -} - -```` -````VB.NET -Private Sub RadButtonEdit_Click(sender As Object, e As EventArgs) Handles RadButtonEdit.Click - Me.RadDiagram1.DiagramElement.TryExecuteCommand(Telerik.WinControls.UI.Diagrams.DiagramCommands.BeginEdit) -End Sub -Private Sub RadButtonConfirm_Click(sender As Object, e As EventArgs) Handles RadButtonConfirm.Click - Me.RadDiagram1.DiagramElement.TryExecuteCommand(Telerik.WinControls.UI.Diagrams.DiagramCommands.CommitEdit) -End Sub -Private Sub RadButtonCancel_Click(sender As Object, e As EventArgs) Handles RadButtonCancel.Click - Me.RadDiagram1.DiagramElement.TryExecuteCommand(Telerik.WinControls.UI.Diagrams.DiagramCommands.CancelEdit) -End Sub - -```` - -{{endregion}} + diff --git a/controls/diagram/items-manipulation/removing-items.md b/controls/diagram/items-manipulation/removing-items.md index 372fd7bf9..9fb5fffd0 100644 --- a/controls/diagram/items-manipulation/removing-items.md +++ b/controls/diagram/items-manipulation/removing-items.md @@ -25,42 +25,20 @@ Below you can see the result of delete operation over the selected __RadDiagramI You can remove __RadDiagramItems__ in code behind by using the RadDiagram.__Items__ collection and its __Remove()__ or __RemoveAt()__ methods: -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=RemoveItems}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=RemoveItems}} + + -````C# -this.radDiagram1.Items.RemoveAt(2); -this.radDiagram1.Items.Remove(shape1); - -```` -````VB.NET -Me.RadDiagram1.Items.RemoveAt(2) -Me.RadDiagram1.Items.Remove(shape1) - -```` - -{{endregion}} + ## Delete with DiagramCommands You can use the __DiagramCommand__ "Delete" in order to remove the selected __RadDiagramItems__. -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=DeleteCommands}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=DeleteCommands}} + + -````C# -this.radDiagram1.SelectedItem = shape1; -this.radDiagram1.DiagramElement.TryExecuteCommand(DiagramCommands.Delete, ""); - -```` -````VB.NET -Me.RadDiagram1.SelectedItem = shape1 -Me.RadDiagram1.DiagramElement.TryExecuteCommand(DiagramCommands.Delete, "") - -```` - -{{endregion}} + diff --git a/controls/diagram/items-manipulation/resizing.md b/controls/diagram/items-manipulation/resizing.md index ff15f4521..aba1609b5 100644 --- a/controls/diagram/items-manipulation/resizing.md +++ b/controls/diagram/items-manipulation/resizing.md @@ -19,19 +19,10 @@ By default, the __RadDiagram__ is enabled for resizing manipulation. In order to ![WinForms RadDiagram Enable/Disable Resizing](images/diagram-items-manipulation-resizing001.png) -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=EnableResizing}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=EnableResizing}} + + -````C# -this.radDiagram1.IsResizingEnabled = false; - -```` -````VB.NET -Me.RadDiagram1.IsResizingEnabled = False - -```` - -{{endregion}} + ## Manipulation adorner @@ -45,36 +36,10 @@ You can resize shapes by using their __Width__ and __Height__ properties: ![WinForms RadDiagram Width and Height](images/diagram-items-manipulation-resizing002.png) -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=ResizeShape}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=ResizeShape}} - -````C# -RadDiagramShape resizedShape = new RadDiagramShape() -{ - Text = "", - ElementShape = new RoundRectShape(5), - BackColor = System.Drawing.Color.LightBlue -}; -resizedShape.Width = 300; -resizedShape.Height = 100; -resizedShape.Position = new Telerik.Windows.Diagrams.Core.Point(10, 10); -radDiagram1.Items.Add(resizedShape); - -```` -````VB.NET -Dim resizedShape As New RadDiagramShape() With { _ - .Text = "", _ - .ElementShape = New RoundRectShape(5), _ - .BackColor = System.Drawing.Color.LightBlue _ -} -resizedShape.Width = 300 -resizedShape.Height = 100 -resizedShape.Position = New Telerik.Windows.Diagrams.Core.Point(10, 10) -RadDiagram1.Items.Add(resizedShape) - -```` - -{{endregion}} + + + + diff --git a/controls/diagram/items-manipulation/rotation.md b/controls/diagram/items-manipulation/rotation.md index df0e68cd8..2f6333989 100644 --- a/controls/diagram/items-manipulation/rotation.md +++ b/controls/diagram/items-manipulation/rotation.md @@ -19,19 +19,10 @@ By default, the __RadDiagram__ is enabled for rotation manipulation. In order to ![WinForms RadDiagram Enable/Disable Rotation](images/diagram-items-manipulation-rotation001.png) -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=EnableRotation}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=EnableRotation}} + + -````C# -this.radDiagram1.IsRotationEnabled = false; - -```` -````VB.NET -Me.RadDiagram1.IsRotationEnabled = False - -```` - -{{endregion}} + ## Rotation Angle @@ -40,30 +31,10 @@ You can rotate shapes by using their __RotationAngle__ property: ![WinForms RadDiagram Rotation Angle](images/diagram-items-manipulation-rotation002.png) -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=RotationAngle}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=RotationAngle}} + + -````C# -RadDiagramShape sourceShape = new RadDiagramShape() -{ - Text = "Text", - BackColor = System.Drawing.Color.LightBlue, - ElementShape = new TabVsShape(), -}; -sourceShape.RotationAngle = 45; - -```` -````VB.NET -Dim sourceShape As New RadDiagramShape() With { _ - .Text = "Text", _ - .BackColor = System.Drawing.Color.LightBlue, _ - .ElementShape = New TabVsShape() _ -} -sourceShape.RotationAngle = 45 - -```` - -{{endregion}} + diff --git a/controls/diagram/items-manipulation/selection.md b/controls/diagram/items-manipulation/selection.md index cea001a27..b7cf44fe7 100644 --- a/controls/diagram/items-manipulation/selection.md +++ b/controls/diagram/items-manipulation/selection.md @@ -46,49 +46,10 @@ In order to select items programmatically, you only need to set their __IsSelect ![WinForms RadDiagram Selection in Code Behind](images/diagram-items-manipulation-selection001.png) -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=IsSelected}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=IsSelected}} - -````C# -RadDiagramShape shape1 = new RadDiagramShape() -{ - Text = "", - IsSelected = true, - ElementShape = new RoundRectShape(5), - BackColor = System.Drawing.Color.LightBlue -}; -shape1.Position = new Telerik.Windows.Diagrams.Core.Point(10, 10); -radDiagram1.AddShape(shape1); -RadDiagramShape shape2 = new RadDiagramShape() -{ - Text = "", - ElementShape = new RoundRectShape(5), - BackColor = System.Drawing.Color.LightGreen -}; -shape2.Position = new Telerik.Windows.Diagrams.Core.Point(180, 10); -radDiagram1.AddShape(shape2); - -```` -````VB.NET -Dim shape1 As New RadDiagramShape() With { _ - .Text = "", _ - .IsSelected = True, _ - .ElementShape = New RoundRectShape(5), _ - .BackColor = System.Drawing.Color.LightBlue _ -} -shape1.Position = New Telerik.Windows.Diagrams.Core.Point(10, 10) -RadDiagram1.AddShape(shape1) -Dim shape2 As New RadDiagramShape() With { _ - .Text = "", _ - .ElementShape = New RoundRectShape(5), _ - .BackColor = System.Drawing.Color.LightGreen _ -} -shape2.Position = New Telerik.Windows.Diagrams.Core.Point(180, 10) -RadDiagram1.AddShape(shape2) - -```` - -{{endregion}} + + + + When multiple items are selected, they are automatically added in one Selection Adorner: @@ -96,53 +57,10 @@ When multiple items are selected, they are automatically added in one Selection ![WinForms RadDiagram Selection Adorner](images/diagram-items-manipulation-selection002.png) -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=MultipleSelection}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=MultipleSelection}} + + -````C# - -RadDiagramShape shape1 = new RadDiagramShape() -{ - Text = "", - IsSelected = true, - ElementShape = new RoundRectShape(5), - BackColor = System.Drawing.Color.LightBlue -}; -shape1.Position = new Telerik.Windows.Diagrams.Core.Point(10, 10); -radDiagram1.AddShape(shape1); - -RadDiagramShape shape2 = new RadDiagramShape() -{ - Text = "", - IsSelected = true, - ElementShape = new RoundRectShape(5), - BackColor = System.Drawing.Color.LightGreen -}; -shape2.Position = new Telerik.Windows.Diagrams.Core.Point(180, 10); -radDiagram1.AddShape(shape2); - -```` -````VB.NET -Dim shape1 As New RadDiagramShape() With { _ - .Text = "", _ - .IsSelected = True, _ - .ElementShape = New RoundRectShape(5), _ - .BackColor = System.Drawing.Color.LightBlue _ -} -shape1.Position = New Telerik.Windows.Diagrams.Core.Point(10, 10) -RadDiagram1.AddShape(shape1) -Dim shape2 As New RadDiagramShape() With { _ - .Text = "", _ - .IsSelected = True, _ - .ElementShape = New RoundRectShape(5), _ - .BackColor = System.Drawing.Color.LightGreen _ -} -shape2.Position = New Telerik.Windows.Diagrams.Core.Point(180, 10) -RadDiagram1.AddShape(shape2) - -```` - -{{endregion}} + @@ -151,19 +69,10 @@ You may also want to use the __SelectedIndex__ or the __SelectedItem__ property ![WinForms RadDiagram SelectedIndex or SelectedItem](images/diagram-items-manipulation-selection003.png) -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=SelectedIndex}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=SelectedIndex}} - -````C# -this.radDiagram1.SelectedIndex = 1; - -```` -````VB.NET -Me.RadDiagram1.SelectedIndex = 1 + + -```` - -{{endregion}} + @@ -172,20 +81,10 @@ Me.RadDiagram1.SelectedIndex = 1 You are able to select all __RadDiagramItems__ interactively (by Mouse or by pressing Ctrl + A), programmatically (via the __SelectAll__ method), set the __IsSelected__ property to every Shape and Connection. Below is demonstrated how you can use the __SelectAll__ command: -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=SelectAllCommand}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=SelectAllCommand}} - -````C# - -this.radDiagram1.DiagramElement.TryExecuteCommand(DiagramCommands.SelectAll, ""); + + -```` -````VB.NET -Me.RadDiagram1.DiagramElement.TryExecuteCommand(DiagramCommands.SelectAll, "") - -```` - -{{endregion}} + ## Selections events diff --git a/controls/diagram/items-manipulation/zorder.md b/controls/diagram/items-manipulation/zorder.md index ee6e86c31..5d33ca05c 100644 --- a/controls/diagram/items-manipulation/zorder.md +++ b/controls/diagram/items-manipulation/zorder.md @@ -17,71 +17,10 @@ __RadDiagram__ gives you the ability to control the Z-Order of shapes and connec Consider the following code: -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=ZOrder}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=ZOrder}} - -````C# - -RadDiagramShape shape1 = new RadDiagramShape() -{ - Text = "shape1", - ZIndex = 3, - ElementShape = new EllipseShape(), - BackColor = System.Drawing.Color.LightBlue -}; -shape1.Position = new Telerik.Windows.Diagrams.Core.Point(100, 10); -radDiagram1.AddShape(shape1); - -RadDiagramShape shape2 = new RadDiagramShape() -{ - Text = "shape2", - ZIndex = 2, - ElementShape = new EllipseShape(), - BackColor = System.Drawing.Color.LightGreen -}; -shape2.Position = new Telerik.Windows.Diagrams.Core.Point(150, 60); -radDiagram1.AddShape(shape2); - -RadDiagramShape shape3 = new RadDiagramShape() -{ - Text = "shape3", - ZIndex = 1, - ElementShape = new EllipseShape(), - BackColor = System.Drawing.Color.LightCoral -}; -shape3.Position = new Telerik.Windows.Diagrams.Core.Point(60, 60); -radDiagram1.AddShape(shape3); - -```` -````VB.NET -Dim shape1 As New RadDiagramShape() With { _ - .Text = "shape1", _ - .ZIndex = 3, _ - .ElementShape = New EllipseShape(), _ - .BackColor = System.Drawing.Color.LightBlue _ -} -shape1.Position = New Telerik.Windows.Diagrams.Core.Point(100, 10) -RadDiagram1.AddShape(shape1) -Dim shape2 As New RadDiagramShape() With { _ - .Text = "shape2", _ - .ZIndex = 2, _ - .ElementShape = New EllipseShape(), _ - .BackColor = System.Drawing.Color.LightGreen _ -} -shape2.Position = New Telerik.Windows.Diagrams.Core.Point(150, 60) -RadDiagram1.AddShape(shape2) -Dim shape3 As New RadDiagramShape() With { _ - .Text = "shape3", _ - .ZIndex = 1, _ - .ElementShape = New EllipseShape(), _ - .BackColor = System.Drawing.Color.LightCoral _ -} -shape3.Position = New Telerik.Windows.Diagrams.Core.Point(60, 60) -radDiagram1.AddShape(shape3) - -```` - -{{endregion}} + + + + We have reversed the natural ZOrder of the 3 Shapes. @@ -92,109 +31,10 @@ We have reversed the natural ZOrder of the 3 Shapes. __RadDiagram__ provides a set of predefined commands for manipulating the selected items' ZIndices. "BringForward" and "SendBackward" allow you to increase/decrease the Z-Indices of the selected __RadDiagramItems__. If you need to bring the selected item(s) on top of all other items or below them, you can use "BringToFront" and "SentToback": -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=CommandZIndex}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=CommandZIndex}} - -````C# - -RadDiagramShape shape1 = new RadDiagramShape() -{ - Text = "shape1", - ZIndex = 1, - ElementShape = new EllipseShape(), - BackColor = System.Drawing.Color.LightBlue -}; -shape1.Position = new Telerik.Windows.Diagrams.Core.Point(100, 10); -radDiagram1.AddShape(shape1); - -RadDiagramShape shape2 = new RadDiagramShape() -{ - Text = "shape2", - ZIndex = 2, - ElementShape = new EllipseShape(), - BackColor = System.Drawing.Color.LightGreen -}; -shape2.Position = new Telerik.Windows.Diagrams.Core.Point(150, 80); -radDiagram1.AddShape(shape2); - -RadDiagramShape shape3 = new RadDiagramShape() -{ - Text = "shape3", - ZIndex = 3, - ElementShape = new EllipseShape(), - BackColor = System.Drawing.Color.LightCoral -}; -shape3.Position = new Telerik.Windows.Diagrams.Core.Point(60, 80); -radDiagram1.AddShape(shape3); - -RadDiagramConnection connection1 = new RadDiagramConnection() { Name = "connection1" }; -connection1.Source = shape1; -connection1.Target = shape2; -connection1.ZIndex = 2; -connection1.SourceConnectorPosition = "Right"; -connection1.TargetConnectorPosition = "Right"; - -radDiagram1.Items.Add(connection1); - -RadDiagramConnection connection2 = new RadDiagramConnection() -{ - Name = "connection2" -}; -connection2.Source = shape1; -connection2.Target = shape3; -connection2.ZIndex = 1; -connection2.SourceConnectorPosition = "Left"; -connection2.TargetConnectorPosition = "Left"; -radDiagram1.Items.Add(connection2); - -```` -````VB.NET -Dim shape1 As New RadDiagramShape() With { _ - .Text = "shape1", _ - .ZIndex = 1, _ - .ElementShape = New EllipseShape(), _ - .BackColor = System.Drawing.Color.LightBlue _ -} -shape1.Position = New Telerik.Windows.Diagrams.Core.Point(100, 10) -radDiagram1.AddShape(shape1) -Dim shape2 As New RadDiagramShape() With { _ - .Text = "shape2", _ - .ZIndex = 2, _ - .ElementShape = New EllipseShape(), _ - .BackColor = System.Drawing.Color.LightGreen _ -} -shape2.Position = New Telerik.Windows.Diagrams.Core.Point(150, 80) -RadDiagram1.AddShape(shape2) -Dim shape3 As New RadDiagramShape() With { _ - .Text = "shape3", _ - .ZIndex = 3, _ - .ElementShape = New EllipseShape(), _ - .BackColor = System.Drawing.Color.LightCoral _ -} -shape3.Position = New Telerik.Windows.Diagrams.Core.Point(60, 80) -RadDiagram1.AddShape(shape3) -Dim connection1 As New RadDiagramConnection() With { _ - .Name = "aaaa" _ -} -connection1.Source = shape1 -connection1.Target = shape2 -connection1.ZIndex = 2 -connection1.SourceConnectorPosition = "Right" -connection1.TargetConnectorPosition = "Right" -RadDiagram1.Items.Add(connection1) -Dim connection2 As New RadDiagramConnection() With { _ - .Name = "bbbb" _ -} -connection2.Source = shape1 -connection2.Target = shape3 -connection2.ZIndex = 1 -connection2.SourceConnectorPosition = "Left" -connection2.TargetConnectorPosition = "Left" -radDiagram1.Items.Add(connection2) - -```` - -{{endregion}} + + + + @@ -208,22 +48,10 @@ Here is the result of selecting the first shape and executing the DiagramCommand ![WinForms RadDiagram diagram-items-manipulation-zorder 003](images/diagram-items-manipulation-zorder003.png) -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=BringToFront}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=BringToFront}} - -````C# - -this.radDiagram1.SelectedItem = shape1; -this.radDiagram1.DiagramElement.TryExecuteCommand(DiagramCommands.BringToFront, ""); - -```` -````VB.NET -Me.RadDiagram1.SelectedItem = shape1 -Me.RadDiagram1.DiagramElement.TryExecuteCommand(DiagramCommands.BringToFront, "") + + -```` - -{{endregion}} + Here is the result of selecting the third shape and executing the DiagramCommands.__SendToBack__: @@ -231,22 +59,10 @@ Here is the result of selecting the third shape and executing the DiagramCommand ![WinForms RadDiagram DiagramCommands SendToBack](images/diagram-items-manipulation-zorder004.png) -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=SendToBack}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=SendToBack}} - -````C# - -this.radDiagram1.SelectedItem = shape3; -this.radDiagram1.DiagramElement.TryExecuteCommand(DiagramCommands.SendToBack, ""); + + -```` -````VB.NET -Me.RadDiagram1.SelectedItem = shape3 -Me.RadDiagram1.DiagramElement.TryExecuteCommand(DiagramCommands.SendToBack, "") - -```` - -{{endregion}} + diff --git a/controls/diagram/localization.md b/controls/diagram/localization.md index c46511608..d411c3879 100644 --- a/controls/diagram/localization.md +++ b/controls/diagram/localization.md @@ -24,63 +24,16 @@ To localize __RadDiagramRibbonBar__ to display control text and messages in a sp 2\. Override the __GetLocalizedString(string id)__ method and provide a translation for the texts. If a translation is not provided, the default value will be returned. This behavior is guaranteed by the call to the base __GetLocalizedString__ method in the default clause of the switch statement in the example. Below is a sample implementation of a custom localization provider: -{{source=..\SamplesCS\Diagram\DiagramLocalization.cs region=RibbonUILocalization}} -{{source=..\SamplesVB\Diagram\DiagramLocalization.vb region=RibbonUILocalization}} + + -````C# - -public class MyDiagramRibbonBarLocalizationProvider : DiagramRibbonBarLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case DiagramRibbonBarStringId.DiagramRibbonBarHomeTab: - return "MyHome"; - case DiagramRibbonBarStringId.DiagramRibbonBarButtonOpen: - return "MyOpen"; - default: - return base.GetLocalizedString(id); - } - } -} - -```` -````VB.NET -Public Class MyDiagramRibbonBarLocalizationProvider - Inherits DiagramRibbonBarLocalizationProvider - Public Overrides Function GetLocalizedString(id As String) As String - Select Case id - Case DiagramRibbonBarStringId.DiagramRibbonBarHomeTab - Return "MyHome" - Case DiagramRibbonBarStringId.DiagramRibbonBarButtonOpen - Return "MyOpen" - Case Else - Return MyBase.GetLocalizedString(id) - End Select - End Function -End Class - -```` - -{{endregion}} - -3\. To apply the custom localization provider, instantiate and assign it to the current localization provider: -{{source=..\SamplesCS\Diagram\DiagramLocalization.cs region=SetRibbonUILocalization}} -{{source=..\SamplesVB\Diagram\DiagramLocalization.vb region=SetRibbonUILocalization}} -````C# - -DiagramRibbonBarLocalizationProvider.CurrentProvider = new MyDiagramRibbonBarLocalizationProvider(); - -```` -````VB.NET -DiagramRibbonBarLocalizationProvider.CurrentProvider = New MyDiagramRibbonBarLocalizationProvider() +3\. To apply the custom localization provider, instantiate and assign it to the current localization provider: -```` + + -{{endregion}} ![WinForms RadDiagram Localization Provider](images/diagram-localization001.png) @@ -95,71 +48,16 @@ To localize __RadDiagramSettingsPane__ to display control text and messages in a 2\. Override the __GetLocalizedString(string id)__ method and provide a translation for the texts. If a translation is not provided, the default value will be returned. This behavior is guaranteed by the call to the base __GetLocalizedString__ method in the default clause of the switch statement in the example. -{{source=..\SamplesCS\Diagram\DiagramLocalization.cs region=SettingsPaneLocalization}} -{{source=..\SamplesVB\Diagram\DiagramLocalization.vb region=SettingsPaneLocalization}} - -````C# - -public class MyDiagramSettingsPaneLocalizationProvider : DiagramSettingsPaneLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case DiagramSettingsPaneStringId.LabelCopy: - return "MyCopy"; - case DiagramSettingsPaneStringId.LabelPaste: - return "MyPaste"; - case DiagramSettingsPaneStringId.LabelCut: - return "MyCut"; - case DiagramSettingsPaneStringId.LabelDelete: - return "MyDelete"; - default: - return base.GetLocalizedString(id); - } - } -} - -```` -````VB.NET -Public Class MyDiagramSettingsPaneLocalizationProvider - Inherits DiagramSettingsPaneLocalizationProvider - Public Overrides Function GetLocalizedString(id As String) As String - Select Case id - Case DiagramSettingsPaneStringId.LabelCopy - Return "MyCopy" - Case DiagramSettingsPaneStringId.LabelPaste - Return "MyPaste" - Case DiagramSettingsPaneStringId.LabelCut - Return "MyCut" - Case DiagramSettingsPaneStringId.LabelDelete - Return "MyDelete" - Case Else - Return MyBase.GetLocalizedString(id) - End Select - End Function -End Class - -```` - -{{endregion}} + + -3\. To apply the custom localization provider, instantiate and assign it to the current localization provider: -{{source=..\SamplesCS\Diagram\DiagramLocalization.cs region=SetSettingsPaneLocalization}} -{{source=..\SamplesVB\Diagram\DiagramLocalization.vb region=SetSettingsPaneLocalization}} -````C# - -DiagramSettingsPaneLocalizationProvider.CurrentProvider = new MyDiagramSettingsPaneLocalizationProvider(); - -```` -````VB.NET -DiagramSettingsPaneLocalizationProvider.CurrentProvider = New MyDiagramSettingsPaneLocalizationProvider() +3\. To apply the custom localization provider, instantiate and assign it to the current localization provider: -```` + + -{{endregion}} ![WinForms RadDiagram Custom Localization Provider](images/diagram-localization002.png) diff --git a/controls/diagram/populating-with-data.md b/controls/diagram/populating-with-data.md index e93672278..56e4a06b3 100644 --- a/controls/diagram/populating-with-data.md +++ b/controls/diagram/populating-with-data.md @@ -17,91 +17,9 @@ This article will demonstrate how to define shapes and connections programmatica Below you can find a code snippet which creates three shapes and connections between them: -{{source=..\SamplesCS\Diagram\DiagramPopulatingWithData.cs region=PopulateData}} -{{source=..\SamplesVB\Diagram\DiagramPopulatingWithData.vb region=PopulateData}} - -````C# - -RadDiagramShape shape1 = new RadDiagramShape() -{ - Text = "Second Level Domain", - ElementShape = new RoundRectShape(4), - BackColor = Color.LimeGreen -}; -shape1.Position = new Telerik.Windows.Diagrams.Core.Point(100, 100); -radDiagram1.Items.Add(shape1); - -RadDiagramShape shape2 = new RadDiagramShape() -{ - Text = "Top Level Domain", - ElementShape = new RoundRectShape(50), - BackColor = Color.Cyan -}; -shape2.Position = new Telerik.Windows.Diagrams.Core.Point(400, 100); -radDiagram1.Items.Add(shape2); - -RadDiagramShape shape3 = new RadDiagramShape() -{ - Text = "Organization Domain", - ElementShape = new RoundRectShape(20), - BackColor = Color.Yellow -}; -shape3.Position = new Telerik.Windows.Diagrams.Core.Point(400, 400); -radDiagram1.Items.Add(shape3); - -RadDiagramConnection connection1 = new RadDiagramConnection() -{ Name = "connection1" }; -connection1.Source = shape1; -connection1.Target = shape2; -radDiagram1.Items.Add(connection1); - -RadDiagramConnection connection2 = new RadDiagramConnection() -{ - Name = "connection2" -}; -connection2.Source = shape1; -connection2.Target = shape3; -radDiagram1.Items.Add(connection2); + + -```` -````VB.NET -Dim shape1 As New RadDiagramShape() With { _ - .Text = "Second Level Domain", _ - .ElementShape = New RoundRectShape(4), _ - .BackColor = Color.LimeGreen _ -} -shape1.Position = New Telerik.Windows.Diagrams.Core.Point(100, 100) -RadDiagram1.Items.Add(shape1) -Dim shape2 As New RadDiagramShape() With { _ - .Text = "Top Level Domain", _ - .ElementShape = New RoundRectShape(50), _ - .BackColor = Color.Cyan _ -} -shape2.Position = New Telerik.Windows.Diagrams.Core.Point(400, 100) -RadDiagram1.Items.Add(shape2) -Dim shape3 As New RadDiagramShape() With { _ - .Text = "Organization Domain", _ - .ElementShape = New RoundRectShape(20), _ - .BackColor = Color.Yellow _ -} -shape3.Position = New Telerik.Windows.Diagrams.Core.Point(400, 400) -RadDiagram1.Items.Add(shape3) -Dim connection1 As New RadDiagramConnection() With { _ - .Name = "connection1" _ -} -connection1.Source = shape1 -connection1.Target = shape2 -RadDiagram1.Items.Add(connection1) -Dim connection2 As New RadDiagramConnection() With { _ - .Name = "connection2" _ -} -connection2.Source = shape1 -connection2.Target = shape3 -RadDiagram1.Items.Add(connection2) - -```` - -{{endregion}} ![WinForms RadDiagram Adding Items in Code Behind](images/diagram-populating-with-data001.png) @@ -110,54 +28,8 @@ RadDiagram1.Items.Add(connection2) You can load items in __RadDiagram__ from XML. Here is a sample code snippet: -{{source=..\SamplesCS\Diagram\DiagramPopulatingWithData.cs region=LoadFromXML}} -{{source=..\SamplesVB\Diagram\DiagramPopulatingWithData.vb region=LoadFromXML}} - -````C# - -OpenFileDialog openFileDialog1 = new OpenFileDialog(); - -openFileDialog1.InitialDirectory = "c:\\"; -openFileDialog1.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*"; -openFileDialog1.RestoreDirectory = true; - -if (openFileDialog1.ShowDialog() == DialogResult.OK) -{ - string filename = openFileDialog1.FileName; - - string filelines = File.ReadAllText(filename); - try - { - radDiagram1.DiagramElement.Items.Clear(); - radDiagram1.DiagramElement.Load(filelines); - } - catch (Exception ex) - { - MessageBox.Show("Unable to load " + filename + "\nError: " + ex.Message); - } -} - -```` -````VB.NET -Dim openFileDialog1 As New OpenFileDialog() -openFileDialog1.InitialDirectory = "c:\" -openFileDialog1.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*" -openFileDialog1.RestoreDirectory = True -If openFileDialog1.ShowDialog() = DialogResult.OK Then - Dim filename As String = openFileDialog1.FileName - Dim filelines As String = File.ReadAllText(filename) - Try - RadDiagram1.DiagramElement.Items.Clear() - RadDiagram1.DiagramElement.Load(filelines) - Catch ex As Exception - MessageBox.Show((Convert.ToString("Unable to load ") & filename) + vbLf & "Error: " + ex.Message) - End Try -End If - -```` - -{{endregion}} - + + diff --git a/controls/diagram/settings-pane.md b/controls/diagram/settings-pane.md index 828e9e023..1aa5e0f80 100644 --- a/controls/diagram/settings-pane.md +++ b/controls/diagram/settings-pane.md @@ -18,19 +18,10 @@ This article will get you familiar with the __SettingsPane__ that is part of __R The __SettingsPane__ control allows the users to examine and modify the settings of the diagramming items at run-time. -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=SettingsPane}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=SettingsPane}} + + -````C# -this.radDiagram1.IsSettingsPaneEnabled = true; - -```` -````VB.NET -Me.RadDiagram1.IsSettingsPaneEnabled = True - -```` - -{{endregion}} + @@ -50,21 +41,10 @@ The __SettingsPane__ control is a standalone control that can be displayed as th In order to display the DiagramElement.__SettingsPane__ in your application, you should click the AdditionalContent of the __ItemInformationAdorner__ which can be accessed as below: -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=AdditionalContent}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=AdditionalContent}} + + -````C# -RadButtonElement additionalContent = Telerik.WinControls.UI.Diagrams.Primitives.ItemInformationAdorner.GetAdditionalContent( - this.radDiagram1.DiagramElement.ItemInformationAdorner) as RadButtonElement; - -```` -````VB.NET -Dim additionalContent As RadButtonElement = TryCast(Telerik.WinControls.UI.Diagrams.Primitives.ItemInformationAdorner.GetAdditionalContent( _ -Me.RadDiagram1.DiagramElement.ItemInformationAdorner), RadButtonElement) - -```` - -{{endregion}} + ## Customization @@ -75,25 +55,10 @@ The __SettingsPane__ has a default view that can be used out-of-the-box in scena * __Add and remove tabs__ - in order to add or remove tabs from the default __SettingsPane__, you need to add or remove a __RadPageViewPage__ to or from the DiagramElement.SettingsPane.RadPageView.__Pages__ as this is the control that represents the content of the __SettingsPane__. -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=AddRemoveTabs}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=AddRemoveTabs}} + + -````C# -this.radDiagram1.DiagramElement.SettingsPane.RadPageView.Pages.Remove(this.radDiagram1.DiagramElement.SettingsPane.RadPageViewPageHome); -RadPageViewPage toolsPage = new RadPageViewPage(); -toolsPage.Text = "Tools"; -this.radDiagram1.DiagramElement.SettingsPane.RadPageView.Pages.Add(toolsPage); - -```` -````VB.NET -Me.RadDiagram1.DiagramElement.SettingsPane.RadPageView.Pages.Remove(Me.RadDiagram1.DiagramElement.SettingsPane.RadPageViewPageHome) -Dim toolsPage As New RadPageViewPage() -toolsPage.Text = "Tools" -Me.RadDiagram1.DiagramElement.SettingsPane.RadPageView.Pages.Add(toolsPage) - -```` - -{{endregion}} + @@ -119,30 +84,10 @@ Me.RadDiagram1.DiagramElement.SettingsPane.RadPageView.Pages.Add(toolsPage) >note You have access to each control in every of the default content pages. Hence, you can add, remove, edit controls: > -{{source=..\SamplesCS\Diagram\DiagramItemsManipulation.cs region=EditTabs}} -{{source=..\SamplesVB\Diagram\DiagramItemsManipulation.vb region=EditTabs}} + + -````C# -RadButton myButton = new RadButton(); -myButton.Text = "New"; -myButton.Size = this.radDiagram1.DiagramElement.SettingsPane.RadButtonCut.Size; -myButton.Location = this.radDiagram1.DiagramElement.SettingsPane.RadButtonCut.Location; -this.radDiagram1.DiagramElement.SettingsPane.PanelCopyCutPaste.Controls.Add(myButton); -this.radDiagram1.DiagramElement.SettingsPane.RadButtonCut.Visible = false; - -```` -````VB.NET -Dim myButton As New RadButton() -myButton.Text = "New" -myButton.Size = Me.RadDiagram1.DiagramElement.SettingsPane.RadButtonCut.Size -myButton.Location = Me.RadDiagram1.DiagramElement.SettingsPane.RadButtonCut.Location -Me.RadDiagram1.DiagramElement.SettingsPane.PanelCopyCutPaste.Controls.Add(myButton) -Me.RadDiagram1.DiagramElement.SettingsPane.RadButtonCut.Visible = False - -```` - -{{endregion}} diff --git a/controls/dock/architecture-and-features/dockingguidestemplate.md b/controls/dock/architecture-and-features/dockingguidestemplate.md index 7f71ffc28..a191f23d8 100644 --- a/controls/dock/architecture-and-features/dockingguidestemplate.md +++ b/controls/dock/architecture-and-features/dockingguidestemplate.md @@ -31,20 +31,10 @@ __RadDock__ comes with four predefined docking guides templates: By default, __RadDock__ uses the VS2010 template. In order to use the VS2008 template, you can set it as shown below: -{{source=..\SamplesCS\Dock\dock-architecture-and-features-docking-guides-template.cs region=VS2008}} -{{source=..\SamplesVB\Dock\dock-architecture-and-features-docking-guides-template.vb region=VS2008}} + + -````C# - -this.radDock1.DockingGuidesTemplate = PredefinedDockingGuidesTemplate.VS2008; - -```` -````VB.NET -Me.RadDock1.DockingGuidesTemplate = PredefinedDockingGuidesTemplate.VS2008 - -```` - -{{endregion}} + ## Creating a custom docking guides template @@ -60,71 +50,10 @@ For our custom **DockingGuidesTemplate** we will use the following images (used We should first create a **DockingGuidesTemplate** object and then set the images and their locations on the center background image. **RadDock** will define its hot mouse areas on the **CenterBackground** image depending on the images' locations that we set. The left, top, right and bottom images are reused for the outer guides (outside the center "compass"): -{{source=..\SamplesCS\Dock\dock-architecture-and-features-docking-guides-template.cs region=Template}} -{{source=..\SamplesVB\Dock\dock-architecture-and-features-docking-guides-template.vb region=Template}} - -````C# -DockingGuidesTemplate template; - -void Form1_Load(object sender, EventArgs e) -{ - template = new DockingGuidesTemplate(); -   - template.DockingHintBackColor = Color.FromArgb(30, Color.Green); - template.DockingHintBorderColor = Color.FromArgb(30, Color.DarkGreen); - - template.LeftImage.Image = Properties.Resources.Left; - template.TopImage.Image = Properties.Resources.Top; - template.RightImage.Image = Properties.Resources.Right; - template.BottomImage.Image = Properties.Resources.Bottom; - template.FillImage.Image = Properties.Resources.Fill; - - template.LeftImage.HotImage = Properties.Resources.LeftHot; - template.TopImage.HotImage = Properties.Resources.TopHot; - template.RightImage.HotImage = Properties.Resources.RightHot; - template.BottomImage.HotImage = Properties.Resources.BottomHot; - template.FillImage.HotImage = Properties.Resources.FillHot; - - template.CenterBackgroundImage.Image = Properties.Resources.Center; - - template.LeftImage.LocationOnCenterGuide = new Point(0, 28); - template.TopImage.LocationOnCenterGuide = new Point(28, 0); - template.RightImage.LocationOnCenterGuide = new Point(65, 28); - template.BottomImage.LocationOnCenterGuide = new Point(28, 65); - template.FillImage.LocationOnCenterGuide = new Point(28, 28); - - this.radDock1.DockingGuidesTemplate = template; -} - -```` -````VB.NET -Private template As DockingGuidesTemplate -Private Sub Form1_Load(sender As Object, e As EventArgs) - template = New DockingGuidesTemplate() - template.DockingHintBackColor = Color.FromArgb(30, Color.Green) - template.DockingHintBorderColor = Color.FromArgb(30, Color.DarkGreen) - template.LeftImage.Image = Resources.Left - template.TopImage.Image = Resources.Top - template.RightImage.Image = Resources.Right - template.BottomImage.Image = Resources.Bottom - template.FillImage.Image = Resources.Fill - template.LeftImage.HotImage = Resources.LeftHot - template.TopImage.HotImage = Resources.TopHot - template.RightImage.HotImage = Resources.RightHot - template.BottomImage.HotImage = Resources.BottomHot - template.FillImage.HotImage = Resources.FillHot - template.CenterBackgroundImage.Image = Resources.Center - template.LeftImage.LocationOnCenterGuide = New Point(0, 28) - template.TopImage.LocationOnCenterGuide = New Point(28, 0) - template.RightImage.LocationOnCenterGuide = New Point(65, 28) - template.BottomImage.LocationOnCenterGuide = New Point(28, 65) - template.FillImage.LocationOnCenterGuide = New Point(28, 28) - Me.RadDock1.DockingGuidesTemplate = template -End Sub - -```` - -{{endregion}} + + + + As you can see in the code snippet, we are setting the __DockingHintBackColor__ and __DockingHintBorderColor__ properties which determine the colors of the docking hint area. The result is shown on the figure below: diff --git a/controls/dock/architecture-and-features/document-manager.md b/controls/dock/architecture-and-features/document-manager.md index 11acc8a2a..72bd264c4 100644 --- a/controls/dock/architecture-and-features/document-manager.md +++ b/controls/dock/architecture-and-features/document-manager.md @@ -20,23 +20,10 @@ This property allows you to get the currently active document among the document ![WinForms RadDock ActiveDocument](images/raddock-document-manager001.png) #### Get the active DocumentWindow\ToolWindow -{{source=..\SamplesCS\Dock\DocumentManager1.cs region=activeWindows}} -{{source=..\SamplesVB\Dock\DocumentManager1.vb region=activeWindows}} + + -````C# -DockWindow activeDocument = this.radDock1.DocumentManager.ActiveDocument; //documentWindow2 -DockWindow activeWindow = this.radDock1.ActiveWindow; //toolWindow2 -//set active window/document -this.radDock1.ActiveWindow = activeDocument; - -```` -````VB.NET -Dim activeDocument As DockWindow = Me.RadDock1.DocumentManager.ActiveDocument 'documentWindow2 -Dim activeWindow As DockWindow = Me.RadDock1.ActiveWindow 'toolWindow2 - -```` - -{{endregion}} + ## BoldActiveDocument @@ -44,19 +31,10 @@ Determines whether the currently active document's **Text** will be displayed i #### Use the __BoldActiveDocument__ property -{{source=..\SamplesCS\Dock\DocumentManager1.cs region=boldActive}} -{{source=..\SamplesVB\Dock\DocumentManager1.vb region=boldActive}} + + -````C# -this.radDock1.DocumentManager.BoldActiveDocument = false; - -```` -````VB.NET -Me.RadDock1.DocumentManager.BoldActiveDocument = False - -```` - -{{endregion}} + ## DocumentInsertOrder @@ -64,19 +42,10 @@ Gets or sets the insert order to be used when adding new documents. By default, #### Set the __DocumentInsertOrder__ property -{{source=..\SamplesCS\Dock\DocumentManager2.cs region=insertOrderInFront}} -{{source=..\SamplesVB\Dock\DocumentManager2.vb region=insertOrderInFront}} + + -````C# -this.radDock1.DocumentManager.DocumentInsertOrder = DockWindowInsertOrder.InFront; - -```` -````VB.NET -Me.RadDock1.DocumentManager.DocumentInsertOrder = DockWindowInsertOrder.InFront - -```` - -{{endregion}} + >caption Figure 1: New DocumentWindows are inserted before the first window. @@ -86,19 +55,10 @@ The other available option for this property is *ToBack.* The behavior of **Docu #### Use the *ToBack* insert order -{{source=..\SamplesCS\Dock\DocumentManager2.cs region=insertOrderToBack}} -{{source=..\SamplesVB\Dock\DocumentManager2.vb region=insertOrderToBack}} + + -````C# -this.radDock1.DocumentManager.DocumentInsertOrder = DockWindowInsertOrder.ToBack; - -```` -````VB.NET -Me.RadDock1.DocumentManager.DocumentInsertOrder = DockWindowInsertOrder.ToBack - -```` - -{{endregion}} + >caption Figure 2: New Document windows are inserted after the first window. diff --git a/controls/dock/architecture-and-features/floating-windows.md b/controls/dock/architecture-and-features/floating-windows.md index 94c21b854..d45b64bbd 100644 --- a/controls/dock/architecture-and-features/floating-windows.md +++ b/controls/dock/architecture-and-features/floating-windows.md @@ -73,19 +73,10 @@ You can drag document windows to an existing floating container. Select left, ri To enable the Visual Studio 2008-like docking behavior, set the __SingleScreen__ property to *true*. Enabling this property will prevent document windows from floating and from docking inside existing floating windows. -{{source=..\SamplesCS\Dock\ArchitectureAndFeatures.cs region=floatingTabsMode}} -{{source=..\SamplesVB\Dock\ArchitectureAndFeatures.vb region=floatingTabsMode}} + + -````C# -this.radDock1.SingleScreen = true; - -```` -````VB.NET -Me.RadDock1.SingleScreen = True - -```` - -{{endregion}} + ## Properties diff --git a/controls/dock/architecture-and-features/using-the-commandmanager.md b/controls/dock/architecture-and-features/using-the-commandmanager.md index 0f9736da8..299d12ce1 100644 --- a/controls/dock/architecture-and-features/using-the-commandmanager.md +++ b/controls/dock/architecture-and-features/using-the-commandmanager.md @@ -27,28 +27,10 @@ The names of all predefined commands may be found in the static **PredefinedComm You may easily specify custom shortcut for any of the predefined commands like this: -{{source=..\SamplesCS\Dock\UsingCommandManager.cs region=Shortcut}} -{{source=..\SamplesVB\Dock\UsingCommandManager.vb region=Shortcut}} - -````C# -private void ChangeNextDocumentShortcut() -{ - RadDockCommand command = this.radDock1.CommandManager.FindCommandByName(PredefinedCommandNames.NextDocument); - command.Shortcuts.Clear(); - command.Shortcuts.Add(new RadShortcut(Keys.Shift, Keys.A, Keys.S)); -} - -```` -````VB.NET -Private Sub ChangeNextDocumentShortcut() - Dim command As RadDockCommand = Me.radDock1.CommandManager.FindCommandByName(PredefinedCommandNames.NextDocument) - command.Shortcuts.Clear() - command.Shortcuts.Add(New RadShortcut(Keys.Shift, Keys.A, Keys.S)) -End Sub - -```` - -{{endregion}} + + + + The above code specifies the **SHIFT+A+S** as a valid key combination that will trigger the **NextDocument** command. @@ -58,90 +40,18 @@ The completely transparent object model of the command manager allows you to cre #### Define the custom command class -{{source=..\SamplesCS\Dock\UsingCommandManager.cs region=RadDockCommand}} -{{source=..\SamplesVB\Dock\UsingCommandManager.vb region=RadDockCommand}} - -````C# -public class FloatWindowCommand : RadDockCommand -{ - public FloatWindowCommand() - { - this.Name = "FloatWindow"; - this.Shortcuts.Add(new RadShortcut(Keys.Control, Keys.F)); - } - public override bool CanExecute(object parameter) - { - RadDock dock = parameter as RadDock; - if (dock == null) - { - return false; - } - return dock.ActiveWindow is ToolWindow; - } - public override object Execute(params object[] settings) - { - RadDock dock = settings[0] as RadDock; - Debug.Assert(dock != null, "Invalid execute parameter!"); - ToolWindow toolWindow = dock.ActiveWindow as ToolWindow; - if (toolWindow != null) - { - dock.FloatWindow(toolWindow); - } - return base.Execute(settings); - } -} - -```` -````VB.NET -Public Class FloatWindowCommand - Inherits RadDockCommand - Public Sub New() - Me.Name = "FloatWindow" - Me.Shortcuts.Add(New RadShortcut(Keys.Control, Keys.F)) - End Sub - Public Overrides Function CanExecute(parameter As Object) As Boolean - Dim dock As RadDock = TryCast(parameter, RadDock) - If dock Is Nothing Then - Return False - End If - Return TypeOf dock.ActiveWindow Is ToolWindow - End Function - Public Overrides Function Execute(ParamArray settings As Object()) As Object - Dim dock As RadDock = TryCast(settings(0), RadDock) - Debug.Assert(dock IsNot Nothing, "Invalid execute parameter!") - Dim toolWindow As ToolWindow = TryCast(dock.ActiveWindow, ToolWindow) - If toolWindow IsNot Nothing Then - dock.FloatWindow(toolWindow) - End If - Return MyBase.Execute(settings) - End Function -End Class - -```` - -{{endregion}} + + + + #### Register the custom command -{{source=..\SamplesCS\Dock\UsingCommandManager.cs region=RegisterCustomCommand}} -{{source=..\SamplesVB\Dock\UsingCommandManager.vb region=RegisterCustomCommand}} - -````C# -private void RegisterCustomCommand() -{ - this.radDock1.CommandManager.RegisterCommand(new FloatWindowCommand()); -} - -```` -````VB.NET -Private Sub RegisterCustomCommand() - Me.radDock1.CommandManager.RegisterCommand(New FloatWindowCommand()) -End Sub - -```` - -{{endregion}} + + + + ## Enable/Disable the Command Manager diff --git a/controls/dock/architecture-and-features/using-the-contextmenuservice.md b/controls/dock/architecture-and-features/using-the-contextmenuservice.md index 83cb77aee..bda9d7413 100644 --- a/controls/dock/architecture-and-features/using-the-contextmenuservice.md +++ b/controls/dock/architecture-and-features/using-the-contextmenuservice.md @@ -26,73 +26,19 @@ Let's get the **ContextMenuService** and subscribe to its **ContextMenuDisplayi #### Getting the ContextMenuService -{{source=..\SamplesCS\Dock\ArchitectureAndFeatures.cs region=gettingContextMenuService}} -{{source=..\SamplesVB\Dock\ArchitectureAndFeatures.vb region=gettingContextMenuService}} + + -````C# -ContextMenuService menuService = this.radDock1.GetService(); -menuService.ContextMenuDisplaying += menuService_ContextMenuDisplaying; - -```` -````VB.NET -Dim menuService As ContextMenuService = Me.RadDock1.GetService(Of ContextMenuService)() -AddHandler menuService.ContextMenuDisplaying, AddressOf menuService_ContextMenuDisplaying - -```` - -{{endregion}} + Then, hide the 'Close' options in the **ContextMenuDisplaying** event handler: #### Hiding the 'close' menu items -{{source=..\SamplesCS\Dock\ArchitectureAndFeatures.cs region=handlingContextMenuDisplaying}} -{{source=..\SamplesVB\Dock\ArchitectureAndFeatures.vb region=handlingContextMenuDisplaying}} - -````C# -private void menuService_ContextMenuDisplaying(object sender, ContextMenuDisplayingEventArgs e) -{ - //the menu request is associated with a valid DockWindow instance, which resides within a DocumentTabStrip - if (e.MenuType == ContextMenuType.DockWindow && - e.DockWindow.DockTabStrip is DocumentTabStrip) - { - //remove the "Close" menu items - for (int i = 0; i < e.MenuItems.Count; i++) - { - RadMenuItemBase menuItem = e.MenuItems[i]; - if (menuItem.Name == "CloseWindow" || - menuItem.Name == "CloseAllButThis" || - menuItem.Name == "CloseAll" || - menuItem is RadMenuSeparatorItem) - { - // In case you just want to disable to option you can set Enabled false - //menuItem.Enabled = false; - menuItem.Visibility = Telerik.WinControls.ElementVisibility.Collapsed; - } - } - } -} + + -```` -````VB.NET -Private Sub menuService_ContextMenuDisplaying(ByVal sender As Object, ByVal e As ContextMenuDisplayingEventArgs) - 'the menu request is associated with a valid DockWindow instance, which resides within a DocumentTabStrip - If e.MenuType = ContextMenuType.DockWindow AndAlso TypeOf e.DockWindow.DockTabStrip Is DocumentTabStrip Then - 'remove the "Close" menu items - For i As Integer = 0 To e.MenuItems.Count - 1 - Dim menuItem As RadMenuItemBase = e.MenuItems(i) - If menuItem.Name = "CloseWindow" OrElse menuItem.Name = "CloseAllButThis" OrElse menuItem.Name = "CloseAll" OrElse TypeOf menuItem Is RadMenuSeparatorItem Then - ' In case you just want to disable to option you can set Enabled false - 'menuItem.Enabled = false; - menuItem.Visibility = Telerik.WinControls.ElementVisibility.Collapsed - End If - Next i - End If -End Sub - -```` - -{{endregion}} + The result is shown on the screenshot below: diff --git a/controls/dock/architecture-and-features/using-the-dragdropservice.md b/controls/dock/architecture-and-features/using-the-dragdropservice.md index bd037c131..6d0c97800 100644 --- a/controls/dock/architecture-and-features/using-the-dragdropservice.md +++ b/controls/dock/architecture-and-features/using-the-dragdropservice.md @@ -20,21 +20,10 @@ A running drag-and-drop operation (DDO) may be easily canceled by either pressin #### Canceling Drag-and-drop operation -{{source=..\SamplesCS\Dock\ArchitectureAndFeatures.cs region=cancellingService}} -{{source=..\SamplesVB\Dock\ArchitectureAndFeatures.vb region=cancellingService}} + + -````C# -DragDropService service = this.radDock1.GetService(); -service.Stop(false); - -```` -````VB.NET -Dim service As DragDropService = Me.RadDock1.GetService(Of DragDropService)() -service.Stop(False) - -```` - -{{endregion}} + The Boolean parameter determines whether the operation should be committed (applied) or not. @@ -46,19 +35,10 @@ You can switch between *Preview* and *Immediate* modes by setting the __DragDro #### Setting DragDropMode -{{source=..\SamplesCS\Dock\ArchitectureAndFeatures.cs region=dragDropMode}} -{{source=..\SamplesVB\Dock\ArchitectureAndFeatures.vb region=dragDropMode}} - -````C# -this.radDock1.DragDropMode = DragDropMode.Preview; + + -```` -````VB.NET -Me.RadDock1.DragDropMode = DragDropMode.Preview - -```` - -{{endregion}} + ## AllowedDockStates @@ -66,21 +46,10 @@ The service may be told which dock states are allowed to be hit-tested. For exam #### Setting AllowedStates -{{source=..\SamplesCS\Dock\ArchitectureAndFeatures.cs region=dragDropAllowedStates}} -{{source=..\SamplesVB\Dock\ArchitectureAndFeatures.vb region=dragDropAllowedStates}} - -````C# -DragDropService service = this.radDock1.GetService(); -service.AllowedStates &= ~AllowedDockState.Floating; + + -```` -````VB.NET -Dim service As DragDropService = Me.RadDock1.GetService(Of DragDropService)() -service.AllowedStates = service.AllowedStates And Not AllowedDockState.Floating - -```` - -{{endregion}} + ## Extending Service’s Behavior by Handling Events @@ -104,39 +73,10 @@ The following example demonstrates how to allow only DockPosition.*Bottom* for t #### Handling DragDropService events -{{source=..\SamplesCS\Dock\ArchitectureAndFeatures.cs region=initDragDropEvents}} -{{source=..\SamplesVB\Dock\ArchitectureAndFeatures.vb region=initDragDropEvents}} - -````C# -private void InitDragDropEvents() -{ - DragDropService service = this.radDock1.GetService(); - service.PreviewDockPosition += new DragDropDockPositionEventHandler(service_PreviewDockPosition); -} - -private void service_PreviewDockPosition(object sender, DragDropDockPositionEventArgs e) -{ - if (e.DropTarget == this.radDock1.MainDocumentContainer) - { - e.AllowedDockPosition = AllowedDockPosition.Bottom; - } -} - -```` -````VB.NET -Private Sub InitDragDropEvents() - Dim service As DragDropService = Me.RadDock1.GetService(Of DragDropService)() - AddHandler service.PreviewDockPosition, AddressOf service_PreviewDockPosition -End Sub -Private Sub service_PreviewDockPosition(ByVal sender As Object, ByVal e As DragDropDockPositionEventArgs) - If e.DropTarget Is Me.RadDock1.MainDocumentContainer Then - e.AllowedDockPosition = AllowedDockPosition.Bottom - End If -End Sub - -```` - -{{endregion}} + + + + >caption Figure 1: Only DockPosition.Bottom is allowed. @@ -148,26 +88,10 @@ The service may be told which edges of the owning **RadDock** instance are allow #### Setting AllowedDockManagerEdges -{{source=..\SamplesCS\Dock\ArchitectureAndFeatures.cs region=initDragDropProperties}} -{{source=..\SamplesVB\Dock\ArchitectureAndFeatures.vb region=initDragDropProperties}} + + -````C# -private void InitDragDropProperties() -{ - DragDropService service = this.radDock1.GetService(); - service.AllowedDockManagerEdges = AllowedDockPosition.Left | AllowedDockPosition.Right; -} - -```` -````VB.NET -Private Sub InitDragDropProperties() - Dim service As DragDropService = Me.RadDock1.GetService(Of DragDropService)() - service.AllowedDockManagerEdges = AllowedDockPosition.Left Or AllowedDockPosition.Right -End Sub - -```` - -{{endregion}} + >caption Figure 2: Only DockPosition.Left and DockPosition.Right are available. diff --git a/controls/dock/architecture-and-features/using-the-redockservice.md b/controls/dock/architecture-and-features/using-the-redockservice.md index 651d70ffb..e5b1d5806 100644 --- a/controls/dock/architecture-and-features/using-the-redockservice.md +++ b/controls/dock/architecture-and-features/using-the-redockservice.md @@ -25,36 +25,10 @@ Let's take a look at the following scenario: 1. Now comes the time when the user wants to re-dock the floating **ToolWindows**. However, the user does not only want to dock the **ToolWindows**, he/she want to achieve the layout that he/she had at the beginning. For that purpose, we can have a button or a menu item on the **Click** of which we get the **RedockService** and return the floating windows to their original docked state by calling the __RestoreMethod__ of the service. When the user clicks that button, he/she will get the layout below, which as you can see is the same as the layout that we had at the beginning: -{{source=..\SamplesCS\Dock\UsingTheRedockService.cs region=redockService}} -{{source=..\SamplesVB\Dock\UsingTheRedockService.vb region=redockService}} + + -````C# -void radButton1_Click(object sender, EventArgs e) -{ - RedockService service = this.radDock1.GetService(); - foreach (DockWindow window in this.radDock1.DockWindows) - { - if (window.DockState == DockState.Floating) - { - service.RestoreState(window, DockState.Docked, true); - } - } -} - -```` -````VB.NET -Private Sub radButton1_Click(ByVal sender As Object, ByVal e As EventArgs) - Dim service As RedockService = Me.RadDock1.GetService(Of RedockService)() - For Each window As DockWindow In Me.RadDock1.DockWindows - If window.DockState = DockState.Floating Then - service.RestoreState(window, DockState.Docked, True) - End If - Next window -End Sub - -```` - -{{endregion}} + ![WinForms RadDock Redock Floating ToolWindows](images/dock-architecture-and-features-using-the-redockservice001.png) diff --git a/controls/dock/docking-usercontrols-and-forms/docking-a-usercontrol-with-custom-event.md b/controls/dock/docking-usercontrols-and-forms/docking-a-usercontrol-with-custom-event.md index a1d9ca2cc..a0eb7ca61 100644 --- a/controls/dock/docking-usercontrols-and-forms/docking-a-usercontrol-with-custom-event.md +++ b/controls/dock/docking-usercontrols-and-forms/docking-a-usercontrol-with-custom-event.md @@ -35,47 +35,19 @@ In our particular case we dock a user control instance inside a __RadDock__ inst #### Setting up DateChanged Event -{{source=..\SamplesCS\Dock\CalendarPanel.cs region=definingDelegates}} -{{source=..\SamplesVB\Dock\CalendarPanel.vb region=definingDelegates}} + + -````C# -public delegate void DateChangedHandler(DateTime date); -public event DateChangedHandler DateChanged; - -```` -````VB.NET -Public Delegate Sub DateChangedHandler(ByVal [date] As DateTime) -Public Event DateChanged As DateChangedHandler - -```` - -{{endregion}} + In the __SelectionChanged__ event handler add the following code: #### Handling the RadCalendar SelectionChanged event -{{source=..\SamplesCS\Dock\CalendarPanel.cs region=handlingSelectionChanged}} -{{source=..\SamplesVB\Dock\CalendarPanel.vb region=handlingSelectionChanged}} + + -````C# -private void radCalendar1_SelectionChanged(object sender, EventArgs e) -{ - if (DateChanged != null) - { - DateChanged((sender as Telerik.WinControls.UI.RadCalendar).SelectedDate); - } -} - -```` -````VB.NET -Private Sub RadCalendar1_SelectionChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadCalendar1.SelectionChanged - RaiseEvent DateChanged((TryCast(sender, RadCalendar)).SelectedDate) -End Sub - -```` - -{{endregion}} + 7\. In the Solution Explorer, double-click the main form to open its design surface. @@ -85,48 +57,19 @@ End Sub #### Docking CalendarPanel user control in RadDock -{{source=..\SamplesCS\Dock\DockingForms.cs region=creatingCalendarPanel}} -{{source=..\SamplesVB\Dock\DockingForms.vb region=creatingCalendarPanel}} - -````C# -CalendarPanel calendarPanel = new CalendarPanel(); -HostWindow host = this.radDock1.DockControl(calendarPanel, Telerik.WinControls.UI.Docking.DockPosition.Left); -host.Text = "Calendar"; -calendarPanel.DateChanged += calendarPanel_DateChanged; - -```` -````VB.NET -Dim calendarPanel As New CalendarPanel() -Dim host As HostWindow = Me.RadDock1.DockControl(calendarPanel, Telerik.WinControls.UI.Docking.DockPosition.Left) -host.Text = "Calendar" -AddHandler calendarPanel.DateChanged, AddressOf calendarPanel_DateChanged - -```` - -{{endregion}} + + + + 10\. Add an event handler for the CalendarPanel **DateChanged** event: #### Handling the Custom DateChanged event -{{source=..\SamplesCS\Dock\DockingForms.cs region=handlingDateChanged}} -{{source=..\SamplesVB\Dock\DockingForms.vb region=handlingDateChanged}} - -````C# -void calendarPanel_DateChanged(DateTime date) -{ - RadMessageBox.Show("Selected date is: " + date.ToShortDateString()); -} + + -```` -````VB.NET -Sub calendarPanel_DateChanged(ByVal [date] As DateTime) - RadMessageBox.Show("Selected date is: " + [date].ToShortDateString()) -End Sub - -```` - -{{endregion}} + 11\. Press __F5__ to run the application. Click the cells in the calendar to display the date in a message dialog. diff --git a/controls/dock/docking-usercontrols-and-forms/docking-singleton-forms.md b/controls/dock/docking-usercontrols-and-forms/docking-singleton-forms.md index e60ba2441..30e1bdf7a 100644 --- a/controls/dock/docking-usercontrols-and-forms/docking-singleton-forms.md +++ b/controls/dock/docking-usercontrols-and-forms/docking-singleton-forms.md @@ -27,111 +27,17 @@ Here is how to do that: 1\. For each of the types of forms that we create, we should create a corresponding **DocumentWindow**/**ToolWindow** that serves as a container. Initially, global variables for the **DocumentWindows**/**ToolWindows** should be defined without creating new objects. -{{source=..\SamplesCS\Dock\SingletonForms.cs region=fields}} -{{source=..\SamplesVB\Dock\SingletonForms.vb region=fields}} + + -````C# -DocumentWindow greenDockWindow; -DocumentWindow yellowDockWindow; - -```` -````VB.NET -Private greenDockWindow As DocumentWindow -Private yellowDockWindow As DocumentWindow - -```` - -{{endregion}} + 2\. Upon clicking a button for opening a specific type of form, we should check if an object of the appropriate **DocumentWindow** exists. If it does not exist, this means that a form of the type that matches the **DocumentWindow** has never been created, so we need to create such a form together with the **DocumentWindow**. Note that we set the __CloseAction__ of the **DocumentWindow** to *Hide*. When the end-user closes the **DocumentWindow**, it actually becomes hidden rather than closed and disposed. This allows us to use the same instance later. After creating the form and the window, we should dock the form in the window - this will allow us to control the form together with the **DocumentWindow** that hosts it using the globally defined **DocumentWindow** variables. Finally, we should just show the **DocumentWindow**. If the **DocumentWindow** has already been created the previous time we pressed the 'show' button, we should just show it: -{{source=..\SamplesCS\Dock\SingletonForms.cs region=clickHandlers}} -{{source=..\SamplesVB\Dock\SingletonForms.vb region=clickHandlers}} + + -````C# -private void btnOpenGreenForm_Click(object sender, EventArgs e) -{ - if (greenDockWindow == null) - { - greenDockWindow = new DocumentWindow(); - greenDockWindow.Text = "Green Form"; - greenDockWindow.CloseAction = DockWindowCloseAction.Hide; - GreenForm gForm = new GreenForm(); - gForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; - gForm.TopLevel = false; - gForm.Dock = DockStyle.Fill; - greenDockWindow.Controls.Add(gForm); - this.radDock1.AddDocument(greenDockWindow); - gForm.Show(); - } - else - { - greenDockWindow.Show(); - } - this.radDock1.ActiveWindow = greenDockWindow; -} -private void btnOpenYellowForm_Click(object sender, EventArgs e) -{ - if (yellowDockWindow == null) - { - yellowDockWindow = new DocumentWindow(); - yellowDockWindow.Text = "Yellow Form"; - yellowDockWindow.CloseAction = DockWindowCloseAction.Hide; - YellowForm yForm = new YellowForm(); - yForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; - yForm.TopLevel = false; - yForm.Dock = DockStyle.Fill; - yellowDockWindow.Controls.Add(yForm); - this.radDock1.AddDocument(yellowDockWindow); - yForm.Show(); - } - else - { - yellowDockWindow.Show(); - } - this.radDock1.ActiveWindow = yellowDockWindow; -} - -```` -````VB.NET -Private Sub btnOpenGreenForm_Click(ByVal sender As Object, ByVal e As EventArgs) - If greenDockWindow Is Nothing Then - greenDockWindow = New DocumentWindow() - greenDockWindow.Text = "Green Form" - greenDockWindow.CloseAction = DockWindowCloseAction.Hide - Dim gForm As New GreenForm() - gForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None - gForm.TopLevel = False - gForm.Dock = DockStyle.Fill - greenDockWindow.Controls.Add(gForm) - Me.RadDock1.AddDocument(greenDockWindow) - gForm.Show() - Else - greenDockWindow.Show() - End If - Me.RadDock1.ActiveWindow = greenDockWindow -End Sub -Private Sub btnOpenYellowForm_Click(ByVal sender As Object, ByVal e As EventArgs) - If yellowDockWindow Is Nothing Then - yellowDockWindow = New DocumentWindow() - yellowDockWindow.Text = "Yellow Form" - yellowDockWindow.CloseAction = DockWindowCloseAction.Hide - Dim yForm As New YellowForm() - yForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None - yForm.TopLevel = False - yForm.Dock = DockStyle.Fill - yellowDockWindow.Controls.Add(yForm) - Me.RadDock1.AddDocument(yellowDockWindow) - yForm.Show() - Else - yellowDockWindow.Show() - End If - Me.RadDock1.ActiveWindow = yellowDockWindow -End Sub - -```` - -{{endregion}} + # See Also diff --git a/controls/dock/docking-usercontrols-and-forms/get-a-hostwindow-by-its-content.md b/controls/dock/docking-usercontrols-and-forms/get-a-hostwindow-by-its-content.md index dbd4bcc7c..c89330386 100644 --- a/controls/dock/docking-usercontrols-and-forms/get-a-hostwindow-by-its-content.md +++ b/controls/dock/docking-usercontrols-and-forms/get-a-hostwindow-by-its-content.md @@ -15,54 +15,19 @@ In certain cases, you may need to perform specific operations depending on the In order to do this, you should first subscribe to the **ActiveWindowChanged** event and then execute the following code snippet in the **ActiveWindowChanged** event handler: -{{source=..\SamplesCS\Dock\DockingForms.cs region=handlingActiveWindowChanged}} -{{source=..\SamplesVB\Dock\DockingForms.vb region=handlingActiveWindowChanged}} + + -````C# -void radDock1_ActiveWindowChanged(object sender, Telerik.WinControls.UI.Docking.DockWindowEventArgs e) -{ - HostWindow hostWin = e.DockWindow as HostWindow; - if (hostWin != null) - { - if (hostWin.Content is VegetablesForm) - { - // custom implementation here - } - } -} - -```` -````VB.NET -Private Sub radDock1_ActiveWindowChanged(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.Docking.DockWindowEventArgs) - Dim hostWin As HostWindow = TryCast(e.DockWindow, HostWindow) - If Not hostWin Is Nothing Then - If TypeOf hostWin.Content Is VegetablesForm Then - ' custom implementation here - End If - End If -End Sub - -```` - -{{endregion}} + ## Getting a HostWindow by its content In order to get a **HostWindow** that hosts a particular form/user control instance, you should call the __GetHostWindows__ method passing the contained control as a parameter. Supposing that `vegetablesForm` is an instance of type **VegetablesForm**, we can use the following code snippet: -{{source=..\SamplesCS\Dock\DockingForms.cs region=gettingWindow}} -{{source=..\SamplesVB\Dock\DockingForms.vb region=gettingWindow}} - -````C# -HostWindow vegetablesWindow = this.radDock1.GetHostWindow(vegetablesForm); - -```` -````VB.NET -Dim vegetablesWindow As HostWindow = Me.RadDock1.GetHostWindow(VegetablesForm) - -```` + + -{{endregion}} + # See Also diff --git a/controls/dock/docking-usercontrols-and-forms/getting-started.md b/controls/dock/docking-usercontrols-and-forms/getting-started.md index 04696144f..51c23bf1e 100644 --- a/controls/dock/docking-usercontrols-and-forms/getting-started.md +++ b/controls/dock/docking-usercontrols-and-forms/getting-started.md @@ -17,27 +17,10 @@ For example, the following code snippet will result in the screenshot shown belo #### Docking a Form -{{source=..\SamplesCS\Dock\DockingForms.cs region=dockingForm}} -{{source=..\SamplesVB\Dock\DockingForms.vb region=dockingForm}} - -````C# -Form form = new Form(); -form.BackColor = Color.Pink; -form.Text = "My Form"; -this.radDock1.DockControl(form, DockPosition.Left); -form.Show(); - -```` -````VB.NET -Dim form As Form = New Form() -form.BackColor = Color.Pink -form.Text = "My Form" -Me.RadDock1.DockControl(form, DockPosition.Left) -form.Show() - -```` - -{{endregion}} + + + + ![WinForms RadDock Getting Started With UserControl and Forms](images/dock-docking-usercontrols-and-forms-getting-started001.png) diff --git a/controls/dock/getting-started.md b/controls/dock/getting-started.md index c2635da40..204023dd5 100644 --- a/controls/dock/getting-started.md +++ b/controls/dock/getting-started.md @@ -86,101 +86,28 @@ For more complex scenarios the advanced layout designer provides full drag and d #### Include namespaces -{{source=..\SamplesCS\Dock\GettingStarted.cs region=namespace}} -{{source=..\SamplesVB\Dock\GettingStarted.vb region=namespace}} + + -````C# -using Telerik.WinControls.UI; -using Telerik.WinControls.UI.Docking; - -```` -````VB.NET -Imports Telerik.WinControls.UI -Imports Telerik.WinControls.UI.Docking - -```` - -{{endregion}} + 15\. Create a Form.__Load__ event handler and copy the code below to it. This code builds the __TreeView__ node structure and links the __Name__ of each __DocumentWindow__ to the corresponding Node.__Tag__ property. Each dockable object has a __Name__ property, a __String__ that uniquely identifies it. Later, we use the __Name__ to locate the __DocumentWindow__ and activate it. #### Initializing RadTreeView -{{source=..\SamplesCS\Dock\GettingStarted.cs region=settingUpTree}} -{{source=..\SamplesVB\Dock\GettingStarted.vb region=settingUpTree}} - -````C# -void Form1_Load(object sender, EventArgs e) -{ - RadTreeNode productNode = radTreeView1.Nodes.Add("Product Reports"); - RadTreeNode customerNode = radTreeView1.Nodes.Add("Customer Reports"); - RadTreeNode productListingNode = new RadTreeNode("Product Listing"); - productListingNode.Tag = dwProductListing.Name; - RadTreeNode productCategoryNode = new RadTreeNode("Product By Category"); - productCategoryNode.Tag = dwProductByCategory.Name; - RadTreeNode top10CustomerNode = new RadTreeNode("Top 10 Customers"); - top10CustomerNode.Tag = dwTop10Customers.Name; - productNode.Nodes.Add(productListingNode); - productNode.Nodes.Add(productCategoryNode); - customerNode.Nodes.Add(top10CustomerNode); - radTreeView1.ExpandAll(); -} - -```` -````VB.NET -Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load - Dim productNode As RadTreeNode = RadTreeView1.Nodes.Add("Product Reports") - Dim customerNode As RadTreeNode = RadTreeView1.Nodes.Add("Customer Reports") - Dim productListingNode As New RadTreeNode("Product Listing") - productListingNode.Tag = dwProductListing.Name - Dim productCategoryNode As New RadTreeNode("Product By Category") - productCategoryNode.Tag = dwProductByCategory.Name - Dim top10CustomerNode As New RadTreeNode("Top 10 Customers") - top10CustomerNode.Tag = dwTop10Customers.Name - productNode.Nodes.Add(productListingNode) - productNode.Nodes.Add(productCategoryNode) - customerNode.Nodes.Add(top10CustomerNode) - RadTreeView1.ExpandAll() -End Sub - -```` - -{{endregion}} + + + + 16\. Create a __SelectedNodeChanged__ event handler and add the following code to it. The code for this event handler verifies that the __Tag__ of the selected node has a value. Further, if this value corresponds to the name of an existing window in __RadDock__, the appropriate **DocumentWindow** gets activated. #### Handling the RadTreeView SelectedNodeChanged event -{{source=..\SamplesCS\Dock\GettingStarted.cs region=handlingSelectedNodeChanged}} -{{source=..\SamplesVB\Dock\GettingStarted.vb region=handlingSelectedNodeChanged}} - -````C# -void radTreeView1_SelectedNodeChanged(object sender, RadTreeViewEventArgs e) -{ - if (e.Node.Tag != null) - { - DockWindow dw = this.radDock1[e.Node.Tag.ToString()]; - if (dw != null) - { - this.radDock1.ActiveWindow = dw; - } - } -} - -```` -````VB.NET -Private Sub RadTreeView1_SelectedNodeChanged(ByVal sender As Object, ByVal e As RadTreeViewEventArgs) - If Not e.Node.Tag Is Nothing Then - Dim dw As DockWindow = Me.RadDock1(e.Node.Tag.ToString()) - If Not dw Is Nothing Then - Me.RadDock1.ActiveWindow = dw - End If - End If -End Sub - -```` - -{{endregion}} + + + + Press __F5__ to run the application. Try experimenting with... diff --git a/controls/dock/loading-and-saving-layouts/loading-and-saving-layouts.md b/controls/dock/loading-and-saving-layouts/loading-and-saving-layouts.md index b223769aa..6b00124de 100644 --- a/controls/dock/loading-and-saving-layouts/loading-and-saving-layouts.md +++ b/controls/dock/loading-and-saving-layouts/loading-and-saving-layouts.md @@ -19,45 +19,17 @@ To save a layout, call the __RadDock.SaveToXML__ method: #### SaveToXml -{{source=..\SamplesCS\Dock\SaveLoadLayout.cs region=saveLayout}} -{{source=..\SamplesVB\Dock\SaveLoadLayout.vb region=saveLayout}} + + -````C# -this.radDock1.SaveToXml("c:\\layout1.xml"); - -```` -````VB.NET -Me.RadDock1.SaveToXml("c:\layout1.xml") - -```` - -{{endregion}} + You can use the __DockWindowSerializing__ event to exclude windows from the saved layout: -{{source=..\SamplesCS\Dock\SaveLoadLayout.cs region=Serializing}} -{{source=..\SamplesVB\Dock\SaveLoadLayout.vb region=Serializing}} - -````C# -void radDock1_DockWindowSerializing(object sender, DockWindowCancelEventArgs e) -{ - if (e.NewWindow.Text == "Window Top") - { - e.Cancel = true; - } -} - -```` -````VB.NET -Private Sub radDock1_DockWindowSerializing(ByVal sender As Object, ByVal e As DockWindowCancelEventArgs) - If e.NewWindow.Text = "Window Top" Then - e.Cancel = True - End If -End Sub - -```` - -{{endregion}} + + + + ## To Load a Layout @@ -66,19 +38,10 @@ To load a layout, call the __RadDock.LoadFromXML__ method: #### LoadFromXml -{{source=..\SamplesCS\Dock\SaveLoadLayout.cs region=loadLayout}} -{{source=..\SamplesVB\Dock\SaveLoadLayout.vb region=loadLayout}} - -````C# -this.radDock1.LoadFromXml("c:\\layout1.xml"); - -```` -````VB.NET -Me.RadDock1.LoadFromXml("c:\layout1.xml") + + -```` - -{{endregion}} + >note With the introduction of the __R3 2023 SP1__ version of our controls, the __LoadFromXml()__ expose second (optional) parameter. This parameter provides the option to specify whether to remove all existing dock windows or not. By default, the second parameter is set to __false__. diff --git a/controls/dock/loading-and-saving-layouts/tutorial-saving-and-loading-layout-and-content.md b/controls/dock/loading-and-saving-layouts/tutorial-saving-and-loading-layout-and-content.md index 8b9a55d7a..f1f8f841c 100644 --- a/controls/dock/loading-and-saving-layouts/tutorial-saving-and-loading-layout-and-content.md +++ b/controls/dock/loading-and-saving-layouts/tutorial-saving-and-loading-layout-and-content.md @@ -28,72 +28,17 @@ As stated in [this documentation article]({%slug winforms/dock/loading-and-savin 2\. Then, let's define the path to the xml file where we will save our layout: -{{source=..\SamplesCS\Dock\SaveLoadLayout.cs region=paths}} -{{source=..\SamplesVB\Dock\SaveLoadLayout.vb region=paths}} + + -````C# -private string dockLayoutPath = Application.StartupPath + "\\dock.xml"; - -```` -````VB.NET -Private dockLayoutPath As String = Application.StartupPath & "\dock.xml" - -```` - -{{endregion}} + 3\. At the **Load** event of our form we will check if the xml file with the saved layout exists. If the file exists at the specified location, we will load the layout as shown in the next paragraphs. If it does not exists, we will create a generic layout in **RadDock** loading our user controls: -{{source=..\SamplesCS\Dock\SaveLoadLayout.cs region=formLoad}} -{{source=..\SamplesVB\Dock\SaveLoadLayout.vb region=formLoad}} - -````C# -private void MainForm_Load(object sender, EventArgs e) -{ - if (!File.Exists(dockLayoutPath)) - { - InitializeLayout(); - } - else - { - this.radDock1.LoadFromXml(dockLayoutPath); - LoadContent(); - } -} -private void InitializeLayout() -{ - this.radDock1.MainDocumentContainerVisible = false; - HostWindow afW = this.radDock1.DockControl(new AvailableFlights(), DockPosition.Left); - afW.Text = "Available Flights"; - HostWindow bfW = this.radDock1.DockControl(new BookFlight(), DockPosition.Left); - bfW.Text = "Book a Flight"; - HostWindow fsW = this.radDock1.DockControl(new FlightsSummary(), DockPosition.Left); - fsW.Text = "Flight Summary"; -} - -```` -````VB.NET -Private Sub MainForm_Load(ByVal sender As Object, ByVal e As EventArgs) - If Not File.Exists(dockLayoutPath) Then - InitializeLayout() - Else - Me.RadDock1.LoadFromXml(dockLayoutPath) - LoadContent() - End If -End Sub -Private Sub InitializeLayout() - Me.RadDock1.MainDocumentContainerVisible = False - Dim afW As HostWindow = Me.RadDock1.DockControl(New AvailableFlights(), DockPosition.Left) - afW.Text = "Available Flights" - Dim bfW As HostWindow = Me.RadDock1.DockControl(New BookFlight(), DockPosition.Left) - bfW.Text = "Book a Flight" - Dim fsW As HostWindow = Me.RadDock1.DockControl(New FlightsSummary(), DockPosition.Left) - fsW.Text = "Flight Summary" -End Sub - -```` - -{{endregion}} + + + + Please note that the names of the types of the **UserControls** are important, because these names will actually give the names of the **HostWindows** that will be created to host the **UserControls**. The names of the **HostWindows** will be later used during the process of loading the content. @@ -105,24 +50,10 @@ Please note that the names of the types of the **UserControls** are important, b 5\. Now close the form containing RadDock. The **FormClosing** event handler is a convenient place to save our layout: -{{source=..\SamplesCS\Dock\SaveLoadLayout.cs region=formClosing}} -{{source=..\SamplesVB\Dock\SaveLoadLayout.vb region=formClosing}} + + -````C# -private void MainForm_FormClosing(object sender, FormClosingEventArgs e) -{ - this.radDock1.SaveToXml(dockLayoutPath); -} - -```` -````VB.NET -Private Sub MainForm_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs) - Me.RadDock1.SaveToXml(dockLayoutPath) -End Sub - -```` - -{{endregion}} + 6\. Reopen the form. Since the XML file defined at paragraph two now exists, our layout and content will be loaded with the help of the following methods: @@ -130,61 +61,10 @@ End Sub * __LoadContent:__ This is our custom method which loads the content in the created **HostWindows**. Note that the different user controls are loaded in the appropriate **HostWindows** depending on the names of these windows. -{{source=..\SamplesCS\Dock\SaveLoadLayout.cs region=loadContent}} -{{source=..\SamplesVB\Dock\SaveLoadLayout.vb region=loadContent}} - -````C# -private void LoadContent() -{ - for (int i = 0; i < this.radDock1.DockWindows.Count; i++) - { - HostWindow hw = this.radDock1.DockWindows[i] as HostWindow; - if (hw != null) - { - if (hw.Name.StartsWith("Available")) - { - hw.LoadContent(new AvailableFlights()); - hw.Text = "Available Flights"; - } - if (hw.Name.StartsWith("Book")) - { - hw.LoadContent(new BookFlight()); - hw.Text = "Book a Flight"; - } - if (hw.Name.StartsWith("Flight")) - { - hw.LoadContent(new FlightsSummary()); - hw.Text = "Flight Summary"; - } - } - } -} - -```` -````VB.NET -Private Sub LoadContent() - For i As Integer = 0 To Me.RadDock1.DockWindows.Count - 1 - Dim hw As HostWindow = TryCast(Me.RadDock1.DockWindows(i), HostWindow) - If hw IsNot Nothing Then - If hw.Name.StartsWith("Available") Then - hw.LoadContent(New AvailableFlights()) - hw.Text = "Available Flights" - End If - If hw.Name.StartsWith("Book") Then - hw.LoadContent(New BookFlight()) - hw.Text = "Book a Flight" - End If - If hw.Name.StartsWith("Flight") Then - hw.LoadContent(New FlightsSummary()) - hw.Text = "Flight Summary" - End If - End If - Next i -End Sub - -```` - -{{endregion}} + + + + As a result we get the layout shown on the screenshot below: diff --git a/controls/dock/localization/localization.md b/controls/dock/localization/localization.md index f1b071a79..596771f82 100644 --- a/controls/dock/localization/localization.md +++ b/controls/dock/localization/localization.md @@ -1,156 +1,46 @@ ---- -title: Localization -page_title: Localization - WinForms Dock Control -description: Learn how you can localize the strings used in WinForms RadDock. -slug: winforms/dock/localization/localization -tags: localization -published: True -position: 0 -previous_url: dock-localization ---- - -# Localization - -To localize __RadDock__ to display control text and messages in a specific language: - -* All required classes for localization are defined in __Telerik.WinControls.UI.Localization__ namespace. - -* Start by creating a descendant of the **RadDockLocalizationProvider** class. - -* Override the __GetLocalizedString(string id)__ method and provide a translation for the label and user messages. If a translation is not provided, the default value will be returned. This behavior is guaranteed by the call to the base __GetLocalizedString__ method in the __default__ clause of the switch statement in the example. - -Below is a sample implementation of a custom localization provider, which returns translations of the default values in English: - -#### Localizing RadDock Strings - -{{source=..\SamplesCS\Dock\CustomDockProvider.cs region=customProvider}} -{{source=..\SamplesVB\Dock\CustomDockProvider.vb region=customProvider}} - -````C# -public class EnglishDockLocalizationProvider : RadDockLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case RadDockStringId.ContextMenuFloating: - return "Floating"; - case RadDockStringId.ContextMenuDockable: - return "Dockable"; - case RadDockStringId.ContextMenuTabbedDocument: - return "Tabbed Document"; - case RadDockStringId.ContextMenuAutoHide: - return "Auto Hide"; - case RadDockStringId.ContextMenuHide: - return "Hide"; - case RadDockStringId.ContextMenuClose: - return "Close"; - case RadDockStringId.ContextMenuCloseAll: - return "Close All"; - case RadDockStringId.ContextMenuCloseAllButThis: - return "Close All But This"; - case RadDockStringId.ContextMenuMoveToPreviousTabGroup: - return "Move to Previous Tab Group"; - case RadDockStringId.ContextMenuMoveToNextTabGroup: - return "Move to Next Tab Group"; - case RadDockStringId.ContextMenuNewHorizontalTabGroup: - return "New Horizontal Tab Group"; - case RadDockStringId.ContextMenuNewVerticalTabGroup: - return "New Vertical Tab Group"; - case RadDockStringId.ToolTabStripCloseButton: - return "Close Window"; - case RadDockStringId.ToolTabStripDockStateButton: - return "Window State"; - case RadDockStringId.ToolTabStripUnpinButton: - return "Auto Hide"; - case RadDockStringId.ToolTabStripPinButton: - return "Docked"; - case RadDockStringId.DocumentTabStripCloseButton: - return "Close Document"; - case RadDockStringId.DocumentTabStripListButton: - return "Active Documents"; - case RadDockStringId.ContextMenuCloseAllButPinned: - return "Close All but Pinned"; - } - return string.Empty; - } -} - -```` -````VB.NET -Public Class EnglishDockLocalizationProvider - Inherits RadDockLocalizationProvider - Public Overrides Function GetLocalizedString(ByVal id As String) As String - Select Case id - Case RadDockStringId.ContextMenuFloating - Return "Floating" - Case RadDockStringId.ContextMenuDockable - Return "Dockable" - Case RadDockStringId.ContextMenuTabbedDocument - Return "Tabbed Document" - Case RadDockStringId.ContextMenuAutoHide - Return "Auto Hide" - Case RadDockStringId.ContextMenuHide - Return "Hide" - Case RadDockStringId.ContextMenuClose - Return "Close" - Case RadDockStringId.ContextMenuCloseAll - Return "Close All" - Case RadDockStringId.ContextMenuCloseAllButThis - Return "Close All But This" - Case RadDockStringId.ContextMenuMoveToPreviousTabGroup - Return "Move to Previous Tab Group" - Case RadDockStringId.ContextMenuMoveToNextTabGroup - Return "Move to Next Tab Group" - Case RadDockStringId.ContextMenuNewHorizontalTabGroup - Return "New Horizontal Tab Group" - Case RadDockStringId.ContextMenuNewVerticalTabGroup - Return "New Vertical Tab Group" - Case RadDockStringId.ToolTabStripCloseButton - Return "Close Window" - Case RadDockStringId.ToolTabStripDockStateButton - Return "Window State" - Case RadDockStringId.ToolTabStripUnpinButton - Return "Auto Hide" - Case RadDockStringId.ToolTabStripPinButton - Return "Docked" - Case RadDockStringId.DocumentTabStripCloseButton - Return "Close Document" - Case RadDockStringId.DocumentTabStripListButton - Return "Active Documents" - Case RadDockStringId.ContextMenuCloseAllButPinned - Return "Close All but Pinned" - End Select - Return String.Empty - End Function -End Class - -```` - -{{endregion}} - - -To apply the custom localization provider, instantiate and assign it to the current localization provider: - -#### Localizing RadDock Strings - -{{source=..\SamplesCS\Dock\CustomDockProvider.cs region=settingCustomProvider}} -{{source=..\SamplesVB\Dock\CustomDockProvider.vb region=settingCustomProvider}} - -````C# -RadDockLocalizationProvider.CurrentProvider = new EnglishDockLocalizationProvider(); - -```` -````VB.NET -RadDockLocalizationProvider.CurrentProvider = New EnglishDockLocalizationProvider() - -```` - -{{endregion}} - - -The code provided above illustrates the approach to be used to localize the __RadDock__ and is not intended as a full translation. - -# See Also - -* [Right-to-left support]({%slug winforms/dock/localization/right-to-left-support%}) +--- +title: Localization +page_title: Localization - WinForms Dock Control +description: Learn how you can localize the strings used in WinForms RadDock. +slug: winforms/dock/localization/localization +tags: localization +published: True +position: 0 +previous_url: dock-localization +--- + +# Localization + +To localize __RadDock__ to display control text and messages in a specific language: + +* All required classes for localization are defined in __Telerik.WinControls.UI.Localization__ namespace. + +* Start by creating a descendant of the **RadDockLocalizationProvider** class. + +* Override the __GetLocalizedString(string id)__ method and provide a translation for the label and user messages. If a translation is not provided, the default value will be returned. This behavior is guaranteed by the call to the base __GetLocalizedString__ method in the __default__ clause of the switch statement in the example. + +Below is a sample implementation of a custom localization provider, which returns translations of the default values in English: + +#### Localizing RadDock Strings + + + + + + + +To apply the custom localization provider, instantiate and assign it to the current localization provider: + +#### Localizing RadDock Strings + + + + + + + +The code provided above illustrates the approach to be used to localize the __RadDock__ and is not intended as a full translation. + +# See Also + +* [Right-to-left support]({%slug winforms/dock/localization/right-to-left-support%}) diff --git a/controls/dock/localization/right-to-left-support.md b/controls/dock/localization/right-to-left-support.md index 11a0c43c9..25773a35b 100644 --- a/controls/dock/localization/right-to-left-support.md +++ b/controls/dock/localization/right-to-left-support.md @@ -13,19 +13,10 @@ previous_url: dock-localization-rtl You can present the content of your dock instance in a right-to-left direction by setting the __RightToLeft__ property to *Yes*: -{{source=..\SamplesCS\Dock\CustomDockProvider.cs region=rtl}} -{{source=..\SamplesVB\Dock\CustomDockProvider.vb region=rtl}} + + -````C# -radDock1.RightToLeft = System.Windows.Forms.RightToLeft.Yes; - -```` -````VB.NET -Me.radDock1.RightToLeft = System.Windows.Forms.RightToLeft.Yes - -```` - -{{endregion}} + ![WinForms RadDock Right-to-Left Support](images/dock-localization-rtl001.png) diff --git a/controls/dock/mdi-mode/automatic-mdi-form-handling.md b/controls/dock/mdi-mode/automatic-mdi-form-handling.md index a8f4c0233..0e29e4972 100644 --- a/controls/dock/mdi-mode/automatic-mdi-form-handling.md +++ b/controls/dock/mdi-mode/automatic-mdi-form-handling.md @@ -24,56 +24,20 @@ To configure your MDI application to use this feature: #### Configuring the Parent Form -{{source=..\SamplesCS\Dock\MDIHandling1.cs region=initialization}} -{{source=..\SamplesVB\Dock\MDIHandling1.vb region=initialization}} - -````C# -private void Form1_Load(object sender, EventArgs e) -{ - this.IsMdiContainer = true; - this.radDock1.AutoDetectMdiChildren = true; -} - -```` -````VB.NET -Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load - Me.IsMdiContainer = True - Me.RadDock1.AutoDetectMdiChildren = True -End Sub - -```` - -{{endregion}} + + + + 3\. Add a form to the project that will serve the role of child form. No properties, methods or event handlers need to be set for this form, except that you may want to add some content that will be visible when the child forms are displayed as tabbed documents. 4\. Add code to the parent form to create the child form and assign it an MDI parent: -{{source=..\SamplesCS\Dock\MDIHandling1.cs region=creatingChildForm}} -{{source=..\SamplesVB\Dock\MDIHandling1.vb region=creatingChildForm}} - -````C# -private void radMenuItem1_Click(object sender, EventArgs e) -{ - Form childForm = new Form(); - childForm.Text = "MDI Child " + DateTime.Now.ToShortTimeString(); - childForm.MdiParent = this; - childForm.Show(); -} - -```` -````VB.NET -Private Sub RadMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadMenuItem1.Click - Dim childForm As New Form() - childForm.Text = "MDI Child " & DateTime.Now.ToShortTimeString() - childForm.MdiParent = Me - childForm.Show() -End Sub - -```` + + -{{endregion}} + ## MdiChildrenDockType @@ -83,19 +47,10 @@ However, you can set the default type to **ToolWindow**: #### Setting the default DockWindow type for MDI children forms -{{source=..\SamplesCS\Dock\MDIHandling1.cs region=mdiChildrenDockType}} -{{source=..\SamplesVB\Dock\MDIHandling1.vb region=mdiChildrenDockType}} + + -````C# -this.radDock1.MdiChildrenDockType = DockType.ToolWindow; - -```` -````VB.NET -Me.RadDock1.MdiChildrenDockType = DockType.ToolWindow - -```` - -{{endregion}} + When initially created, these **ToolWindows** look like **DocumentWindows**. This is just because their state is Tabbed Document. However, their real identity is **ToolWindow** - i.e. these windows can be docked, auto-hidden and floated. @@ -120,28 +75,10 @@ This chain of events allows you to encapsulate all your business logic in the re The __CloseAllWindows__ returns a bool value which indicates if the operation is successful (it will return *true* if all child windows are closed). This is allowing you to keep the main form opened if some of the MDI children cannot be closed for the moment. You can use the method as follows: #### Using the CloseAllWindows method. -{{source=..\SamplesCS\Dock\MDIHandling1.cs region=closing}} -{{source=..\SamplesVB\Dock\MDIHandling1.vb region=closing}} - -````C# -protected override void OnClosing(CancelEventArgs e) -{ - bool canClose = radDock1.CloseAllWindows(); - e.Cancel = !canClose; - base.OnClosing(e); -} - -```` -````VB.NET -Protected Overrides Sub OnClosing(ByVal e As CancelEventArgs) - Dim canClose As Boolean = RadDock1.CloseAllWindows() - e.Cancel = Not canClose - MyBase.OnClosing(e) -End Sub - -```` - -{{endregion}} + + + + ## Using Singleton forms in MDI scenario with RadDock diff --git a/controls/dock/object-model/accessing-dockwindows.md b/controls/dock/object-model/accessing-dockwindows.md index 4196d41ad..bae2edef0 100644 --- a/controls/dock/object-model/accessing-dockwindows.md +++ b/controls/dock/object-model/accessing-dockwindows.md @@ -19,39 +19,17 @@ The __DockWindows__ property returns an array of all **DockWindow** in a __RadDo * __GetWindows(DockState state):__ Returns an array of **DockWindows** that are put in a specific **DockState**. For example, the following code snippet will return an array of **DockWindows** that are currently hidden: -{{source=..\SamplesCS\Dock\CreatingWindows.cs region=gettingHiddenWindows}} -{{source=..\SamplesVB\Dock\CreatingWindows.vb region=gettingHiddenWindows}} - -````C# -DockWindow[] hiddenWindows = radDock1.DockWindows.GetWindows(DockState.Hidden); - -```` -````VB.NET -Dim hiddenWindows As DockWindow() = Me.RadDock1.DockWindows.GetWindows(DockState.Hidden) - -```` - -{{endregion}} + + + + You can get a desired ToolWindow\DocumentWindow by specifying its __Name__ as an index: -{{source=..\SamplesCS\Dock\CreatingWindows.cs region=gettingWindowByName}} -{{source=..\SamplesVB\Dock\CreatingWindows.vb region=gettingWindowByName}} - -````C# -DockWindow window1 = this.radDock1.DockWindows["Form1"]; -// or simply -DockWindow window2 = this.radDock1["Form1"]; - -```` -````VB.NET -Dim window1 As DockWindow = Me.RadDock1.DockWindows("Form1") -' or simply -Dim window2 As DockWindow = Me.RadDock1("Form1") - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/dock/object-model/alloweddockstates.md b/controls/dock/object-model/alloweddockstates.md index 20e5e3a03..477835d7a 100644 --- a/controls/dock/object-model/alloweddockstates.md +++ b/controls/dock/object-model/alloweddockstates.md @@ -15,19 +15,10 @@ __AllowedDockState__ property gives you the ability to determine the available d #### Allow two states only. -{{source=..\SamplesCS\Dock\CreatingRadDock.cs region=allowedDockState}} -{{source=..\SamplesVB\Dock\CreatingRadDock.vb region=allowedDockState}} + + -````C# -toolWindow1.AllowedDockState = AllowedDockState.Docked | AllowedDockState.Floating; - -```` -````VB.NET -toolWindow1.AllowedDockState = AllowedDockState.Docked Or AllowedDockState.Floating - -```` - -{{endregion}} + This automatically will remove the caption buttons that may be responsible for an unwanted state, for example *Closed*. In addition, the unwanted menu items from the context menu will be disabled: @@ -37,19 +28,10 @@ The following setting will disable the __Floating__ option: #### Disable the floating dock state -{{source=..\SamplesCS\Dock\CreatingRadDock.cs region=notFloating}} -{{source=..\SamplesVB\Dock\CreatingRadDock.vb region=notFloating}} + + -````C# -toolWindow1.AllowedDockState = ~AllowedDockState.Floating; - -```` -````VB.NET -toolWindow1.AllowedDockState = Not AllowedDockState.Floating - -```` - -{{endregion}} + ![WinForms RadDock Disable the Floating Dock State](images/dock-object-model-allowed-dock-states002.png) diff --git a/controls/dock/object-model/creating-a-raddock-at-runtime.md b/controls/dock/object-model/creating-a-raddock-at-runtime.md index 64440d8b7..364b04561 100644 --- a/controls/dock/object-model/creating-a-raddock-at-runtime.md +++ b/controls/dock/object-model/creating-a-raddock-at-runtime.md @@ -17,29 +17,10 @@ To create a __RadDock__ in code, construct a __RadDock__, set properties and add #### Creating a simple RadDock instance -{{source=..\SamplesCS\Dock\CreatingRadDock.cs region=creatingDock}} -{{source=..\SamplesVB\Dock\CreatingRadDock.vb region=creatingDock}} - -````C# -RadDock radDock1 = new RadDock(); -radDock1.Dock = DockStyle.Fill; -this.Controls.Add(radDock1); -ToolWindow toolWindow1 = new ToolWindow(); -toolWindow1.Text = "A ToolWindow"; -radDock1.DockWindow(toolWindow1, DockPosition.Left); - -```` -````VB.NET -Dim radDock1 As RadDock = New RadDock() -radDock1.Dock = DockStyle.Fill -Me.Controls.Add(radDock1) -Dim toolWindow1 As ToolWindow = New ToolWindow() -toolWindow1.Text = "A ToolWindow" -radDock1.DockWindow(toolWindow1, DockPosition.Left) - -```` - -{{endregion}} + + + + >caution You cannot set the DockPosition of the ToolWindow to Fill, unless you specify a target ToolWindow. If you try to set the DockPosition of a ToolWindow to Fill when there is no target ToolWindow, we throw an exception since a ToolWindow cannot fill RadDock entirely. This behavior is by design and it is the same as it is in Visual Studio. If you want to have a ToolWindow occupying RadDock entirely, you should dock it to a side (left/right/top/bottom) and set MainDocumentContainerVisible to false. > diff --git a/controls/dock/object-model/creating-toolwindow-and-documentwindow-at-runtime.md b/controls/dock/object-model/creating-toolwindow-and-documentwindow-at-runtime.md index e8ed0ffe8..eba158567 100644 --- a/controls/dock/object-model/creating-toolwindow-and-documentwindow-at-runtime.md +++ b/controls/dock/object-model/creating-toolwindow-and-documentwindow-at-runtime.md @@ -17,50 +17,22 @@ To create a new __ToolWindow__, construct a __ToolWindow__ instance, set proper #### Creating a ToolWindow -{{source=..\SamplesCS\Dock\CreatingWindows.cs region=creatingToolWindow}} -{{source=..\SamplesVB\Dock\CreatingWindows.vb region=creatingToolWindow}} + + -````C# -ToolWindow windowTop = new ToolWindow(); -windowTop.Text = "Window Top"; -this.radDock1.DockWindow(windowTop, DockPosition.Top); -```` -````VB.NET - -Dim windowTop As ToolWindow = New ToolWindow() -windowTop.Text = "Window Top" -Me.RadDock1.DockWindow(windowTop, DockPosition.Top) -```` - -{{endregion}} - ## Creating DocumentWindow at Runtime To create a __DocumentWindow__, construct an instance of __DocumentWindow__, assign properties and call the __AddDocument__ method, passing the __DocumentWindow__ instance. #### Creating a DocumentWindow -{{source=..\SamplesCS\Dock\CreatingWindows.cs region=creatingDocumentWindow}} -{{source=..\SamplesVB\Dock\CreatingWindows.vb region=creatingDocumentWindow}} - -````C# -DocumentWindow documentTop = new DocumentWindow(); -documentTop.Text = "New Document"; -this.radDock1.AddDocument(documentTop); + + -```` -````VB.NET -Dim documentTop As DocumentWindow = New DocumentWindow() -documentTop.Text = "New Document" -Me.RadDock1.AddDocument(documentTop) -```` -{{endregion}} - - ## Example: Creating Multiple ToolWindow and DocumentWindow at Runtime The following example creates multiple panels and document panes at runtime. @@ -69,53 +41,10 @@ The following example creates multiple panels and document panes at runtime. #### Creating ToolWindows and DocumentWindows -{{source=..\SamplesCS\Dock\CreatingWindows.cs region=winInitialization}} -{{source=..\SamplesVB\Dock\CreatingWindows.vb region=winInitialization}} - -````C# -ToolWindow windowLeft = new ToolWindow(); -windowLeft.Text = "Window Left"; -this.radDock1.DockWindow(windowLeft, DockPosition.Left); -ToolWindow windowBottom = new ToolWindow(); -windowBottom.Text = "Window Bottom"; -this.radDock1.DockWindow(windowBottom, DockPosition.Bottom); -ToolWindow windowBottomRight = new ToolWindow(); -windowBottomRight.Text = "Window Bottom Right"; -this.radDock1.DockWindow(windowBottomRight, windowBottom, DockPosition.Right); -DocumentWindow document1 = new DocumentWindow(); -document1.Text = "Document 1"; -this.radDock1.AddDocument(document1); -DocumentWindow document2 = new DocumentWindow(); -document2.Text = "Document 2"; -this.radDock1.AddDocument(document2); -DocumentWindow document3 = new DocumentWindow(); -document3.Text = "Document 3"; -this.radDock1.AddDocument(document3); - -```` -````VB.NET -Dim windowLeft As ToolWindow = New ToolWindow() -windowLeft.Text = "Window Left" -Me.RadDock1.DockWindow(windowLeft, DockPosition.Top) -Dim windowBottom As ToolWindow = New ToolWindow() -windowBottom.Text = "Window Bottom" -Me.RadDock1.DockWindow(windowBottom, DockPosition.Bottom) -Dim windowBottomRight As ToolWindow = New ToolWindow() -windowBottomRight.Text = "Window Bottom Right" -Me.RadDock1.DockWindow(windowBottomRight, windowBottom, DockPosition.Right) -Dim document1 As DocumentWindow = New DocumentWindow() -document1.Text = "Document 1" -Me.RadDock1.AddDocument(document1) -Dim document2 As DocumentWindow = New DocumentWindow() -document2.Text = "Document 2" -Me.RadDock1.AddDocument(document2) -Dim document3 As DocumentWindow = New DocumentWindow() -document3.Text = "Document 3" -Me.RadDock1.AddDocument(document3) - -```` - -{{endregion}} + + + + ## Creating and docking multiple windows in a single strip @@ -125,56 +54,11 @@ There are cases in which you might prefer docking two or more windows to the rig The bellow code shows how you can create each one of the windows: -{{source=..\SamplesCS\Dock\How-To\DockingWindowsToRight.cs region=wrongApproach}} -{{source=..\SamplesVB\Dock\How-To\DockingWindowsToRight.vb region=wrongApproach}} - -````C# -private void menuItemTeamExplorer_Click1(object sender, EventArgs e) -{ - TeamExplorerUserControl teuc = new TeamExplorerUserControl(); - DockPosition dockTo = DockPosition.Right; - HostWindow hw = this.radDock1.DockControl(teuc, dockTo); - hw.Text = "Team Explorer"; -} -private void menuItemServerExplorer_Click1(object sender, EventArgs e) -{ - ServerExplorerUserControl seuc = new ServerExplorerUserControl(); - DockPosition dockTo = DockPosition.Right; - HostWindow hw = this.radDock1.DockControl(seuc, dockTo); - hw.Text = "Server Explorer"; -} -private void menuItemSolutionExplorer_Click1(object sender, EventArgs e) -{ - SolutionExplorerUserControl seuc = new SolutionExplorerUserControl(); - DockPosition dockTo = DockPosition.Right; - HostWindow hw = this.radDock1.DockControl(seuc, dockTo); - hw.Text = "Solution Explorer"; -} - -```` -````VB.NET -Private Sub menuItemTeamExplorer_Click1(ByVal sender As Object, ByVal e As EventArgs) - Dim teuc As New TeamExplorerUserControl() - Dim dockTo As DockPosition = DockPosition.Right - Dim hw As HostWindow = Me.RadDock1.DockControl(teuc, dockTo) - hw.Text = "Team Explorer" -End Sub -Private Sub menuItemServerExplorer_Click1(ByVal sender As Object, ByVal e As EventArgs) - Dim seuc As New ServerExplorerUserControl() - Dim dockTo As DockPosition = DockPosition.Right - Dim hw As HostWindow = Me.RadDock1.DockControl(seuc, dockTo) - hw.Text = "Server Explorer" -End Sub -Private Sub menuItemSolutionExplorer_Click1(ByVal sender As Object, ByVal e As EventArgs) - Dim seuc As New SolutionExplorerUserControl() - Dim dockTo As DockPosition = DockPosition.Right - Dim hw As HostWindow = Me.RadDock1.DockControl(seuc, dockTo) - hw.Text = "Solution Explorer" -End Sub - -```` - -{{endregion}} + + + + + However, this API docks the windows to right of **RadDock**, not taking into consideration other right-docked windows: ![WinForms RadDock Windows are Docked To the Right](images/dock-object-model-creating-toolwindow-and-documentwindow-at-runtime002.png) @@ -182,103 +66,10 @@ However, this API docks the windows to right of **RadDock**, not taking into con So, we need to follow another approach. What we need to do is to globally define a **ToolTabStrip** variable that would be set the first time a window is right-docked. Then, the next time we dock a window, we will do it in the context of the already created **ToolTabStrip**. Here is what should be done in code on click of the menu items: -{{source=..\SamplesCS\Dock\How-To\DockingWindowsToRight.cs region=menuItemsClick}} -{{source=..\SamplesVB\Dock\How-To\DockingWindowsToRight.vb region=menuItemsClick}} - -````C# -ToolTabStrip rightHandStrip = null; -private void menuItemTeamExplorer_Click(object sender, EventArgs e) -{ - TeamExplorerUserControl teuc = new TeamExplorerUserControl(); - ToolWindow teucW = new ToolWindow(); - teucW.Controls.Add(teuc); - teucW.Text = "Team Explorer"; - if (rightHandStrip == null) - { - this.radDock1.DockWindow(teucW, DockPosition.Right); - rightHandStrip = (ToolTabStrip)teucW.Parent; - } - else - { - this.radDock1.DockWindow(teucW, rightHandStrip, DockPosition.Fill); - } -} -private void menuItemServerExplorer_Click(object sender, EventArgs e) -{ - ServerExplorerUserControl seuc = new ServerExplorerUserControl(); - ToolWindow seucW = new ToolWindow(); - seucW.Controls.Add(seuc); - seucW.Text = "Server Explorer"; - if (rightHandStrip == null) - { - this.radDock1.DockWindow(seucW, DockPosition.Right); - rightHandStrip = (ToolTabStrip)seucW.Parent; - } - else - { - this.radDock1.DockWindow(seucW, rightHandStrip, DockPosition.Fill); - } -} -private void menuItemSolutionExplorer_Click(object sender, EventArgs e) -{ - SolutionExplorerUserControl seuc = new SolutionExplorerUserControl(); - ToolWindow seucW = new ToolWindow(); - seucW.Controls.Add(seuc); - seucW.Text = "Solution Explorer"; - if (rightHandStrip == null) - { - this.radDock1.DockWindow(seucW, DockPosition.Right); - rightHandStrip = (ToolTabStrip)seucW.Parent; - } - else - { - this.radDock1.DockWindow(seucW, rightHandStrip, DockPosition.Fill); - } -} - -```` -````VB.NET -Private rightHandStrip As ToolTabStrip = Nothing -Private Sub menuItemTeamExplorer_Click(ByVal sender As Object, ByVal e As EventArgs) - Dim teuc As New TeamExplorerUserControl() - Dim teucW As New ToolWindow() - teucW.Controls.Add(teuc) - teucW.Text = "Team Explorer" - If rightHandStrip Is Nothing Then - Me.RadDock1.DockWindow(teucW, DockPosition.Right) - rightHandStrip = CType(teucW.Parent, ToolTabStrip) - Else - Me.RadDock1.DockWindow(teucW, rightHandStrip, DockPosition.Fill) - End If -End Sub -Private Sub menuItemServerExplorer_Click(ByVal sender As Object, ByVal e As EventArgs) - Dim seuc As New ServerExplorerUserControl() - Dim seucW As New ToolWindow() - seucW.Controls.Add(seuc) - seucW.Text = "Server Explorer" - If rightHandStrip Is Nothing Then - Me.RadDock1.DockWindow(seucW, DockPosition.Right) - rightHandStrip = CType(seucW.Parent, ToolTabStrip) - Else - Me.RadDock1.DockWindow(seucW, rightHandStrip, DockPosition.Fill) - End If -End Sub -Private Sub menuItemSolutionExplorer_Click(ByVal sender As Object, ByVal e As EventArgs) - Dim seuc As New SolutionExplorerUserControl() - Dim seucW As New ToolWindow() - seucW.Controls.Add(seuc) - seucW.Text = "Solution Explorer" - If rightHandStrip Is Nothing Then - Me.RadDock1.DockWindow(seucW, DockPosition.Right) - rightHandStrip = CType(seucW.Parent, ToolTabStrip) - Else - Me.RadDock1.DockWindow(seucW, rightHandStrip, DockPosition.Fill) - End If -End Sub - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/dock/object-model/customizing-floating-windows.md b/controls/dock/object-model/customizing-floating-windows.md index fe36e9b63..1cb26d37f 100644 --- a/controls/dock/object-model/customizing-floating-windows.md +++ b/controls/dock/object-model/customizing-floating-windows.md @@ -17,28 +17,10 @@ __FloatingWindows__ provide a useful way of reordering pieces of content on your In order to enable the `Maximize` and `Minimize` buttons for a **FloatingWindow**, you have to handle the `FloatingWindowCreated` event and set the **MinimizeBox**, **MaximizeBox** and **FormBorderStyle** properties of the **FloatingWindow** the following way: -{{source=..\SamplesCS\Dock\CustomizingFloatingWindows.cs region=buttons}} -{{source=..\SamplesVB\Dock\CustomizingFloatingWindows.vb region=buttons}} - -````C# -void radDock1_FloatingWindowCreated1(object sender, Telerik.WinControls.UI.Docking.FloatingWindowEventArgs e) -{ - e.Window.MaximizeBox = true; - e.Window.MinimizeBox = true; - e.Window.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable; -} - -```` -````VB.NET -Private Sub radDock1_FloatingWindowCreated1(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.Docking.FloatingWindowEventArgs) - e.Window.MaximizeBox = True - e.Window.MinimizeBox = True - e.Window.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable -End Sub - -```` - -{{endregion}} + + + + The result is: ![WinForms RadDock Enabling Minimize and Maximize buttons](images/dock-object-model-customizing-floating-windows001.png) @@ -48,69 +30,17 @@ The result is: Sometimes, you may want to prevent the **FloatingWindow** from being always on top of the form that contains the **RadDock** manager. In order to do that, you need to extend the **FloatingWindow** class and use an instance of the extended type. In the extended **FloatingWindow** type, we need to override the **OnActivated** method, and after the base implementation takes place, we should remove the window from the collection of owned forms that the main form has: -{{source=..\SamplesCS\Dock\CustomFloatingWindow.cs region=customFloatingWindow}} -{{source=..\SamplesVB\Dock\CustomFloatingWindow.vb region=customFloatingWindow}} - -````C# -public class CustomFloatingWindow : FloatingWindow -{ - public CustomFloatingWindow(RadDock dockManager) - : base(dockManager) - { - } - protected override void OnActivated(EventArgs e) - { - base.OnActivated(e); - Form dockForm = this.DockManager.FindForm(); - if (dockForm != null) - { - dockForm.RemoveOwnedForm(this); - } - } -} - -```` -````VB.NET -Public Class CustomFloatingWindow - Inherits FloatingWindow - Public Sub New(ByVal dockManager As RadDock) - MyBase.New(dockManager) - End Sub - Protected Overrides Sub OnActivated(ByVal e As EventArgs) - MyBase.OnActivated(e) - Dim dockForm As Form = Me.DockManager.FindForm() - If dockForm IsNot Nothing Then - dockForm.RemoveOwnedForm(Me) - End If - End Sub -End Class - -```` - -{{endregion}} + + + + Finally, we have to pass an instance of the custom **FloatingWindow** to the event arguments of the **FloatingWindowCreated** event: -{{source=..\SamplesCS\Dock\CustomizingFloatingWindows.cs region=showBehind}} -{{source=..\SamplesVB\Dock\CustomizingFloatingWindows.vb region=showBehind}} - -````C# -void radDock1_FloatingWindowCreated2(object sender, Telerik.WinControls.UI.Docking.FloatingWindowEventArgs e) -{ - CustomFloatingWindow customWindow = new CustomFloatingWindow(this.radDock1); - e.Window = customWindow; -} - -```` -````VB.NET -Private Sub radDock1_FloatingWindowCreated2(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.Docking.FloatingWindowEventArgs) - Dim customWindow As New CustomFloatingWindow(Me.RadDock1) - e.Window = customWindow -End Sub + + -```` - -{{endregion}} + Here is the result. As you can see, the form that contains the **RadDock** manager can cover the **FloatingWindow**: @@ -120,24 +50,10 @@ Here is the result. As you can see, the form that contains the **RadDock** manag **FloatingWindow** is a descendant class of **RadForm**. As such, **FloatingWindow** has the __ThemeName__ property that you can set in the **FloatingWindowCreated** event in order to change its theme: -{{source=..\SamplesCS\Dock\CustomizingFloatingWindows.cs region=themeName}} -{{source=..\SamplesVB\Dock\CustomizingFloatingWindows.vb region=themeName}} - -````C# -void radDock1_FloatingWindowCreated3(object sender, Telerik.WinControls.UI.Docking.FloatingWindowEventArgs e) -{ - e.Window.ThemeName = "TelerikMetroBlue"; -} + + -```` -````VB.NET -Private Sub radDock1_FloatingWindowCreated3(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.Docking.FloatingWindowEventArgs) - e.Window.ThemeName = "TelerikMetroBlue" -End Sub - -```` - -{{endregion}} + ![WinForms RadDock FloatingWindow Theme](images/dock-object-model-customizing-floating-windows003.png) diff --git a/controls/dock/object-model/customizing-tabstrip-items.md b/controls/dock/object-model/customizing-tabstrip-items.md index f68fefdff..337b28087 100644 --- a/controls/dock/object-model/customizing-tabstrip-items.md +++ b/controls/dock/object-model/customizing-tabstrip-items.md @@ -18,79 +18,27 @@ This article demonstrates how you can customize or replace the **TabStrip** item The above examples are using the __TabStripItemCreating__ event. This event cannot be accessed via the **RadDock** instance. You can subscribe to the event by using the static __RadDockEvents__ class. You should do that before the **InitializeComponent** method call: -{{source=..\SamplesCS\Dock\CustomizingTabStripItems.cs region=subscribe}} -{{source=..\SamplesVB\Dock\CustomizingTabStripItems.vb region=subscribe}} + + -````C# -public CustomizingTabStripItems() -{ - RadDockEvents.TabStripItemCreating += RadDockEvents_TabStripItemCreating; - InitializeComponent(); -} - -```` -````VB.NET -Public Sub New() - AddHandler RadDockEvents.TabStripItemCreating, AddressOf RadDockEvents_TabStripItemCreating - InitializeComponent() -End Sub - -```` - -{{endregion}} + Please note that when such static events are used it is mandatory to unsubscribe from the event. If you do not do that the form would not be disposed properly: -{{source=..\SamplesCS\Dock\CustomizingTabStripItems.cs region=closed}} -{{source=..\SamplesVB\Dock\CustomizingTabStripItems.vb region=closed}} - -````C# -protected override void OnClosed(EventArgs e) -{ - RadDockEvents.TabStripItemCreating -= RadDockEvents_TabStripItemCreating; - base.OnClosed(e); -} + + -```` -````VB.NET -Protected Overrides Sub OnClosed(ByVal e As EventArgs) - RemoveHandler RadDockEvents.TabStripItemCreating, AddressOf RadDockEvents_TabStripItemCreating - MyBase.OnClosed(e) -End Sub -```` - -{{endregion}} ## Adding element to the TabStrip item The **TabStripItemCreating** event can be used for adding any kind of **RadElements** to the **TabStrip**. For example, the following code adds text box to each **TabStrip** item: -{{source=..\SamplesCS\Dock\CustomizingTabStripItems.cs region=element}} -{{source=..\SamplesVB\Dock\CustomizingTabStripItems.vb region=element}} - -````C# -void RadDockEvents_TabStripItemCreating1(object sender, TabStripItemCreatingEventArgs args) -{ - RadTextBoxControlElement textbox = new RadTextBoxControlElement(); - textbox.Margin = new System.Windows.Forms.Padding(80, 5, 5, 5); - textbox.MinSize = new System.Drawing.Size(50, 0); - args.TabItem.Children.Add(textbox); -} - -```` -````VB.NET -Private Sub RadDockEvents_TabStripItemCreating1(ByVal sender As Object, ByVal args As TabStripItemCreatingEventArgs) - Dim textbox As New RadTextBoxControlElement() - textbox.Margin = New System.Windows.Forms.Padding(80, 5, 5, 5) - textbox.MinSize = New System.Drawing.Size(50, 0) - args.TabItem.Children.Add(textbox) -End Sub - -```` - -{{endregion}} + + + + The tabs will look like this: @@ -100,102 +48,17 @@ The tabs will look like this: The **TabStripItemCreating** event can be used for replacing the entire element as well. First you need to create a **TabStripItem** class descendant -{{source=..\SamplesCS\Dock\CustomizingTabStripItems.cs region=Item}} -{{source=..\SamplesVB\Dock\CustomizingTabStripItems.vb region=Item}} - -````C# -class MyTabStripItem : TabStripItem -{ - public MyTabStripItem(TabPanel panel) - : base(panel) - { } - protected override void CreateChildElements() - { - base.CreateChildElements(); - this.Children.Add(CreateCustomElement()); - } - RadElement CreateCustomElement() - { - StackLayoutElement element = new StackLayoutElement(); - element.Orientation = Orientation.Horizontal; - element.StretchHorizontally = true; - element.MinSize = new System.Drawing.Size(100, 0); - RadButtonElement button = new RadButtonElement(); - button.Text = "Search"; - element.Children.Add(button); - RadTextBoxControlElement textbox = new RadTextBoxControlElement(); - element.Children.Add(textbox); - element.Margin = new Padding(5, 2, 2, 2); - this.DrawText = false; - this.Padding = new Padding(40, 5, 40, 5); - return element; - } - protected override Type ThemeEffectiveType - { - get - { - return typeof(TabStripItem); - } - } -} - -```` -````VB.NET -Friend Class MyTabStripItem - Inherits TabStripItem - Public Sub New(ByVal panel As TabPanel) - MyBase.New(panel) - End Sub - Protected Overrides Sub CreateChildElements() - MyBase.CreateChildElements() - Me.Children.Add(CreateCustomElement()) - End Sub - Private Function CreateCustomElement() As RadElement - Dim element As New StackLayoutElement() - element.Orientation = Orientation.Horizontal - element.StretchHorizontally = True - element.MinSize = New System.Drawing.Size(100, 0) - Dim button As New RadButtonElement() - button.Text = "Search" - element.Children.Add(button) - Dim textbox As New RadTextBoxControlElement() - element.Children.Add(textbox) - element.Margin = New Padding(5, 2, 2, 2) - Me.DrawText = False - Me.Padding = New Padding(40, 5, 40, 5) - Return element - End Function - Protected Overrides ReadOnly Property ThemeEffectiveType() As Type - Get - Return GetType(TabStripItem) - End Get - End Property -End Class - -```` - -{{endregion}} + + + + Then you can just replace the default item: -{{source=..\SamplesCS\Dock\CustomizingTabStripItems.cs region=replace}} -{{source=..\SamplesVB\Dock\CustomizingTabStripItems.vb region=replace}} - -````C# -void RadDockEvents_TabStripItemCreating(object sender, TabStripItemCreatingEventArgs args) -{ - args.TabItem = new MyTabStripItem(args.TabItem.TabPanel); -} - -```` -````VB.NET -Private Sub RadDockEvents_TabStripItemCreating(ByVal sender As Object, ByVal args As TabStripItemCreatingEventArgs) - args.TabItem = New MyTabStripItem(args.TabItem.TabPanel) -End Sub - -```` + + -{{endregion}} + The tabs will look like in the following image: @@ -209,70 +72,18 @@ The tab items of the __DocumentWindows__ in __RadDock__ have a predefined shape >note Since the __TabStripItemCreating__ event is static the event subscription have to be defined before the call to the InitializeComponent method. > -{{source=..\SamplesCS\Dock\CustomizingTabStripItemsForm.cs region=MultiLineRowLayoutInit}} -{{source=..\SamplesVB\Dock\CustomizingTabStripItemsForm.vb region=MultiLineRowLayoutInit}} - -````C# -public CustomizingTabStripItemsForm() -{ - RadDockEvents.TabStripItemCreating += RadDockEvents_TabStripItemCreating; - InitializeComponent(); - DocumentContainer container = this.documentContainer1; - DocumentTabStrip tabStrip = container.Controls[0] as DocumentTabStrip; - if (tabStrip != null) - { - tabStrip.TabStripElement.ItemFitMode = StripViewItemFitMode.MultiLine; - } -} -void RadDockEvents_TabStripItemCreating(object sender, TabStripItemCreatingEventArgs args) -{ - args.TabItem.Shape = new ChamferedRectShape(); - args.TabItem.Padding = new System.Windows.Forms.Padding(4, 4, 7, 4); -} - -```` -````VB.NET -Public Sub New() - AddHandler RadDockEvents.TabStripItemCreating, AddressOf RadDockEvents_TabStripItemCreating - InitializeComponent() - Dim container As DocumentContainer = Me.DocumentContainer1 - Dim tabStrip As DocumentTabStrip = TryCast(container.Controls(0), DocumentTabStrip) - If tabStrip IsNot Nothing Then - tabStrip.TabStripElement.ItemFitMode = StripViewItemFitMode.MultiLine - End If -End Sub -Private Sub RadDockEvents_TabStripItemCreating(sender As Object, args As TabStripItemCreatingEventArgs) - args.TabItem.Shape = New ChamferedRectShape() - args.TabItem.Padding = New System.Windows.Forms.Padding(4, 4, 7, 4) -End Sub - -```` - -{{endregion}} + + + + >note Because we are subscribing to a static event, we need to take care of the unscibription as well. Otherwise the form would not be disposed properly. > -{{source=..\SamplesCS\Dock\CustomizingTabStripItems.cs region=closed}} -{{source=..\SamplesVB\Dock\CustomizingTabStripItems.vb region=closed}} - -````C# -protected override void OnClosed(EventArgs e) -{ - RadDockEvents.TabStripItemCreating -= RadDockEvents_TabStripItemCreating; - base.OnClosed(e); -} - -```` -````VB.NET -Protected Overrides Sub OnClosed(ByVal e As EventArgs) - RemoveHandler RadDockEvents.TabStripItemCreating, AddressOf RadDockEvents_TabStripItemCreating - MyBase.OnClosed(e) -End Sub + + -```` -{{endregion}} Here is the outcome of the code above: diff --git a/controls/dock/object-model/example-building-an-advanced-layout-at-runtime.md b/controls/dock/object-model/example-building-an-advanced-layout-at-runtime.md index 2d2d70186..da692f732 100644 --- a/controls/dock/object-model/example-building-an-advanced-layout-at-runtime.md +++ b/controls/dock/object-model/example-building-an-advanced-layout-at-runtime.md @@ -29,29 +29,10 @@ So, let's start building the layout: #### Docking two ToolWindows -{{source=..\SamplesCS\Dock\BuildingAdvancedLayout.cs region=dockingTwoToolWindows}} -{{source=..\SamplesVB\Dock\BuildingAdvancedLayout.vb region=dockingTwoToolWindows}} - -````C# -ToolWindow window1 = new ToolWindow(); -window1.Name = "window1"; -this.radDock1.DockWindow(window1, DockPosition.Left); -ToolWindow window2 = new ToolWindow(); -window2.Name = "window2"; -this.radDock1.DockWindow(window2, window1, DockPosition.Bottom); - -```` -````VB.NET -Dim window1 As ToolWindow = New ToolWindow() -window1.Name = "window1" -Me.RadDock1.DockWindow(window1, DockPosition.Left) -Dim window2 As ToolWindow = New ToolWindow() -window2.Name = "window2" -Me.RadDock1.DockWindow(window2, window1, DockPosition.Bottom) - -```` - -{{endregion}} + + + + ![WinForms RadDock Two Windows Docked](images/dock-object-model-example-building-an-advanced-layout-at-runtime002.png) @@ -59,21 +40,10 @@ Me.RadDock1.DockWindow(window2, window1, DockPosition.Bottom) #### Setting relative size -{{source=..\SamplesCS\Dock\BuildingAdvancedLayout.cs region=settingRelativeSize}} -{{source=..\SamplesVB\Dock\BuildingAdvancedLayout.vb region=settingRelativeSize}} - -````C# -window2.TabStrip.SizeInfo.SizeMode = SplitPanelSizeMode.Relative; -window2.TabStrip.SizeInfo.RelativeRatio = new SizeF(0, 0.33f); + + -```` -````VB.NET -window2.TabStrip.SizeInfo.SizeMode = SplitPanelSizeMode.Relative -window2.TabStrip.SizeInfo.RelativeRatio = New System.Drawing.SizeF(0, 0.33F) - -```` - -{{endregion}} + The result is shown on the picture below: @@ -87,33 +57,10 @@ Now, if we decide to resize the form, the ration of the **TabStrips**' height wi #### Setting absolute size -{{source=..\SamplesCS\Dock\BuildingAdvancedLayout.cs region=settingAbsoliteSize}} -{{source=..\SamplesVB\Dock\BuildingAdvancedLayout.vb region=settingAbsoliteSize}} - -````C# -ToolWindow window3 = new ToolWindow(); -window3.Name = "window3"; -this.radDock1.DockWindow(window3, DockPosition.Bottom); -ToolWindow window4 = new ToolWindow(); -window4.Name = "window4"; -this.radDock1.DockWindow(window4, window3, DockPosition.Right); -window4.TabStrip.SizeInfo.SizeMode = SplitPanelSizeMode.Absolute; -window4.TabStrip.SizeInfo.AbsoluteSize = new Size(150, 0); - -```` -````VB.NET -Dim window3 As ToolWindow = New ToolWindow() -window3.Name = "window3" -Me.RadDock1.DockWindow(window3, DockPosition.Bottom) -Dim window4 As ToolWindow = New ToolWindow() -window4.Name = "window4" -Me.RadDock1.DockWindow(window4, window3, DockPosition.Right) -window4.TabStrip.SizeInfo.SizeMode = SplitPanelSizeMode.Absolute -window4.TabStrip.SizeInfo.AbsoluteSize = New Size(150, 0) - -```` - -{{endregion}} + + + + This time we set the __Width__ of the `window4` to an absolute value of 150 pixels. @@ -125,29 +72,10 @@ This time we set the __Width__ of the `window4` to an absolute value of 150 pixe #### Floating ToolWindows -{{source=..\SamplesCS\Dock\BuildingAdvancedLayout.cs region=floatingWindows}} -{{source=..\SamplesVB\Dock\BuildingAdvancedLayout.vb region=floatingWindows}} - -````C# -ToolWindow window5 = new ToolWindow(); -window5.Name = "window5"; -this.radDock1.FloatWindow(window5, new Rectangle(250, 250, 300, 150)); -ToolWindow window6 = new ToolWindow(); -window6.Name = "window6"; -this.radDock1.DockWindow(window6, window5, DockPosition.Right); - -```` -````VB.NET -Dim window5 As ToolWindow = New ToolWindow() -window5.Name = "window5" -Me.RadDock1.FloatWindow(window5, New Rectangle(250, 250, 300, 150)) -Dim window6 As ToolWindow = New ToolWindow() -window6.Name = "window6" -Me.RadDock1.DockWindow(window6, window5, DockPosition.Right) - -```` - -{{endregion}} + + + + ![WinForms RadDock Floating ToolWindows](images/dock-object-model-example-building-an-advanced-layout-at-runtime007.png) @@ -155,27 +83,10 @@ Me.RadDock1.DockWindow(window6, window5, DockPosition.Right) #### Setting the AutoHidePosition and AutoHideSize properties -{{source=..\SamplesCS\Dock\BuildingAdvancedLayout.cs region=autoHide}} -{{source=..\SamplesVB\Dock\BuildingAdvancedLayout.vb region=autoHide}} - -````C# -ToolWindow window7 = new ToolWindow(); -window7.Name = "window7"; -window7.AutoHideSize = new Size(100, 100); -this.radDock1.DockWindow(window7, window4, DockPosition.Bottom); -((ToolTabStrip)window7.TabStrip).AutoHidePosition = AutoHidePosition.Top; + + -```` -````VB.NET -Dim window7 As ToolWindow = New ToolWindow() -window7.Name = "window7" -window7.AutoHideSize = New Drawing.Size(100, 100) -Me.RadDock1.DockWindow(window7, window4, DockPosition.Bottom) -CType(window7.TabStrip, ToolTabStrip).AutoHidePosition = AutoHidePosition.Top - -```` - -{{endregion}} + Initially, the layout will look like this: @@ -189,29 +100,10 @@ If the user clicks the `Pin` button of `window7`, it will become auto-hidden to #### Adding DocumentWindows -{{source=..\SamplesCS\Dock\BuildingAdvancedLayout.cs region=addingDocumentWindows}} -{{source=..\SamplesVB\Dock\BuildingAdvancedLayout.vb region=addingDocumentWindows}} - -````C# -DocumentWindow document1 = new DocumentWindow(); -document1.Name = "document1"; -this.radDock1.AddDocument(document1); -DocumentWindow document2 = new DocumentWindow(); -document2.Name = "document2"; -this.radDock1.AddDocument(document2, document1, DockPosition.Bottom); - -```` -````VB.NET -Dim document1 As DocumentWindow = New DocumentWindow() -document1.Name = "document1" -Me.RadDock1.AddDocument(document1) -Dim document2 As DocumentWindow = New DocumentWindow() -document2.Name = "document2" -Me.RadDock1.AddDocument(document2, document1, DockPosition.Bottom) - -```` + + -{{endregion}} + ![WinForms RadDock Adding DocumentWindows](images/dock-object-model-example-building-an-advanced-layout-at-runtime010.png) @@ -220,19 +112,10 @@ However, you may not want to have any documents. In this case, set the __MainDoc #### Hiding the main DocumentContainer -{{source=..\SamplesCS\Dock\BuildingAdvancedLayout.cs region=dockContainerVisible}} -{{source=..\SamplesVB\Dock\BuildingAdvancedLayout.vb region=dockContainerVisible}} - -````C# -this.radDock1.MainDocumentContainerVisible = false; - -```` -````VB.NET -Me.RadDock1.MainDocumentContainerVisible = False + + -```` - -{{endregion}} + ![WinForms RadDock Hiding the Main DocumentContainer ](images/dock-object-model-example-building-an-advanced-layout-at-runtime011.png) diff --git a/controls/dock/object-model/tabs-and-captions.md b/controls/dock/object-model/tabs-and-captions.md index b7950bcbb..fbcf4c059 100644 --- a/controls/dock/object-model/tabs-and-captions.md +++ b/controls/dock/object-model/tabs-and-captions.md @@ -21,19 +21,10 @@ __RadDock__ exposes several properties which allow you to have full control over #### Setting DocumentTabsAlignment to Left -{{source=..\SamplesCS\Dock\TabsAndCaptions.cs region=documentTabsAlignment}} -{{source=..\SamplesVB\Dock\TabsAndCaptions.vb region=documentTabsAlignment}} + + -````C# -this.radDock1.DocumentTabsAlignment = TabStripAlignment.Left; - -```` -````VB.NET -Me.RadDock1.DocumentTabsAlignment = TabStripAlignment.Left - -```` - -{{endregion}} + ![WinForms RadDock Left DocumentTabsAlignment](images/dock-object-model-tabs-and-captions001.png) @@ -42,19 +33,10 @@ Me.RadDock1.DocumentTabsAlignment = TabStripAlignment.Left #### Hiding the document tabs -{{source=..\SamplesCS\Dock\TabsAndCaptions.cs region=documentTabsVisible}} -{{source=..\SamplesVB\Dock\TabsAndCaptions.vb region=documentTabsVisible}} - -````C# -this.radDock1.DocumentTabsVisible = false; - -```` -````VB.NET -Me.RadDock1.DocumentTabsVisible = False + + -```` - -{{endregion}} + ![WinForms RadDock Hiding Document Tabs](images/dock-object-model-tabs-and-captions002.png) @@ -63,19 +45,10 @@ Me.RadDock1.DocumentTabsVisible = False #### Setting the ToolTabsAlignment to Right -{{source=..\SamplesCS\Dock\TabsAndCaptions.cs region=toolTabsAlignment}} -{{source=..\SamplesVB\Dock\TabsAndCaptions.vb region=toolTabsAlignment}} - -````C# -this.radDock1.ToolTabsAlignment = TabStripAlignment.Right; + + -```` -````VB.NET -Me.RadDock1.ToolTabsAlignment = TabStripAlignment.Right - -```` - -{{endregion}} + ![WinForms RadDock ToolTabsAlignment Right](images/dock-object-model-tabs-and-captions003.png) @@ -84,19 +57,10 @@ Me.RadDock1.ToolTabsAlignment = TabStripAlignment.Right #### Hiding the tool tabs -{{source=..\SamplesCS\Dock\TabsAndCaptions.cs region=toolTabsVisible}} -{{source=..\SamplesVB\Dock\TabsAndCaptions.vb region=toolTabsVisible}} + + -````C# -this.radDock1.ToolTabsVisible = false; - -```` -````VB.NET -Me.RadDock1.ToolTabsVisible = False - -```` - -{{endregion}} + ![WinForms RadDock Hiding Tool Tabs](images/dock-object-model-tabs-and-captions004.png) @@ -104,19 +68,10 @@ Me.RadDock1.ToolTabsVisible = False #### Hiding the caption of ToolTabStrip -{{source=..\SamplesCS\Dock\TabsAndCaptions.cs region=captionVisible}} -{{source=..\SamplesVB\Dock\TabsAndCaptions.vb region=captionVisible}} - -````C# -this.toolTabStrip1.CaptionVisible = false; - -```` -````VB.NET -Me.ToolTabStrip1.CaptionVisible = False + + -```` - -{{endregion}} + ![WinForms RadDock Hinding Caption ToolTabStrip](images/dock-object-model-tabs-and-captions005.png) @@ -124,21 +79,10 @@ Me.ToolTabStrip1.CaptionVisible = False #### Showing close buttons -{{source=..\SamplesCS\Dock\TabsAndCaptions.cs region=showToolCloseButton}} -{{source=..\SamplesVB\Dock\TabsAndCaptions.vb region=showToolCloseButton}} - -````C# -this.radDock1.ShowToolCloseButton = true; -this.radDock1.ShowDocumentCloseButton = true; + + -```` -````VB.NET -Me.RadDock1.ShowToolCloseButton = True -Me.RadDock1.ShowDocumentCloseButton = True - -```` - -{{endregion}} + ![WinForms RadDock Showing Close Buttons](images/dock-object-model-tabs-and-captions006.png) diff --git a/controls/dock/object-model/toolwindow-and-documentwindow-properties-and-methods.md b/controls/dock/object-model/toolwindow-and-documentwindow-properties-and-methods.md index 8de0fbc34..5deda3cdc 100644 --- a/controls/dock/object-model/toolwindow-and-documentwindow-properties-and-methods.md +++ b/controls/dock/object-model/toolwindow-and-documentwindow-properties-and-methods.md @@ -45,19 +45,10 @@ __ToolWindow__ and __DocumentWindow__ both implement the same interfaces, such a #### Using DockTo() -{{source=..\SamplesCS\Dock\CreatingWindows.cs region=usingDockTo}} -{{source=..\SamplesVB\Dock\CreatingWindows.vb region=usingDockTo}} + + -````C# -toolWindow2.DockTo(toolWindow1, DockPosition.Fill); - -```` -````VB.NET -toolWindow2.DockTo(ToolWindow1, DockPosition.Fill) - -```` - -{{endregion}} + # See Also diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/autocompletemodes.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/autocompletemodes.md index 9beb950e5..fd85e4cf4 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/autocompletemodes.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/autocompletemodes.md @@ -18,19 +18,10 @@ You can set the __AutoCompleteMode__ as follows: #### Set AutoCompleteMode -{{source=..\SamplesCS\DropDownListControl\CheckedDropDownList\AutoCompleteModes1.cs region=SetMode}} -{{source=..\SamplesVB\DropDownListControl\CheckedDropDownList\AutoCompleteModes1.vb region=SetMode}} + + -````C# -this.radCheckedDropDownList1.AutoCompleteMode = AutoCompleteMode.SuggestAppend; -```` -````VB.NET -Me.RadCheckedDropDownList1.AutoCompleteMode = AutoCompleteMode.SuggestAppend - -```` - -{{endregion}} * *None*: Nothing happens when a user begins to type into the text box portion of the control. diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/customizing-appearance/accessing-and-customizing-elements.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/customizing-appearance/accessing-and-customizing-elements.md index 26e6dc49b..3151ee084 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/customizing-appearance/accessing-and-customizing-elements.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/customizing-appearance/accessing-and-customizing-elements.md @@ -33,27 +33,10 @@ You can customize the nested elements at run time as well: #### Customize elements -{{source=..\SamplesCS\DropDownListControl\CheckedDropDownList\Customization1.cs region=CustomizeElements}} -{{source=..\SamplesVB\DropDownListControl\CheckedDropDownList\Customization1.vb region=CustomizeElements}} - -````C# - -this.radCheckedDropDownList1.DropDownListElement.ArrowButton.Fill.BackColor = Color.Aqua; -this.radCheckedDropDownList1.DropDownListElement.EditableElement.BorderColor = Color.Red; -this.radCheckedDropDownList1.DropDownListElement.EditableElement.DrawBorder = true; -this.radCheckedDropDownList1.DropDownListElement.EditableElement.BorderGradientStyle = GradientStyles.Solid; -this.radCheckedDropDownList1.DropDownListElement.EditableElement.BorderWidth = 1; - -```` -````VB.NET -Me.RadCheckedDropDownList1.DropDownListElement.ArrowButton.Fill.BackColor = Color.Aqua -Me.RadCheckedDropDownList1.DropDownListElement.EditableElement.BorderColor = Color.Red -Me.RadCheckedDropDownList1.DropDownListElement.EditableElement.DrawBorder = True -Me.RadCheckedDropDownList1.DropDownListElement.EditableElement.BorderGradientStyle = GradientStyles.Solid -Me.RadCheckedDropDownList1.DropDownListElement.EditableElement.BorderWidth = 1 - -```` - -{{endregion}} + + + + + In order to style the pop-up items it is suitable to use the [Formatting Items]({%slug winforms/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/customization%}) event. diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/customizing-appearance/customization.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/customizing-appearance/customization.md index 7369c2481..caf727653 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/customizing-appearance/customization.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/customizing-appearance/customization.md @@ -20,58 +20,18 @@ In order to customize the editable area, you must subscribe to the __TextBlockFo #### Subscribe to TextBlockFormatting -{{source=..\SamplesCS\DropDownListControl\CheckedDropDownList\Customization1.cs region=TextBlockFormattingSubscribe}} -{{source=..\SamplesVB\DropDownListControl\CheckedDropDownList\Customization1.vb region=TextBlockFormattingSubscribe}} + + -````C# -this.radCheckedDropDownList1.TextBlockFormatting += radCheckedDropDownList1_TextBlockFormatting; -```` -````VB.NET -AddHandler Me.RadCheckedDropDownList1.TextBlockFormatting, AddressOf radCheckedDropDownList1_TextBlockFormatting -```` -{{endregion}} +#### Modify properties + + -#### Modify properties -{{source=..\SamplesCS\DropDownListControl\CheckedDropDownList\Customization1.cs region=TextBlockFormattingHandler}} -{{source=..\SamplesVB\DropDownListControl\CheckedDropDownList\Customization1.vb region=TextBlockFormattingHandler}} - -````C# -void radCheckedDropDownList1_TextBlockFormatting(object sender, TextBlockFormattingEventArgs e) -{ - TokenizedTextBlockElement token = e.TextBlock as TokenizedTextBlockElement; - if (token != null) - { - token.ForeColor = Color.DarkBlue; - token.DrawFill = false; - token.BorderColor = Color.DarkRed; - token.BorderWidth = 1.3f; - token.DrawBorder = true; - token.BorderGradientStyle = GradientStyles.Solid; - } -} - -```` -````VB.NET -Private Sub radCheckedDropDownList1_TextBlockFormatting(sender As Object, e As TextBlockFormattingEventArgs) - Dim token As TokenizedTextBlockElement = TryCast(e.TextBlock, TokenizedTextBlockElement) - If token IsNot Nothing Then - token.ForeColor = Color.DarkBlue - token.DrawFill = False - token.BorderColor = Color.DarkRed - token.BorderWidth = 1.3F - token.DrawBorder = True - token.BorderGradientStyle = GradientStyles.Solid - End If -End Sub - -```` - -{{endregion}} >caption Figure 1: Customizing tokens @@ -83,54 +43,18 @@ Customizing the drop down items is similar. Subscribe to the __VisualListItemFor #### Subscribe to VisualListItemFormatting -{{source=..\SamplesCS\DropDownListControl\CheckedDropDownList\Customization1.cs region=VisualListItemFormattingSubscribe}} -{{source=..\SamplesVB\DropDownListControl\CheckedDropDownList\Customization1.vb region=VisualListItemFormattingSubscribe}} + + -````C# -this.radCheckedDropDownList1.VisualListItemFormatting += radCheckedDropDownList1_VisualListItemFormatting; -```` -````VB.NET -AddHandler Me.RadCheckedDropDownList1.VisualListItemFormatting, AddressOf radCheckedDropDownList1_VisualListItemFormatting -```` -{{endregion}} +#### Modify properties + + -#### Modify properties -{{source=..\SamplesCS\DropDownListControl\CheckedDropDownList\Customization1.cs region=VisualListItemFormattingHandler}} -{{source=..\SamplesVB\DropDownListControl\CheckedDropDownList\Customization1.vb region=VisualListItemFormattingHandler}} - -````C# -void radCheckedDropDownList1_VisualListItemFormatting(object sender, VisualItemFormattingEventArgs args) -{ - bool itemChecked = ((RadCheckedListDataItem)args.VisualItem.Data).Checked; - if (itemChecked) - { - args.VisualItem.ForeColor = Color.Green; - } - else - { - args.VisualItem.ForeColor = Color.Red; - } -} - -```` -````VB.NET -Private Sub radCheckedDropDownList1_VisualListItemFormatting(sender As Object, args As VisualItemFormattingEventArgs) - Dim itemChecked As Boolean = DirectCast(args.VisualItem.Data, RadCheckedListDataItem).Checked - If itemChecked Then - args.VisualItem.ForeColor = Color.Green - Else - args.VisualItem.ForeColor = Color.Red - End If -End Sub - -```` - -{{endregion}} >caption Figure 2: Customizing dropdown items diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/getting-started.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/getting-started.md index 0d1ed328e..2e65ce563 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/getting-started.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/getting-started.md @@ -57,22 +57,10 @@ The following tutorial demonstrates how to populate __RadCheckedDropDownList__ a #### Handling ItemCheckedChanged event -{{source=..\SamplesCS\DropDownListControl\CheckedDropDownList\GettingStarted1.cs region=AddItems}} -{{source=..\SamplesVB\DropDownListControl\CheckedDropDownList\GettingStarted1.vb region=AddItems}} - -````C# -private void radCheckedDropDownList1_ItemCheckedChanged(object sender, RadCheckedListDataItemEventArgs e) -{ - RadMessageBox.Show(" Item >> " + e.Item.Text + " Checked state >> " + e.Item.Checked); -} - -```` -````VB.NET -Private Sub radCheckedDropDownList1_ItemCheckedChanged(sender As Object, e As RadCheckedListDataItemEventArgs) - RadMessageBox.Show(" Item >> " + e.Item.Text + " Checked state >> " + e.Item.Checked) -End Sub - -```` + + + + >caption Figure 2: Handling ItemCheckedChanged diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/how-to/add-non-existing-items.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/how-to/add-non-existing-items.md index 6d027efca..e1afd5727 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/how-to/add-non-existing-items.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/how-to/add-non-existing-items.md @@ -17,55 +17,18 @@ For this purpose, __RadCheckedDropDownList__ has the __TokenValidating__ event. #### Subscribe for TokenValidating -{{source=..\SamplesCS\DropDownListControl\CheckedDropDownList\How-To\AddNonExistingItems1.cs region=Subscribe}} -{{source=..\SamplesVB\DropDownListControl\CheckedDropDownList\How-To\AddNonExistingItems1.vb region=Subscribe}} + + -````C# -this.radCheckedDropDownList1.TokenValidating += radCheckedDropDownList1_TokenValidating; -```` -````VB.NET -AddHandler Me.RadCheckedDropDownList1.TokenValidating, AddressOf radCheckedDropDownList1_TokenValidating -```` -{{endregion}} +#### Add non-existing items + + -#### Add non-existing items -{{source=..\SamplesCS\DropDownListControl\CheckedDropDownList\How-To\AddNonExistingItems1.cs region=Handler}} -{{source=..\SamplesVB\DropDownListControl\CheckedDropDownList\How-To\AddNonExistingItems1.vb region=Handler}} - -````C# -void radCheckedDropDownList1_TokenValidating(object sender, TokenValidatingEventArgs e) -{ - if (!e.IsValidToken) - { - AutoCompleteBoxViewElement textBox = sender as AutoCompleteBoxViewElement; - if (this.radCheckedDropDownList1.DropDownListElement.FindStringExact(e.Text) == -1) - { - this.radCheckedDropDownList1.Items.Add(new RadCheckedListDataItem(e.Text, false)); - e.IsValidToken = true; - } - } -} - -```` -````VB.NET -Private Sub radCheckedDropDownList1_TokenValidating(sender As Object, e As TokenValidatingEventArgs) - If Not e.IsValidToken Then - Dim textBox As AutoCompleteBoxViewElement = TryCast(sender, AutoCompleteBoxViewElement) - If Me.RadCheckedDropDownList1.DropDownListElement.FindStringExact(e.Text) = -1 Then - Me.RadCheckedDropDownList1.Items.Add(New RadCheckedListDataItem(e.Text, False)) - e.IsValidToken = True - End If - End If -End Sub - -```` - -{{endregion}} >note In order to make the custom text a valid token, it is necessary to enter the delimeter which is __;__ by default. diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/how-to/use-as-radgridview-editor.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/how-to/use-as-radgridview-editor.md index 46fe9dfb0..020eaefb6 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/how-to/use-as-radgridview-editor.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/how-to/use-as-radgridview-editor.md @@ -24,144 +24,30 @@ As many other RadControls, __RadCheckedDropDownList__ can also be used as [edito #### Initialize -{{source=..\SamplesCS\DropDownListControl\CheckedDropDownList\How-To\UseAsRadGridViewEditor1.cs region=InitGrid}} -{{source=..\SamplesVB\DropDownListControl\CheckedDropDownList\How-To\UseAsRadGridViewEditor1.vb region=InitGrid}} + + + + -````C# - -BindingList columnData; -BindingList datasource; -public UseAsRadGridViewEditor1() -{ - InitializeComponent(); - - columnData = new BindingList(); - datasource = new BindingList(); - - for (int i = 0; i < 5; i++) - { - datasource.Add(new MyPart("Part " + i + ";Part " + (i + 1) + ";")); - } - radGridView1.AutoGenerateColumns = false; - radGridView1.DataSource = datasource; - - GridViewTextBoxColumn checkedDropDownListColumn = new GridViewTextBoxColumn(); - checkedDropDownListColumn.FieldName = "CurrentParts"; - checkedDropDownListColumn.Width = 200; - - this.radGridView1.Columns.Add(checkedDropDownListColumn); - - for (int i = 0; i < 10; i++) - { - columnData.Add(new MyPart("Part " + i)); - } - - this.radGridView1.EditorRequired += radGridView1_EditorRequired; -} - -```` -````VB.NET -Private columnData As BindingList(Of MyPart) -Private datasource As BindingList(Of MyPart) -Public Sub New() - InitializeComponent() - columnData = New BindingList(Of MyPart)() - datasource = New BindingList(Of MyPart)() - For i As Integer = 0 To 4 - datasource.Add(New MyPart("Part " & i & ";Part " & (i + 1) & ";")) - Next i - radGridView1.AutoGenerateColumns = False - radGridView1.DataSource = datasource - Dim checkedDropDownListColumn As New GridViewTextBoxColumn() - checkedDropDownListColumn.FieldName = "CurrentParts" - checkedDropDownListColumn.Width = 200 - Me.RadGridView1.Columns.Add(checkedDropDownListColumn) - For i As Integer = 0 To 9 - columnData.Add(New MyPart("Part " & i)) - Next i - AddHandler Me.radGridView1.EditorRequired, AddressOf radGridView1_EditorRequired -End Sub - -```` - -{{endregion}} 2\. The next step is to replace the default editor. This can be achieved by handling the __EditorReqired__ event. This is the place where the data source should be set as well. #### Change the editor -{{source=..\SamplesCS\DropDownListControl\CheckedDropDownList\How-To\UseAsRadGridViewEditor1.cs region=Required}} -{{source=..\SamplesVB\DropDownListControl\CheckedDropDownList\How-To\UseAsRadGridViewEditor1.vb region=Required}} - -````C# - -void radGridView1_EditorRequired(object sender, EditorRequiredEventArgs e) -{ - if (this.radGridView1.CurrentColumn.Index == 0) - { - RadCheckedDropDownListElement editor = new GridViewCheckedDropDownListEditor(); - editor.DataSource = this.columnData; - editor.DisplayMember = "CurrentParts"; - e.Editor = editor; - } -} - -```` -````VB.NET -Private Sub radGridView1_EditorRequired(ByVal sender As Object, ByVal e As EditorRequiredEventArgs) - If Me.radGridView1.CurrentColumn.Index = 0 Then - Dim editor As RadCheckedDropDownListElement = New GridViewCheckedDropDownListEditor() - editor.DataSource = Me.columnData - editor.DisplayMember = "CurrentParts" - e.Editor = editor - End If -End Sub - -```` - -{{endregion}} + + + + + 3\. The final step is creating the editor. This can be achieved by creating a descendant of __RadCheckedDropDownListElement__ and overriding its __Value__ property. #### Editor -{{source=..\SamplesCS\DropDownListControl\CheckedDropDownList\How-To\UseAsRadGridViewEditor1.cs region=Editor}} -{{source=..\SamplesVB\DropDownListControl\CheckedDropDownList\How-To\UseAsRadGridViewEditor1.vb region=Editor}} + + + -````C# - -public class GridViewCheckedDropDownListEditor : RadCheckedDropDownListElement -{ - public override object Value - { - get - { - return this.Text; - } - set - { - this.Text = value.ToString(); - } - } -} - -```` -````VB.NET -Public Class GridViewCheckedDropDownListEditor - Inherits RadCheckedDropDownListElement - Public Overrides Property Value() As Object - Get - Return Me.Text - End Get - Set(ByVal value As Object) - Me.Text = value.ToString() - End Set - End Property -End Class - -```` - -{{endregion}} diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/populating-with-data/adding-items-programmatically.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/populating-with-data/adding-items-programmatically.md index 1146fa552..6fb111180 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/populating-with-data/adding-items-programmatically.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/populating-with-data/adding-items-programmatically.md @@ -28,34 +28,10 @@ You can use one of the following item types: #### Add items programmatically -{{source=..\SamplesCS\DropDownListControl\CheckedDropDownList\CheckedDropDownList1.cs region=AddItemsProgrammatically}} -{{source=..\SamplesVB\DropDownListControl\CheckedDropDownList\CheckedDropDownList1.vb region=AddItemsProgrammatically}} - -````C# -RadCheckedListDataItem dataItem = new RadCheckedListDataItem(); -dataItem.Text = "Chicken toast"; -radCheckedDropDownList1.Items.Add(dataItem); - -DescriptionTextCheckedListDataItem descriptionItem = new DescriptionTextCheckedListDataItem(); -descriptionItem.Text = "Chicken wings"; -descriptionItem.Checked = true; -descriptionItem.DescriptionText = "some description"; -radCheckedDropDownList1.Items.Add(descriptionItem); - -```` -````VB.NET -Dim dataItem As New RadCheckedListDataItem() -dataItem.Text = "Chicken toast" -radCheckedDropDownList1.Items.Add(dataItem) -Dim descriptionItem As New DescriptionTextCheckedListDataItem() -descriptionItem.Text = "Chicken wings" -descriptionItem.Checked = True -descriptionItem.DescriptionText = "some description" -radCheckedDropDownList1.Items.Add(descriptionItem) - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/populating-with-data/data-binding.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/populating-with-data/data-binding.md index 6d7d32366..fcbebdb05 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/populating-with-data/data-binding.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/checkeddropdownlist/populating-with-data/data-binding.md @@ -56,148 +56,20 @@ First, our model. It must implement the __INotifyPropertyChanged__ interface, so #### Model -{{source=..\SamplesCS\DropDownListControl\CheckedDropDownList\DataBinding1.cs region=Model}} -{{source=..\SamplesVB\DropDownListControl\CheckedDropDownList\DataBinding1.vb region=Model}} - -````C# -class Model : INotifyPropertyChanged -{ - private int id; - private bool selected; - private string name; - public int Id - { - get { return this.id; } - set { this.id = value; this.OnPropertyChanged("Id"); } - } - public bool Selected - { - get { return this.selected; } - set { this.selected = value; this.OnPropertyChanged("Selected"); } - } - public string Name - { - get { return this.name; } - set { this.name = value; this.OnPropertyChanged("Name"); } - } - public event PropertyChangedEventHandler PropertyChanged; - protected virtual void OnPropertyChanged(string propName) - { - if (this.PropertyChanged != null) - { - this.PropertyChanged(this, new PropertyChangedEventArgs(propName)); - } - } -} - -```` -````VB.NET -Private Class Model - Implements INotifyPropertyChanged - Private m_id As Integer - Private m_selected As Boolean - Private m_name As String - Public Property Id() As Integer - Get - Return Me.m_id - End Get - Set(value As Integer) - Me.m_id = value - Me.OnPropertyChanged("Id") - End Set - End Property - Public Property Selected() As Boolean - Get - Return Me.m_selected - End Get - Set(value As Boolean) - Me.m_selected = value - Me.OnPropertyChanged("Selected") - End Set - End Property - Public Property Name() As String - Get - Return Me.m_name - End Get - Set(value As String) - Me.m_name = value - Me.OnPropertyChanged("Name") - End Set - End Property - Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged - Protected Overridable Sub OnPropertyChanged(propName As String) - RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propName)) - End Sub -End Class - -```` - -{{endregion}} + + + + Now drag a __RadCheckedDropDownList__ to the form and a __RadButton__. The button will be used to check a random item in our data source. In order to bind __RadCheckedDropDownList__ we must assign it a __BindingList__ filled with items and set its *Checked*, *Display* and *Value* members: #### Model -{{source=..\SamplesCS\DropDownListControl\CheckedDropDownList\DataBinding1.cs region=DataAndBinding}} -{{source=..\SamplesVB\DropDownListControl\CheckedDropDownList\DataBinding1.vb region=DataAndBinding}} - -````C# -private BindingList dataSource = new BindingList(); -private Random rnd = new Random(); -public DataBinding1() -{ - InitializeComponent(); - this.radCheckedDropDownList1.CheckedMember = "Selected"; - this.radCheckedDropDownList1.DisplayMember = "Name"; - this.radCheckedDropDownList1.ValueMember = "Id"; - for (int i = 0; i < 15; i++) - { - dataSource.Add(new Model - { - Id = i, - Name = "Item " + i - }); - } - this.radCheckedDropDownList1.DataSource = this.dataSource; - this.radButton1.Text = "Toggle Random Item"; - this.radButton1.Click += radButton1_Click; -} -void radButton1_Click(object sender, EventArgs e) -{ - int index = rnd.Next(0, dataSource.Count); - Model item = this.dataSource[index]; - item.Selected = !item.Selected; -} - -```` -````VB.NET -Private dataSource As New BindingList(Of Model)() -Private rnd As New Random() -Public Sub New() - InitializeComponent() - Me.RadCheckedDropDownList1.CheckedMember = "Selected" - Me.RadCheckedDropDownList1.DisplayMember = "Name" - Me.RadCheckedDropDownList1.ValueMember = "Id" - For i As Integer = 0 To 14 - dataSource.Add(New Model() With { _ - .Id = i, _ - .Name = "Item " & i _ - }) - Next - Me.RadCheckedDropDownList1.DataSource = Me.dataSource - Me.radButton1.Text = "Toggle Random Item" - AddHandler Me.radButton1.Click, AddressOf radButton1_Click -End Sub -Private Sub radButton1_Click(sender As Object, e As EventArgs) - Dim index As Integer = rnd.[Next](0, dataSource.Count) - Dim item As Model = Me.dataSource(index) - item.Selected = Not item.Selected -End Sub - -```` - -{{endregion}} + + + + >caption Figure 4: RadCheckedDropDownList bound at Run time diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/animation-effects.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/animation-effects.md index 75961c2f6..605e62b78 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/animation-effects.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/animation-effects.md @@ -27,23 +27,10 @@ Three properties define the animation behavior of __RadDropDownList__: #### Animation Settings -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListAnimation.cs region=SetAnimation}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListAnimation.vb region=SetAnimation}} + + -````C# -this.radDropDownList1.DropDownAnimationEnabled = true; -this.radDropDownList1.DropDownAnimationFrames = 50; -this.radDropDownList1.DropDownAnimationEasing = RadEasingType.OutSine; -```` -````VB.NET -Me.radDropDownList1.DropDownAnimationEnabled = True -Me.radDropDownList1.DropDownAnimationFrames = 50 -Me.radDropDownList1.DropDownAnimationEasing = RadEasingType.OutSine - -```` - -{{endregion}} # See Also diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/custom-items.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/custom-items.md index 93ac9917e..dc3c9c607 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/custom-items.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/custom-items.md @@ -25,258 +25,26 @@ This article demonstrates how to display detailed information for each employee #### Custom RadListVisualItem -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListCustomItems.cs region=CustomVisualItem}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListCustomItems.vb region=CustomVisualItem}} + + -````C# - -public class CustomVisualItem : RadListVisualItem -{ - Font boldFont = new Font("Arial",10f, FontStyle.Bold); - Font italicFont = new Font("Arial",10f, FontStyle.Italic); - DockLayoutPanel mainContainer; - StackLayoutElement leftColumn; - StackLayoutElement rightColumn; - LightVisualElement titleElement; - LightVisualElement photoElement; - LightVisualElement nameElement; - LightVisualElement addressElement; - LightVisualElement phoneElement; - - protected override Type ThemeEffectiveType - { - get - { - return typeof(RadListVisualItem); - } - } - - protected override void CreateChildElements() - { - base.CreateChildElements(); - - mainContainer = new DockLayoutPanel(); - leftColumn = new StackLayoutElement(); - rightColumn = new StackLayoutElement(); - titleElement = new LightVisualElement(); - photoElement = new LightVisualElement(); - nameElement = new LightVisualElement(); - addressElement = new LightVisualElement(); - phoneElement = new LightVisualElement(); - - this.Children.Add(mainContainer); - mainContainer.LastChildFill = true; - - leftColumn.Orientation = Orientation.Vertical; - leftColumn.Children.Add(photoElement); - photoElement.DrawBorder = true; - - rightColumn.Orientation = Orientation.Vertical; - rightColumn.Children.Add(nameElement); - nameElement.Font = boldFont; - rightColumn.Children.Add(addressElement); - rightColumn.Children.Add(phoneElement); - rightColumn.Children.Add(titleElement); - titleElement.DrawBorder = true; - titleElement.Font = italicFont; - titleElement.BorderBoxStyle = Telerik.WinControls.BorderBoxStyle.FourBorders; - titleElement.BorderLeftWidth = 0; - titleElement.BorderTopWidth = 1; - titleElement.BorderRightWidth = 0; - titleElement.BorderBottomWidth = 0; - - mainContainer.Children.Add(leftColumn); - mainContainer.Children.Add(rightColumn); - DockLayoutPanel.SetDock(leftColumn, Telerik.WinControls.Layouts.Dock.Left); - DockLayoutPanel.SetDock(rightColumn, Telerik.WinControls.Layouts.Dock.Right); - leftColumn.NotifyParentOnMouseInput = true; - rightColumn.NotifyParentOnMouseInput = true; - titleElement.NotifyParentOnMouseInput = true; - photoElement.NotifyParentOnMouseInput = true; - nameElement.NotifyParentOnMouseInput = true; - addressElement.NotifyParentOnMouseInput = true; - phoneElement.NotifyParentOnMouseInput = true; - } - - public override void Synchronize() - { - base.Synchronize(); - this.Text = string.Empty; - DataRowView rowView = this.Data.DataBoundItem as DataRowView; - if (rowView != null) - { - this.photoElement.Image = GetImageFromData(rowView.Row["Photo"] as byte[]); - this.titleElement.Text = rowView.Row["Title"].ToString(); - this.nameElement.Text = rowView.Row["FirstName"].ToString() + " " + rowView.Row["LastName"].ToString(); - this.addressElement.Text = "Address: " + rowView.Row["Address"].ToString().Replace(System.Environment.NewLine, " "); - this.phoneElement.Text = "Phone: " + rowView.Row["HomePhone"].ToString(); - } - } - - private Image GetImageFromData(byte[] imageData) - { - const int OleHeaderLength = 78; - MemoryStream memoryStream = new MemoryStream(); - if (HasOleContainerHeader(imageData)) - { - memoryStream.Write(imageData, OleHeaderLength, imageData.Length - OleHeaderLength); - } - else - { - memoryStream.Write(imageData, 0, imageData.Length); - } - Bitmap bitmap = new Bitmap(memoryStream); - return bitmap.GetThumbnailImage(55, 65, null, new IntPtr()); - } - - private bool HasOleContainerHeader(byte[] imageByteArray) - { - const byte OleByte0 = 21; - const byte OleByte1 = 28; - return (imageByteArray[0] == OleByte0) && (imageByteArray[1] == OleByte1); - } -} -```` -````VB.NET - -Public Class CustomVisualItem -Inherits RadListVisualItem - Private boldFont As Font - Private italicFont As Font - Private mainContainer As DockLayoutPanel - Private leftColumn As StackLayoutElement - Private rightColumn As StackLayoutElement - Private titleElement As LightVisualElement - Private photoElement As LightVisualElement - Private nameElement As LightVisualElement - Private addressElement As LightVisualElement - Private phoneElement As LightVisualElement - Protected Overrides ReadOnly Property ThemeEffectiveType() As Type - Get - Return GetType(RadListVisualItem) - End Get - End Property - Protected Overrides Sub CreateChildElements() - MyBase.CreateChildElements() - boldFont = New Font("Arial", 10.0F, FontStyle.Bold) - italicFont = New Font("Arial", 10.0F, FontStyle.Italic) - mainContainer = New DockLayoutPanel() - leftColumn = New StackLayoutElement() - rightColumn = New StackLayoutElement() - titleElement = New LightVisualElement() - photoElement = New LightVisualElement() - nameElement = New LightVisualElement() - addressElement = New LightVisualElement() - phoneElement = New LightVisualElement() - Me.Children.Add(mainContainer) - mainContainer.LastChildFill = True - leftColumn.Orientation = Orientation.Vertical - leftColumn.Children.Add(photoElement) - photoElement.DrawBorder = True - rightColumn.Orientation = Orientation.Vertical - rightColumn.Children.Add(nameElement) - nameElement.Font = boldFont - rightColumn.Children.Add(addressElement) - rightColumn.Children.Add(phoneElement) - rightColumn.Children.Add(titleElement) - titleElement.DrawBorder = True - titleElement.Font = italicFont - titleElement.BorderBoxStyle = Telerik.WinControls.BorderBoxStyle.FourBorders - titleElement.BorderLeftWidth = 0 - titleElement.BorderTopWidth = 1 - titleElement.BorderRightWidth = 0 - titleElement.BorderBottomWidth = 0 - mainContainer.Children.Add(leftColumn) - mainContainer.Children.Add(rightColumn) - DockLayoutPanel.SetDock(leftColumn, Telerik.WinControls.Layouts.Dock.Left) - DockLayoutPanel.SetDock(rightColumn, Telerik.WinControls.Layouts.Dock.Right) - leftColumn.NotifyParentOnMouseInput = True - rightColumn.NotifyParentOnMouseInput = True - titleElement.NotifyParentOnMouseInput = True - photoElement.NotifyParentOnMouseInput = True - nameElement.NotifyParentOnMouseInput = True - addressElement.NotifyParentOnMouseInput = True - phoneElement.NotifyParentOnMouseInput = True - End Sub - Public Overrides Sub Synchronize() - MyBase.Synchronize() - Me.Text = String.Empty - Dim rowView As DataRowView = TryCast(Me.Data.DataBoundItem, DataRowView) - If rowView IsNot Nothing Then - Me.photoElement.Image = GetImageFromData(TryCast(rowView.Row("Photo"), Byte())) - Me.titleElement.Text = rowView.Row("Title").ToString() - Me.nameElement.Text = rowView.Row("FirstName").ToString() & " " & rowView.Row("LastName").ToString() - Me.addressElement.Text = "Address: " & rowView.Row("Address").ToString().Replace(System.Environment.NewLine, " ") - Me.phoneElement.Text = "Phone: " & rowView.Row("HomePhone").ToString() - End If - End Sub - Private Function GetImageFromData(imageData As Byte()) As Image - Const OleHeaderLength As Integer = 78 - Dim memoryStream As New MemoryStream() - If HasOleContainerHeader(imageData) Then - memoryStream.Write(imageData, OleHeaderLength, imageData.Length - OleHeaderLength) - Else - memoryStream.Write(imageData, 0, imageData.Length) - End If - Dim bitmap As New Bitmap(memoryStream) - Return bitmap.GetThumbnailImage(55, 65, Nothing, New IntPtr()) - End Function - Private Function HasOleContainerHeader(imageByteArray As Byte()) As Boolean - Const OleByte0 As Byte = 21 - Const OleByte1 As Byte = 28 - Return (imageByteArray(0) = OleByte0) AndAlso (imageByteArray(1) = OleByte1) - End Function -End Class - -```` - -{{endregion}} 3\. Subscribe to the __CreatingVisualListItem__ event before populating the __RadDropDownList__ with data and replace the default item with your custom one: #### Custom RadListVisualItem -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListCustomItems.cs region=ReplaceItem}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListCustomItems.vb region=ReplaceItem}} + + -````C# - -private void radDropDownList1_CreatingVisualListItem(object sender, Telerik.WinControls.UI.CreatingVisualListItemEventArgs args) -{ - args.VisualItem = new CustomVisualItem(); -} -```` -````VB.NET -Private Sub radDropDownList1_CreatingVisualListItem(sender As Object, args As Telerik.WinControls.UI.CreatingVisualListItemEventArgs) - args.VisualItem = New CustomVisualItem() -End Sub -```` - -{{endregion}} - 4\. The last thing we need to do is to set the RadDropDownList.__AutoSizeItems__ property to *false* and specify the __ItemHeight__: #### Custom RadListVisualItem -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListCustomItems.cs region=AdjustHeight}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListCustomItems.vb region=AdjustHeight}} - -````C# - -this.radDropDownList1.AutoSizeItems = false; -this.radDropDownList1.DropDownListElement.ListElement.ItemHeight = 90; - -```` -````VB.NET -Me.RadDropDownList1.AutoSizeItems = False -Me.RadDropDownList1.DropDownListElement.ListElement.ItemHeight = 90 - -```` - -{{endregion}} + + diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/customizing-appearance/accessing-and-customizing-elements.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/customizing-appearance/accessing-and-customizing-elements.md index 34b9bf535..f3b1d2e03 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/customizing-appearance/accessing-and-customizing-elements.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/customizing-appearance/accessing-and-customizing-elements.md @@ -32,21 +32,9 @@ You can customize the nested elements at run time as well: #### Customize elements -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownList1.cs region=CustomizeElements}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownList1.vb region=CustomizeElements}} + + -````C# - -this.radDropDownList1.DropDownListElement.ArrowButton.Fill.BackColor = Color.Aqua; -this.radDropDownList1.DropDownListElement.EditableElement.ForeColor = Color.Red; -```` -````VB.NET -Me.radDropDownList1.DropDownListElement.ArrowButton.Fill.BackColor = Color.Aqua -Me.radDropDownList1.DropDownListElement.EditableElement.ForeColor = Color.Red -```` - -{{endregion}} - In order to style the pop-up items it is suitable to use the [VisualItemFormatting]({%slug winforms/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/formatting-items%}) event. diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/customizing-appearance/formatting-items.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/customizing-appearance/formatting-items.md index 2d683bfe4..05621fc0a 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/customizing-appearance/formatting-items.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/customizing-appearance/formatting-items.md @@ -24,44 +24,10 @@ Items appearance in __RadDropDownList__ can be customized by making use of the _ #### Customize selected item appearance -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListCustomizeItems.cs region=CustomizeItems}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListCustomizeItems.vb region=CustomizeItems}} - -````C# -private void radDropDownList1_VisualListItemFormatting(object sender, VisualItemFormattingEventArgs args) -{ - if (args.VisualItem.Selected) - { - args.VisualItem.NumberOfColors = 1; - args.VisualItem.BackColor = Color.Yellow; - args.VisualItem.BorderColor = Color.Blue; - } - else - { - args.VisualItem.ResetValue(LightVisualElement.NumberOfColorsProperty, Telerik.WinControls.ValueResetFlags.Local); - args.VisualItem.ResetValue(LightVisualElement.BackColorProperty, Telerik.WinControls.ValueResetFlags.Local); - args.VisualItem.ResetValue(LightVisualElement.BorderColorProperty, Telerik.WinControls.ValueResetFlags.Local); - } -} - -```` -````VB.NET -Private Sub radDropDownList1_VisualListItemFormatting(sender As Object, args As VisualItemFormattingEventArgs) - If args.VisualItem.Selected Then - args.VisualItem.NumberOfColors = 1 - args.VisualItem.BackColor = Color.Yellow - args.VisualItem.BorderColor = Color.Blue - Else - args.VisualItem.ResetValue(LightVisualElement.NumberOfColorsProperty, Telerik.WinControls.ValueResetFlags.Local) - args.VisualItem.ResetValue(LightVisualElement.BackColorProperty, Telerik.WinControls.ValueResetFlags.Local) - args.VisualItem.ResetValue(LightVisualElement.BorderColorProperty, Telerik.WinControls.ValueResetFlags.Local) - End If -End Sub - -```` - -{{endregion}} - + + + + ## Customizing auto-complete drop-down appearance @@ -69,42 +35,18 @@ In order to customize the auto complete pop-up, you should subscribe to the __Vi #### Subscribe to the VisualItemFormatting event of the auto complete popup -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListCustomizeItems.cs region=Event}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListCustomizeItems.vb region=Event}} -````C# -radDropDownList1.DropDownListElement.AutoCompleteSuggest.DropDownList.ListElement.VisualItemFormatting += new VisualListItemFormattingEventHandler(ListElement_VisualItemFormatting); + + -```` -````VB.NET -AddHandler RadDropDownList1.DropDownListElement.AutoCompleteSuggest.DropDownList.ListElement.VisualItemFormatting, AddressOf ListElement_VisualItemFormatting -```` - -{{endregion}} The following code snippet, will demonstrate how to change the Font of all items in the auto complete drop down. #### Customize auto complete items appearance -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListCustomizeItems.cs region=CustomizeAutoCompleteDropDown}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListCustomizeItems.vb region=CustomizeAutoCompleteDropDown}} -````C# -Font myFont = new Font("Segoe UI", 14, FontStyle.Bold); -private void ListElement_VisualItemFormatting(object sender, VisualItemFormattingEventArgs args) -{ - args.VisualItem.Font = myFont; -} - -```` -````VB.NET -Private myFont As New Font("Segoe UI", 14, FontStyle.Bold) -Private Sub ListElement_VisualItemFormatting(sender As Object, args As VisualItemFormattingEventArgs) - args.VisualItem.Font = myFont -End Sub - -```` - -{{endregion}} + + + >note Here we do not reset the style because we do want the Font for all items to be changed not only on certain one. diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/dropdown-resizing.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/dropdown-resizing.md index 2e986931a..52f645671 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/dropdown-resizing.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/dropdown-resizing.md @@ -25,21 +25,13 @@ The __SizingMode__ enumeration has the following members: ![WinForms RadDropDownList SizingMode None](images/dropdown-and-listcontrol-dropdownlist-dropdown-resizing001.png) -#### SizingMode.None +#### SizingMode.None + + + -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListItemSizing.cs region=None}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListItemSizing.vb region=None}} -````C# -this.radDropDownList1.DropDownSizingMode = SizingMode.None; -```` -````VB.NET -Me.radDropDownList1.DropDownSizingMode = SizingMode.None - -```` - -{{endregion}} * __RightBottom__: allows sizing in horizontal direction. @@ -47,21 +39,13 @@ Me.radDropDownList1.DropDownSizingMode = SizingMode.None ![WinForms RadDropDownList SizingMode RightBottom](images/dropdown-and-listcontrol-dropdownlist-dropdown-resizing002.png) -#### SizingMode.RightBottom - -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListItemSizing.cs region=RightBottom}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListItemSizing.vb region=RightBottom}} +#### SizingMode.RightBottom + + + -````C# -this.radDropDownList1.DropDownSizingMode = SizingMode.RightBottom; -```` -````VB.NET -Me.radDropDownList1.DropDownSizingMode = SizingMode.RightBottom -```` - -{{endregion}} * __UpDown__: allows sizing in vertical direction. @@ -70,21 +54,13 @@ Me.radDropDownList1.DropDownSizingMode = SizingMode.RightBottom ![WinForms RadDropDownList SizingMode UpDown](images/dropdown-and-listcontrol-dropdownlist-dropdown-resizing003.png) -#### SizingMode.UpDown - -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListItemSizing.cs region=UpDown}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListItemSizing.vb region=UpDown}} +#### SizingMode.UpDown + + + -````C# -this.radDropDownList1.DropDownSizingMode = SizingMode.UpDown; -```` -````VB.NET -Me.radDropDownList1.DropDownSizingMode = SizingMode.UpDown -```` - -{{endregion}} * __UpDownAndRightBottom__: allows sizing in both directions. @@ -93,21 +69,13 @@ Me.radDropDownList1.DropDownSizingMode = SizingMode.UpDown ![WinForms RadDropDownList SizingMode UpDownAndRightBottom](images/dropdown-and-listcontrol-dropdownlist-dropdown-resizing004.png) -#### SizingMode.UpDownAndRightBottom - -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListItemSizing.cs region=UpDownAndRightBottom}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListItemSizing.vb region=UpDownAndRightBottom}} - -````C# -this.radDropDownList1.DropDownSizingMode = SizingMode.UpDownAndRightBottom; +#### SizingMode.UpDownAndRightBottom + + + -```` -````VB.NET -Me.radDropDownList1.DropDownSizingMode = SizingMode.UpDownAndRightBottom -```` -{{endregion}} ## Fixed size @@ -118,41 +86,25 @@ You can specify a fixed height or width of the drop-down by setting the __DropDo ![WinForms RadDropDownList DropDownHeight](images/dropdown-and-listcontrol-dropdownlist-dropdown-resizing005.png) -#### DropDownHeight - -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListItemSizing.cs region=DropDownHeight}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListItemSizing.vb region=DropDownHeight}} - -````C# -this.radDropDownList1.DropDownListElement.DropDownHeight = 400; +#### DropDownHeight + + + -```` -````VB.NET -Me.radDropDownList1.DropDownListElement.DropDownHeight = 400 -```` -{{endregion}} >caption Figure 6: DropDownWidth ![WinForms RadDropDownList DropDownWidth](images/dropdown-and-listcontrol-dropdownlist-dropdown-resizing007.png) -#### DropDownWidth +#### DropDownWidth + + + -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListItemSizing.cs region=DropDownWidth}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListItemSizing.vb region=DropDownWidth}} -````C# -this.radDropDownList1.DropDownListElement.DropDownWidth = 400; -```` -````VB.NET -Me.radDropDownList1.DropDownListElement.DropDownWidth = 400 - -```` - -{{endregion}} You can set the __DropDownMinSize__ property in order to specify the exact minimum height and width for the drop-down. @@ -161,73 +113,23 @@ You can set the __DropDownMinSize__ property in order to specify the exact minim ![WinForms RadDropDownList DropDownMinSize](images/dropdown-and-listcontrol-dropdownlist-dropdown-resizing006.png) -#### DropDownMinSize - -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListItemSizing.cs region=DropDownMinSize}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListItemSizing.vb region=DropDownMinSize}} - -````C# -this.radDropDownList1.DropDownMinSize = new Size(400, 400); - -```` -````VB.NET -Me.radDropDownList1.DropDownMinSize = New Size(400, 400) +#### DropDownMinSize + + + -```` -{{endregion}} ## Auto size The following example demonstrates a sample approach how to handle the RadDropDownList.__PopupOpening__ event and achieve auto size functionality for the pop up in __RadDropDownList__: -#### Auto size drop down - -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownList1.cs region=AutoSizeDropDown}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownList1.vb region=AutoSizeDropDown}} - -````C# -private void RadDropDownList1_PopupOpening(object sender, CancelEventArgs e) -{ - RadDropDownListElement list = sender as RadDropDownListElement; - float width = 0; - for (int x = 0; x < list.Items.Count(); x++) - { - width = Math.Max(width, TextRenderer.MeasureText(list.Items[x].Text, list.Font).Width); - } - if (list.Items.Count * (list.ItemHeight-1) > list.DropDownHeight) - { - width += list.ListElement.VScrollBar.Size.Width; - } - list.Popup.Width = (int)width; -} - -```` -````VB.NET -Private Sub RadDropDownList1_PopupOpening(sender As Object, e As CancelEventArgs) - Dim list As RadDropDownListElement = TryCast(sender, RadDropDownListElement) - Dim width As Single = 0 - For x As Integer = 0 To list.Items.Count() - 1 - width = Math.Max(width, TextRenderer.MeasureText(list.Items(x).Text, list.Font).Width) - Next - If list.Items.Count * (list.ItemHeight - 1) > list.DropDownHeight Then - width += list.ListElement.VScrollBar.Size.Width - End If - list.Popup.Width = CInt(width) -End Sub -'#End Region -'#Region "FilteringPredicate" -Private Function FilterItem(item As RadListDataItem) As Boolean - If item.Text.StartsWith("L") Then - Return True - End If - - Return False -End Function - -```` - -{{endregion}} +#### Auto size drop down + + + + + |Default pop up size|Auto sized popup| |----|----| @@ -241,21 +143,12 @@ By default, __RadDropDownList__ displays 6 items in the pop-up. In case you need ![WinForms RadDropDownList DefaultItemsCountInDropDown](images/dropdown-and-listcontrol-dropdownlist-dropdown-resizing008.png) -#### DefaultItemsCountInDropDown - -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListItemSizing.cs region=DefaultItemsCountInDropDown}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListItemSizing.vb region=DefaultItemsCountInDropDown}} - -````C# -this.radDropDownList1.DropDownListElement.DefaultItemsCountInDropDown = 3; - -```` -````VB.NET -Me.radDropDownList1.DropDownListElement.DefaultItemsCountInDropDown = 3 +#### DefaultItemsCountInDropDown + + + -```` -{{endregion}} diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/dropdownstyle.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/dropdownstyle.md index 869c07be0..ef6d461b3 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/dropdownstyle.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/dropdownstyle.md @@ -23,41 +23,19 @@ The __RadDropDownList.DropDownStyle__ property determines if the text area at th #### Setting DropDownStyle -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownList1.cs region=dropDownStyle}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownList1.vb region=dropDownStyle}} + + -````C# - -this.radDropDownList1.DropDownStyle = Telerik.WinControls.RadDropDownStyle.DropDown; -```` -````VB.NET -Me.radDropDownList1.DropDownStyle = Telerik.WinControls.RadDropDownStyle.DropDown - -```` - -{{endregion}} When __RadDropDownList__ is set to *RadDropDownStyle.DropDownList* one can control if an image will be displayed in the editor: #### Image in Editor -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownList1.cs region=ImageInEditor}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownList1.vb region=ImageInEditor}} - -````C# -this.radDropDownList1.DropDownStyle = Telerik.WinControls.RadDropDownStyle.DropDownList; -this.radDropDownList1.ShowImageInEditorArea = false; - -```` -````VB.NET -Me.radDropDownList1.DropDownStyle = Telerik.WinControls.RadDropDownStyle.DropDownList -Me.radDropDownList1.ShowImageInEditorArea = False + + -```` -{{endregion}} - ## User Defined Values @@ -69,83 +47,19 @@ This section describes how user defined values can be added to the data source p #### Initial Set Up -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListUserDefinedValues.cs region=InitialSetUp}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListUserDefinedValues.vb region=InitialSetUp}} - -````C# -private BindingList data; -public DropDownListUserDefinedValues() -{ - InitializeComponent(); - this.data = new BindingList(); - this.data.Add("Sofia"); - this.data.Add("New York"); - this.data.Add("Delhi"); - this.data.Add("Tokyo"); - this.data.Add("Berlin"); - this.data.Add("Moscow"); - this.data.Add("Beijing"); - this.data.Add("Bern"); - this.data.Add("Paris"); - this.data.Add("London"); - this.radDropDownList1.DataSource = this.data; - this.radDropDownList1.KeyUp += radDropDownList1_KeyUp; -} - -```` -````VB.NET -Private data As BindingList(Of String) -Public Sub New() - InitializeComponent() - Me.data = New BindingList(Of String)() - Me.data.Add("Sofia") - Me.data.Add("New York") - Me.data.Add("Delhi") - Me.data.Add("Tokyo") - Me.data.Add("Berlin") - Me.data.Add("Moscow") - Me.data.Add("Beijing") - Me.data.Add("Bern") - Me.data.Add("Paris") - Me.data.Add("London") - Me.RadDropDownList1.DataSource = Me.data - AddHandler Me.RadDropDownList1.KeyUp, AddressOf RadDropDownList1_KeyUp -End Sub - -```` - -{{endregion}} - + + + + Now we need to handle the event, perform the required checks and update our data source. #### Initial Set Up -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListUserDefinedValues.cs region=HandleEvent}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListUserDefinedValues.vb region=HandleEvent}} - -````C# -private void radDropDownList1_KeyUp(object sender, KeyEventArgs e) -{ - string result = this.radDropDownList1.DropDownListElement.Text; - if (e.KeyCode == Keys.Enter && !this.data.Contains(result)) - { - this.data.Insert(0, result); - } -} - -```` -````VB.NET -Private Sub RadDropDownList1_KeyUp(sender As Object, e As KeyEventArgs) - Dim result As String = Me.RadDropDownList1.DropDownListElement.Text - If e.KeyCode = Keys.Enter AndAlso Not Me.data.Contains(result) Then - Me.data.Insert(0, result) - End If -End Sub - -```` - -{{endregion}} + + + + # See Also * [Indicating Focus in RadDropDownList]({%slug dropdownlist-style-indicating-focus%}) diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/features/auto-complete.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/features/auto-complete.md index d5494457a..403ba6dac 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/features/auto-complete.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/features/auto-complete.md @@ -27,41 +27,22 @@ The RadDropDownList.__AutoCompleteMode__ property controls auto-complete behavio ![WinForms RadDropDownList AutoCompleteMode None](images/dropdown-and-listcontrol-dropdownlist-autocompleate001.png) -#### AutoCompleteMode.None - -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownList1.cs region=autoCNone}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownList1.vb region=autoCNone}} - -````C# - -this.radDropDownList1.AutoCompleteMode = AutoCompleteMode.None; +#### AutoCompleteMode.None + + + -```` -````VB.NET -Me.radDropDownList1.AutoCompleteMode = AutoCompleteMode.None -```` -{{endregion}} * __Suggest__: As the user types an entry into the text box, the drop-down part of the control is shown, and the displayed items are filtered according to the entered text. -#### AutoCompleteMode.Suggest - -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownList1.cs region=autoCSuggest}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownList1.vb region=autoCSuggest}} - -````C# - -this.radDropDownList1.AutoCompleteMode = AutoCompleteMode.Suggest; +#### AutoCompleteMode.Suggest + + + -```` -````VB.NET -Me.radDropDownList1.AutoCompleteMode = AutoCompleteMode.Suggest -```` - -{{endregion}} >caption Figure 2: AutoCompleteMode.Suggest @@ -73,41 +54,22 @@ Me.radDropDownList1.AutoCompleteMode = AutoCompleteMode.Suggest ![WinForms RadDropDownList AutoCompleteMode Append ](images/dropdown-and-listcontrol-dropdownlist-autocompleate003.png) -#### AutoCompleteMode.Append - -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownList1.cs region=autoCAppend}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownList1.vb region=autoCAppend}} +#### AutoCompleteMode.Append + + + -````C# - -this.radDropDownList1.AutoCompleteMode = AutoCompleteMode.Append; -```` -````VB.NET -Me.radDropDownList1.AutoCompleteMode = AutoCompleteMode.Append -```` - -{{endregion}} * __SuggestAppend__: Similar to the Append setting, but the drop-down list is shown and the suggested item is highlighted. -#### AutoCompleteMode.SuggestAppend +#### AutoCompleteMode.SuggestAppend + + + -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownList1.cs region=autoCSuggestAppend}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownList1.vb region=autoCSuggestAppend}} -````C# - -this.radDropDownList1.AutoCompleteMode = AutoCompleteMode.SuggestAppend; - -```` -````VB.NET -Me.radDropDownList1.AutoCompleteMode = AutoCompleteMode.SuggestAppend - -```` - -{{endregion}} >caption Figure 4: AutoCompleteMode.SuggestAppend @@ -122,21 +84,12 @@ __RadDropDownList__ internally uses auto-complete helpers to perform the auto-co * __SuggestMode__: determines whether the items are auto-completed considering whether the text starts with or contains the searched text. -#### SuggestMode.Contains - -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownList1.cs region=autoCsuggestMode}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownList1.vb region=autoCsuggestMode}} - -````C# -this.radDropDownList1.DropDownListElement.AutoCompleteSuggest.SuggestMode = Telerik.WinControls.UI.SuggestMode.Contains; +#### SuggestMode.Contains + + + -```` -````VB.NET -Me.radDropDownList1.DropDownListElement.AutoCompleteSuggest.SuggestMode = Telerik.WinControls.UI.SuggestMode.Contains -```` - -{{endregion}} >caption Figure 5: SuggestMode.Contains @@ -151,88 +104,24 @@ Me.radDropDownList1.DropDownListElement.AutoCompleteSuggest.SuggestMode = Teleri \* __AutoCompleteAppendHelper__: it is created when the __AutoCompleteMode__ property is set to AutoCompleteMode.*Append* or AutoCompleteMode.*SuggestAppend*. The __LimitToList__ property controls whether the user is blocked to enter invalid string in the editable part. -#### Limit the user to enter only valid values - -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownList1.cs region=autoClimitToList}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownList1.vb region=autoClimitToList}} - -````C# -this.radDropDownList1.DropDownListElement.AutoCompleteAppend.LimitToList = true; +#### Limit the user to enter only valid values + + + -```` -````VB.NET -Me.radDropDownList1.DropDownListElement.AutoCompleteAppend.LimitToList = True -```` -{{endregion}} ## Customize auto-complete helpers By default, the items displayed in the __AutoCompleteSuggestHelper__’s pop-up are sorted alphabetically. The following example demonstrates how to manipulate the sort order considering the item’s Text.__Length__ property: -#### Custom comparer - -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownList1.cs region=CustomComparer}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownList1.vb region=CustomComparer}} - -````C# - -public void ApplyComparer() -{ - this.radDropDownList1.AutoCompleteMode = AutoCompleteMode.Suggest; - this.radDropDownList1.DropDownListElement.AutoCompleteSuggest = new CustomAutoCompleteSuggestHelper(this.radDropDownList1.DropDownListElement); - this.radDropDownList1.DropDownListElement.AutoCompleteSuggest.SuggestMode = SuggestMode.Contains; -} - -public class CustomAutoCompleteSuggestHelper : AutoCompleteSuggestHelper -{ - public CustomAutoCompleteSuggestHelper(RadDropDownListElement owner) : base(owner) - { - } - - public override void ApplyFilterToDropDown(string filter) - { - base.ApplyFilterToDropDown(filter); - this.DropDownList.ListElement.DataLayer.DataView.Comparer = new CustomComparer(); - } -} - -public class CustomComparer: IComparer -{ - public int Compare(RadListDataItem x, RadListDataItem y) - { - return x.Text.Length.CompareTo(y.Text.Length); - } -} - -```` -````VB.NET -Public Sub ApplyComparer() - Me.radDropDownList1.AutoCompleteMode = AutoCompleteMode.Suggest - Me.radDropDownList1.DropDownListElement.AutoCompleteSuggest = New CustomAutoCompleteSuggestHelper(Me.radDropDownList1.DropDownListElement) - Me.radDropDownList1.DropDownListElement.AutoCompleteSuggest.SuggestMode = SuggestMode.Contains -End Sub -Public Class CustomAutoCompleteSuggestHelper - Inherits AutoCompleteSuggestHelper - Public Sub New(owner As RadDropDownListElement) - MyBase.New(owner) - End Sub - Public Overrides Sub ApplyFilterToDropDown(filter As String) - MyBase.ApplyFilterToDropDown(filter) - Me.DropDownList.ListElement.DataLayer.DataView.Comparer = New CustomComparer() - End Sub -End Class -Public Class CustomComparer - Implements IComparer(Of RadListDataItem) - Public Function [Compare](x As RadListDataItem, y As RadListDataItem) As Integer Implements IComparer(Of RadListDataItem).[Compare] - Return x.Text.Length.CompareTo(y.Text.Length) - End Function -End Class - -```` - -{{endregion}} +#### Custom comparer + + + + + >caption Figure 6: Custom comparer diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/features/filtering.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/features/filtering.md index 8cfabe62a..4fed25d28 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/features/filtering.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/features/filtering.md @@ -15,48 +15,17 @@ __RadDropDownList__ supports filtering of its items. In order to apply a filter, #### Filter -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownList1.cs region=Filter}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownList1.vb region=Filter}} -````C# - -this.radDropDownList1.Filter = FilterItem; + + -```` -````VB.NET -Me.radDropDownList1.Filter = AddressOf FilterItem - -```` - -{{endregion}} + #### Filtering predicate -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownList1.cs region=FilteringPredicate}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownList1.vb region=FilteringPredicate}} -````C# - -private bool FilterItem(RadListDataItem item) -{ - if (item.Text.StartsWith("L")) - { - return true; - } - return false; -} - -```` -````VB.NET -Private Function FilterItem(item As RadListDataItem) As Boolean - If item.Text.StartsWith("L") Then - Return True - End If - - Return False -End Function - -```` - -{{endregion}} + + + + If you apply the above filter to a __RadDropDownList__ that is bound to the Northwind.__Customers__ table you will obtain the following result: @@ -69,18 +38,10 @@ Another option to filter the items is to specify the __FilterExpression__ proper #### FilteringExpression -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownList1.cs region=FilteringExpression}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownList1.vb region=FilteringExpression}} -````C# -this.radDropDownList1.FilterExpression = "Country LIKE 'Argentina'"; - -```` -````VB.NET -Me.radDropDownList1.FilterExpression = "Country LIKE 'Argentina'" + + -```` - -{{endregion}} + >caption Figure 2: FilteringExpression diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/features/scrolling.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/features/scrolling.md index 6e389a23e..735b42620 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/features/scrolling.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/features/scrolling.md @@ -23,19 +23,10 @@ This feature ensures that the control is ready for modern touch-screen applicati #### Enabling Kinetic Scrolling -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListScrolling.cs region=KineticScrolling}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListScrolling.vb region=KineticScrolling}} + + -````C# -this.radDropDownList1.EnableKineticScrolling = true; - -```` -````VB.NET -Me.RadDropDownList1.EnableKineticScrolling = True - -```` - -{{endregion}} + ## Programmatically Scrolling @@ -53,19 +44,10 @@ __RadDropDownList__ provides out of the box functionality for programmatically s #### Scroll to Item -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListScrolling.cs region=ScrollToItem}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListScrolling.vb region=ScrollToItem}} - -````C# -this.radDropDownList1.DropDownListElement.ListElement.ScrollToItem(this.radDropDownList1.Items.Last()); - -```` -````VB.NET -Me.RadDropDownList1.DropDownListElement.ListElement.ScrollToItem(Me.RadDropDownList1.Items.Last()) + + -```` - -{{endregion}} + >caption Figure 3: Scroll to Active Item @@ -74,19 +56,10 @@ Me.RadDropDownList1.DropDownListElement.ListElement.ScrollToItem(Me.RadDropDownL #### Scroll to Active Item -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListScrolling.cs region=ScrollToActiveItem}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListScrolling.vb region=ScrollToActiveItem}} - -````C# -this.radDropDownList1.DropDownListElement.ListElement.ScrollToActiveItem(); + + -```` -````VB.NET -Me.RadDropDownList1.DropDownListElement.ListElement.ScrollToActiveItem() - -```` - -{{endregion}} + ## Scrolling Modes @@ -108,19 +81,10 @@ The __ListElement__ contained in the popup of __RadDropDownList__ supports three #### Discrete Scrolling -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListScrolling.cs region=DiscreteScrolling}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListScrolling.vb region=DiscreteScrolling}} + + -````C# -this.radDropDownList1.DropDownListElement.ListElement.ScrollMode = ItemScrollerScrollModes.Discrete; - -```` -````VB.NET -Me.RadDropDownList1.DropDownListElement.ListElement.ScrollMode = ItemScrollerScrollModes.Discrete - -```` - -{{endregion}} + >caption Figure 5: Smooth Scrolling @@ -128,19 +92,10 @@ Me.RadDropDownList1.DropDownListElement.ListElement.ScrollMode = ItemScrollerScr #### Smooth Scrolling -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListScrolling.cs region=SmoothScrolling}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListScrolling.vb region=SmoothScrolling}} - -````C# -this.radDropDownList1.DropDownListElement.ListElement.ScrollMode = ItemScrollerScrollModes.Smooth; - -```` -````VB.NET -Me.RadDropDownList1.DropDownListElement.ListElement.ScrollMode = ItemScrollerScrollModes.Smooth + + -```` - -{{endregion}} + >caption Figure 6: Deferred Scrolling @@ -148,19 +103,10 @@ Me.RadDropDownList1.DropDownListElement.ListElement.ScrollMode = ItemScrollerScr #### Deferred Scrolling -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListScrolling.cs region=DeferredScrolling}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListScrolling.vb region=DeferredScrolling}} - -````C# -this.radDropDownList1.DropDownListElement.ListElement.ScrollMode = ItemScrollerScrollModes.Deferred; + + -```` -````VB.NET -Me.RadDropDownList1.DropDownListElement.ListElement.ScrollMode = ItemScrollerScrollModes.Deferred - -```` - -{{endregion}} + diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/features/selection.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/features/selection.md index 10e3f5af5..84b5af885 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/features/selection.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/features/selection.md @@ -30,19 +30,10 @@ __RadDropDownList__ supports three types of selection modes: #### Setting a Selection Mode -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListSelection.cs region=MultiExtendedSelection}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListSelection.vb region=MultiExtendedSelection}} + + -````C# -this.radDropDownList1.DropDownListElement.SelectionMode = SelectionMode.MultiExtended; - -```` -````VB.NET -Me.radDropDownList1.DropDownListElement.SelectionMode = SelectionMode.MultiExtended - -```` - -{{endregion}} + ## Select Next Item @@ -54,19 +45,10 @@ __RadDropDownList__ can automatically select the next item when a double click i #### Next Item Selection -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListSelection.cs region=NextItemSelection}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListSelection.vb region=NextItemSelection}} - -````C# -this.radDropDownList1.SelectNextOnDoubleClick = true; - -```` -````VB.NET -Me.radDropDownList1.SelectNextOnDoubleClick = True - -```` + + -{{endregion}} + ## Selection Events @@ -103,21 +85,10 @@ Items can be programmatically selected either by their value or by their logical >note Setting these properties will result in raising the selection events. > -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListSelection.cs region=SetSelectedItem}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListSelection.vb region=SetSelectedItem}} - -````C# - -this.radDropDownList1.SelectedItem = this.radDropDownList1.Items[1]; - -```` -````VB.NET + + -Me.radDropDownList1.SelectedItem = Me.radDropDownList1.Items(1) - -```` - -{{endregion}} + diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/features/sorting.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/features/sorting.md index 6a4f28581..096e01cde 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/features/sorting.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/features/sorting.md @@ -29,20 +29,10 @@ __RadDropDownList__ supports sorting of its pop-up items. You can control how th #### SortStyle -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListSorting.cs region=SortStyle}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListSorting.vb region=SortStyle}} + + -````C# - -this.radDropDownList1.SortStyle = Telerik.WinControls.Enumerations.SortStyle.Descending; - -```` -````VB.NET -Me.RadDropDownList1.SortStyle = Telerik.WinControls.Enumerations.SortStyle.Descending - -```` - -{{endregion}} + ## Customizing sort order @@ -55,69 +45,10 @@ When the __SortStyle__ property is set to *Ascending* or *Descending* you can ma #### Custom comparer -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListSorting.cs region=CustomComparer}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListSorting.vb region=CustomComparer}} + + -````C# - -public DropDownListSorting() -{ - InitializeComponent(); - - for (int i = 0; i < 10; i++) - { - RadListDataItem item = new RadListDataItem(); - item.Value = 10 - i; - item.Text = i + ".Item"; - this.radDropDownList1.Items.Add(item); - } - this.radDropDownList1.SortStyle = Telerik.WinControls.Enumerations.SortStyle.Ascending; - this.radDropDownList1.ItemsSortComparer = new CustomComparer(); -} - -public class CustomComparer : IComparer -{ - public int Compare(RadListDataItem x, RadListDataItem y) - { - int xId = 0; - int yId = 0; - if (int.TryParse(x.Value.ToString(), out xId) && int.TryParse(y.Value.ToString(), out yId)) - { - return xId.CompareTo(yId); - } - return x.Value.ToString().CompareTo(y.Value.ToString()); - } -} - -```` -````VB.NET -Public Sub New() - InitializeComponent() - For i As Integer = 0 To 9 - Dim item As New RadListDataItem() - item.Value = 10 - i - item.Text = i & ".Item" - Me.RadDropDownList1.Items.Add(item) - Next - Me.RadDropDownList1.SortStyle = Telerik.WinControls.Enumerations.SortStyle.Ascending - Me.RadDropDownList1.ItemsSortComparer = New CustomComparer() -End Sub - -Public Class CustomComparer -Implements IComparer(Of RadListDataItem) - Public Function [Compare](x As RadListDataItem, y As RadListDataItem) As Integer Implements IComparer(Of RadListDataItem).[Compare] - Dim xId As Integer = 0 - Dim yId As Integer = 0 - If Integer.TryParse(x.Value.ToString(), xId) AndAlso Integer.TryParse(y.Value.ToString(), yId) Then - Return xId.CompareTo(yId) - End If - Return x.Value.ToString().CompareTo(y.Value.ToString()) - End Function -End Class - -```` - -{{endregion}} + diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/getting-started.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/getting-started.md index 9952d881e..a309cdd9d 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/getting-started.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/getting-started.md @@ -67,33 +67,11 @@ The following tutorial demonstrates how to add items and images to a __RadDropDo #### Handling the SelectedIndexChanged event -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownList1.cs region=handlingSelectedIndexChanged}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownList1.vb region=handlingSelectedIndexChanged}} - -````C# - -void radDropDownList1_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e) -{ - if (this.radDropDownList1.SelectedIndex > -1) - { - this.radLabelElement1.Text = this.radDropDownList1.SelectedItem.Text; - this.radImageButtonElement1.Image = this.radDropDownList1.SelectedItem.Image; - } -} - -```` -````VB.NET -Private Sub radDropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.Data.PositionChangedEventArgs) - If Me.radDropDownList1.SelectedIndex > -1 Then - radLabelElement1.Text = Me.radDropDownList1.SelectedItem.Text - Me.radImageButtonElement1.Image = Me.radDropDownList1.SelectedItem.Image - End If -End Sub - -```` - -{{endregion}} - + + + + + This is it! Now the change in the selection of the __RadDropDownList__ instance will be reflected on __RadStatusStrip__. ## Telerik UI for WinForms Learning Resources diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/item-sizing.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/item-sizing.md index 790914ac3..d173b183d 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/item-sizing.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/item-sizing.md @@ -19,24 +19,13 @@ By default, all items in __RadDropDownList__ have equal height, *18px*. You can ![WinForms RadDropDownList ItemHeight](images/dropdown-and-listcontrol-dropdownlist-item-sizing001.png) -#### ItemHeight +#### ItemHeight + + + -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListItemSizing.cs region=ItemHeight}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListItemSizing.vb region=ItemHeight}} -````C# - -this.radDropDownList1.DropDownListElement.ListElement.Font = new Font("Arial", 18f); -this.radDropDownList1.ListElement.ItemHeight = 40; -```` -````VB.NET -Me.RadDropDownList1.DropDownListElement.ListElement.Font = New Font("Arial", 18.0F) -Me.RadDropDownList1.ListElement.ItemHeight = 40 - -```` - -{{endregion}} ## AutoSizeItems @@ -47,23 +36,12 @@ The RadDropDownList.__AutoSizeItems__ property indicates whether items will be s ![WinForms RadDropDownList AutoSizeItems](images/dropdown-and-listcontrol-dropdownlist-item-sizing002.png) -#### AutoSizeItems - -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListItemSizing.cs region=AutoSizeItems}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListItemSizing.vb region=AutoSizeItems}} +#### AutoSizeItems + + + -````C# -this.radDropDownList1.DropDownListElement.ListElement.Font = new Font("Arial", 8f); -this.radDropDownList1.AutoSizeItems = true; -```` -````VB.NET -Me.RadDropDownList1.DropDownListElement.ListElement.Font = New Font("Arial", 8.0F) -Me.RadDropDownList1.AutoSizeItems = True - -```` - -{{endregion}} If this property is set to *false* the user can set the __Height__ property of each individual __RadListDataItem__ in the __Items__ collection in order to override the automatic sizing. @@ -72,46 +50,13 @@ If this property is set to *false* the user can set the __Height__ property of e ![WinForms RadDropDownList Custom Height for Each Item](images/dropdown-and-listcontrol-dropdownlist-item-sizing003.gif) -#### Height - -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListItemSizing.cs region=Height}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListItemSizing.vb region=Height}} - -````C# - -this.radDropDownList1.AutoSizeItems = false; -StringBuilder sb; -for (int i = 0; i < 10; i++) -{ - RadListDataItem item = new RadListDataItem(); - sb = new StringBuilder(); - for (int j = 0; j < i + 1; j++) - { - sb.AppendLine("Item" + i + " Line" + j); - } - item.Text = sb.ToString(); - item.Height = this.radDropDownList1.ListElement.ItemHeight * (i + 1); - this.radDropDownList1.Items.Add(item); -} - -```` -````VB.NET -Me.RadDropDownList1.AutoSizeItems = False -Dim sb As StringBuilder -For i As Integer = 0 To 9 - Dim item As New RadListDataItem() - sb = New StringBuilder() - For j As Integer = 0 To i - sb.AppendLine("Item" & i & " Line" & j) - Next - item.Text = sb.ToString() - item.Height = Me.RadDropDownList1.ListElement.ItemHeight * (i + 1) - Me.RadDropDownList1.Items.Add(item) -Next - -```` - -{{endregion}} +#### Height + + + + + + ## Sizing auto-complete pop-up items @@ -121,23 +66,12 @@ When the RadDropDownList.__AutoCompleteMode__ property is set to *Suggest* or *S ![WinForms RadDropDownList AutoCompleteSuggest DropDownList ListElement ItemHeight](images/dropdown-and-listcontrol-dropdownlist-item-sizing004.png) -#### Auto-complete items height - -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListItemSizing.cs region=AutoCompleteItemsHeight}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListItemSizing.vb region=AutoCompleteItemsHeight}} - -````C# -this.radDropDownList1.AutoCompleteMode = AutoCompleteMode.SuggestAppend; -this.radDropDownList1.DropDownListElement.AutoCompleteSuggest.DropDownList.ListElement.ItemHeight = 40; - -```` -````VB.NET -Me.RadDropDownList1.AutoCompleteMode = AutoCompleteMode.SuggestAppend -Me.RadDropDownList1.DropDownListElement.AutoCompleteSuggest.DropDownList.ListElement.ItemHeight = 40 +#### Auto-complete items height + + + -```` -{{endregion}} diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/populating-with-data/adding-items-programmatically.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/populating-with-data/adding-items-programmatically.md index b6995b7dd..4d17ed9a7 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/populating-with-data/adding-items-programmatically.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/populating-with-data/adding-items-programmatically.md @@ -29,37 +29,10 @@ You can use one of the following item types: #### Add items programmatically -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownList1.cs region=AddItemsProgrammatically}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownList1.vb region=AddItemsProgrammatically}} + + -````C# - -DescriptionTextListDataItem descriptionItem = new DescriptionTextListDataItem(); -descriptionItem.Text = "Chicken wings"; -descriptionItem.Image = Properties.Resources.chicken_wings; -descriptionItem.DescriptionText = "some description"; -this.radDropDownList1.Items.Add(descriptionItem); - -RadListDataItem dataItem = new RadListDataItem(); -dataItem.Text = "Chicken toast"; -dataItem.Image = Properties.Resources.chicken_toast; -this.radDropDownList1.Items.Add(dataItem); - -```` -````VB.NET -Dim descriptionItem As New DescriptionTextListDataItem() -descriptionItem.Text = "Chicken wings" -descriptionItem.Image = My.Resources.chicken_wings -descriptionItem.DescriptionText = "some description" -Me.radDropDownList1.Items.Add(descriptionItem) -Dim dataItem As New RadListDataItem() -dataItem.Text = "Chicken toast" -dataItem.Image = My.Resources.chicken_toast -Me.radDropDownList1.Items.Add(dataItem) - -```` - -{{endregion}} + # See Also diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/populating-with-data/data-binding.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/populating-with-data/data-binding.md index 081606706..0b70b7bd2 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/populating-with-data/data-binding.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/populating-with-data/data-binding.md @@ -51,75 +51,10 @@ You can bind __RadDropDownList__ programmatically as well. The following code sn #### Data binding at run time -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownList1.cs region=Binding}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownList1.vb region=Binding}} - -````C# - -public class Item -{ - public int Id { get; set; } - - public string Description { get; set; } - - public Item(int id, string description) - { - this.Id = id; - this.Description = description; - } -} - -public void Bind() -{ - List items = new List(); - for (int i = 0; i < 10; i++) - { - items.Add(new Item(i,"Data" + i)); - } - this.radDropDownList1.DataSource = items; - this.radDropDownList1.DisplayMember = "Description"; - this.radDropDownList1.ValueMember = "Id"; -} - -```` -````VB.NET -Public Class Item - Public Property Id() As Integer - Get - Return m_Id - End Get - Set(value As Integer) - m_Id = value - End Set - End Property - Private m_Id As Integer - Public Property Description() As String - Get - Return m_Description - End Get - Set(value As String) - m_Description = value - End Set - End Property - Private m_Description As String - Public Sub New(id As Integer, description As String) - Me.Id = id - Me.Description = description - End Sub -End Class -Public Sub Bind() - Dim items As New List(Of Item)() - For i As Integer = 0 To 9 - items.Add(New Item(i, "Data" + i)) - Next - Me.radDropDownList1.DataSource = items - Me.radDropDownList1.DisplayMember = "Description" - Me.radDropDownList1.ValueMember = "Id" -End Sub - -```` - -{{endregion}} + + + + >caption Figure: 4 RadDropDownList bound at Run time diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/right-to-left-support.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/right-to-left-support.md index fb5587165..8db1c0dc5 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/right-to-left-support.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/dropdownlist/right-to-left-support.md @@ -27,19 +27,10 @@ __RadDropDownList__ fully supports right-to-left (RTL) language locales. You can #### Assigning RightToLeft -{{source=..\SamplesCS\DropDownListControl\DropDownList\DropDownListRightToLeft.cs region=SetRightToLeft}} -{{source=..\SamplesVB\DropDownListControl\DropDownList\DropDownListRightToLeft.vb region=SetRightToLeft}} + + -````C# -this.radDropDownList1.RightToLeft = RightToLeft.Yes; - -```` -````VB.NET -Me.radDropDownList1.RightToLeft = RightToLeft.Yes - -```` - -{{endregion}} + diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/fontdropdownlist/add-custom-fonts.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/fontdropdownlist/add-custom-fonts.md index 056f80f1e..95d637d38 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/fontdropdownlist/add-custom-fonts.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/fontdropdownlist/add-custom-fonts.md @@ -14,20 +14,18 @@ Since R2 2019 SP1 (version 2019.2.618) __RadFontDropDownList__ supports adding c #### Add Custom Font to RadFontDropDownList -{{source=..\SamplesCS\Editors\FontDropDownList.cs region=AddCustomFont}} -{{source=..\SamplesVB\Editors\FontDropDownList.vb region=AddCustomFont}} - + + -{{endregion}} + The font can be easily removed as well. #### Remove Custom Font from RadFontDropDownList -{{source=..\SamplesCS\Editors\FontDropDownList.cs region=RemoveCustomFont}} -{{source=..\SamplesVB\Editors\FontDropDownList.vb region=RemoveCustomFont}} - + + -{{endregion}} + diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/fontdropdownlist/customizing-appearance/accessing-and-customizing-elements.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/fontdropdownlist/customizing-appearance/accessing-and-customizing-elements.md index 7366153fa..604c6a850 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/fontdropdownlist/customizing-appearance/accessing-and-customizing-elements.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/fontdropdownlist/customizing-appearance/accessing-and-customizing-elements.md @@ -33,30 +33,9 @@ You can customize the nested elements at run time as well: #### Customize elements -{{source=..\SamplesCS\Editors\FontDropDownList.cs region=CustomizeElements}} -{{source=..\SamplesVB\Editors\FontDropDownList.vb region=CustomizeElements}} - -````C# -this.radFontDropDownList1.BackColor = Color.Yellow; -this.radFontDropDownList1.PopupEditorElement.ArrowButtonElement.Fill.BackColor = Color.Aqua; -this.radFontDropDownList1.PopupEditorElement.ArrowButtonElement.Fill.GradientStyle = GradientStyles.Solid; -this.radFontDropDownList1.EditableAreaElement.ForeColor = Color.Red; -this.radFontDropDownList1.EditableAreaElement.DrawBorder = true; -this.radFontDropDownList1.EditableAreaElement.BorderColor = Color.Red; -this.radFontDropDownList1.EditableAreaElement.BorderGradientStyle = GradientStyles.Solid; - -```` -````VB.NET -Me.RadFontDropDownList1.BackColor = Color.Yellow -Me.RadFontDropDownList1.PopupEditorElement.ArrowButtonElement.Fill.BackColor = Color.Aqua -Me.RadFontDropDownList1.PopupEditorElement.ArrowButtonElement.Fill.GradientStyle = GradientStyles.Solid -Me.RadFontDropDownList1.EditableAreaElement.ForeColor = Color.Red -Me.RadFontDropDownList1.EditableAreaElement.DrawBorder = True -Me.RadFontDropDownList1.EditableAreaElement.BorderColor = Color.Red -Me.RadFontDropDownList1.EditableAreaElement.BorderGradientStyle = GradientStyles.Solid - -```` - -{{endregion}} + + + + In order to style the pop-up items it is suitable to use the [Formatting Items]({%slug winforms/editors/fontdropdownlist/accessing-and-customizing-elements/formatting-items%}) event. diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/fontdropdownlist/customizing-appearance/formatting-items.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/fontdropdownlist/customizing-appearance/formatting-items.md index 7ec42a33b..f3672009e 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/fontdropdownlist/customizing-appearance/formatting-items.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/fontdropdownlist/customizing-appearance/formatting-items.md @@ -18,59 +18,7 @@ You can access the hosted **RadListView** control by the RadFontDropDownList.**F #### Formatting the cell elements -{{source=..\SamplesCS\Editors\FontDropDownList.cs region=ItemsFormatting}} -{{source=..\SamplesVB\Editors\FontDropDownList.vb region=ItemsFormatting}} + + -````C# -private void FontListView_CellFormatting(object sender, Telerik.WinControls.UI.ListViewCellFormattingEventArgs e) -{ - DetailListViewDataCellElement cell = e.CellElement as DetailListViewDataCellElement; - if (cell == null) - { - return; - } - if (e.CellElement.Data.Name == "Preview" && e.CellElement.Text == "Aharoni") - { - e.CellElement.BackColor = Color.Yellow; - e.CellElement.ForeColor = Color.Red; - e.CellElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid; - } - else if (cell.Row.Selected) - { - e.CellElement.BackColor = Color.Aqua; - e.CellElement.ForeColor = Color.Black; - e.CellElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid; - } - else - { - e.CellElement.ResetValue(LightVisualElement.BackColorProperty, Telerik.WinControls.ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.ForeColorProperty, Telerik.WinControls.ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.GradientStyleProperty, Telerik.WinControls.ValueResetFlags.Local); - } -} - -```` -````VB.NET -Private Sub FontListView_CellFormatting(sender As Object, e As UI.ListViewCellFormattingEventArgs) - Dim cell As DetailListViewDataCellElement = TryCast(e.CellElement, DetailListViewDataCellElement) - If cell Is Nothing Then - Return - End If - If e.CellElement.Data.Name = "Preview" AndAlso e.CellElement.Text = "Aharoni" Then - e.CellElement.BackColor = Color.Yellow - e.CellElement.ForeColor = Color.Red - e.CellElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid - ElseIf cell.Row.Selected Then - e.CellElement.BackColor = Color.Aqua - e.CellElement.ForeColor = Color.Black - e.CellElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid - Else - e.CellElement.ResetValue(LightVisualElement.BackColorProperty, Telerik.WinControls.ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.ForeColorProperty, Telerik.WinControls.ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.GradientStyleProperty, Telerik.WinControls.ValueResetFlags.Local) - End If -End Sub - -```` - -{{endregion}} + diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/fontdropdownlist/getting-started.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/fontdropdownlist/getting-started.md index c9ab68c47..d42cc77a4 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/fontdropdownlist/getting-started.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/fontdropdownlist/getting-started.md @@ -46,53 +46,10 @@ The following tutorial demonstrates how to add a **RadFontDropDownList** and how 5. Subscribe to the **SelectedFontChanged** event and use the following code snippet: -{{source=..\SamplesCS\Editors\FontDropDownList.cs region=ChangeFont}} -{{source=..\SamplesVB\Editors\FontDropDownList.vb region=ChangeFont}} - -````C# -private void radFontDropDownList1_SelectedFontChanged(object sender, EventArgs e) -{ - FontFamily ff = new FontFamily(this.radFontDropDownList1.SelectedFont); - if (ff.IsStyleAvailable(FontStyle.Regular)) - { - Font font = new Font(ff.Name, 10, FontStyle.Regular); - this.radLabel1.Font = font; - } - else - { - foreach (FontStyle style in Enum.GetValues(typeof(FontStyle))) - { - if (ff.IsStyleAvailable(style)) - { - Font font = new Font(ff.Name, 10, style); - this.radLabel1.Font = font; - break; - } - } - } -} - -```` -````VB.NET -Private Sub radFontDropDownList1_SelectedFontChanged(ByVal sender As Object, ByVal e As EventArgs) - Dim ff As FontFamily = New FontFamily(Me.RadFontDropDownList1.SelectedFont) - If ff.IsStyleAvailable(FontStyle.Regular) Then - Dim font As Font = New Font(ff.Name, 10, FontStyle.Regular) - Me.radLabel1.Font = font - Else - For Each style As FontStyle In [Enum].GetValues(GetType(FontStyle)) - If ff.IsStyleAvailable(style) Then - Dim font As Font = New Font(ff.Name, 10, style) - Me.radLabel1.Font = font - Exit For - End If - Next - End If -End Sub - -```` - -{{endregion}} + + + + ![WinForms RadFontDropDownList SelectedFont](images/fontdropdownlist-getting-started003.gif) diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/fontdropdownlist/localization.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/fontdropdownlist/localization.md index b760aee4b..e20a42380 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/fontdropdownlist/localization.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/fontdropdownlist/localization.md @@ -14,21 +14,7 @@ RadFontDropDownList has only two string that can be localized and these are the #### Localizing RadFontDropDownList -{{source=..\SamplesCS\Editors\FontDropDownList.cs region=Localize}} -{{source=..\SamplesVB\Editors\FontDropDownList.vb region=Localize}} -````C# -var element = radFontDropDownList1.PopupEditorElement as RadFontPopupEditorElement; -element.AllFontsItemText = "All Fonts"; -element.RecentlyUsedItemText = "Recently Used Fonts"; + + -```` -````VB.NET -Dim element = TryCast(RadFontDropDownList1.PopupEditorElement, RadFontPopupEditorElement) -element.AllFontsItemText = "All Fonts" -element.RecentlyUsedItemText = "Recently Used Fonts" - -```` - - - -{{endregion}} + diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/fontdropdownlist/update-recently-used-fonts.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/fontdropdownlist/update-recently-used-fonts.md index 2d77a0735..90b08fea9 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/fontdropdownlist/update-recently-used-fonts.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/fontdropdownlist/update-recently-used-fonts.md @@ -17,9 +17,8 @@ To update the fonts yu can use the __UpdateRecentlyUsedFonts__ method and pass t #### Update the recently used fonts -{{source=..\SamplesCS\Editors\FontDropDownList.cs region=UpdateRecentlyUsed}} -{{source=..\SamplesVB\Editors\FontDropDownList.vb region=UpdateRecentlyUsed}} - + + -{{endregion}} + diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/customizing-appearance/formatting-items.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/customizing-appearance/formatting-items.md index 62f87f27c..67e035b15 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/customizing-appearance/formatting-items.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/customizing-appearance/formatting-items.md @@ -20,143 +20,19 @@ Items appearance in __RadListControl__ can be customized by making use of the __ #### Formatting items -{{source=..\SamplesCS\DropDownListControl\ListControl\ListControl1.cs region=VisualItemFormatting}} -{{source=..\SamplesVB\DropDownListControl\ListControl\ListControl1.vb region=VisualItemFormatting}} - -````C# -Font font = new Font("Consolas", 14, FontStyle.Bold); -private void radListControl1_VisualItemFormatting(object sender, VisualItemFormattingEventArgs args) -{ - if (args.VisualItem.Selected) - { - args.VisualItem.NumberOfColors = 1; - args.VisualItem.BackColor = Color.LightGreen; - args.VisualItem.ForeColor = Color.Red; - args.VisualItem.BorderColor = Color.Blue; - args.VisualItem.Font = font; - } - else - { - args.VisualItem.ResetValue(LightVisualElement.NumberOfColorsProperty, Telerik.WinControls.ValueResetFlags.Local); - args.VisualItem.ResetValue(LightVisualElement.BackColorProperty, Telerik.WinControls.ValueResetFlags.Local); - args.VisualItem.ResetValue(LightVisualElement.ForeColorProperty, Telerik.WinControls.ValueResetFlags.Local); - args.VisualItem.ResetValue(LightVisualElement.BorderColorProperty, Telerik.WinControls.ValueResetFlags.Local); - args.VisualItem.ResetValue(LightVisualElement.FontProperty, Telerik.WinControls.ValueResetFlags.Local); - } -} - -```` -````VB.NET -Private font As New Font("Consolas", 14, FontStyle.Bold) -Private Sub radListControl1_VisualItemFormatting(sender As Object, args As VisualItemFormattingEventArgs) - If args.VisualItem.Selected Then - args.VisualItem.NumberOfColors = 1 - args.VisualItem.BackColor = Color.LightGreen - args.VisualItem.ForeColor = Color.Red - args.VisualItem.BorderColor = Color.Blue - args.VisualItem.Font = font - Else - args.VisualItem.ResetValue(LightVisualElement.NumberOfColorsProperty, Telerik.WinControls.ValueResetFlags.Local) - args.VisualItem.ResetValue(LightVisualElement.BackColorProperty, Telerik.WinControls.ValueResetFlags.Local) - args.VisualItem.ResetValue(LightVisualElement.ForeColorProperty, Telerik.WinControls.ValueResetFlags.Local) - args.VisualItem.ResetValue(LightVisualElement.BorderColorProperty, Telerik.WinControls.ValueResetFlags.Local) - args.VisualItem.ResetValue(LightVisualElement.FontProperty, Telerik.WinControls.ValueResetFlags.Local) - End If -End Sub -'#End Region -Class -gion customDataItem -ic Class CustomDataItem -rits RadListDataItem -Public Shared ReadOnly AvailableProperty As RadProperty = RadProperty.Register("Available", GetType(Boolean), GetType(CustomDataItem), New RadElementPropertyMetadata(False)) -Public Property Available() As Boolean - Get - Return CBool(Me.GetValue(CustomDataItem.AvailableProperty)) - End Get - Set(ByVal value As Boolean) - Me.SetValue(CustomDataItem.AvailableProperty, value) - End Set -End Property -Class - -```` - -{{endregion}} + + + + ## Alternating Item Color __RadListControl__ supports alternating item color which can be easily enabled by just setting a couple of properties: -{{source=..\SamplesCS\DropDownListControl\ListControl\ListControl1.cs region=alternating}} -{{source=..\SamplesVB\DropDownListControl\ListControl\ListControl1.vb region=alternating}} - -````C# -radListControl1.EnableAlternatingItemColor = true; -radListControl1.ListElement.AlternatingItemColor = Color.Red; - -```` -````VB.NET -radListControl1.EnableAlternatingItemColor = True -radListControl1.ListElement.AlternatingItemColor = Color.Red -'#End Region -'#Region "AddItemsProgrammatically" -Dim descriptionItem As New DescriptionTextListDataItem() -descriptionItem.Text = "Chicken wings" -descriptionItem.Image = My.Resources.chicken_wings -descriptionItem.DescriptionText = "some description" -Me.radListControl1.Items.Add(descriptionItem) -Dim dataItem As New RadListDataItem() -dataItem.Text = "Chicken toast" -dataItem.Image = My.Resources.chicken_toast -Me.radListControl1.Items.Add(dataItem) -'#End Region -'#Region "expression" -Me.radListControl1.FilterExpression = "Country LIKE 'Argentina'" -'#End Region -End Sub -'#Region "Binding" -Public Class Item -Public Property Id() As Integer - Get - Return m_Id - End Get - Set(value As Integer) - m_Id = value - End Set -End Property -Private m_Id As Integer -Public Property Description() As String - Get - Return m_Description - End Get - Set(value As String) - m_Description = value - End Set -End Property -Private m_Description As String -Public Sub New(id As Integer, description As String) - Me.Id = id - Me.Description = description -End Sub -End Class -Public Sub Bind() -Dim items As New List(Of Item)() -For i As Integer = 0 To 9 - items.Add(New Item(i, "Data" + i)) -Next -radListControl1.DataSource = items -radListControl1.DisplayMember = "Description" -radListControl1.ValueMember = "Id" -End Sub -'#End Region -'#region creatingVisualListItem -Private Sub radListControl1_CreatingVisualListItem(ByVal sender As Object, ByVal args As CreatingVisualListItemEventArgs) -args.VisualItem = New CustomVisualItem() -End Sub - -```` - -{{endregion}} + + + + >caption Figure 2: AlternatingItemColor diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/customizing-items-(visual-appearance).md b/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/customizing-items-(visual-appearance).md index a051e9806..d329a1715 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/customizing-items-(visual-appearance).md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/customizing-items-(visual-appearance).md @@ -25,131 +25,38 @@ The aim of this article is to demonstrate how you can achieve to look shown belo #### Handling the ItemDataBound event -{{source=..\SamplesCS\DropDownListControl\ListControl\CustomizingItems.cs region=itemDataBound}} -{{source=..\SamplesVB\DropDownListControl\ListControl\CustomizingItems.vb region=itemDataBound}} - -````C# -void radListControl1_ItemDataBound(object sender, ListItemDataBoundEventArgs args) -{ - DataRowView view = (DataRowView)args.NewItem.DataBoundItem; - args.NewItem.Text = "" + view["TitleOfCourtesy"] + "" + - " " + view["FirstName"] + - " " + view["LastName"] + - "
" + view["Title"]; - NwindDataSet.EmployeesRow row = view.Row as NwindDataSet.EmployeesRow; - args.NewItem.Image = GetImageFromData(row.Photo); -} - -```` -````VB.NET -Private Sub radListControl1_ItemDataBound(ByVal sender As Object, ByVal args As Telerik.WinControls.UI.ListItemDataBoundEventArgs) - Dim view As DataRowView = CType(args.NewItem.DataBoundItem, DataRowView) - args.NewItem.Text = "" & view("TitleOfCourtesy") & "" & " " & view("FirstName") & " " & view("LastName") & "
" & view("Title") - Dim row As NwindDataSet.EmployeesRow = TryCast(view.Row, NwindDataSet.EmployeesRow) - args.NewItem.Image = GetImageFromData(row.Photo) -End Sub - -```` - -{{endregion}} + + + + #### Image helper method -{{source=..\SamplesCS\DropDownListControl\ListControl\CustomizingItems.cs region=getImageData}} -{{source=..\SamplesVB\DropDownListControl\ListControl\CustomizingItems.vb region=getImageData}} - -````C# -private bool HasOleContainerHeader(byte[] imageByteArray) -{ - const byte OleByte0 = 21; - const byte OleByte1 = 28; - return (imageByteArray[0] == OleByte0) && (imageByteArray[1] == OleByte1); -} -private Image GetImageFromData(byte[] imageData) -{ - const int OleHeaderLength = 78; - MemoryStream memoryStream = new MemoryStream(); - if (HasOleContainerHeader(imageData)) - { - memoryStream.Write(imageData, OleHeaderLength, imageData.Length - OleHeaderLength); - } - else - { - memoryStream.Write(imageData, 0, imageData.Length); - } - Bitmap bitmap = new Bitmap(memoryStream); - return bitmap.GetThumbnailImage(55, 65, null, new IntPtr()); -} - -```` -````VB.NET -Private Function HasOleContainerHeader(ByVal imageByteArray As Byte()) As Boolean - Const OleByte0 As Byte = 21 - Const OleByte1 As Byte = 28 - Return (imageByteArray(0) = OleByte0) AndAlso (imageByteArray(1) = OleByte1) -End Function -Private Function GetImageFromData(ByVal imageData As Byte()) As Image - Const OleHeaderLength As Integer = 78 - Dim memoryStream As MemoryStream = New MemoryStream() - If HasOleContainerHeader(imageData) Then - memoryStream.Write(imageData, OleHeaderLength, imageData.Length - OleHeaderLength) - Else - memoryStream.Write(imageData, 0, imageData.Length) - End If - Dim bitmap As Bitmap = New Bitmap(memoryStream) - Return bitmap.GetThumbnailImage(55, 65, Nothing, New IntPtr()) -End Function - -```` - -{{endregion}} + + + + 2\. Since the *< br >* tag will split the __Text__ value in different lines, it is essential to set the __AutoSizeItems__ of RadListControl to *true*: #### Setting AutoSizeItems -{{source=..\SamplesCS\DropDownListControl\ListControl\CustomizingItems.cs region=autoSizeItems}} -{{source=..\SamplesVB\DropDownListControl\ListControl\CustomizingItems.vb region=autoSizeItems}} + + -````C# -this.radListControl1.AutoSizeItems = true; -```` -````VB.NET -Me.radListControl1.AutoSizeItems = True -```` - -{{endregion}} 3\. Should you want to have apply some padding to the visual items, you should do it on CreatingVisualListItem event: #### Applying Padding to the visual list items -{{source=..\SamplesCS\DropDownListControl\ListControl\CustomizingItems.cs region=creatingVisualListItem}} -{{source=..\SamplesVB\DropDownListControl\ListControl\CustomizingItems.vb region=creatingVisualListItem}} - -````C# -void radListControl1_CreatingVisualListItem(object sender, CreatingVisualListItemEventArgs args) -{ - RadListVisualItem visualItem = new RadListVisualItem(); - visualItem.Padding = new Padding(5, 5, 0, 5); - args.VisualItem = visualItem; -} - -```` -````VB.NET -Private Sub radListControl1_CreatingVisualListItem(ByVal sender As Object, ByVal args As Telerik.WinControls.UI.CreatingVisualListItemEventArgs) - Dim visualItem As RadListVisualItem = New RadListVisualItem() - visualItem.Padding = New Padding(5, 5, 0, 5) - args.VisualItem = visualItem -End Sub + + -```` -{{endregion}} # See Also diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/data-representation.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/data-representation.md index daef005ce..0e4f34076 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/data-representation.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/data-representation.md @@ -19,67 +19,21 @@ __RadListDataItem__ initially has the most basic visual properties required whic #### RadListDataItem -{{source=..\SamplesCS\DropDownListControl\ListControl\ListControl1.cs region=customDataItem}} -{{source=..\SamplesVB\DropDownListControl\ListControl\ListControl1.vb region=customDataItem}} - -````C# -public class CustomDataItem : RadListDataItem -{ - public static readonly RadProperty AvailableProperty = RadProperty.Register("Available", typeof(bool), typeof(CustomDataItem), new RadElementPropertyMetadata(false)); - public bool Available - { - get - { - return (bool)this.GetValue(CustomDataItem.AvailableProperty); - } - set - { - this.SetValue(CustomDataItem.AvailableProperty, value); - } - } -} - -```` -````VB.NET -Public Class CustomDataItem -Inherits RadListDataItem - Public Shared ReadOnly AvailableProperty As RadProperty = RadProperty.Register("Available", GetType(Boolean), GetType(CustomDataItem), New RadElementPropertyMetadata(False)) - Public Property Available() As Boolean - Get - Return CBool(Me.GetValue(CustomDataItem.AvailableProperty)) - End Get - Set(ByVal value As Boolean) - Me.SetValue(CustomDataItem.AvailableProperty, value) - End Set - End Property -End Class - -```` - -{{endregion}} + + + + + Once we have the custom data item with the additional information, we can convince __RadListControl__ to use our class when creating logical items by using the __ItemDataBinding__ event. Consider the following code snippet: #### using custom data items -{{source=..\SamplesCS\DropDownListControl\ListControl\ListControl1.cs region=itemDataBinding}} -{{source=..\SamplesVB\DropDownListControl\ListControl\ListControl1.vb region=itemDataBinding}} - -````C# -void radListControl1_ItemDataBinding(object sender, ListItemDataBindingEventArgs args) -{ - args.NewItem = new CustomDataItem(); -} + + -```` -````VB.NET -Private Sub radListControl1_ItemDataBinding(ByVal sender As Object, ByVal args As ListItemDataBindingEventArgs) - args.NewItem = New CustomDataItem() -End Sub -```` -{{endregion}} With this in place we have modified __RadListControl__ to use our type of logical objects which will provide the ability to display custom visual elements, a checkbox for example, in the visual representation of the data items. The next topic describes how to extend the visual items and how to provide the visual synchronization of the additional properties defined for the data item. diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/drag-and-drop/drag-and-drop-in-bound-mode.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/drag-and-drop/drag-and-drop-in-bound-mode.md index 8aee27a82..64df269e2 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/drag-and-drop/drag-and-drop-in-bound-mode.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/drag-and-drop/drag-and-drop-in-bound-mode.md @@ -26,263 +26,49 @@ The drag and drop functionality is achieved with the help of four events: __Mous #### MouseDown and MouseMove -{{source=..\SamplesCS\DropDownListControl\ListControl\DragAndDrop.cs region=MouseDownMove}} -{{source=..\SamplesVB\DropDownListControl\ListControl\DragAndDrop.vb region=MouseDownMove}} - -````C# - -private Point mouseDownPosition; - -void radListControl1_MouseDown(object sender, MouseEventArgs e) -{ - this.mouseDownPosition = e.Location; -} - -void radListControl1_MouseMove(object sender, MouseEventArgs e) -{ - if (e.Button != MouseButtons.Left) - { - return; - } - - RadListControl listControl = sender as RadListControl; - RadListVisualItem draggedItem = listControl.ElementTree.GetElementAtPoint(this.mouseDownPosition) as RadListVisualItem; - if (draggedItem != null&& IsRealDrag(mouseDownPosition, e.Location)) - { - (sender as RadListControl).DoDragDrop(draggedItem.Data, DragDropEffects.Move); - } -} -private static bool IsRealDrag(Point mousePosition, Point initialMousePosition) -{ - return (Math.Abs(mousePosition.X - initialMousePosition.X) >= SystemInformation.DragSize.Width) || - (Math.Abs(mousePosition.Y - initialMousePosition.Y) >= SystemInformation.DragSize.Height); -} - -```` -````VB.NET -Private mouseDownPosition As Point -Private Sub radListControl1_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) - Me.mouseDownPosition = e.Location -End Sub -Private Sub radListControl1_MouseMove(ByVal sender As Object, ByVal e As MouseEventArgs) - If e.Button <> MouseButtons.Left Then - Return - End If - Dim listControl As RadListControl = TryCast(sender, RadListControl) - Dim draggedItem As RadListVisualItem = TryCast(listControl.ElementTree.GetElementAtPoint(Me.mouseDownPosition), RadListVisualItem) - If draggedItem IsNot Nothing AndAlso IsRealDrag(mouseDownPosition, e.Location) Then - TryCast(sender, RadListControl).DoDragDrop(draggedItem.Data, DragDropEffects.Move) - End If -End Sub -Private Shared Function IsRealDrag(ByVal mousePosition As Point, ByVal initialMousePosition As Point) As Boolean - Return (Math.Abs(mousePosition.X - initialMousePosition.X) >= SystemInformation.DragSize.Width) OrElse (Math.Abs(mousePosition.Y - initialMousePosition.Y) >= SystemInformation.DragSize.Height) -End Function - -```` - -{{endregion}} + + + + + 2\. Handling the __DragEnter__ event: This event will fire when the mouse is hovering over a control that allows dropping. Here you can use it to disable the drop operation within the same control. #### The DragEnter event handler -{{source=..\SamplesCS\DropDownListControl\ListControl\DragAndDrop.cs region=DragEnter}} -{{source=..\SamplesVB\DropDownListControl\ListControl\DragAndDrop.vb region=DragEnter}} - -````C# -void radListControl1_DragEnter(object sender, DragEventArgs e) -{ - RadListControl listControl = sender as RadListControl; - RadListDataItem draggedItem = e.Data.GetData(typeof(RadListDataItem)) as RadListDataItem; - - if (draggedItem.OwnerControl == listControl) - { - e.Effect = DragDropEffects.None; - } - else - { - e.Effect = DragDropEffects.Move; - } -} - -```` -````VB.NET -Private Sub radListControl1_DragEnter(ByVal sender As Object, ByVal e As DragEventArgs) - Dim listControl As RadListControl = TryCast(sender, RadListControl) - Dim draggedItem As RadListDataItem = TryCast(e.Data.GetData(GetType(RadListDataItem)), RadListDataItem) - If draggedItem.OwnerControl Is listControl Then - e.Effect = DragDropEffects.None - Else - e.Effect = DragDropEffects.Move - End If -End Sub - -```` - -{{endregion}} + + + + + 3\. Handling the __DragDrop__ event: This is the most important event. In it you have access to both, the dragged element and the control where the item is dropped. This allows you to handle the drop operation appropriately according to your specific requirements. In this case, both controls are bound, and this allows you to just add/remove items from/to their data source (the changes will be immediately reflected by the controls). #### The DragDrop event handler -{{source=..\SamplesCS\DropDownListControl\ListControl\DragAndDrop.cs region=DragDrop}} -{{source=..\SamplesVB\DropDownListControl\ListControl\DragAndDrop.vb region=DragDrop}} - -````C# -void radListControl2_DragDrop(object sender, DragEventArgs e) -{ - RadListControl listControl = sender as RadListControl; - RadListDataItem draggedItem = e.Data.GetData(typeof(RadListDataItem)) as RadListDataItem; - - MyCustomObject dragedData = draggedItem.DataBoundItem as MyCustomObject; - - if (myList1.Contains(dragedData)) - { - myList1.Remove(dragedData); - myList.Add(dragedData); - } - else - { - myList.Remove(dragedData); - myList1.Add(dragedData); - } -} - -```` -````VB.NET -Private Sub radListControl2_DragDrop(ByVal sender As Object, ByVal e As DragEventArgs) - Dim listControl As RadListControl = TryCast(sender, RadListControl) - Dim draggedItem As RadListDataItem = TryCast(e.Data.GetData(GetType(RadListDataItem)), RadListDataItem) - Dim dragedData As CustomObject = TryCast(draggedItem.DataBoundItem, CustomObject) - If myList1.Contains(dragedData) Then - myList1.Remove(dragedData) - myList.Add(dragedData) - Else - myList.Remove(dragedData) - myList1.Add(dragedData) - End If -End Sub - -```` - -{{endregion}} + + + + + Additionally, you should enable the __AllowDrop__ property for both controls. With this example you can move from the first __RadListControl__ to the second and vice versa. Along with this, the following snippet shows how you can bind the controls and subscribe to the events. The same events are used for both controls. #### Controls initialization -{{source=..\SamplesCS\DropDownListControl\ListControl\DragAndDrop.cs region=Initialize}} -{{source=..\SamplesVB\DropDownListControl\ListControl\DragAndDrop.vb region=Initialize}} - -````C# - -BindingList myList; -BindingList myList1; - -public DragAndDrop() -{ - InitializeComponent(); - - myList = new BindingList(); - myList1 = new BindingList(); - - myList.Add(new MyCustomObject(1, "Outdoor")); - myList.Add(new MyCustomObject(8, "Hardware")); - myList.Add(new MyCustomObject(3, "Tools")); - myList1.Add(new MyCustomObject(6, "Books")); - myList1.Add(new MyCustomObject(2, "Appliances")); - - radListControl1.DataSource = myList; - radListControl1.DisplayMember = "Category"; - radListControl1.ValueMember = "ID"; - radListControl1.AllowDrop = true; - - radListControl2.DataSource = myList1; - radListControl2.DisplayMember = "Category"; - radListControl2.ValueMember = "ID"; - radListControl2.AllowDrop = true; - - radListControl1.MouseDown += radListControl1_MouseDown; - radListControl1.MouseMove += radListControl1_MouseMove; - radListControl1.DragEnter += radListControl1_DragEnter; - radListControl1.DragDrop += radListControl2_DragDrop; - - radListControl2.MouseDown += radListControl1_MouseDown; - radListControl2.MouseMove += radListControl1_MouseMove; - radListControl2.DragEnter += radListControl1_DragEnter; - radListControl2.DragDrop += radListControl2_DragDrop; -} - -```` -````VB.NET -Private myList As BindingList(Of CustomObject) -Private myList1 As BindingList(Of CustomObject) -Public Sub New() - InitializeComponent() - myList = New BindingList(Of CustomObject)() - myList1 = New BindingList(Of CustomObject)() - myList.Add(New CustomObject(1, "Outdoor")) - myList.Add(New CustomObject(8, "Hardware")) - myList.Add(New CustomObject(3, "Tools")) - myList1.Add(New CustomObject(6, "Books")) - myList1.Add(New CustomObject(2, "Appliances")) - radListControl1.DataSource = myList - radListControl1.DisplayMember = "Category" - radListControl1.ValueMember = "ID" - radListControl1.AllowDrop = True - radListControl2.DataSource = myList1 - radListControl2.DisplayMember = "Category" - radListControl2.ValueMember = "ID" - radListControl2.AllowDrop = True - AddHandler radListControl1.MouseDown, AddressOf radListControl1_MouseDown - AddHandler radListControl1.MouseMove, AddressOf radListControl1_MouseMove - AddHandler radListControl1.DragEnter, AddressOf radListControl1_DragEnter - AddHandler radListControl1.DragDrop, AddressOf radListControl2_DragDrop - AddHandler radListControl2.MouseDown, AddressOf radListControl1_MouseDown - AddHandler radListControl2.MouseMove, AddressOf radListControl1_MouseMove - AddHandler radListControl2.DragEnter, AddressOf radListControl1_DragEnter - AddHandler radListControl2.DragDrop, AddressOf radListControl2_DragDrop -End Sub - -```` - -{{endregion}} + + + + To complete the example you can use the following sample class. #### Sample business object for the example -{{source=..\SamplesCS\DropDownListControl\ListControl\DragAndDrop.cs region=CustomObject}} -{{source=..\SamplesVB\DropDownListControl\ListControl\DragAndDrop.vb region=CustomObject}} - -````C# - -public class MyCustomObject -{ - public int ID { get; set; } - - public string Category { get; set; } - public MyCustomObject(int iD, string category) - { - this.ID = iD; - this.Category = category; - } -} - -```` -````VB.NET -Public Class CustomObject - Public Property ID() As Integer - Public Property Category() As String - Public Sub New(ByVal iD As Integer, ByVal category As String) - Me.ID = iD - Me.Category = category - End Sub -End Class - -```` - -{{endregion}} + + + + diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/drag-and-drop/listcontroldragdropservice.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/drag-and-drop/listcontroldragdropservice.md index 0bfe44c85..3cfd67908 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/drag-and-drop/listcontroldragdropservice.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/drag-and-drop/listcontroldragdropservice.md @@ -32,225 +32,25 @@ The following steps demonstrates how to populate two **RadListControls** with it 1\. Consider that you have two **RadListControls** which are bound to a **BindingList** of custom *Item* objects. -{{source=..\SamplesCS\DropDownListControl\ListControl\ListControlBoundDragDrop.cs region=BoundListControl}} -{{source=..\SamplesVB\DropDownListControl\ListControl\ListControlBoundDragDrop.vb region=BoundListControl}} + + -````C# - -public ListControlBoundDragDrop() -{ - InitializeComponent(); - BindingList items = new BindingList(); - BindingList items2 = new BindingList(); - for (int i = 0; i < 20; i++) - { - items.Add(new Item(i, "Item.1." + i)); - items2.Add(new Item(i, "Item.2." + i)); - } - - this.radListControl1.DataSource = items; - this.radListControl1.DisplayMember = "Name"; - this.radListControl1.ValueMember = "Id"; - - this.radListControl2.DataSource = items2; - this.radListControl2.DisplayMember = "Name"; - this.radListControl2.ValueMember = "Id"; -} - -public class Item -{ - public int Id { get; set; } - - public string Name { get; set; } - - public Item(int id, string name) - { - this.Id = id; - this.Name = name; - } -} -```` -````VB.NET -Public Sub New() - InitializeComponent() - Dim items As New BindingList(Of Item)() - Dim items2 As New BindingList(Of Item)() - For i As Integer = 0 To 19 - items.Add(New Item(i, "Item.1." & i)) - items2.Add(New Item(i, "Item.2." & i)) - Next - Me.RadListControl1.DataSource = items - Me.RadListControl1.DisplayMember = "Name" - Me.RadListControl1.ValueMember = "Id" - Me.RadListControl2.DataSource = items2 - Me.RadListControl2.DisplayMember = "Name" - Me.RadListControl2.ValueMember = "Id" -End Sub -Public Class Item - Public Property Id() As Integer - Get - Return m_Id - End Get - Set(value As Integer) - m_Id = value - End Set - End Property - Private m_Id As Integer - Public Property Name() As String - Get - Return m_Name - End Get - Set(value As String) - m_Name = value - End Set - End Property - Private m_Name As String - Public Sub New(id As Integer, name As String) - Me.Id = id - Me.Name = name - End Sub -End Class - -```` - -{{endregion}} 2\. Set the **AllowDragDrop** property for both of the **RadListControls** to *true*. -{{source=..\SamplesCS\DropDownListControl\ListControl\ListControlBoundDragDrop.cs region=EnableDragDrop}} -{{source=..\SamplesVB\DropDownListControl\ListControl\ListControlBoundDragDrop.vb region=EnableDragDrop}} - -````C# - -this.radListControl1.AllowDragDrop = true; -this.radListControl2.AllowDragDrop = true; + + -```` -````VB.NET -Me.RadListControl1.AllowDragDrop = True -Me.RadListControl2.AllowDragDrop = True -```` - -{{endregion}} 3\. Handle the service's events in order to achieve the desired drag and drop behavior. In the **PreviewDragStart** event of **ListControlDragDropService** you can store the dragged data item. Set the PreviewDragStartEventArgs.**CanStart** property to *true* in order to indicate the drag operation is allowed. The **PreviewDragOver** event allows you to control on what targets the item being dragged can be dropped on. The **PreviewDragDrop** event allows you to get a handle on all the aspects of the drag and drop operation, the source (drag) **RadListControl**, the destination (target) control, as well as the item being dragged. This is where we will initiate the actual physical move of the item(s) from **RadListControl** to the target control. -{{source=..\SamplesCS\DropDownListControl\ListControl\ListControlBoundDragDrop.cs region=ListControlDragDrop}} -{{source=..\SamplesVB\DropDownListControl\ListControl\ListControlBoundDragDrop.vb region=ListControlDragDrop}} - -````C# - -private void ListControlBoundDragDrop_Shown(object sender, EventArgs e) -{ - this.radListControl1.ListElement.DragDropService.PreviewDragStart += DragDropService_PreviewDragStart; - this.radListControl1.ListElement.DragDropService.PreviewDragOver += DragDropService_PreviewDragOver; - this.radListControl1.ListElement.DragDropService.PreviewDragDrop += DragDropService_PreviewDragDrop; -} - -RadListDataItem draggedItem = null; - -private void DragDropService_PreviewDragStart(object sender, Telerik.WinControls.PreviewDragStartEventArgs e) -{ - RadListVisualItem draggedVisualitem = e.DragInstance as RadListVisualItem; - if (draggedVisualitem != null) - { - draggedItem = draggedVisualitem.Data; - e.CanStart = true; - } - else - { - e.CanStart = false; - } -} - -private void DragDropService_PreviewDragOver(object sender, Telerik.WinControls.RadDragOverEventArgs e) -{ - RadListVisualItem targetVisualItem = e.HitTarget as RadListVisualItem; - RadListElement targetListElement = e.HitTarget as RadListElement; - if (targetVisualItem != null || targetListElement != null) - { - e.CanDrop = true; - } - else - { - e.CanDrop = false; - } -} - -private void DragDropService_PreviewDragDrop(object sender, Telerik.WinControls.RadDropEventArgs e) -{ - RadListVisualItem targetVisualItem = e.HitTarget as RadListVisualItem; - RadListElement targetListElement = e.HitTarget as RadListElement; - if (targetVisualItem != null) - { - targetListElement = targetVisualItem.Data.Owner as RadListElement; - } - if (targetListElement == null) - { - return; - } - e.Handled = true; - BindingList targetSourceItems = targetListElement.DataSource as BindingList; - BindingList draggtedSourceItems = this.draggedItem.Owner.DataSource as BindingList; - int draggedItemIndex = draggtedSourceItems.IndexOf(this.draggedItem.DataBoundItem as Item); - int targetItemIndex = targetVisualItem == null ? targetSourceItems.Count-1 : targetSourceItems.IndexOf(targetVisualItem.Data.DataBoundItem as Item); - - Item item = this.draggedItem.DataBoundItem as Item; - targetSourceItems.RemoveAt(draggedItemIndex); - targetSourceItems.Insert(targetItemIndex, new Item(item.Id, item.Name)); -} - -```` -````VB.NET -Private Sub ListControlBoundDragDrop_Shown(sender As Object, e As EventArgs) Handles Me.Shown - AddHandler Me.RadListControl1.ListElement.DragDropService.PreviewDragStart, AddressOf DragDropService_PreviewDragStart - AddHandler Me.RadListControl1.ListElement.DragDropService.PreviewDragOver, AddressOf DragDropService_PreviewDragOver - AddHandler Me.RadListControl1.ListElement.DragDropService.PreviewDragDrop, AddressOf DragDropService_PreviewDragDrop -End Sub -Private draggedItem As RadListDataItem = Nothing -Private Sub DragDropService_PreviewDragStart(sender As Object, e As Telerik.WinControls.PreviewDragStartEventArgs) - Dim draggedVisualitem As RadListVisualItem = TryCast(e.DragInstance, RadListVisualItem) - If draggedVisualitem IsNot Nothing Then - draggedItem = draggedVisualitem.Data - e.CanStart = True - Else - e.CanStart = False - End If -End Sub -Private Sub DragDropService_PreviewDragOver(sender As Object, e As Telerik.WinControls.RadDragOverEventArgs) - Dim targetVisualItem As RadListVisualItem = TryCast(e.HitTarget, RadListVisualItem) - Dim targetListElement As RadListElement = TryCast(e.HitTarget, RadListElement) - If targetVisualItem IsNot Nothing OrElse targetListElement IsNot Nothing Then - e.CanDrop = True - Else - e.CanDrop = False - End If -End Sub -Private Sub DragDropService_PreviewDragDrop(sender As Object, e As Telerik.WinControls.RadDropEventArgs) - Dim targetVisualItem As RadListVisualItem = TryCast(e.HitTarget, RadListVisualItem) - Dim targetListElement As RadListElement = TryCast(e.HitTarget, RadListElement) - If targetVisualItem IsNot Nothing Then - targetListElement = TryCast(targetVisualItem.Data.Owner, RadListElement) - End If - If targetListElement Is Nothing Then - Return - End If - e.Handled = True - Dim targetSourceItems As BindingList(Of Item) = TryCast(targetListElement.DataSource, BindingList(Of Item)) - Dim draggtedSourceItems As BindingList(Of Item) = TryCast(Me.draggedItem.Owner.DataSource, BindingList(Of Item)) - Dim draggedItemIndex As Integer = draggtedSourceItems.IndexOf(TryCast(Me.draggedItem.DataBoundItem, Item)) - Dim targetItemIndex As Integer = If(targetVisualItem Is Nothing, targetSourceItems.Count - 1, targetSourceItems.IndexOf(TryCast(targetVisualItem.Data.DataBoundItem, Item))) - Dim item As Item = TryCast(Me.draggedItem.DataBoundItem, Item) - targetSourceItems.RemoveAt(draggedItemIndex) - targetSourceItems.Insert(targetItemIndex, New Item(item.Id, item.Name)) -End Sub + + -```` -{{endregion}} >caption Figure 2: Drag and Drop in Bound Mode diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/features.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/features.md index 6ca80d178..d1d6de6a4 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/features.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/features.md @@ -21,19 +21,11 @@ Sorting in RadListControl is controlled via the __SortStyle__ property. It suppo #### Sorting -{{source=..\SamplesCS\DropDownListControl\ListControl\ListControl1.cs region=sorting}} -{{source=..\SamplesVB\DropDownListControl\ListControl\ListControl1.vb region=sorting}} + + -````C# -radListControl1.SortStyle = Telerik.WinControls.Enumerations.SortStyle.Ascending; -```` -````VB.NET -radListControl1.SortStyle = Telerik.WinControls.Enumerations.SortStyle.Ascending -```` - -{{endregion}} Changing the sort style may cause the SelectedIndexChanged event to fire if the position of the previously selected item has changed after the sort operation. @@ -44,41 +36,19 @@ RadListControl can filter which items are currently visible by using the __Filte #### Filtering method body -{{source=..\SamplesCS\DropDownListControl\ListControl\ListControl1.cs region=filteringMethod}} -{{source=..\SamplesVB\DropDownListControl\ListControl\ListControl1.vb region=filteringMethod}} - -````C# -private bool FilterMethod(RadListDataItem itemToFilter) -{ - return itemToFilter.Text.EndsWith("SomeString"); -} + + -```` -````VB.NET -Private Function FilterMethod(ByVal itemToFilter As RadListDataItem) As Boolean - Return itemToFilter.Text.EndsWith("SomeString") -End Function -```` - -{{endregion}} #### Setting the Filter property -{{source=..\SamplesCS\DropDownListControl\ListControl\ListControl1.cs region=filtering}} -{{source=..\SamplesVB\DropDownListControl\ListControl\ListControl1.vb region=filtering}} - -````C# -radListControl1.Filter = FilterMethod; + + -```` -````VB.NET -radListControl1.Filter = AddressOf FilterMethod -```` -{{endregion}} Setting the Filter property will start a filtering operation which will call the FilterMethod for every item in RadListControl to determine if the item should be visible. After filtering RadListControl will contain the same number of items as before or less. Setting the Filter property to null resets any filtering and all items will be visible. Filtering may change the SelectedIndex property depending on whether the previously selected item is still visible. @@ -89,37 +59,21 @@ RadListControl can search for an item with the FindString() and FindStringExact( #### Searching -{{source=..\SamplesCS\DropDownListControl\ListControl\ListControl1.cs region=searching}} -{{source=..\SamplesVB\DropDownListControl\ListControl\ListControl1.vb region=searching}} + + -````C# -int index = radListControl1.FindString("someitem"); -```` -````VB.NET -Dim index As Integer = radListControl1.FindString("someitem") -```` - -{{endregion}} This method call will return the index of the first item with "someitem" as its text or -1 if no item has this been found. The second overload is called like this: #### Searching -{{source=..\SamplesCS\DropDownListControl\ListControl\ListControl1.cs region=index}} -{{source=..\SamplesVB\DropDownListControl\ListControl\ListControl1.vb region=index}} - -````C# -int index = radListControl1.FindString("someitem", 5); + + -```` -````VB.NET -Dim index As Integer = radListControl1.FindString("someitem", 5) -```` -{{endregion}} The second argument specifies the index after which the search will start. This means that in this case, the search will start at index 6. An important fact is that FindString() uses a wrapping linear search algorithm. If the item is not found when the end of the items collection is reached, it wraps and continues the search from the beginning until the start index is reached. Users can also search for an item with the keyboard. Setting the KeyboardSearchEnabled property to true will cause RadListControl to process keystrokes, build a string by appending each keystroke and then use the built string to find an item. Every keystroke initiates a new search starting at the last found item. This feature is also known as incremental search. The KeyboardSearchResetInterval property can be set in order to define how long the user must wait after pressing a key in order for the search to start from the beginning and for the built string to be destroyed. @@ -146,76 +100,10 @@ RadListControl provides three scrolling modes that can be used depending on user __RadListControl__ supports alternating item color which can be easily enabled by just setting a couple of properties: -{{source=..\SamplesCS\DropDownListControl\ListControl\ListControl1.cs region=alternating}} -{{source=..\SamplesVB\DropDownListControl\ListControl\ListControl1.vb region=alternating}} - -````C# -radListControl1.EnableAlternatingItemColor = true; -radListControl1.ListElement.AlternatingItemColor = Color.Red; - -```` -````VB.NET -radListControl1.EnableAlternatingItemColor = True -radListControl1.ListElement.AlternatingItemColor = Color.Red -'#End Region -'#Region "AddItemsProgrammatically" -Dim descriptionItem As New DescriptionTextListDataItem() -descriptionItem.Text = "Chicken wings" -descriptionItem.Image = My.Resources.chicken_wings -descriptionItem.DescriptionText = "some description" -Me.radListControl1.Items.Add(descriptionItem) -Dim dataItem As New RadListDataItem() -dataItem.Text = "Chicken toast" -dataItem.Image = My.Resources.chicken_toast -Me.radListControl1.Items.Add(dataItem) -'#End Region -'#Region "expression" -Me.radListControl1.FilterExpression = "Country LIKE 'Argentina'" -'#End Region -End Sub -'#Region "Binding" -Public Class Item -Public Property Id() As Integer - Get - Return m_Id - End Get - Set(value As Integer) - m_Id = value - End Set -End Property -Private m_Id As Integer -Public Property Description() As String - Get - Return m_Description - End Get - Set(value As String) - m_Description = value - End Set -End Property -Private m_Description As String -Public Sub New(id As Integer, description As String) - Me.Id = id - Me.Description = description -End Sub -End Class -Public Sub Bind() -Dim items As New List(Of Item)() -For i As Integer = 0 To 9 - items.Add(New Item(i, "Data" + i)) -Next -radListControl1.DataSource = items -radListControl1.DisplayMember = "Description" -radListControl1.ValueMember = "Id" -End Sub -'#End Region -'#region creatingVisualListItem -Private Sub radListControl1_CreatingVisualListItem(ByVal sender As Object, ByVal args As CreatingVisualListItemEventArgs) -args.VisualItem = New CustomVisualItem() -End Sub - -```` - -{{endregion}} + + + + diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/features/filtering.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/features/filtering.md index 120bfeb9d..4a541cb3a 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/features/filtering.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/features/filtering.md @@ -18,41 +18,19 @@ The __Filter__ property accepts a predicate method that can be used for arbitrar #### Filtering method body -{{source=..\SamplesCS\DropDownListControl\ListControl\ListControl1.cs region=filteringMethod}} -{{source=..\SamplesVB\DropDownListControl\ListControl\ListControl1.vb region=filteringMethod}} + + -````C# -private bool FilterMethod(RadListDataItem itemToFilter) -{ - return itemToFilter.Text.EndsWith("SomeString"); -} -```` -````VB.NET -Private Function FilterMethod(ByVal itemToFilter As RadListDataItem) As Boolean - Return itemToFilter.Text.EndsWith("SomeString") -End Function - -```` - -{{endregion}} #### Setting the Filter property -{{source=..\SamplesCS\DropDownListControl\ListControl\ListControl1.cs region=filtering}} -{{source=..\SamplesVB\DropDownListControl\ListControl\ListControl1.vb region=filtering}} - -````C# -radListControl1.Filter = FilterMethod; + + -```` -````VB.NET -radListControl1.Filter = AddressOf FilterMethod -```` -{{endregion}} Setting the __Filter__ property will start a filtering operation which will call the __FilterMethod__ for every item in __RadListControl__ to determine if the item should be visible or not. After filtering, __RadListControl__ will contain the same number of items as before or less. Setting the __Filter__ property to *null* resets any filtering and all items will be visible. @@ -64,59 +42,9 @@ Another option to filter the items is to specify the FilterExpression property. #### Setting the FilterExpression property -{{source=..\SamplesCS\DropDownListControl\ListControl\ListControl1.cs region=expression}} -{{source=..\SamplesVB\DropDownListControl\ListControl\ListControl1.vb region=expression}} - -````C# -this.radListControl1.FilterExpression = "Country LIKE 'Argentina'"; - -```` -````VB.NET -Me.radListControl1.FilterExpression = "Country LIKE 'Argentina'" -'#End Region -End Sub -'#Region "Binding" -Public Class Item -Public Property Id() As Integer - Get - Return m_Id - End Get - Set(value As Integer) - m_Id = value - End Set -End Property -Private m_Id As Integer -Public Property Description() As String - Get - Return m_Description - End Get - Set(value As String) - m_Description = value - End Set -End Property -Private m_Description As String -Public Sub New(id As Integer, description As String) - Me.Id = id - Me.Description = description -End Sub -End Class -Public Sub Bind() -Dim items As New List(Of Item)() -For i As Integer = 0 To 9 - items.Add(New Item(i, "Data" + i)) -Next -radListControl1.DataSource = items -radListControl1.DisplayMember = "Description" -radListControl1.ValueMember = "Id" -End Sub -'#End Region -'#region creatingVisualListItem -Private Sub radListControl1_CreatingVisualListItem(ByVal sender As Object, ByVal args As CreatingVisualListItemEventArgs) -args.VisualItem = New CustomVisualItem() -End Sub - -```` - -{{endregion}} + + + + >note The __RadListControl.FilterExpression__ property value resembles a SQL expression. diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/features/searching.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/features/searching.md index b8f04bbb7..3343091e2 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/features/searching.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/features/searching.md @@ -14,36 +14,20 @@ __RadListControl__ can search for an item with the __FindString__ and __FindStri #### Searching an item -{{source=..\SamplesCS\DropDownListControl\ListControl\ListControl1.cs region=searching}} -{{source=..\SamplesVB\DropDownListControl\ListControl\ListControl1.vb region=searching}} + + -````C# -int index = radListControl1.FindString("someitem"); -```` -````VB.NET -Dim index As Integer = radListControl1.FindString("someitem") -```` - -{{endregion}} This method call will return the index of the first item with *"someitem"* as its text or *-1* if no item has been found. The second overload is called like this: #### Searching after a given index -{{source=..\SamplesCS\DropDownListControl\ListControl\ListControl1.cs region=index}} -{{source=..\SamplesVB\DropDownListControl\ListControl\ListControl1.vb region=index}} - -````C# -int index = radListControl1.FindString("someitem", 5); + + -```` -````VB.NET -Dim index As Integer = radListControl1.FindString("someitem", 5) -```` -{{endregion}} The second argument specifies the index after which the search will start. This means that in this case, the search will start at index 6. An important fact is that __FindString__ method uses a wrapping linear search algorithm. If the item is not found when the end of the items collection is reached, it wraps and continues the search from the beginning until the start index is reached. Users can also search for an item with the keyboard. Setting the __KeyboardSearchEnabled__ property to *true* will cause __RadListControl__ to process keystrokes, build a string by appending each keystroke and then use the built string to find an item. Every keystroke initiates a new search starting at the last found item. This feature is also known as incremental search. The __KeyboardSearchResetInterval__ property can be set in order to define how long the user must wait after pressing a key in order for the search to start from the beginning and for the built string to be destroyed. diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/features/selection.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/features/selection.md index 82366b93d..a06970c48 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/features/selection.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/features/selection.md @@ -20,42 +20,22 @@ The selection in __RadListControl__ is determined by the __SelectionMode__ prope >note There is **ActiveItem** property that gets or sets the active item. The **ActiveItem** is relevant only for **MultiSimple** and **MultiExtended** selection modes. #### Set the selection mode -{{source=..\SamplesCS\DropDownListControl\ListControl\ListControl1.cs region=SelectionMode}} -{{source=..\SamplesVB\DropDownListControl\ListControl\ListControl1.vb region=SelectionMode}} -````C# -this.radListControl1.SelectionMode = SelectionMode.MultiSimple; + + -```` -````VB.NET -Me.radListControl1.SelectionMode = SelectionMode.MultiSimple -```` - -{{endregion}} ## Select items programmatically In order to select an item programmatically you should use the **SelectedItem** property. You can select an item by index as well by using the **SelectedIndex** property. If you want to select an item by its value you can use the **SelectedValue** property. When usng the **SelectedValue** property a linear search is performed to find a data item that has the same value in its **Value** property. #### Select items programmatically -{{source=..\SamplesCS\DropDownListControl\ListControl\ListControl1.cs region=SelectItems}} -{{source=..\SamplesVB\DropDownListControl\ListControl\ListControl1.vb region=SelectItems}} - -````C# -this.radListControl1.SelectedItem = this.radListControl1.Items[1]; -this.radListControl1.SelectedIndex = 2; -this.radListControl1.SelectedValue = "MP3"; -```` -````VB.NET -Me.radListControl1.SelectedItem = Me.radListControl1.Items(1) -Me.radListControl1.SelectedIndex = 2 -Me.radListControl1.SelectedValue = "MP3" + + -```` -{{endregion}} ![WinForms RadListControl Select Items Programmatically ](images/listcontrol-selectitems001.png) diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/features/sorting.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/features/sorting.md index a8de8adc3..15c52b5bd 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/features/sorting.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/features/sorting.md @@ -27,18 +27,10 @@ Sorting in __RadListControl__ is controlled by the __SortStyle__ property. The a #### Setting Sorting -{{source=..\SamplesCS\DropDownListControl\ListControl\ListControl1.cs region=sorting}} -{{source=..\SamplesVB\DropDownListControl\ListControl\ListControl1.vb region=sorting}} + + -````C# -radListControl1.SortStyle = Telerik.WinControls.Enumerations.SortStyle.Ascending; -```` -````VB.NET -radListControl1.SortStyle = Telerik.WinControls.Enumerations.SortStyle.Ascending -```` - -{{endregion}} >caution Changing the __SortStyle__ property may cause the __SelectedIndexChanged__ event to fire if the position of the currently selected item has changed after the sort operation. diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/getting-started.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/getting-started.md index bf58ba654..e494bb75d 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/getting-started.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/getting-started.md @@ -66,26 +66,9 @@ This tutorial demonstrates how to manually populate __RadListControl__ and how #### Handling the SelectedIndexChanged event -{{source=..\SamplesCS\DropDownListControl\ListControl\ListControl1.cs region=handlingSelectedIndexChanged}} -{{source=..\SamplesVB\DropDownListControl\ListControl\ListControl1.vb region=handlingSelectedIndexChanged}} - -````C# -void radListControl1_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e) -{ - RadListDataItem item = this.radListControl1.SelectedItem as RadListDataItem; - radLabel1.Text = "Selected control: " + item.Text; -} - -```` -````VB.NET -Private Sub radListControl1_SelectedIndexChanged(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.Data.PositionChangedEventArgs) - Dim item As RadListDataItem = TryCast(Me.radListControl1.SelectedItem, RadListDataItem) - radLabel1.Text = "Selected control: " & item.Text -End Sub - -```` - -{{endregion}} + + + 11\. Press __F5__ to run the project. Select an item in the list box and note the value of the label. diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/populating-with-data/adding-items-programmatically.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/populating-with-data/adding-items-programmatically.md index c164d8992..49f130a50 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/populating-with-data/adding-items-programmatically.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/populating-with-data/adding-items-programmatically.md @@ -26,79 +26,11 @@ You can use one of the following item types: #### Add items programmatically -{{source=..\SamplesCS\DropDownListControl\ListControl\ListControl1.cs region=AddItemsProgrammatically}} -{{source=..\SamplesVB\DropDownListControl\ListControl\ListControl1.vb region=AddItemsProgrammatically}} - -````C# -DescriptionTextListDataItem descriptionItem = new DescriptionTextListDataItem(); -descriptionItem.Text = "Chicken wings"; -descriptionItem.Image = Properties.Resources.chicken_wings; -descriptionItem.DescriptionText = "some description"; -this.radListControl1.Items.Add(descriptionItem); -RadListDataItem dataItem = new RadListDataItem(); -dataItem.Text = "Chicken toast"; -dataItem.Image = Properties.Resources.chicken_toast; -this.radListControl1.Items.Add(dataItem); - -```` -````VB.NET -Dim descriptionItem As New DescriptionTextListDataItem() -descriptionItem.Text = "Chicken wings" -descriptionItem.Image = My.Resources.chicken_wings -descriptionItem.DescriptionText = "some description" -Me.radListControl1.Items.Add(descriptionItem) -Dim dataItem As New RadListDataItem() -dataItem.Text = "Chicken toast" -dataItem.Image = My.Resources.chicken_toast -Me.radListControl1.Items.Add(dataItem) -'#End Region -'#Region "expression" -Me.radListControl1.FilterExpression = "Country LIKE 'Argentina'" -'#End Region -End Sub -'#Region "Binding" -Public Class Item -Public Property Id() As Integer - Get - Return m_Id - End Get - Set(value As Integer) - m_Id = value - End Set -End Property -Private m_Id As Integer -Public Property Description() As String - Get - Return m_Description - End Get - Set(value As String) - m_Description = value - End Set -End Property -Private m_Description As String -Public Sub New(id As Integer, description As String) - Me.Id = id - Me.Description = description -End Sub -End Class -Public Sub Bind() -Dim items As New List(Of Item)() -For i As Integer = 0 To 9 - items.Add(New Item(i, "Data" + i)) -Next -radListControl1.DataSource = items -radListControl1.DisplayMember = "Description" -radListControl1.ValueMember = "Id" -End Sub -'#End Region -'#region creatingVisualListItem -Private Sub radListControl1_CreatingVisualListItem(ByVal sender As Object, ByVal args As CreatingVisualListItemEventArgs) -args.VisualItem = New CustomVisualItem() -End Sub - -```` - -{{endregion}} + + + + + # See Also diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/populating-with-data/databinding.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/populating-with-data/databinding.md index 335417dd9..6c96f189e 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/populating-with-data/databinding.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/populating-with-data/databinding.md @@ -43,76 +43,10 @@ You can set the __DataSource__ property at design time in the *Properties* windo ## Data binding at run time -{{source=..\SamplesCS\DropDownListControl\ListControl\ListControl1.cs region=Binding}} -{{source=..\SamplesVB\DropDownListControl\ListControl\ListControl1.vb region=Binding}} - -````C# -public class Item -{ - public int Id { get; set; } - public string Description { get; set; } - public Item(int id, string description) - { - this.Id = id; - this.Description = description; - } -} -public void Bind() -{ - List items = new List(); - for (int i = 0; i < 10; i++) - { - items.Add(new Item(i, "Data" + i)); - } - radListControl1.DataSource = items; - radListControl1.DisplayMember = "Description"; - radListControl1.ValueMember = "Id"; -} - -```` -````VB.NET -Public Class Item - Public Property Id() As Integer - Get - Return m_Id - End Get - Set(value As Integer) - m_Id = value - End Set - End Property - Private m_Id As Integer - Public Property Description() As String - Get - Return m_Description - End Get - Set(value As String) - m_Description = value - End Set - End Property - Private m_Description As String - Public Sub New(id As Integer, description As String) - Me.Id = id - Me.Description = description - End Sub -End Class -Public Sub Bind() - Dim items As New List(Of Item)() - For i As Integer = 0 To 9 - items.Add(New Item(i, "Data" + i)) - Next - radListControl1.DataSource = items - radListControl1.DisplayMember = "Description" - radListControl1.ValueMember = "Id" -End Sub -'#End Region -'#region creatingVisualListItem -Private Sub radListControl1_CreatingVisualListItem(ByVal sender As Object, ByVal args As CreatingVisualListItemEventArgs) - args.VisualItem = New CustomVisualItem() -End Sub - -```` - -{{endregion}} + + + + >caption Figure: 4 RadListControl bound at Run time diff --git a/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/visual-data-representation.md b/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/visual-data-representation.md index 025623037..9d4777058 100644 --- a/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/visual-data-representation.md +++ b/controls/dropdown-listcontrol-and-checkeddropdownlist/listcontrol/visual-data-representation.md @@ -21,57 +21,10 @@ Here is how our visual item class could look like: #### Custom RadListVisualItem -{{source=..\SamplesCS\DropDownListControl\ListControl\ListControl1.cs region=customVisualItem}} -{{source=..\SamplesVB\DropDownListControl\ListControl\ListControl1.vb region=customVisualItem}} + + -````C# -public class CustomVisualItem : RadListVisualItem -{ - private RadCheckBoxElement checkBox = null; - static CustomVisualItem() - { - RadListVisualItem.SynchronizationProperties.Add(CustomDataItem.AvailableProperty); - } - protected override void PropertySynchronized(RadProperty property) - { - base.PropertySynchronized(property); - if (property == CustomDataItem.AvailableProperty) - { - this.checkBox.Checked = (bool)this.GetValue(property); - } - } - protected override void CreateChildElements() - { - base.CreateChildElements(); - this.checkBox = new RadCheckBoxElement(); - this.Children.Add(checkBox); - } -} - -```` -````VB.NET -Public Class CustomVisualItem -Inherits RadListVisualItem - Private checkBox As RadCheckBoxElement = Nothing - Shared Sub New() - RadListVisualItem.SynchronizationProperties.Add(CustomDataItem.AvailableProperty) - End Sub - Protected Overrides Sub PropertySynchronized(ByVal [property] As RadProperty) - MyBase.PropertySynchronized([property]) - If [property] Is CustomDataItem.AvailableProperty Then - Me.checkBox.Checked = CBool(Me.GetValue([property])) - End If - End Sub - Protected Overrides Sub CreateChildElements() - MyBase.CreateChildElements() - Me.checkBox = New RadCheckBoxElement() - Me.Children.Add(checkBox) - End Sub -End Class - -```` - -{{endregion}} + Two things are important in order for the synchronization to work. First, the base __RadListVisualItem__ has a static list of __RadProperty__ objects that are iterated over and for each property in the list, the property value is synchronized between the logical and the visual item. In order for the custom __Available__ property to take part in this synchronization it must be added to the static list which should be done in the static constructor of the __CustomVisualItem__. Second, after this property is added to the static property list, the base implementation will notify the inheritors who override the __PropertySynchronized__ method. In this method we can get the updated value for the custom property and update the visual elements accordingly. Again, the two necessary steps to perform are to add the new property to the property list and to override __PropertySynchronized__ so that we can update the UI. The property synchronization works only one way, from the data to the visuals. If the visuals are updated the programmer who created the new visual item is responsible for updating the data item. Every __RadListVisualItem__ has a __Data__ property that points to the data item. It is an interface reference and if a custom data item is provided, it must be explicitly cast to the correct type. @@ -81,24 +34,10 @@ Once we have created a custom visual item, we need to subscribe to the __Creatin #### Replace the default visual items -{{source=..\SamplesCS\DropDownListControl\ListControl\ListControl1.cs region=creatingVisualListItem}} -{{source=..\SamplesVB\DropDownListControl\ListControl\ListControl1.vb region=creatingVisualListItem}} - -````C# -void radListControl1_CreatingVisualListItem(object sender, CreatingVisualListItemEventArgs args) -{ - args.VisualItem = new CustomVisualItem(); -} - -```` -````VB.NET -Private Sub radListControl1_CreatingVisualListItem(ByVal sender As Object, ByVal args As CreatingVisualListItemEventArgs) - args.VisualItem = New CustomVisualItem() -End Sub - -```` + + -{{endregion}} + This is all there is to it, with that infrastructure in place users can create just about any visual representation of the data that __RadListControl__ is bound to or filled with in unbound mode. diff --git a/controls/editors/autocompletebox/auto-complete.md b/controls/editors/autocompletebox/auto-complete.md index e35f24e3a..352c5968d 100644 --- a/controls/editors/autocompletebox/auto-complete.md +++ b/controls/editors/autocompletebox/auto-complete.md @@ -65,55 +65,11 @@ __AutoCompleteValueMember__: To set the __AutoCompleteValueMember__ property, fi To use auto-completion without specifying a data source, you need to populate the items which will be used for completing the input string in RadAutoCompleteBox in the __Items__ collection of the control: -{{source=..\SamplesCS\Editors\AutoCompleteBox.cs region=addItems}} -{{source=..\SamplesVB\Editors\AutoCompleteBox.vb region=addItems}} - -````C# -private void AddAutoCompleteItems() -{ - RadListDataItemCollection items = this.radAutoCompleteBox1.AutoCompleteItems; - items.Add(new RadListDataItem("Joe Smith", "joe@fakecompany.com")); - items.Add(new RadListDataItem("Adam Petersen", "adam@qwerty.com")); - items.Add(new RadListDataItem("Jack Russel", "jack@russel.nocom")); - items.Add(new RadListDataItem("Daniel Finger", "daniel.pinger@gmail.com")); - items.Add(new RadListDataItem("Richard Vail", "rvail@richardvail.com")); - items.Add(new RadListDataItem("Sebastian Jonnson", "s.jonnson@sjonnson.com")); - items.Add(new RadListDataItem("Lee Cooper", "lee.cooper@coopercoorp.com")); - items.Add(new RadListDataItem("Kelvin Clain", "kclain@clainkevin.com")); - items.Add(new RadListDataItem("Maria Jenson", "mjenson@mariajenson.com")); - items.Add(new RadListDataItem("Chelsea Maarten", "chelsea@maarten.com")); - items.Add(new RadListDataItem("Jenson Chew", "jenson.chew@nospam.com")); - items.Add(new RadListDataItem("Martin Williams", "m.williams@martinandwilliams.com")); - items.Add(new RadListDataItem("Telerik", "clientservice@telerik.com")); - items.Add(new RadListDataItem("James Stone", "james.stone@manystones.com")); - items.Add(new RadListDataItem("Samuel Jackson", "samuel.jackson@nojackson.com")); -} - -```` -````VB.NET -Private Sub AddAutoCompleteItems() - Dim items As RadListDataItemCollection = Me.RadAutoCompleteBox1.AutoCompleteItems - items.Add(New RadListDataItem("Joe Smith", "joe@fakecompany.com")) - items.Add(New RadListDataItem("Adam Petersen", "adam@qwerty.com")) - items.Add(New RadListDataItem("Jack Russel", "jack@russel.nocom")) - items.Add(New RadListDataItem("Daniel Finger", "daniel.pinger@gmail.com")) - items.Add(New RadListDataItem("Richard Vail", "rvail@richardvail.com")) - items.Add(New RadListDataItem("Sebastian Jonnson", "s.jonnson@sjonnson.com")) - items.Add(New RadListDataItem("Lee Cooper", "lee.cooper@coopercoorp.com")) - items.Add(New RadListDataItem("Kelvin Clain", "kclain@clainkevin.com")) - items.Add(New RadListDataItem("Maria Jenson", "mjenson@mariajenson.com")) - items.Add(New RadListDataItem("Chelsea Maarten", "chelsea@maarten.com")) - items.Add(New RadListDataItem("Jenson Chew", "jenson.chew@nospam.com")) - items.Add(New RadListDataItem("Martin Williams", "m.williams@martinandwilliams.com")) - items.Add(New RadListDataItem("Telerik", "clientservice@telerik.com")) - items.Add(New RadListDataItem("James Stone", "james.stone@manystones.com")) - items.Add(New RadListDataItem("Samuel Jackson", "samuel.jackson@nojackson.com")) -End Sub - -```` - -{{endregion}} - + + + + + >caption Figure 2: RadAutoCompleteBox with some items added directly. ![WinForms RadAutoCompleteBox With Some Items Added Directly](images/editors-autocompletebox-autocomplete002.png) @@ -128,29 +84,9 @@ As of **R1 2020 SP1** **RadAutoCompleteBox** offers the **AllowDuplicates** prop Note that you can still add duplicated tokens in the editor if you type them manually. In order to avoid that you can subscribe to **TokenValidating** event and if the existing text in **RadAutoCompleteBox** contains the new text, set the **IsValidToken** property to *false*. The **TokenValidating** event will be called for each token that is going to be added to the control text area. -{{source=..\SamplesCS\Editors\AutoCompleteBox.cs region=InvalidToken}} -{{source=..\SamplesVB\Editors\AutoCompleteBox.vb region=InvalidToken}} - -````C# - private void RadAutoCompleteBox1_TokenValidating(object sender, TokenValidatingEventArgs e) - { - if (this.radAutoCompleteBox1.Text.Contains(e.Text)) - { - e.IsValidToken = false; - } - } - -```` -````VB.NET - Private Sub RadAutoCompleteBox1_TokenValidating(ByVal sender As Object, ByVal e As TokenValidatingEventArgs) - If Me.radAutoCompleteBox1.Text.Contains(e.Text) Then - e.IsValidToken = False - End If - End Sub - -```` - -{{endregion}} + + + # See Also diff --git a/controls/editors/autocompletebox/caret-positioning-and-selection.md b/controls/editors/autocompletebox/caret-positioning-and-selection.md index 24093fd03..84c4c6c55 100644 --- a/controls/editors/autocompletebox/caret-positioning-and-selection.md +++ b/controls/editors/autocompletebox/caret-positioning-and-selection.md @@ -22,51 +22,17 @@ The __SelectionStart__ property is an integer that indicates the insertion point Setting the __SelectionLength__ to a number greater than 0 causes that number of characters to be selected, starting from the current insertion point. -{{source=..\SamplesCS\editors\AutoCompleteBox.cs region=SetSelection}} -{{source=..\SamplesVB\editors\AutoCompleteBox.vb region=SetSelection}} + + -````C# -private void SetSelection() -{ - this.radAutoCompleteBox1.Text = "Pepsi; Sprite; Coca-Cola;"; - this.radAutoCompleteBox1.SelectionStart = 6; - this.radAutoCompleteBox1.SelectionLength = 7; -} -```` -````VB.NET -Private Sub SetSelection() - Me.RadAutoCompleteBox1.Text = "Pepsi; Sprite; Coca-Cola;" - Me.RadAutoCompleteBox1.SelectionStart = 6 - Me.RadAutoCompleteBox1.SelectionLength = 7 -End Sub - -```` - -{{endregion}} Alternatively, you can use the __Select__ method to select the same part of the text: -{{source=..\SamplesCS\editors\AutoCompleteBox.cs region=SetSelectionRange}} -{{source=..\SamplesVB\editors\AutoCompleteBox.vb region=SetSelectionRange}} - -````C# -private void SetSelectionRange() -{ - this.radAutoCompleteBox1.Text = "Pepsi;Sprite;Coca-Cola"; - this.radAutoCompleteBox1.Select(6, 7); -} - -```` -````VB.NET -Private Sub SetSelectionRange() - Me.RadAutoCompleteBox1.Text = "Pepsi;Sprite;Coca-Cola" - Me.RadAutoCompleteBox1.[Select](6, 7) -End Sub + + -```` -{{endregion}} The both approaches produce same result: diff --git a/controls/editors/autocompletebox/creating-custom-blocks.md b/controls/editors/autocompletebox/creating-custom-blocks.md index 3174eb336..91a0b637b 100644 --- a/controls/editors/autocompletebox/creating-custom-blocks.md +++ b/controls/editors/autocompletebox/creating-custom-blocks.md @@ -16,102 +16,28 @@ __RadAutoCompleteBox__ allows not only appearance customization via the formatti You should create a custom text block that inherits from __ITextBlock__ and any inheritor of __RadElement__. Let’s extend the default __TokenizedTextBlockElement__ by adding a check box. You don’t need to implement the __ITextBlock__ interface, because it is already defined in the base class: -{{source=..\SamplesCS\Editors\AutoCompleteBox.cs region=customTokens}} -{{source=..\SamplesVB\Editors\AutoCompleteBox.vb region=customTokens}} - -````C# -public class MyTokenizedTextBlockElement : TokenizedTextBlockElement -{ - private RadCheckBoxElement checkBox; - protected override Type ThemeEffectiveType - { - get - { - return typeof(TokenizedTextBlockElement); - } - } - protected override void CreateChildElements() - { - base.CreateChildElements(); - int index = this.Children.IndexOf(this.RemoveButton); - this.checkBox = new RadCheckBoxElement(); - this.checkBox.StretchVertically = true; - this.checkBox.StretchHorizontally = false; - this.Children.Insert(index, this.checkBox); - } -} - -```` -````VB.NET -Public Class MyTokenizedTextBlockElement - Inherits TokenizedTextBlockElement - Private checkBox As RadCheckBoxElement - Protected Overrides ReadOnly Property ThemeEffectiveType() As Type - Get - Return GetType(TokenizedTextBlockElement) - End Get - End Property - Protected Overrides Sub CreateChildElements() - MyBase.CreateChildElements() - Dim index As Integer = Me.Children.IndexOf(Me.RemoveButton) - Me.checkBox = New RadCheckBoxElement() - Me.checkBox.StretchVertically = True - Me.checkBox.StretchHorizontally = False - Me.Children.Insert(index, Me.checkBox) - End Sub -End Class - -```` - -{{endregion}} + + + + Then you should replace the default text block in the __CreateTextBlock__ event handler, in the following manner: -{{source=..\SamplesCS\Editors\AutoCompleteBox.cs region=replaceTokens}} -{{source=..\SamplesVB\Editors\AutoCompleteBox.vb region=replaceTokens}} - -````C# -private void radAutoCompleteBox1_CreateTextBlock(object sender, CreateTextBlockEventArgs e) -{ - if (e.TextBlock is TokenizedTextBlockElement) - { - e.TextBlock = new MyTokenizedTextBlockElement(); - } -} - -```` -````VB.NET -Private Sub radAutoCompleteBox1_CreateTextBlock(sender As Object, e As CreateTextBlockEventArgs) - If TypeOf e.TextBlock Is TokenizedTextBlockElement Then - e.TextBlock = New MyTokenizedTextBlockElement() - End If -End Sub - -```` - -{{endregion}} - + + + + + Finally, the text property should be set: >note The subscription to the event, should be introduced before setting the text of the control. > -{{source=..\SamplesCS\Editors\AutoCompleteBox.cs region=SubscribeToCreateTextBlock}} -{{source=..\SamplesVB\Editors\AutoCompleteBox.vb region=SubscribeToCreateTextBlock}} -````C# -radAutoCompleteBox1.CreateTextBlock+=new CreateTextBlockEventHandler(radAutoCompleteBox1_CreateTextBlock); -this.radAutoCompleteBox1.Text = "Euro;USD;GBP;"; - -```` -````VB.NET -AddHandler RadAutoCompleteBox1.CreateTextBlock, AddressOf radAutoCompleteBox1_CreateTextBlock -Me.RadAutoCompleteBox1.Text = "Euro;USD;GBP;" - -```` + + -{{endregion}} The following image demonstrates the final result: diff --git a/controls/editors/autocompletebox/customizing-appearance/formatting-blocks.md b/controls/editors/autocompletebox/customizing-appearance/formatting-blocks.md index a87377a4e..e63ad0c28 100644 --- a/controls/editors/autocompletebox/customizing-appearance/formatting-blocks.md +++ b/controls/editors/autocompletebox/customizing-appearance/formatting-blocks.md @@ -13,33 +13,10 @@ previous_url: editors-autocompletetextbox-formatting-blocks, editors/autocomplet The __RadAutoCompleteBox__ allows appearance customization of each instance of __ITextBlock__. This can be easily achieved by subscribing to the __FormattingTextBlock__ event: -{{source=..\SamplesCS\Editors\AutoCompleteBox.cs region=formatting}} -{{source=..\SamplesVB\Editors\AutoCompleteBox.vb region=formatting}} - -````C# -void radAutoCompleteBox1_TextBlockFormatting(object sender, TextBlockFormattingEventArgs e) -{ - TokenizedTextBlockElement token = e.TextBlock as TokenizedTextBlockElement; - if (token != null) - { - token.GradientStyle = Telerik.WinControls.GradientStyles.Solid; - token.BackColor = Color.Yellow; - } -} - -```` -````VB.NET -Private Sub radAutoCompleteBox1_TextBlockFormatting(sender As Object, e As TextBlockFormattingEventArgs) - Dim token As TokenizedTextBlockElement = TryCast(e.TextBlock, TokenizedTextBlockElement) - If token IsNot Nothing Then - token.GradientStyle = Telerik.WinControls.GradientStyles.Solid - token.BackColor = Color.Yellow - End If -End Sub - -```` - -{{endregion}} + + + + >caption Figure 1: Items with yellow background. diff --git a/controls/editors/autocompletebox/getting-started.md b/controls/editors/autocompletebox/getting-started.md index b7aa2b0fe..80871bc71 100644 --- a/controls/editors/autocompletebox/getting-started.md +++ b/controls/editors/autocompletebox/getting-started.md @@ -45,44 +45,21 @@ Each tokenized text block is separated by character, specified by the __Delimite The code below sets text in the control at run time: -{{source=..\SamplesCS\editors\AutoCompleteBox.cs region=SetText}} -{{source=..\SamplesVB\editors\AutoCompleteBox.vb region=SetText}} + + -````C# -private void SetText() -{ - this.radAutoCompleteBox1.Text = "Germany;USA;Brazil;Bulgaria;Croatia;Serbia;"; -} -```` -````VB.NET -Private Sub SetText() - Me.RadAutoCompleteBox1.Text = "Germany;USA;Brazil;Bulgaria;Croatia;Serbia;" -End Sub -```` - -{{endregion}} - >caption Figure 1: Set the text of RadAutoCompleteBox. ![WinForms RadAutoCompleteBox Text of RadAutoCompleteBox](images/editors-autocompletebox-getting-started001.png) You can determine the visibility of the remove button by changing the __ShowRemoveButton__ property: -{{source=..\SamplesCS\editors\AutoCompleteBox.cs region=ShowRemoveButton}} -{{source=..\SamplesVB\editors\AutoCompleteBox.vb region=ShowRemoveButton}} - -````C# -this.radAutoCompleteBox1.ShowRemoveButton = false; - -```` -````VB.NET -Me.RadAutoCompleteBox1.ShowRemoveButton = False + + -```` -{{endregion}} >caption Figure 2: The Tokenized items are not showing the close button. diff --git a/controls/editors/autocompletebox/text-editing.md b/controls/editors/autocompletebox/text-editing.md index 4086a8bda..3bab391c9 100644 --- a/controls/editors/autocompletebox/text-editing.md +++ b/controls/editors/autocompletebox/text-editing.md @@ -18,29 +18,11 @@ You can insert text programmatically at concrete position by using the __Insert_ #### Using the Insert method. -{{source=..\SamplesCS\editors\AutoCompleteBox.cs region=insert}} -{{source=..\SamplesVB\editors\AutoCompleteBox.vb region=insert}} - -````C# -private void Insert() -{ - this.radAutoCompleteBox1.Text = "USA;"; - this.radAutoCompleteBox1.CaretIndex = 0; - this.radAutoCompleteBox1.Insert("Canada;"); -} - -```` -````VB.NET -Private Sub Insert() - Me.RadAutoCompleteBox1.Text = "USA;" - Me.RadAutoCompleteBox1.CaretIndex = 0 - Me.RadAutoCompleteBox1.Insert("Canada;") -End Sub - -```` - -{{endregion}} - + + + + + >caption Figure 1: Inserting text. ![WinForms RadAutoCompleteBox Inserting text](images/editors-autocompletebox-text-editing001.png) @@ -49,27 +31,11 @@ Alternatively, you can insert text at the end of the __RadAutoCompleteBox__ cont #### Using the AppendText method. -{{source=..\SamplesCS\editors\AutoCompleteBox.cs region=Append}} -{{source=..\SamplesVB\editors\AutoCompleteBox.vb region=Append}} + + -````C# -private void Append() -{ - this.radAutoCompleteBox1.Text = "IT Department;"; - this.radAutoCompleteBox1.AppendText("Marketing Team;"); -} -```` -````VB.NET -Private Sub Append() - Me.RadAutoCompleteBox1.Text = "IT Department;" - Me.RadAutoCompleteBox1.AppendText("Marketing Team;") -End Sub -```` - -{{endregion}} - >caption Figure 2: The text is appended at the end. ![WinForms RadAutoCompleteBox Text is Appended at the End](images/editors-autocompletebox-text-editing002.png) @@ -78,29 +44,11 @@ You can delete the selected text or character at the caret position by using the #### Using the Delete method. -{{source=..\SamplesCS\editors\AutoCompleteBox.cs region=Delete}} -{{source=..\SamplesVB\editors\AutoCompleteBox.vb region=Delete}} - -````C# -private void DeleteText() -{ - this.radAutoCompleteBox1.Text = "Germany;USA;Brazil;Bulgaria;Croatia;Serbia;"; - this.radAutoCompleteBox1.Select(0, 8); - this.radAutoCompleteBox1.Delete(); -} - -```` -````VB.NET -Private Sub DeleteText() - Me.RadAutoCompleteBox1.Text = "Germany;USA;Brazil;Bulgaria;Croatia;Serbia;" - Me.RadAutoCompleteBox1.[Select](0, 8) - Me.RadAutoCompleteBox1.Delete() -End Sub - -```` - -{{endregion}} - + + + + + >caption Figure 3: The firs word is deleted. ![WinForms RadAutoCompleteBox The Firs Word Deleted](images/editors-autocompletebox-text-editing003.png) @@ -109,24 +57,10 @@ Each editing operation raises the __TextChanging__ and __TextChanged__ events. N #### Prevent deleting a tokenized text blocks in RadAutoCompleteBox. -{{source=..\SamplesCS\editors\AutoCompleteBox.cs region=PreventDeleteOfTokens}} -{{source=..\SamplesVB\editors\AutoCompleteBox.vb region=PreventDeleteOfTokens}} - -````C# -void radAutoCompleteBox1_TextChanging(object sender, Telerik.WinControls.TextChangingEventArgs e) -{ - e.Cancel = string.IsNullOrEmpty(e.NewValue) && e.OldValue.Contains(this.radAutoCompleteBox1.Delimiter.ToString()); -} - -```` -````VB.NET -Private Sub radAutoCompleteBox1_TextChanging(sender As Object, e As Telerik.WinControls.TextChangingEventArgs) - e.Cancel = String.IsNullOrEmpty(e.NewValue) AndAlso e.OldValue.Contains(Me.RadAutoCompleteBox1.Delimiter.ToString()) -End Sub + + -```` -{{endregion}} The code above prevents deleting a tokenized text blocks in RadAutoCompleteBox. diff --git a/controls/editors/browseeditor/customizing-appearance/accessing-and-customizing-elements.md b/controls/editors/browseeditor/customizing-appearance/accessing-and-customizing-elements.md index 7fdc95b16..a84c5baa0 100644 --- a/controls/editors/browseeditor/customizing-appearance/accessing-and-customizing-elements.md +++ b/controls/editors/browseeditor/customizing-appearance/accessing-and-customizing-elements.md @@ -30,22 +30,10 @@ You can customize the nested elements at run time as well: #### Customize elements -{{source=..\SamplesCS\Editors\BrowseEditor1.cs region=CustomizeElementProgrammatically}} -{{source=..\SamplesVB\Editors\BrowseEditor1.vb region=CustomizeElementProgrammatically}} -````C# -this.radBrowseEditor1.BrowseElement.BrowseButton.ButtonFillElement.NumberOfColors = 1; -this.radBrowseEditor1.BrowseElement.BrowseButton.ButtonFillElement.BackColor = Color.LightGreen; + + -```` -````VB.NET -Me.RadBrowseEditor1.BrowseElement.BrowseButton.ButtonFillElement.NumberOfColors = 1 -Me.RadBrowseEditor1.BrowseElement.BrowseButton.ButtonFillElement.BackColor = Color.LightGreen -```` - - - -{{endregion}} # See Also diff --git a/controls/editors/browseeditor/dialog-types.md b/controls/editors/browseeditor/dialog-types.md index ed11efb1e..97cedd339 100644 --- a/controls/editors/browseeditor/dialog-types.md +++ b/controls/editors/browseeditor/dialog-types.md @@ -26,20 +26,10 @@ As of **R1 2020 SP1** the Telerik [File Dialogs]({%slug winforms/file-dialogs/ov #### FolderBrowseDialog -{{source=..\SamplesCS\Editors\BrowseEditor1.cs region=FolderBrowseDialog}} -{{source=..\SamplesVB\Editors\BrowseEditor1.vb region=FolderBrowseDialog}} -````C# -this.radBrowseEditor1.DialogType = BrowseEditorDialogType.FolderBrowseDialog; + + -```` -````VB.NET -Me.RadBrowseEditor1.DialogType = BrowseEditorDialogType.FolderBrowseDialog -```` - - - -{{endregion}} >caption Figure 1: FolderBrowseDialog @@ -47,20 +37,10 @@ Me.RadBrowseEditor1.DialogType = BrowseEditorDialogType.FolderBrowseDialog #### FontDialog -{{source=..\SamplesCS\Editors\BrowseEditor1.cs region=FontDialog}} -{{source=..\SamplesVB\Editors\BrowseEditor1.vb region=FontDialog}} -````C# -this.radBrowseEditor1.DialogType = BrowseEditorDialogType.FontDialog; - -```` -````VB.NET -Me.RadBrowseEditor1.DialogType = BrowseEditorDialogType.FontDialog - -```` - + + -{{endregion}} >caption Figure 2: FontDialog @@ -68,20 +48,10 @@ Me.RadBrowseEditor1.DialogType = BrowseEditorDialogType.FontDialog #### OpenFileDialog -{{source=..\SamplesCS\Editors\BrowseEditor1.cs region=OpenFileDialog}} -{{source=..\SamplesVB\Editors\BrowseEditor1.vb region=OpenFileDialog}} -````C# -this.radBrowseEditor1.DialogType = BrowseEditorDialogType.OpenFileDialog; + + -```` -````VB.NET -Me.RadBrowseEditor1.DialogType = BrowseEditorDialogType.OpenFileDialog -```` - - - -{{endregion}} >caption Figure 3: OpenFileDialog @@ -89,17 +59,10 @@ Me.RadBrowseEditor1.DialogType = BrowseEditorDialogType.OpenFileDialog #### SaveFileDialog -{{source=..\SamplesCS\Editors\BrowseEditor1.cs region=SaveFileDialog}} -{{source=..\SamplesVB\Editors\BrowseEditor1.vb region=SaveFileDialog}} -````C# -this.radBrowseEditor1.DialogType = BrowseEditorDialogType.SaveFileDialog; + + -```` -````VB.NET -Me.RadBrowseEditor1.DialogType = BrowseEditorDialogType.SaveFileDialog -```` -{{endregion}} >caption Figure 4: SaveFileDialog @@ -108,18 +71,10 @@ Me.RadBrowseEditor1.DialogType = BrowseEditorDialogType.SaveFileDialog #### RadOpenFileDialog -{{source=..\SamplesCS\Editors\BrowseEditor1.cs region=TelerikOpenFileDialog}} -{{source=..\SamplesVB\Editors\BrowseEditor1.vb region=TelerikOpenFileDialog}} + + -````C# -this.radBrowseEditor1.DialogType = BrowseEditorDialogType.RadOpenFileDialog; -```` -````VB.NET -Me.RadBrowseEditor1.DialogType = BrowseEditorDialogType.RadOpenFileDialog - -```` -{{endregion}} >caption Figure 5: RadOpenFileDialog @@ -127,18 +82,10 @@ Me.RadBrowseEditor1.DialogType = BrowseEditorDialogType.RadOpenFileDialog #### RadOpenFolderDialog -{{source=..\SamplesCS\Editors\BrowseEditor1.cs region=TelerikOpenFolderDialog}} -{{source=..\SamplesVB\Editors\BrowseEditor1.vb region=TelerikOpenFolderDialog}} - -````C# -this.radBrowseEditor1.DialogType = BrowseEditorDialogType.RadOpenFolderDialog; + + -```` -````VB.NET -Me.RadBrowseEditor1.DialogType = BrowseEditorDialogType.RadOpenFolderDialog -```` -{{endregion}} >caption Figure 6: RadOpenFolderDialog @@ -148,18 +95,10 @@ Me.RadBrowseEditor1.DialogType = BrowseEditorDialogType.RadOpenFolderDialog #### RadSaveFileDialog -{{source=..\SamplesCS\Editors\BrowseEditor1.cs region=TelerikSaveFileDialog}} -{{source=..\SamplesVB\Editors\BrowseEditor1.vb region=TelerikSaveFileDialog}} - -````C# - this.radBrowseEditor1.DialogType = BrowseEditorDialogType.RadSaveFileDialog; + + -```` -````VB.NET -Me.RadBrowseEditor1.DialogType = BrowseEditorDialogType.RadSaveFileDialog -```` -{{endregion}} >caption Figure 7: RadSaveFileDialog diff --git a/controls/editors/browseeditor/getting-started.md b/controls/editors/browseeditor/getting-started.md index 56a577881..5a8ebe07f 100644 --- a/controls/editors/browseeditor/getting-started.md +++ b/controls/editors/browseeditor/getting-started.md @@ -46,24 +46,10 @@ The following example demonstrates how to change the image of a __RadButton__ us 3\. Select the __RadBrowseEditor__, click the __Events tab__ of the __Property Window__, locate the __ValueChanged__ event and double-click it in order to create an event handler. Replace the event handler with the following code. -{{source=..\SamplesCS\Editors\BrowseEditor1.cs region=browseEditorValueChanged}} -{{source=..\SamplesVB\Editors\BrowseEditor1.vb region=browseEditorValueChanged}} + + -````C# -private void radBrowseEditor1_ValueChanged(object sender, EventArgs e) -{ - this.radButton1.Image = Image.FromFile(this.radBrowseEditor1.Value); -} -```` -````VB.NET -Private Sub RadBrowseEditor1_ValueChanged(sender As Object, e As EventArgs) - Me.RadButton1.Image = System.Drawing.Image.FromFile(Me.RadBrowseEditor1.Value) -End Sub - -```` - -{{endregion}} 4\. Press __F5__ to run the application. Press the browse button and select an image. The image is then applied to the __RadButton__. diff --git a/controls/editors/browseeditor/working-with-radbrowseeditor.md b/controls/editors/browseeditor/working-with-radbrowseeditor.md index 4c1a2c912..1d4075cb9 100644 --- a/controls/editors/browseeditor/working-with-radbrowseeditor.md +++ b/controls/editors/browseeditor/working-with-radbrowseeditor.md @@ -15,25 +15,11 @@ The events defined in __RadBrowseEditor__ provide an easy way to track user inpu #### Cancel ValueChanging Event -{{source=..\SamplesCS\Editors\BrowseEditor1.cs region=browseEditorValueChanging}} -{{source=..\SamplesVB\Editors\BrowseEditor1.vb region=browseEditorValueChanging}} - -````C# -private void radBrowseEditor1_ValueChanging(object sender, ValueChangingEventArgs e) -{ - e.Cancel = !File.Exists(e.NewValue.ToString()); -} - -```` -````VB.NET -Private Sub RadBrowseEditor1_ValueChanging(sender As Object, e As Telerik.WinControls.UI.ValueChangingEventArgs) - e.Cancel = Not System.IO.File.Exists(e.NewValue.ToString()) -End Sub - -```` - -{{endregion}} - + + + + + ## See Also * [Properties and Events]({%slug winforms/editors/browseeditor/properties-events%}) diff --git a/controls/editors/buttontextbox/customizing-appearance/accessing-and-customizing-elements.md b/controls/editors/buttontextbox/customizing-appearance/accessing-and-customizing-elements.md index fa54b9f86..72d14f5bc 100644 --- a/controls/editors/buttontextbox/customizing-appearance/accessing-and-customizing-elements.md +++ b/controls/editors/buttontextbox/customizing-appearance/accessing-and-customizing-elements.md @@ -34,29 +34,5 @@ You can customize the nested elements at run time as well: #### Customize elements -{{source=..\SamplesCS\Editors\ButtonTextBox.cs region=CustomizeElements}} -{{source=..\SamplesVB\Editors\ButtonTextBox.vb region=CustomizeElements}} - -````C# -this.radButtonTextBox1.TextBoxElement.ForeColor = Color.Red; -this.radButtonTextBox1.TextBoxElement.BackColor = Color.Yellow; -RadButtonElement button = this.radButtonTextBox1.LeftButtonItems[0] as RadButtonElement; -button.Text = "BUL"; -button.TextImageRelation = TextImageRelation.ImageBeforeText; -button.ButtonFillElement.BackColor = Color.Fuchsia; -button.ShowBorder = false; - -```` -````VB.NET -Me.RadButtonTextBox1.TextBoxElement.ForeColor = Color.Red -Me.RadButtonTextBox1.TextBoxElement.BackColor = Color.Yellow -Dim button As RadButtonElement = TryCast(Me.RadButtonTextBox1.LeftButtonItems(0), RadButtonElement) -button.Text = "BUL" -button.TextImageRelation = TextImageRelation.ImageBeforeText -button.ButtonFillElement.BackColor = Color.Fuchsia -button.ShowBorder = False - -```` - -{{endregion}} - + + \ No newline at end of file diff --git a/controls/editors/buttontextbox/populating-with-items/adding-items-programmatically.md b/controls/editors/buttontextbox/populating-with-items/adding-items-programmatically.md index ae997b414..e86cbb2ed 100644 --- a/controls/editors/buttontextbox/populating-with-items/adding-items-programmatically.md +++ b/controls/editors/buttontextbox/populating-with-items/adding-items-programmatically.md @@ -19,66 +19,10 @@ position: 1 #### Add button elements programmatically -{{source=..\SamplesCS\Editors\ButtonTextBox.cs region=AddItemsProgrammatically}} -{{source=..\SamplesVB\Editors\ButtonTextBox.vb region=AddItemsProgrammatically}} - -````C# -Dictionary glyphs = new Dictionary(); -List buttons = new List(); -glyphs.Add(0, ""); //yammer -glyphs.Add(1, ""); //twitter -glyphs.Add(2, ""); //pinterest -glyphs.Add(3, ""); //google -glyphs.Add(4, ""); //facebook -glyphs.Add(5, ""); //linkedin -glyphs.Add(6, "\ue817"); //Reddit -glyphs.Add(7, "\ue81d"); //Tumbler -glyphs.Add(8, "\ue813"); // MySpace -for (int i = 0; i < 9; i++) -{ - RadButtonElement radButtonElement = new RadButtonElement(); - radButtonElement.DisplayStyle = Telerik.WinControls.DisplayStyle.Text; - radButtonElement.TextElement.CustomFont = "TelerikWebUI"; - radButtonElement.TextElement.CustomFontSize = 10; - radButtonElement.TextElement.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; - radButtonElement.Text = glyphs[i]; - buttons.Add(radButtonElement); -} -radButtonTextBox1.RightButtonItems.AddRange(buttons[0], buttons[1], buttons[3], buttons[4]); -radButtonTextBox1.LeftButtonItems.AddRange(buttons[5], buttons[6], buttons[7], buttons[8]); -radButtonTextBox1.AutoSize = false; -radButtonTextBox1.Text = ""; - -```` -````VB.NET -Dim glyphs As Dictionary(Of Integer, String) = New Dictionary(Of Integer, String)() -Dim buttons As List(Of RadButtonElement) = New List(Of RadButtonElement)() -glyphs.Add(0, "") -glyphs.Add(1, "") -glyphs.Add(2, "") -glyphs.Add(3, "") -glyphs.Add(4, "") -glyphs.Add(5, "") -glyphs.Add(6, "") -glyphs.Add(7, "") -glyphs.Add(8, "") -For i As Integer = 0 To 9 - 1 - Dim radButtonElement As RadButtonElement = New RadButtonElement() - radButtonElement.DisplayStyle = Telerik.WinControls.DisplayStyle.Text - radButtonElement.TextElement.CustomFont = "TelerikWebUI" - radButtonElement.TextElement.CustomFontSize = 10 - radButtonElement.TextElement.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias - radButtonElement.Text = glyphs(i) - buttons.Add(radButtonElement) -Next -RadButtonTextBox1.RightButtonItems.AddRange(buttons(0), buttons(1), buttons(3), buttons(4)) -RadButtonTextBox1.LeftButtonItems.AddRange(buttons(5), buttons(6), buttons(7), buttons(8)) -RadButtonTextBox1.AutoSize = False -RadButtonTextBox1.Text = "" - -```` - -{{endregion}} + + + + The following code snippet demonstrates how to add programmatically different types of elements in **RadButtonTextBox**: @@ -88,95 +32,10 @@ The following code snippet demonstrates how to add programmatically different ty #### Add different elements programmatically -{{source=..\SamplesCS\Editors\ButtonTextBox.cs region=AllItems}} -{{source=..\SamplesVB\Editors\ButtonTextBox.vb region=AllItems}} - -````C# -private void AddDifferentItems() -{ - this.radButtonTextBox1.Multiline = true; - RadButtonElement buttonElement = new RadButtonElement(); - buttonElement.Text = "Button"; - buttonElement.Click += buttonElement_Click; - this.radButtonTextBox1.LeftButtonItems.Add(buttonElement); - RadToggleButtonElement toggleButtonElement = new RadToggleButtonElement(); - toggleButtonElement.Text = "ToggleButton"; - toggleButtonElement.ToggleStateChanged += toggleButtonElement_ToggleStateChanged; - this.radButtonTextBox1.LeftButtonItems.Add(toggleButtonElement); - CommandBarSeparator separator = new CommandBarSeparator(); - this.radButtonTextBox1.LeftButtonItems.Add(separator); - RadRepeatButtonElement repeatButtonElement = new RadRepeatButtonElement(); - repeatButtonElement.Text = "RepeatButton"; - repeatButtonElement.Click += repeatButtonElement_Click; - this.radButtonTextBox1.LeftButtonItems.Add(repeatButtonElement); - RadCheckBoxElement checkBoxElement = new RadCheckBoxElement(); - checkBoxElement.Text = "CheckBox"; - checkBoxElement.CheckStateChanged += checkBoxElement_CheckStateChanged; - this.radButtonTextBox1.RightButtonItems.Add(checkBoxElement); -} -private void checkBoxElement_CheckStateChanged(object sender, EventArgs e) -{ - RadMessageBox.Show("RRadCheckBoxElement is toggled"); -} -private void repeatButtonElement_Click(object sender, EventArgs e) -{ - Console.WriteLine("RadRepeatButtonElement"); -} -private void toggleButtonElement_ToggleStateChanged(object sender, StateChangedEventArgs args) -{ - RadMessageBox.Show("RadToggleButtonElement.ToggleState is changed to " + args.ToggleState.ToString()); -} -private void buttonElement_Click(object sender, EventArgs e) -{ - RadMessageBox.Show("RadButtonElement is clicked"); -} -private void RadForm1_Load(object sender, EventArgs e) -{ - AddDifferentItems(); -} - -```` -````VB.NET -Private Sub AddDifferentItems() - Me.RadButtonTextBox1.Multiline = True - Dim buttonElement As RadButtonElement = New RadButtonElement() - buttonElement.Text = "Button" - AddHandler buttonElement.Click, AddressOf buttonElement_Click - Me.RadButtonTextBox1.LeftButtonItems.Add(buttonElement) - Dim toggleButtonElement As RadToggleButtonElement = New RadToggleButtonElement() - toggleButtonElement.Text = "ToggleButton" - AddHandler toggleButtonElement.ToggleStateChanged, AddressOf toggleButtonElement_ToggleStateChanged - Me.RadButtonTextBox1.LeftButtonItems.Add(toggleButtonElement) - Dim separator As CommandBarSeparator = New CommandBarSeparator() - Me.RadButtonTextBox1.LeftButtonItems.Add(separator) - Dim repeatButtonElement As RadRepeatButtonElement = New RadRepeatButtonElement() - repeatButtonElement.Text = "RepeatButton" - AddHandler repeatButtonElement.Click, AddressOf repeatButtonElement_Click - Me.RadButtonTextBox1.LeftButtonItems.Add(repeatButtonElement) - Dim checkBoxElement As RadCheckBoxElement = New RadCheckBoxElement() - checkBoxElement.Text = "CheckBox" - AddHandler checkBoxElement.CheckStateChanged, AddressOf checkBoxElement_CheckStateChanged - Me.RadButtonTextBox1.RightButtonItems.Add(checkBoxElement) -End Sub -Private Sub checkBoxElement_CheckStateChanged(ByVal sender As Object, ByVal e As EventArgs) - RadMessageBox.Show("RRadCheckBoxElement is toggled") -End Sub -Private Sub repeatButtonElement_Click(ByVal sender As Object, ByVal e As EventArgs) - Console.WriteLine("RadRepeatButtonElement") -End Sub -Private Sub toggleButtonElement_ToggleStateChanged(ByVal sender As Object, ByVal args As StateChangedEventArgs) - RadMessageBox.Show("RadToggleButtonElement.ToggleState is changed to " & args.ToggleState.ToString()) -End Sub -Private Sub buttonElement_Click(ByVal sender As Object, ByVal e As EventArgs) - RadMessageBox.Show("RadButtonElement is clicked") -End Sub -Private Sub RadForm1_Load(ByVal sender As Object, ByVal e As EventArgs) - AddDifferentItems() -End Sub - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/editors/calculatordropdown/customizing-appearance/accessing-and-customizing-elements.md b/controls/editors/calculatordropdown/customizing-appearance/accessing-and-customizing-elements.md index b80f870bc..57fcde103 100644 --- a/controls/editors/calculatordropdown/customizing-appearance/accessing-and-customizing-elements.md +++ b/controls/editors/calculatordropdown/customizing-appearance/accessing-and-customizing-elements.md @@ -15,84 +15,40 @@ This topic will demonstrate how to access different element in the control in or ## Memory Element Visual Customization -{{source=..\SamplesCS\Editors\RadCalculatorDropDownCustomization.cs region=ChangeTheImageOfMemoryElement}} -{{source=..\SamplesVB\Editors\RadCalculatorDropDownCustomization.vb region=ChangeTheImageOfMemoryElement}} + + -````C# -this.radCalculatorDropDown1.CalculatorElement.MemoryElement.Image = Resources.email; -```` -````VB.NET -Me.RadCalculatorDropDown1.CalculatorElement.MemoryElement.Image = My.Resources.email - -```` - -{{endregion}} >caption Figure 1: RadCalculatorMemoryElement Customization ![WinForms RadCalculatorDropDown RadCalculatorMemoryElement Customization](images/editors-calculatordropdown-customization001.png) ## Text Box Visual Customization -{{source=..\SamplesCS\Editors\RadCalculatorDropDownCustomization.cs region=ChangeTheBackColorOfTheTextBox}} -{{source=..\SamplesVB\Editors\RadCalculatorDropDownCustomization.vb region=ChangeTheBackColorOfTheTextBox}} - -````C# -this.radCalculatorDropDown1.CalculatorElement.FillPrimitive.BackColor = Color.Yellow; -this.radCalculatorDropDown1.CalculatorElement.EditorContentElement.Fill.BackColor = Color.Yellow; - -```` -````VB.NET -Me.RadCalculatorDropDown1.CalculatorElement.FillPrimitive.BackColor = Color.Yellow -Me.RadCalculatorDropDown1.CalculatorElement.EditorContentElement.Fill.BackColor = Color.Yellow + + -```` -{{endregion}} >caption Figure 2: Text Box Customization ![WinForms RadCalculatorDropDown Text Box Customization](images/editors-calculatordropdown-customization002.png) ## Calculator Visual Customization -{{source=..\SamplesCS\Editors\RadCalculatorDropDownCustomization.cs region=ChangeTheBackColorOfTheCalculator}} -{{source=..\SamplesVB\Editors\RadCalculatorDropDownCustomization.vb region=ChangeTheBackColorOfTheCalculator}} + + -````C# -this.radCalculatorDropDown1.CalculatorElement.CalculatorContentElement.BackColor = Color.Green; -```` -````VB.NET -Me.RadCalculatorDropDown1.CalculatorElement.CalculatorContentElement.BackColor = Color.Green - -```` - -{{endregion}} >caption Figure 3: Calculator Customization ![WinForms RadCalculatorDropDown Customization](images/editors-calculatordropdown-customization003.png) ## Buttons Visual Customization -{{source=..\SamplesCS\Editors\RadCalculatorDropDownCustomization.cs region=ChangeTheBackColorOfButtons}} -{{source=..\SamplesVB\Editors\RadCalculatorDropDownCustomization.vb region=ChangeTheBackColorOfButtons}} - -````C# -this.radCalculatorDropDown1.CalculatorElement.CalculatorContentElement.ButtonEquals.GradientStyle = Telerik.WinControls.GradientStyles.Solid; -this.radCalculatorDropDown1.CalculatorElement.CalculatorContentElement.ButtonEquals.BackColor = Color.Navy; -this.radCalculatorDropDown1.CalculatorElement.CalculatorContentElement.ButtonDelete.GradientStyle = Telerik.WinControls.GradientStyles.Solid; -this.radCalculatorDropDown1.CalculatorElement.CalculatorContentElement.ButtonDelete.BackColor = Color.Red; - -```` -````VB.NET -Me.RadCalculatorDropDown1.CalculatorElement.CalculatorContentElement.ButtonEquals.GradientStyle = Telerik.WinControls.GradientStyles.Solid -Me.RadCalculatorDropDown1.CalculatorElement.CalculatorContentElement.ButtonEquals.BackColor = Color.Navy -Me.RadCalculatorDropDown1.CalculatorElement.CalculatorContentElement.ButtonDelete.GradientStyle = Telerik.WinControls.GradientStyles.Solid -Me.RadCalculatorDropDown1.CalculatorElement.CalculatorContentElement.ButtonDelete.BackColor = Color.Red + + -```` -{{endregion}} >caption Figure 4: Button Elements Customization ![WinForms RadCalculatorDropDown Button Elements Customization](images/editors-calculatordropdown-customization004.png) diff --git a/controls/editors/calculatordropdown/getting-started.md b/controls/editors/calculatordropdown/getting-started.md index f89427c32..4be399d34 100644 --- a/controls/editors/calculatordropdown/getting-started.md +++ b/controls/editors/calculatordropdown/getting-started.md @@ -42,23 +42,10 @@ The following example demonstrates how to set up __RadCalculatorDropDown__ with 2\. In the constructor of your form add the following code: -{{source=..\SamplesCS\Editors\RadCalculatorDropDownGettingStarted.cs region=MinWidth}} -{{source=..\SamplesVB\Editors\RadCalculatorDropDownGettingStarted.vb region=MinWidth}} + + -````C# -int desiredWidth = this.radCalculatorDropDown1.Width; -this.radCalculatorDropDown1.CalculatorElement.MinPopupWidth = desiredWidth; -this.radCalculatorDropDown1.CalculatorElement.MinPopupHeight = desiredWidth; -```` -````VB.NET -Dim desiredWidth As Integer = Me.RadCalculatorDropDown1.Width -Me.RadCalculatorDropDown1.CalculatorElement.MinPopupWidth = desiredWidth -Me.RadCalculatorDropDown1.CalculatorElement.MinPopupHeight = desiredWidth - -```` - -{{endregion}} 3\. Press __F5__ to run the application. Click the arrow button to open the drop-down. Notice its size equaling that of the editor. diff --git a/controls/editors/colorbox/getting-started.md b/controls/editors/colorbox/getting-started.md index fc32f3ebb..0a2fb7ff7 100644 --- a/controls/editors/colorbox/getting-started.md +++ b/controls/editors/colorbox/getting-started.md @@ -44,28 +44,14 @@ The following example demonstrates how to change the __ForeColor__ of __RadLabe 2\. Select the __RadColorBox__, click the __Events tab__ of the __Property Window__, locate the __ValueChanged__ event and double-click it to create an event handler. Replace the event handler with the following code. -{{source=..\SamplesCS\Editors\ColorBox1.cs region=colorBoxValueChanged}} -{{source=..\SamplesVB\Editors\ColorBox1.vb region=colorBoxValueChanged}} + + -````C# -private void radColorBox1_ValueChanged(object sender, EventArgs e) -{ - this.radLabel1.ForeColor = this.radColorBox1.Value; -} -```` -````VB.NET -Private Sub RadColorBox1_ValueChanged(sender As Object, e As EventArgs) - Me.RadLabel1.ForeColor = Me.RadColorBox1.Value -End Sub -```` - -{{endregion}} - 3\. Press __F5__ to run the application. Press the color dialog button and select a color. The color is then applied as __ForeColor__ of the __RadLabel__. -#№ See Also +## See Also * [Design Time]({%slug winforms/editors/design-time%}) * [Structure]({%slug winforms/editors/structure%}) diff --git a/controls/editors/colorbox/properies-and-events.md b/controls/editors/colorbox/properies-and-events.md index 9a68bd7d2..cd74f25c6 100644 --- a/controls/editors/colorbox/properies-and-events.md +++ b/controls/editors/colorbox/properies-and-events.md @@ -31,25 +31,11 @@ The __ValueChanging__ event fires before the value is changed and allows you to #### Cancel ValueChanging. -{{source=..\SamplesCS\Editors\ColorBox1.cs region=colorBoxValueChanging}} -{{source=..\SamplesVB\Editors\ColorBox1.vb region=colorBoxValueChanging}} - -````C# -private void radColorBox1_ValueChanging(object sender, Telerik.WinControls.UI.ValueChangingEventArgs e) -{ - e.Cancel = !((Color)e.NewValue).IsNamedColor; -} - -```` -````VB.NET -Private Sub RadColorBox1_ValueChanging(sender As Object, e As Telerik.WinControls.UI.ValueChangingEventArgs) - e.Cancel = Not DirectCast(e.NewValue, System.Drawing.Color).IsNamedColor -End Sub - -```` - -{{endregion}} - + + + + + # See Also * [Properties](https://docs.telerik.com/devtools/winforms/api/telerik.wincontrols.ui.radcolorbox.html#properties) diff --git a/controls/editors/dateonlypicker/how-to/set-null-or-empty-value.md b/controls/editors/dateonlypicker/how-to/set-null-or-empty-value.md index 90df413aa..7da12699b 100644 --- a/controls/editors/dateonlypicker/how-to/set-null-or-empty-value.md +++ b/controls/editors/dateonlypicker/how-to/set-null-or-empty-value.md @@ -14,57 +14,27 @@ __RadDateOnlyPicker__ has __NullableValue__ property which supports *null* value #### Set to null -{{source=..\SamplesCS\Editors\DateOnlyPicker.cs region=SetToNullValue}} -{{source=..\SamplesVB\Editors\DateOnlyPicker.vb region=SetToNullValue}} + + -````C# -this.radDateOnlyPicker1.NullableValue = null; -this.radDateOnlyPicker1.SetToNullValue(); -```` -````VB.NET -Me.RadDateOnlyPicker1.NullableValue = Nothing -Me.RadDateOnlyPicker1.SetToNullValue() -```` - -{{endregion}} - If you set the __NullText__ property, you can conditionally display a text based on the selected date. The null text will be displayed when the __NullableValue__ is null or when the __NullDate__ property value matches the current value. #### Setting the NullText property of RadDateOnlyPicker -{{source=..\SamplesCS\Editors\DateOnlyPicker.cs region=NullText}} -{{source=..\SamplesVB\Editors\DateOnlyPicker.vb region=NullText}} - -````C# -this.radDateOnlyPicker1.NullText = "No date selected"; + + -```` -````VB.NET -Me.RadDateOnlyPicker1.NullText = "No date selected" -```` -{{endregion}} - When the __NullDate__ property value is equal to the control value no text will be displayed in the text box part (if the __NullText__ is set it will appear). The default value of the property is __MinDate__, which is *1/1/1*. Below is the code snippet for setting __NullDate__ to a specific date (*01-01-2024*): #### Setting the NullDate property of RadDateOnlyPicker -{{source=..\SamplesCS\Editors\DateOnlyPicker.cs region=NullDate}} -{{source=..\SamplesVB\Editors\DateOnlyPicker.vb region=NullDate}} - -````C# -this.radDateOnlyPicker1.DateOnlyPickerElement.NullDate = new DateOnly(2024, 01, 01); - -```` -````VB.NET -Me.RadDateOnlyPicker1.DateOnlyPickerElement.NullDate = New DateOnly(2024, 1, 1) - -```` + + -{{endregion}} ## See Also diff --git a/controls/editors/dateonlypicker/properties-events.md b/controls/editors/dateonlypicker/properties-events.md index 76fd7ca9e..0078e370a 100644 --- a/controls/editors/dateonlypicker/properties-events.md +++ b/controls/editors/dateonlypicker/properties-events.md @@ -16,132 +16,47 @@ The significant properties for __RadDateOnlyPicker__ are: #### Setting the value of RadDateOnlyPicker -{{source=..\SamplesCS\Editors\DateOnlyPicker.cs region=Value}} -{{source=..\SamplesVB\Editors\DateOnlyPicker.vb region=Value}} + + -````C# -this.radDateOnlyPicker1.Value = new DateOnly(2024,1,1); -```` -````VB.NET -Me.RadDateOnlyPicker1.Value = New DateOnly(2024,1,1) -```` - -{{endregion}} - * __MinDate, MaxDate:__ These two __DateOnly__ type properties form the bounds that dates can be selected from in the picker. Attempts to select outside these bounds are ignored. #### Setting the MinDate property of RadDateOnlyPicker -{{source=..\SamplesCS\Editors\DateOnlyPicker.cs region=MinMaxDate}} -{{source=..\SamplesVB\Editors\DateOnlyPicker.vb region=MinMaxDate}} - -````C# -this.radDateOnlyPicker1.MinDate = new DateOnly(2024,10,1); -this.radDateOnlyPicker1.MaxDate = new DateOnly(2024,10,31); + + -```` -````VB.NET -Me.RadDateOnlyPicker1.MinDate = New DateOnly(2024,10,1) -Me.RadDateOnlyPicker1.MaxDate = New DateOnly(2024,10,31) -```` -{{endregion}} - * __NullableValue__ is same as the __Value__ property, but the __NullableValue__ property is of type *Nullable DateOnly*. It can be *null* – in this case if **RadDateOnlyPicker** is not selected, it will show its __NullText__. In case **RadDateOnlyPicker** is selected, it will show the last entered date – this allows the end-user to enter and edit the date. #### Setting the NullableValue property of RadDateOnlyPicker -{{source=..\SamplesCS\Editors\DateOnlyPicker.cs region=NullableValue}} -{{source=..\SamplesVB\Editors\DateOnlyPicker.vb region=NullableValue}} - -````C# -this.radDateOnlyPicker1.NullableValue = null; + + -```` -````VB.NET -Me.RadDateOnlyPicker1.NullableValue = Nothing -```` -{{endregion}} - __NullableValue__ can be bound to a business object that exposes a property of type nullable DateOnly. The code below demonstrates how to do this: #### Bind the NullableValue to a business object. -{{source=..\SamplesCS\Editors\DateOnlyPicker.cs region=NullableBinding}} -{{source=..\SamplesVB\Editors\DateOnlyPicker.vb region=NullableBinding}} - -````C# -public class MyObject -{ - public MyObject(DateOnly? _endTime) - { - this._endTime = _endTime; - } - private DateOnly? _endTime; - public DateOnly? EndTime - { - get { return _endTime; } - set { _endTime = value; } - } -} - -protected override void OnLoad(EventArgs e) -{ - base.OnLoad(e); - MyObject myObject = new MyObject(DateOnly.FromDateTime(DateTime.Now.AddDays(1))); - this.radDateOnlyPicker1.DataBindings.Add(new Binding("NullableValue", myObject, "EndTime", true, DataSourceUpdateMode.OnPropertyChanged)); -} - -```` -````VB.NET -Public Class MyObject - Public Sub New(ByVal _endTime? As DateOnly) - Me._endTime = _endTime - End Sub - Private _endTime? As DateOnly - Public Property EndTime() As DateOnly? - Get - Return _endTime - End Get - Set(ByVal value? As DateOnly) - _endTime = value - End Set - End Property -End Class - -Protected Overrides Sub OnLoad(ByVal e As EventArgs) - MyBase.OnLoad(e) - Dim myObject As MyObject = New MyObject(DateOnly.FromDateTime(DateTime.Now.AddDays(1))) - Me.radDateOnlyPicker1.DataBindings.Add(New Binding("NullableValue", myObject, "EndTime", True, DataSourceUpdateMode.OnPropertyChanged)) -End Sub - -```` - -{{endregion}} - + + + + + * __NullText:__ This property defines the text that will be displayed in **RadDateOnlyPicker** when the __NullableValue__ property is set to *null* and **RadDateOnlyPicker** is not in focus. By default, __NullText__ is an empty string. #### Setting the NullText property of RadDateOnlyPicker -{{source=..\SamplesCS\Editors\DateOnlyPicker.cs region=NullText}} -{{source=..\SamplesVB\Editors\DateOnlyPicker.vb region=NullText}} + + -````C# -this.radDateOnlyPicker1.NullText = "No date selected"; -```` -````VB.NET -Me.RadDateOnlyPicker1.NullText = "No date selected" -```` - -{{endregion}} - * __TextBoxElement__: Gets an instance of RadTextBoxElement. * __ArrowButton__: Gets an instance of RadArrowButtonElement. diff --git a/controls/editors/datetimepicker/MaskDateTimeProvider.md b/controls/editors/datetimepicker/MaskDateTimeProvider.md index 1a3c9c9b1..b000a5d5d 100644 --- a/controls/editors/datetimepicker/MaskDateTimeProvider.md +++ b/controls/editors/datetimepicker/MaskDateTimeProvider.md @@ -26,21 +26,10 @@ The MaskDateTimeProvider is responsible for the parsing of the dates. The MaskDa The following code spinet demonstrates how one can access and use the provider: -{{source=..\SamplesCS\Editors\DateTimePicker2.cs region=provider}} -{{source=..\SamplesVB\Editors\DateTimePicker2.vb region=provider}} + + -````C# -MaskDateTimeProvider provider = this.radDateTimePicker1.DateTimePickerElement.TextBoxElement.Provider as MaskDateTimeProvider; -provider.AutoSelectNextPart = true; -```` -````VB.NET -Dim provider As MaskDateTimeProvider = TryCast(Me.radDateTimePicker1.DateTimePickerElement.TextBoxElement.Provider, MaskDateTimeProvider) -provider.AutoSelectNextPart = True - -```` - -{{endregion}} >note The __MaskProviderCreated__ event will be fired each time when new provider instance is created. For example when the MaskType is changed. diff --git a/controls/editors/datetimepicker/customizing-appearance/customize-radcalendar-programmatically.md b/controls/editors/datetimepicker/customizing-appearance/customize-radcalendar-programmatically.md index 83109e1b1..8742c8569 100644 --- a/controls/editors/datetimepicker/customizing-appearance/customize-radcalendar-programmatically.md +++ b/controls/editors/datetimepicker/customizing-appearance/customize-radcalendar-programmatically.md @@ -16,51 +16,10 @@ In order to customize __RadCalendar__ in __RadDateTimePicker__, you should first #### Changing the font of RadCalendar navigation title -{{source=..\SamplesCS\Editors\DateTimePicker1.cs region=customizeRadCalendarProgramatically}} -{{source=..\SamplesVB\Editors\DateTimePicker1.vb region=customizeRadCalendarProgramatically}} - -````C# -Font headerFont = new Font("Arial", 9.0f, FontStyle.Bold); -Font datesFont = new Font("Arial", 9.0f, FontStyle.Italic); -RadDateTimePickerCalendar calendarBehavior = this.radDateTimePicker1.DateTimePickerElement.GetCurrentBehavior() as RadDateTimePickerCalendar; -RadCalendar calendar = calendarBehavior.Calendar as RadCalendar; -RadCalendarElement calendarElement = calendar.CalendarElement as RadCalendarElement; -calendarElement.CalendarNavigationElement.Font = headerFont; -calendarElement.CalendarNavigationElement.ForeColor = Color.Yellow; -calendarElement.CalendarNavigationElement.BackColor = Color.White; -calendarElement.CalendarNavigationElement.BackColor2 = Color.Gray; -calendarElement.CalendarNavigationElement.BackColor3 = Color.DarkGray; -calendarElement.CalendarNavigationElement.BackColor4 = Color.Gainsboro; -calendarElement.CalendarNavigationElement.BorderColor = Color.DarkGray; -MonthViewElement monthView = calendarBehavior.Calendar.CalendarElement.CalendarVisualElement as MonthViewElement; -foreach (RadItem item in monthView.TableElement.Children) -{ - item.Font = datesFont; -} - -```` -````VB.NET -Dim headerFont As Font = New Font("Arial", 9.0F, FontStyle.Bold) -Dim datesFont As Font = New Font("Arial", 9.0F, FontStyle.Italic) -Dim calendarBehavior As RadDateTimePickerCalendar = TryCast(Me.RadDateTimePicker1.DateTimePickerElement.GetCurrentBehavior(), RadDateTimePickerCalendar) -Dim calendar As RadCalendar = TryCast(calendarBehavior.Calendar, RadCalendar) -Dim calendarElement As RadCalendarElement = TryCast(calendar.CalendarElement, RadCalendarElement) -calendarElement.CalendarNavigationElement.Font = headerFont -calendarElement.CalendarNavigationElement.ForeColor = Color.Yellow -calendarElement.CalendarNavigationElement.BackColor = Color.White -calendarElement.CalendarNavigationElement.BackColor2 = Color.Gray -calendarElement.CalendarNavigationElement.BackColor3 = Color.DarkGray -calendarElement.CalendarNavigationElement.BackColor4 = Color.Gainsboro -calendarElement.CalendarNavigationElement.BorderColor = Color.DarkGray -Dim monthView As MonthViewElement = TryCast(calendarBehavior.Calendar.CalendarElement.CalendarVisualElement, MonthViewElement) -For Each item As RadItem In monthView.TableElement.Children - item.Font = datesFont -Next item - -```` - -{{endregion}} - + + + + >caption Figure 1: The result from the above code: @@ -71,21 +30,10 @@ Next item The Clear and Today buttons of the calendar are located in its footer. The footer of the calendar is hidden in the RadDateTimePicker control. To show it, we need to call the __GetCurrentBehavior__() method to gen an instance of the RadCalendar inside the RadDateTimePicker control. -{{source=..\SamplesCS\Editors\DateTimePicker1.cs region=showCalendarFooter}} -{{source=..\SamplesVB\Editors\DateTimePicker1.vb region=showCalendarFooter}} - -````C# -RadDateTimePickerCalendar calendarBehavior = this.radDateTimePicker1.DateTimePickerElement.GetCurrentBehavior() as RadDateTimePickerCalendar; -calendarBehavior.Calendar.ShowFooter = true; - -```` -````VB.NET -Dim calendarBehavior As RadDateTimePickerCalendar = TryCast(Me.radDateTimePicker1.DateTimePickerElement.GetCurrentBehavior(), RadDateTimePickerCalendar) -calendarBehavior.Calendar.ShowFooter = True + + -```` -{{endregion}} ![WinForms RadDateTimePicker Show Clear Today Buttons](images/datetimepicker-calendar-footer002.png) diff --git a/controls/editors/datetimepicker/free-form-date-time-parsing.md b/controls/editors/datetimepicker/free-form-date-time-parsing.md index f2e408e8b..3824d9ed2 100644 --- a/controls/editors/datetimepicker/free-form-date-time-parsing.md +++ b/controls/editors/datetimepicker/free-form-date-time-parsing.md @@ -17,21 +17,11 @@ You can read more about this parsing logic [here]({%slug winforms/editors/masked #### Setting the value of RadDateTimePicker -{{source=..\SamplesCS\Editors\DateTimePicker2.cs region=FreeFormDateTimeDateTimePicker}} -{{source=..\SamplesVB\Editors\DateTimePicker2.vb region=FreeFormDateTimeDateTimePicker}} - -````C# -this.radDateTimePicker1.DateTimePickerElement.TextBoxElement.MaskType = MaskType.FreeFormDateTime; - -```` -````VB.NET -Me.radDateTimePicker1.DateTimePickerElement.TextBoxElement.MaskType = MaskType.FreeFormDateTime - -```` - -{{endregion}} - - + + + + + # See Also * [Design Time]({%slug winforms/editors/datetimepicker/designtime%}) diff --git a/controls/editors/datetimepicker/how-to/set-null-or-empty-value.md b/controls/editors/datetimepicker/how-to/set-null-or-empty-value.md index 6d8ad748d..c84db3319 100644 --- a/controls/editors/datetimepicker/how-to/set-null-or-empty-value.md +++ b/controls/editors/datetimepicker/how-to/set-null-or-empty-value.md @@ -15,57 +15,27 @@ __RadDateTimePicker__ now has __NullableValue__ property which supports *null* v #### Set to null -{{source=..\SamplesCS\Editors\DateTimePicker1.cs region=SetToNullValue}} -{{source=..\SamplesVB\Editors\DateTimePicker1.vb region=SetToNullValue}} + + -````C# -this.radDateTimePicker1.NullableValue = null; -this.radDateTimePicker1.SetToNullValue(); -```` -````VB.NET -Me.RadDateTimePicker1.NullableValue = Nothing -Me.RadDateTimePicker1.DateTimePickerElement.SetToNullValue() -```` - -{{endregion}} - If you set the __NullText__ property, you can conditionally display a text based on the selected date. The null text will be displayed when the __NullableValue__ is null or when the __NullDate__ property value matches the current value. #### Setting the NullText property of RadDateTimePicker -{{source=..\SamplesCS\Editors\DateTimePicker1.cs region=NullText}} -{{source=..\SamplesVB\Editors\DateTimePicker1.vb region=NullText}} - -````C# -this.radDateTimePicker1.NullText = "No date selected"; + + -```` -````VB.NET -Me.RadDateTimePicker1.NullText = "No date selected" -```` -{{endregion}} - When the __NullDate__ property value is equal to the control value no text will be displayed in the text box part (if the __NullText__ is set it will appear). The default value of the property is __MinDate__, which is *1/1/1900*. Below is the code snippet for setting __NullDate__ to a specific date (*01-01-2000*): #### Setting the NullDate property of RadDateTimePicker -{{source=..\SamplesCS\Editors\DateTimePicker1.cs region=NullDate}} -{{source=..\SamplesVB\Editors\DateTimePicker1.vb region=NullDate}} - -````C# -this.radDateTimePicker1.DateTimePickerElement.NullDate = new DateTime(2000, 01, 01); - -```` -````VB.NET -Me.RadDateTimePicker1.DateTimePickerElement.NullDate = New DateTime(2000, 1, 1) - -```` + + -{{endregion}} # See Also diff --git a/controls/editors/datetimepicker/how-to/tweak-increment-step.md b/controls/editors/datetimepicker/how-to/tweak-increment-step.md index 4347eefca..4ec35264a 100644 --- a/controls/editors/datetimepicker/how-to/tweak-increment-step.md +++ b/controls/editors/datetimepicker/how-to/tweak-increment-step.md @@ -19,118 +19,27 @@ When the user clicks the up/down arrow buttons or presses the arrow keys, the __ As a prerequisite for the example, __RadDateTimePicker__ should of course show minutes and to demonstrate the full power of the example, we also may want to show up/down arrow buttons instead of a dropdown button. To these customizations, we need to add the following code: -{{source=..\SamplesCS\Editors\DateTimePicker1.cs region=prerequisite}} -{{source=..\SamplesVB\Editors\DateTimePicker1.vb region=prerequisite}} + + -````C# -this.radDateTimePicker1.CustomFormat = "hh:mm"; -this.radDateTimePicker1.Format = System.Windows.Forms.DateTimePickerFormat.Custom; -this.radDateTimePicker1.ShowUpDown = true; -```` -````VB.NET -Me.RadDateTimePicker1.CustomFormat = "hh:mm" -Me.RadDateTimePicker1.Format = System.Windows.Forms.DateTimePickerFormat.Custom -Me.RadDateTimePicker1.ShowUpDown = True -```` - -{{endregion}} - Here is the approach divided into separate steps: 1\. In the form's `Load` event handler subscribe to the __ValueChanged__ event of RadDateTimePicker. Define a DateTime variable globally which holds the initial value: -{{source=..\SamplesCS\Editors\DateTimePicker1.cs region=initialization}} -{{source=..\SamplesVB\Editors\DateTimePicker1.vb region=initialization}} + + -````C# -DateTime initialDateTime; -private void Form1_Load(object sender, EventArgs e) -{ - initialDateTime = this.radDateTimePicker1.Value; - this.radDateTimePicker1.ValueChanged += new EventHandler(radDateTimePicker1_ValueChanged); -} -```` -````VB.NET -Private initialDateTime As Date -Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load - initialDateTime = Me.RadDateTimePicker1.Value - AddHandler RadDateTimePicker1.ValueChanged, AddressOf radDateTimePicker1_ValueChanged -End Sub -```` - -{{endregion}} - 2\. Here comes the ValueChanged handler implementation. In this part we are first checking whether the new value of RadDateTimePicker is bigger than the old one or not. Then, we are getting the MaskDateTimeProvider responsible for the navigation between the date/time parts - hours, minutes, etc. If the provider states that the currently selected time part is minutes, we, depending on the the direction in which we want to change the value, call the __Up/Down__ method four times, so that we can have a step of 5 minutes as a result. Please note that we are setting and resetting the boolean flag __suspendValueChanged__ so that we can safely call __Up/Down__ methods: -{{source=..\SamplesCS\Editors\DateTimePicker1.cs region=valueChanged}} -{{source=..\SamplesVB\Editors\DateTimePicker1.vb region=valueChanged}} - -````C# -bool suspendValueChanged = false; -void radDateTimePicker1_ValueChanged(object sender, EventArgs e) -{ - DateTime dt = this.radDateTimePicker1.Value; - TimeSpan sp = dt - initialDateTime; - if (!suspendValueChanged) - { - MaskDateTimeProvider provider = (this.radDateTimePicker1.DateTimePickerElement.TextBoxElement.Provider as MaskDateTimeProvider); - if (provider.List[provider.SelectedItemIndex].type == PartTypes.Minutes) - { - suspendValueChanged = true; - if (sp.Ticks < 0) - { - for (int i = 0; i < 4; ++i) - { - this.radDateTimePicker1.DateTimePickerElement.TextBoxElement.Down(); - } - } - if (sp.Ticks > 0) - { - for (int i = 0; i < 4; ++i) - { - this.radDateTimePicker1.DateTimePickerElement.TextBoxElement.Up(); - } - } - initialDateTime = this.radDateTimePicker1.Value; - suspendValueChanged = false; - } - } -} - -```` -````VB.NET -Private suspendValueChanged As Boolean = False -Private Sub radDateTimePicker1_ValueChanged(ByVal sender As Object, ByVal e As EventArgs) - Dim dt As Date = Me.RadDateTimePicker1.Value - Dim sp As TimeSpan = dt.Subtract(initialDateTime) - If Not suspendValueChanged Then - Dim provider As MaskDateTimeProvider = (TryCast(Me.RadDateTimePicker1.DateTimePickerElement.TextBoxElement.Provider, MaskDateTimeProvider)) - If provider.List(provider.SelectedItemIndex).type = PartTypes.Minutes Then - suspendValueChanged = True - If sp.Ticks < 0 Then - For i As Integer = 0 To 3 - Me.RadDateTimePicker1.DateTimePickerElement.TextBoxElement.Down() - Next i - End If - If sp.Ticks > 0 Then - For i As Integer = 0 To 3 - Me.RadDateTimePicker1.DateTimePickerElement.TextBoxElement.Up() - Next i - End If - initialDateTime = Me.RadDateTimePicker1.Value - suspendValueChanged = False - End If - End If -End Sub - -```` - -{{endregion}} - + + + + + The result is shown below. Just with a single click of the up arrow key, we increase the value of the minutes by 5: ![WinForms RadDateTimePicker Tweak Increment Step](images/editors-maskededitbox-how-to-tweak-increment-step001.gif) diff --git a/controls/editors/datetimepicker/internationalization/cultureinfo-and-regioninfo-basics.md b/controls/editors/datetimepicker/internationalization/cultureinfo-and-regioninfo-basics.md index 882522d6b..a88df88f9 100644 --- a/controls/editors/datetimepicker/internationalization/cultureinfo-and-regioninfo-basics.md +++ b/controls/editors/datetimepicker/internationalization/cultureinfo-and-regioninfo-basics.md @@ -40,19 +40,10 @@ The table below is a sample list of the names and identifiers found in the Cult ![WinForms RadDateTimePicker Setting Arabic Culture](images/editors-datetimepicker-internationalization-cultureinfo-and-regioninfo-basics001.png) -{{source=..\SamplesCS\Editors\DateTimePicker1.cs region=SetPashtoCulture}} -{{source=..\SamplesVB\Editors\DateTimePicker1.vb region=SetPashtoCulture}} + + -````C# -this.radDateTimePicker1.Culture = new System.Globalization.CultureInfo("ps-AF"); -```` -````VB.NET -Me.RadDateTimePicker1.Culture = New System.Globalization.CultureInfo("ps-AF") - -```` - -{{endregion}} >note There is a known issue in the .NET Framework considering the "fa-IR" culture. Please refer to the following MSDN resource for a solution: > diff --git a/controls/editors/datetimepicker/internationalization/date-formats.md b/controls/editors/datetimepicker/internationalization/date-formats.md index 19002567a..770882d90 100644 --- a/controls/editors/datetimepicker/internationalization/date-formats.md +++ b/controls/editors/datetimepicker/internationalization/date-formats.md @@ -59,21 +59,10 @@ The table below shows a list of patterns that can be combined to create custo >note It is possible to define your own format and set the RadDateTimePicker.**Format** property to **Custom** . Then, specify the desired **CustomFormat**, e.g. "**dd/MM/yyyy**". -{{source=..\SamplesCS\Editors\DateTimePicker2.cs region=customFormat}} -{{source=..\SamplesVB\Editors\DateTimePicker2.vb region=customFormat}} + + -````C# -this.radDateTimePicker1.Format = DateTimePickerFormat.Custom; -this.radDateTimePicker1.CustomFormat = "yyyy/MM/dd"; -```` -````VB.NET -Me.radDateTimePicker1.Format = DateTimePickerFormat.Custom -Me.radDateTimePicker1.CustomFormat = "yyyy/MM/dd" - -```` - -{{endregion}} # See Also diff --git a/controls/editors/datetimepicker/internationalization/internationalization.md b/controls/editors/datetimepicker/internationalization/internationalization.md index 4549c6a4c..027c47661 100644 --- a/controls/editors/datetimepicker/internationalization/internationalization.md +++ b/controls/editors/datetimepicker/internationalization/internationalization.md @@ -15,19 +15,10 @@ RadCalendar provides built in internationalization support to build world-ready \* The __Culture__ property can be set using the drop down list in the Properties Window or set in code. The screenshot below shows the __Culture__ property set to "German(Germany)". -{{source=..\SamplesCS\Editors\DateTimePicker1.cs region=culture}} -{{source=..\SamplesVB\Editors\DateTimePicker1.vb region=culture}} + + -````C# -this.radDateTimePicker1.Culture = new System.Globalization.CultureInfo("de-DE"); -```` -````VB.NET -Me.RadDateTimePicker1.Culture = New System.Globalization.CultureInfo("de-DE") - -```` - -{{endregion}} >caption Figure 1: The culture is changed to German. @@ -38,38 +29,20 @@ Me.RadDateTimePicker1.Culture = New System.Globalization.CultureInfo("de-DE") * Right-to-Left = No (default value) -{{source=..\SamplesCS\Editors\DateTimePicker1.cs region=rightNo}} -{{source=..\SamplesVB\Editors\DateTimePicker1.vb region=rightNo}} - -````C# -this.radDateTimePicker1.RightToLeft = RightToLeft.No; - -```` -````VB.NET -Me.RadDateTimePicker1.RightToLeft = RightToLeft.No + + -```` -{{endregion}} >caption Figure 2: The right to left support is turned off. ![WinForms RadDateTimePicker Right to Left Off](images/editors-datetimepicker-internationalization002.png) \* Right-to-Left = Yes -{{source=..\SamplesCS\Editors\DateTimePicker1.cs region=rightYes}} -{{source=..\SamplesVB\Editors\DateTimePicker1.vb region=rightYes}} + + -````C# -this.radDateTimePicker1.RightToLeft = RightToLeft.Yes; -```` -````VB.NET -Me.RadDateTimePicker1.RightToLeft = RightToLeft.Yes - -```` - -{{endregion}} >caption Figure 3: The right to left support is turned on. @@ -77,21 +50,10 @@ Me.RadDateTimePicker1.RightToLeft = RightToLeft.Yes \* [Date Format Pattern]({%slug winforms/editors/datetimepicker/internationalization/date-formats%}): The __Format__ property has valid values of __Short__, __Long__, __Time__ and __Custom__. The __Custom__enables the __CustomFormat__ property. -{{source=..\SamplesCS\Editors\DateTimePicker1.cs region=customFormat}} -{{source=..\SamplesVB\Editors\DateTimePicker1.vb region=customFormat}} - -````C# -this.radDateTimePicker1.Format = DateTimePickerFormat.Custom; -this.radDateTimePicker1.CustomFormat = "MMM - dd - yyyy"; - -```` -````VB.NET -Me.RadDateTimePicker1.Format = DateTimePickerFormat.Custom -Me.RadDateTimePicker1.CustomFormat = "MMM - dd - yyyy" + + -```` -{{endregion}} >caption Figure 4: Using Custom Format diff --git a/controls/editors/datetimepicker/navigation-modes.md b/controls/editors/datetimepicker/navigation-modes.md index 3a172ae5d..a063de0db 100644 --- a/controls/editors/datetimepicker/navigation-modes.md +++ b/controls/editors/datetimepicker/navigation-modes.md @@ -20,19 +20,10 @@ The embedded __RadCalendar__ has `HeaderNavigationMode` property, which determin #### Setting the value of RadDateTimePicker -{{source=..\SamplesCS\Editors\DateTimePicker2.cs region=HeaderNavigationMode}} -{{source=..\SamplesVB\Editors\DateTimePicker2.vb region=HeaderNavigationMode}} + + -````C# -this.radDateTimePicker1.DateTimePickerElement.Calendar.HeaderNavigationMode = HeaderNavigationMode.Zoom; -```` -````VB.NET -Me.radDateTimePicker1.DateTimePickerElement.Calendar.HeaderNavigationMode = HeaderNavigationMode.Zoom - -```` - -{{endregion}} ![WinForms RadDateTimePicker Value Property](images/editors-datetimepicker-navigation-modes002.gif) diff --git a/controls/editors/datetimepicker/raddatetimepicker-properties.md b/controls/editors/datetimepicker/raddatetimepicker-properties.md index 376b27a13..b5d608df8 100644 --- a/controls/editors/datetimepicker/raddatetimepicker-properties.md +++ b/controls/editors/datetimepicker/raddatetimepicker-properties.md @@ -17,72 +17,30 @@ The significant properties for __RadDateTimePicker__ are: #### Setting the value of RadDateTimePicker -{{source=..\SamplesCS\Editors\DateTimePicker1.cs region=Value}} -{{source=..\SamplesVB\Editors\DateTimePicker1.vb region=Value}} + + -````C# -this.radDateTimePicker1.Value = DateTime.Today.AddDays(1); - -```` -````VB.NET -Me.RadDateTimePicker1.Value = DateTime.Now.AddDays(1) - -```` - -{{endregion}} - * __MinDate, MaxDate:__ These two dates form the bounds that dates can be selected from in the picker. Attempts to select outside these bounds are ignored. The example below sets the __MinDate__ property to be the first day of the current month. #### Setting the MinDate property of RadDateTimePicker -{{source=..\SamplesCS\Editors\DateTimePicker1.cs region=MinDate}} -{{source=..\SamplesVB\Editors\DateTimePicker1.vb region=MinDate}} - -````C# -this.radDateTimePicker1.MinDate = DateTime.Today.AddDays(-DateTime.Today.Day); - -```` -````VB.NET -Me.RadDateTimePicker1.MinDate = DateTime.Today.AddDays(-DateTime.Today.Day) - -```` + + -{{endregion}} - * __NullText:__ This property defines the text that will be displayed in **RadDateTimePicker** when the __NullableValue__ property is set to *null* and **RadDateTimePicker** is not in focus. By default, __NullText__ is an empty string. -#### Setting the NullText property of RadDateTimePicker - -{{source=..\SamplesCS\Editors\DateTimePicker1.cs region=NullText}} -{{source=..\SamplesVB\Editors\DateTimePicker1.vb region=NullText}} - -````C# -this.radDateTimePicker1.NullText = "No date selected"; - -```` -````VB.NET -Me.RadDateTimePicker1.NullText = "No date selected" - -```` - -{{endregion}} +#### Setting the NullText property of RadDateTimePicker + +* __ShowTimePicker:__ Gets or sets a value indicating whether the time picker is displayed alongside the calendar in the drop-down popup of __RadDateTimePicker__. The default value is *false*. When set to *true*, selecting a date in the calendar does not auto-close the popup, allowing the user to also select a time. -* __ShowTimePicker:__ Gets or sets a value indicating whether the time picker is displayed alongside the calendar in the drop-down popup of __RadDateTimePicker__. The default value is *false*. When set to *true*, selecting a date in the calendar does not auto-close the popup, allowing the user to also select a time. + + -{{source=..\SamplesCS\Editors\DateTimePicker2.cs region=ShowTimePicker1}} -{{source=..\SamplesVB\Editors\DateTimePicker2.vb region=ShowTimePicker1}} +* __ShowTimePicker:__ this property determines the display of __TimePicker__ in popup element of __RadDateTimePicker__. -````C# -this.radDateTimePicker1.DateTimePickerElement.ShowTimePicker = true; + + -```` -````VB.NET -Me.radDateTimePicker1.DateTimePickerElement.ShowTimePicker = True - -```` - -{{endregion}} - * __Format:__ The __DateTimePickerFormat__ enumeration values are __Long__, __Short__, __Time__ and __Custom__. Set __Format__ to __Custom__ to enable the __CustomFormat__ property. @@ -113,108 +71,24 @@ Me.radDateTimePicker1.DateTimePickerElement.CalendarSize = New Size(300, 300) #### Setting the NullableValue property of RadDateTimePicker -{{source=..\SamplesCS\Editors\DateTimePicker1.cs region=NullableValue}} -{{source=..\SamplesVB\Editors\DateTimePicker1.vb region=NullableValue}} - -````C# -this.radDateTimePicker1.NullableValue = null; - -```` -````VB.NET -Me.RadDateTimePicker1.NullableValue = Nothing - -```` + + -{{endregion}} - __NullableValue__ can be bound to a business object that exposes a property of type nullable DateTime. The code below demonstrates how to do this: #### Bind the NullableValue to a business object. -{{source=..\SamplesCS\Editors\DateTimePicker1.cs region=NullableBinding}} -{{source=..\SamplesVB\Editors\DateTimePicker1.vb region=NullableBinding}} - -````C# -public class MyObject -{ - public MyObject(DateTime? _endTime) - { - this._endTime = _endTime; - } - private DateTime? _endTime; - public DateTime? EndTime - { - get { return _endTime; } - set { _endTime = value; } - } -} -private BindingList myList; -protected override void OnLoad(EventArgs e) -{ - base.OnLoad(e); - myList = new BindingList(); - myList.Add(new MyObject(null)); - myList.Add(new MyObject(DateTime.Now)); - myList.RaiseListChangedEvents = true; - this.radDateTimePicker1.DataBindings.Add(new Binding("NullableValue", this.myList, "EndTime", true, DataSourceUpdateMode.OnPropertyChanged)); -} - -```` -````VB.NET -Public Class MyObject - Public Sub New(ByVal _endTime? As Date) - Me._endTime = _endTime - End Sub - Private _endTime? As Date - Public Property EndTime() As Date? - Get - Return _endTime - End Get - Set(ByVal value? As Date) - _endTime = value - End Set - End Property -End Class -Private myList As BindingList(Of MyObject) -Protected Overrides Sub OnLoad(ByVal e As EventArgs) - MyBase.OnLoad(e) - myList = New BindingList(Of MyObject)() - myList.Add(New MyObject(Nothing)) - myList.Add(New MyObject(Date.Now)) - myList.RaiseListChangedEvents = True - Me.RadDateTimePicker1.DataBindings.Add(New Binding("NullableValue", Me.myList, "EndTime", True, DataSourceUpdateMode.OnPropertyChanged)) -End Sub - -```` + + -{{endregion}} - * __Editing Time in RadDateTimePicker__ To use **RadDateTimePicker** as date and time editor you need to enable the embedded __TimePicker__ and set the desired mask that shows the time parts. #### Enable the time picker. -{{source=..\SamplesCS\Editors\DateTimePicker2.cs region=ShowTimePicker2}} -{{source=..\SamplesVB\Editors\DateTimePicker2.vb region=ShowTimePicker2}} - -````C# -this.radDateTimePicker1.DateTimePickerElement.ShowTimePicker = true; -this.radDateTimePicker1.Format = DateTimePickerFormat.Custom; -this.radDateTimePicker1.CustomFormat = "MMM - dd - yyyy hh:mm tt"; -(this.radDateTimePicker1.DateTimePickerElement.CurrentBehavior as RadDateTimePickerCalendar).DropDownMinSize = new System.Drawing.Size(330, 250); - -```` -````VB.NET -Me.radDateTimePicker1.DateTimePickerElement.ShowTimePicker = True -Me.radDateTimePicker1.Format = DateTimePickerFormat.[Custom] -Me.radDateTimePicker1.CustomFormat = "MMM - dd - yyyy hh:mm tt" -TryCast(Me.radDateTimePicker1.DateTimePickerElement.CurrentBehavior, RadDateTimePickerCalendar).DropDownMinSize = New System.Drawing.Size(330, 250) - -```` - -{{endregion}} - + + # See Also diff --git a/controls/editors/domainupdown/customizing-appearance/accessing-and-customizing-elements.md b/controls/editors/domainupdown/customizing-appearance/accessing-and-customizing-elements.md index fc71bfe55..0c4c1e734 100644 --- a/controls/editors/domainupdown/customizing-appearance/accessing-and-customizing-elements.md +++ b/controls/editors/domainupdown/customizing-appearance/accessing-and-customizing-elements.md @@ -48,9 +48,6 @@ You can customize the nested elements at run time as well: Me.radDomainUpDown1.DomainUpDownElement.EditableElement.BorderGradientStyle = Telerik.WinControls.GradientStyles.Solid ```` - -{{endregion}} - # See Also * [Design Time]({%slug winforms/editors/domainupdown/design-time%}) diff --git a/controls/editors/domainupdown/getting-started.md b/controls/editors/domainupdown/getting-started.md index c56cb8eee..e4f4b7c8d 100644 --- a/controls/editors/domainupdown/getting-started.md +++ b/controls/editors/domainupdown/getting-started.md @@ -87,9 +87,6 @@ End Sub ```` - -{{endregion}} - This is it! Now the change in the selection of the **RadDomainUpDown** instance will be reflected on **RadStatusStrip**. ## See Also diff --git a/controls/editors/domainupdown/populating-with-data/adding-items-programmatically.md b/controls/editors/domainupdown/populating-with-data/adding-items-programmatically.md index 323a25966..abc8db287 100644 --- a/controls/editors/domainupdown/populating-with-data/adding-items-programmatically.md +++ b/controls/editors/domainupdown/populating-with-data/adding-items-programmatically.md @@ -50,9 +50,6 @@ position: 1 Me.radDomainUpDown1.Items.Add(itemGermany) ```` - -{{endregion}} - # See Also * [Populating with data at Design Time]({%slug winforms/editors/domainupdown/populating-with-data/design-time%}) diff --git a/controls/editors/domainupdown/populating-with-data/data-binding.md b/controls/editors/domainupdown/populating-with-data/data-binding.md index c47f68abd..f2ebf873c 100644 --- a/controls/editors/domainupdown/populating-with-data/data-binding.md +++ b/controls/editors/domainupdown/populating-with-data/data-binding.md @@ -121,9 +121,6 @@ You can bind **RadDomainUpDown** programmatically as well. The following code sn ```` - -{{endregion}} - >caption Figure: 4 RadDomainUpDown bound at Run time ![WinForms RadDomainUpDown Bound at Run Time](images/domainupdown-populating-with-data-data-binding004.gif) diff --git a/controls/editors/maskededitbox/customizing-appearance/accessing-and-customizing-elements.md b/controls/editors/maskededitbox/customizing-appearance/accessing-and-customizing-elements.md index e75c647b9..d8909b0f3 100644 --- a/controls/editors/maskededitbox/customizing-appearance/accessing-and-customizing-elements.md +++ b/controls/editors/maskededitbox/customizing-appearance/accessing-and-customizing-elements.md @@ -19,9 +19,6 @@ You can access and modify the style for different elements in __RadMaskedEditBox >caption Figure 1: Element Hierarchy Editor ![WinForms RadMaskedEditBox Element Hierarchy Editor](images/radmaskededitbox-customizing-appearance-customizing-appearance001.png.png) - -{{endregion}} - # See Also * [Element Hierarchy Editor]({%slug winforms/tools/element-hierarchy-editor%}) diff --git a/controls/editors/maskededitbox/date-and-time-masks.md b/controls/editors/maskededitbox/date-and-time-masks.md index a1026ae4e..8e2702305 100644 --- a/controls/editors/maskededitbox/date-and-time-masks.md +++ b/controls/editors/maskededitbox/date-and-time-masks.md @@ -66,24 +66,11 @@ For example, a DateFormat of "ddd, MMMM yyyy - dd" might display:![WinForms RadM When the mask type is set to *DateTime* you can access the MaskDateTimeProvider by casting to that appropriate type. -{{source=..\SamplesCS\Editors\MaskEditBox1.cs region=provider}} -{{source=..\SamplesVB\Editors\MaskEditBox1.vb region=provider}} + + -````C# -radMaskedEditBox1.MaskType = MaskType.DateTime; -MaskDateTimeProvider provider = this.radMaskedEditBox1.MaskedEditBoxElement.Provider as MaskDateTimeProvider; -provider.AutoSelectNextPart = true; -```` -````VB.NET -RadMaskedEditBox1.MaskType = MaskType.DateTime -Dim provider As MaskDateTimeProvider = TryCast(Me.RadMaskedEditBox1.MaskedEditBoxElement.Provider, MaskDateTimeProvider) -provider.AutoSelectNextPart = True -```` - -{{endregion}} - More information about this provider can be found in the last section of the following article: [RadDateTimePicker Properties]({%slug winforms/editors/datetimepicker/raddatetimepicker-properties%}) ## See Also diff --git a/controls/editors/maskededitbox/localization.md b/controls/editors/maskededitbox/localization.md index b1ba7e38f..3426d4671 100644 --- a/controls/editors/maskededitbox/localization.md +++ b/controls/editors/maskededitbox/localization.md @@ -20,66 +20,14 @@ To localize **RadMaskedEditBox** to display text and messages in a specific lang Below is a sample implementation of an English localization provider: -{{source=..\SamplesCS\Editors\MaskEditBox1.cs region=MyRadMaskedEditBoxLocalizationProvider}} -{{source=..\SamplesVB\Editors\MaskEditBox1.vb region=MyRadMaskedEditBoxLocalizationProvider}} + + -````C# -public class MyRadMaskedEditBoxLocalizationProvider : RadMaskedEditBoxLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case RadMaskedEditBoxStringId.CopyMenuItem: return "Copy"; - case RadMaskedEditBoxStringId.CutMenuItem: return "Cut"; - case RadMaskedEditBoxStringId.DeleteMenuItem: return "Delete"; - case RadMaskedEditBoxStringId.PasteMenuItem: return "Paste"; - case RadMaskedEditBoxStringId.SelectAllMenuItem: return "SelectAll"; - } - - return string.Empty; - } -} -```` -````VB.NET -Public Class MyRadMaskedEditBoxLocalizationProvider - Inherits RadMaskedEditBoxLocalizationProvider - Public Overrides Function GetLocalizedString(ByVal id As String) As String - Select Case id - Case RadMaskedEditBoxStringId.CopyMenuItem - Return "Copy" - Case RadMaskedEditBoxStringId.CutMenuItem - Return "Cut" - Case RadMaskedEditBoxStringId.DeleteMenuItem - Return "Delete" - Case RadMaskedEditBoxStringId.PasteMenuItem - Return "Paste" - Case RadMaskedEditBoxStringId.SelectAllMenuItem - Return "SelectAll" - End Select - - Return String.Empty - End Function - -```` - -{{endregion}} To apply the custom localization provider, instantiate and assign it to the current localization provider: #### Assigning the Current Localization Provider -{{source=..\SamplesCS\Editors\MaskEditBox1.cs region=localizeMaskEditBox}} -{{source=..\SamplesVB\Editors\MaskEditBox1.vb region=localizeMaskEditBox}} -````C# -RadMaskedEditBoxLocalizationProvider.CurrentProvider = new MyRadMaskedEditBoxLocalizationProvider(); - -```` -````VB.NET -RadMaskedEditBoxLocalizationProvider.CurrentProvider = New MyRadMaskedEditBoxLocalizationProvider() - -```` - -{{endregion}} - + + \ No newline at end of file diff --git a/controls/editors/maskededitbox/standard-masks.md b/controls/editors/maskededitbox/standard-masks.md index 9dec18d6d..c11e66370 100644 --- a/controls/editors/maskededitbox/standard-masks.md +++ b/controls/editors/maskededitbox/standard-masks.md @@ -39,21 +39,10 @@ The table below describe the mask characters that can be used when the __MaskTyp When the mask type is set to *Standard* you can access the **StandardMaskTextBoxProvider** by casting to that appropriate type. -{{source=..\SamplesCS\Editors\MaskEditBox1.cs region=StandardProvider}} -{{source=..\SamplesVB\Editors\MaskEditBox1.vb region=StandardProvider}} + + -````C# -this.radMaskedEditBox1.MaskType = Telerik.WinControls.UI.MaskType.Standard; -StandardMaskTextBoxProvider provider = this.radMaskedEditBox1.MaskedEditBoxElement.Provider as StandardMaskTextBoxProvider; -```` -````VB.NET -Me.radMaskedEditBox1.MaskType = Telerik.WinControls.UI.MaskType.Standard -Dim provider As StandardMaskTextBoxProvider = TryCast(Me.radMaskedEditBox1.MaskedEditBoxElement.Provider, StandardMaskTextBoxProvider) - -```` - -{{endregion}} ### Useful properties diff --git a/controls/editors/maskededitbox/textmaskformat-property.md b/controls/editors/maskededitbox/textmaskformat-property.md index bc95fe4c1..46ba6db3e 100644 --- a/controls/editors/maskededitbox/textmaskformat-property.md +++ b/controls/editors/maskededitbox/textmaskformat-property.md @@ -27,24 +27,10 @@ Let's now analyze how this property works in the context of several popular mask 1\. First, we need to define our mask: -{{source=..\SamplesCS\Editors\MaskEditBox1.cs region=phoneMask}} -{{source=..\SamplesVB\Editors\MaskEditBox1.vb region=phoneMask}} + + -````C# - -this.radMaskedEditBox1.MaskType = Telerik.WinControls.UI.MaskType.Standard; -this.radMaskedEditBox1.Mask = "(000) 000-0000"; -this.radMaskedEditBox1.PromptChar = '_'; - -```` -````VB.NET -Me.RadMaskedEditBox1.MaskType = Telerik.WinControls.UI.MaskType.Standard -Me.RadMaskedEditBox1.Mask = "(000) 000-0000" -Me.RadMaskedEditBox1.PromptChar = "_" - -```` -{{endregion}} 2\. Then, let's assume that the user types "123123123". As you can notice, the number of digits is smaller than the provided prompt places by one and this is for demonstration purposes. The result in the UI of RadMaskedEditBox will look like this: @@ -72,22 +58,10 @@ And here is what the __Value__ property of RadMaskedEditBox will return dependin 1\. Define the Current mask as show below: -{{source=..\SamplesCS\Editors\MaskEditBox1.cs region=currencyMask}} -{{source=..\SamplesVB\Editors\MaskEditBox1.vb region=currencyMask}} - -````C# - -this.radMaskedEditBox1.MaskType = Telerik.WinControls.UI.MaskType.Numeric; -this.radMaskedEditBox1.Mask = "C2"; - -```` -````VB.NET -Me.RadMaskedEditBox1.MaskType = Telerik.WinControls.UI.MaskType.Numeric -Me.RadMaskedEditBox1.Mask = "C2" + + -```` -{{endregion}} 2\. Now, assume that the user types "-1234.12". The UI of RadMaskedEditBox in this case look like this: diff --git a/controls/editors/maskededitbox/timespan-masks.md b/controls/editors/maskededitbox/timespan-masks.md index 37d461d97..26009e07b 100644 --- a/controls/editors/maskededitbox/timespan-masks.md +++ b/controls/editors/maskededitbox/timespan-masks.md @@ -65,9 +65,6 @@ When the mask type is set to *TimeSpan* you can access the **MaskTimeSpanProvide provider.MillisecondsStep = 5 ```` - -{{endregion}} - ## See Also * [Standard]({%slug winforms/editors/maskededitbox/standard-masks%}) diff --git a/controls/editors/maskededitbox/working-with-radmaskededitbox.md b/controls/editors/maskededitbox/working-with-radmaskededitbox.md index dcceeeeb9..dd24169ae 100644 --- a/controls/editors/maskededitbox/working-with-radmaskededitbox.md +++ b/controls/editors/maskededitbox/working-with-radmaskededitbox.md @@ -47,24 +47,10 @@ __RadMaskedEditBox__ descends from RadTextBox and so has the same properties, me ![WinForms RadMaskedEditBox German Culture](images/editors-maskededitbox-properties-and-events001.png) -{{source=..\SamplesCS\Editors\MaskEditBox1.cs region=workingWithRadMaskedEditBox}} -{{source=..\SamplesVB\Editors\MaskEditBox1.vb region=workingWithRadMaskedEditBox}} + + -````C# - -this.radMaskedEditBox1.MaskType = Telerik.WinControls.UI.MaskType.DateTime; -this.radMaskedEditBox1.Mask = "d"; -this.radMaskedEditBox1.Culture = new System.Globalization.CultureInfo("de-de"); -```` -````VB.NET -Me.RadMaskedEditBox1.MaskType = Telerik.WinControls.UI.MaskType.DateTime -Me.RadMaskedEditBox1.Mask = "D" -Me.RadMaskedEditBox1.Culture = New System.Globalization.CultureInfo("de-DE") - -```` - -{{endregion}} * __Value:__ This property returns user input without the formatting characters. If you want the input and the formatting characters, use the __Text__ property. diff --git a/controls/editors/popupeditor/customize-elements.md b/controls/editors/popupeditor/customize-elements.md index 2a148f334..0c93e33d6 100644 --- a/controls/editors/popupeditor/customize-elements.md +++ b/controls/editors/popupeditor/customize-elements.md @@ -17,22 +17,10 @@ You can access the text box by using the __TextBoxElement__ property. This allow #### Customize TextBoxElement -{{source=..\SamplesCS\Editors\PopupEditor\PopupEditorCode.cs region=TextBox}} -{{source=..\SamplesVB\Editors\PopupEditor\PopupEditorCode.vb region=TextBox}} + + -````C# -radPopupEditor1.TextBoxElement.Font = new Font("Arial", 12, FontStyle.Regular); -radPopupEditor1.ForeColor = ColorTranslator.FromHtml("#008de7"); -```` -````VB.NET -radPopupEditor1.TextBoxElement.Font = New Font("Arial", 12, FontStyle.Regular) -radPopupEditor1.ForeColor = ColorTranslator.FromHtml("#008de7") - -```` - -{{endregion}} - >caption Figure 1: Customizing the text box Font and ForeColor. @@ -45,21 +33,8 @@ The arrow button can be accessed via the __ArrowButtonElement__ property. The fo #### Set arrow button BackColor -{{source=..\SamplesCS\Editors\PopupEditor\PopupEditorCode.cs region=Button}} -{{source=..\SamplesVB\Editors\PopupEditor\PopupEditorCode.vb region=Button}} - -````C# -radPopupEditor1.PopupEditorElement.ArrowButtonElement.Fill.BackColor = ColorTranslator.FromHtml("#009de1"); -radPopupEditor1.PopupEditorElement.ArrowButtonElement.Fill.GradientStyle = Telerik.WinControls.GradientStyles.Solid; - -```` -````VB.NET -radPopupEditor1.PopupEditorElement.ArrowButtonElement.Fill.BackColor = ColorTranslator.FromHtml("#009de1") -radPopupEditor1.PopupEditorElement.ArrowButtonElement.Fill.GradientStyle = Telerik.WinControls.GradientStyles.Solid - -```` - -{{endregion}} + + @@ -73,25 +48,10 @@ The popup can be access with the __Popup__ property. This gives you access to al #### Change Popup BackColor -{{source=..\SamplesCS\Editors\PopupEditor\PopupEditorCode.cs region=DropDown}} -{{source=..\SamplesVB\Editors\PopupEditor\PopupEditorCode.vb region=DropDown}} - -````C# -void RadForm1_Load(object sender, EventArgs e) -{ - radPopupEditor1.Popup.BackColor = ColorTranslator.FromHtml("#009de1"); -} - -```` -````VB.NET -Private Sub RadForm1_Load(ByVal sender As Object, ByVal e As EventArgs) - radPopupEditor1.Popup.BackColor = ColorTranslator.FromHtml("#009de1") -End Sub + + -```` -{{endregion}} - >caption Figure 3: Change Popup BackColor. diff --git a/controls/editors/popupeditor/getting-started.md b/controls/editors/popupeditor/getting-started.md index b28825738..d8f1963c6 100644 --- a/controls/editors/popupeditor/getting-started.md +++ b/controls/editors/popupeditor/getting-started.md @@ -50,41 +50,10 @@ Add __Click__ event handlers for the both buttons and then use the following cod #### Buttons event handlers -{{source=..\SamplesCS\Editors\PopupEditor\PopupEditorCode.cs region=EventHandlers}} -{{source=..\SamplesVB\Editors\PopupEditor\PopupEditorCode.vb region=EventHandlers}} - -````C# -private void radButton1_Click(object sender, EventArgs e) -{ - this.radPopupEditor1.Text = radTextBox1.Text + " " + radTextBox2.Text; - radPopupEditor1.PopupEditorElement.ClosePopup(); -} -private void radButton2_Click(object sender, EventArgs e) -{ - this.radPopupEditor1.Text = ""; - radTextBox1.Text = ""; - radTextBox2.Text = ""; - radTextBox3.Text = ""; - radPopupEditor1.PopupEditorElement.ClosePopup(); -} - -```` -````VB.NET -Private Sub radButton1_Click(ByVal sender As Object, ByVal e As EventArgs) - Me.radPopupEditor1.Text = radTextBox1.Text & " " & radTextBox2.Text - radPopupEditor1.PopupEditorElement.ClosePopup() -End Sub -Private Sub radButton2_Click(ByVal sender As Object, ByVal e As EventArgs) - Me.radPopupEditor1.Text = "" - radTextBox1.Text = "" - radTextBox2.Text = "" - radTextBox3.Text = "" - radPopupEditor1.PopupEditorElement.ClosePopup() -End Sub - -```` - -{{endregion}} + + + + This way when __Submit__ is pressed the name will be displayed in the control's text box. diff --git a/controls/editors/popupeditor/handling-popup-keyboard-input.md b/controls/editors/popupeditor/handling-popup-keyboard-input.md index 4783f50bc..47e5ba0b7 100644 --- a/controls/editors/popupeditor/handling-popup-keyboard-input.md +++ b/controls/editors/popupeditor/handling-popup-keyboard-input.md @@ -16,29 +16,10 @@ As of **R1 2021** the RadPopupEditor.**Popup** offers keyboard handling via its #### Handling Escape -{{source=..\SamplesCS\Editors\PopupEditor\PopupEditorCode.cs region=HandleEscape}} -{{source=..\SamplesVB\Editors\PopupEditor\PopupEditorCode.vb region=HandleEscape}} - -````C# - private void Popup_KeyDown(object sender, KeyEventArgs e) - { - if (e.KeyData== Keys.Escape) - { - e.Handled = true; - } - } - -```` -````VB.NET - Private Sub Popup_KeyDown(sender As Object, e As KeyEventArgs) - If e.KeyData = Keys.Escape Then - e.Handled = True - End If - End Sub - -```` - -{{endregion}} + + + + The **KeyEventArgs** exposes the following useful information: diff --git a/controls/editors/popupeditor/properties-events-and-methods.md b/controls/editors/popupeditor/properties-events-and-methods.md index fa75a66bf..f3620bf18 100644 --- a/controls/editors/popupeditor/properties-events-and-methods.md +++ b/controls/editors/popupeditor/properties-events-and-methods.md @@ -81,39 +81,20 @@ This article describes the most commonly used properties, events and methods. #### Close Popup -{{source=..\SamplesCS\Editors\PopupEditor\PopupEditorCode.cs region=close}} -{{source=..\SamplesVB\Editors\PopupEditor\PopupEditorCode.vb region=close}} + + -````C# -radPopupEditor1.PopupEditorElement.ClosePopup(RadPopupCloseReason.CloseCalled); -```` -````VB.NET -radPopupEditor1.PopupEditorElement.ClosePopup(RadPopupCloseReason.CloseCalled) -```` - -{{endregion}} - * __ShowPopup:__ This method can be used for programmatically showing the popup. #### Show Popup -{{source=..\SamplesCS\Editors\PopupEditor\PopupEditorCode.cs region=show}} -{{source=..\SamplesVB\Editors\PopupEditor\PopupEditorCode.vb region=show}} - -````C# -radPopupEditor1.PopupEditorElement.ShowPopup(); - -```` -````VB.NET -radPopupEditor1.PopupEditorElement.ShowPopup() + + -```` -{{endregion}} - # See Also diff --git a/controls/editors/spineditor/getting-started.md b/controls/editors/spineditor/getting-started.md index 959283fd2..5173ffe0a 100644 --- a/controls/editors/spineditor/getting-started.md +++ b/controls/editors/spineditor/getting-started.md @@ -44,25 +44,11 @@ The following tutorial demonstrates changing the thumb position on a __RadTrackB 3\. Click the `Events` tab of the Property Window, locate the __ValueChanged__ event and double-click it to create an event handler. Replace the event handler with the following code. -{{source=..\SamplesCS\Editors\SpinEditor1.cs region=spinEditorAndTrackBar}} -{{source=..\SamplesVB\Editors\SpinEditor1.vb region=spinEditorAndTrackBar}} + + -````C# -void radSpinEditor1_ValueChanged(object sender, EventArgs e) -{ - this.radTrackBar1.Value = Convert.ToInt32(radSpinEditor1.Value); -} -```` -````VB.NET -Private Sub RadSpinEditor1_ValueChanged1(ByVal sender As Object, ByVal e As System.EventArgs) Handles RadSpinEditor1.ValueChanged - Me.RadTrackBar1.Value = Convert.ToInt32(RadSpinEditor1.Value) -End Sub -```` - -{{endregion}} - 4\. Press __F5__ to run the application. Experiment with the behavior of the RadSpinEditor by typing values directly to the editor, by clicking the up and down arrows, and by pressing the up and down arrow diff --git a/controls/editors/spineditor/null-value-support.md b/controls/editors/spineditor/null-value-support.md index f1fb02a75..cffee238d 100644 --- a/controls/editors/spineditor/null-value-support.md +++ b/controls/editors/spineditor/null-value-support.md @@ -18,111 +18,10 @@ You can find below a sample code snippet demonstrating how to use the **Nullable #### Simple data binding with null value -{{source=..\SamplesCS\Editors\SpinEditor1.cs region=NullableValue}} -{{source=..\SamplesVB\Editors\SpinEditor1.vb region=NullableValue}} + + -````C# -public void InitializeNullableSpinEditor() -{ - - this.radSpinEditor1.EnableNullValueInput = true; - this.radSpinEditor1.NullableValueChanged += radSpinEditor1_NullableValueChanged; - Item item = new Item("Apple", 2); - this.radSpinEditor1.DataBindings.Add("NullableValue", item, "Id", true, DataSourceUpdateMode.OnPropertyChanged); -} -private void radSpinEditor1_NullableValueChanged(object sender, EventArgs e) -{ - RadMessageBox.Show("NullableValue is changed "+ this.radSpinEditor1.NullableValue); -} -public class Item : System.ComponentModel.INotifyPropertyChanged -{ - private string _name; - private int? _id; - public Item(string name, int? id) - { - this._name = name; - this._id = id; - } - public string Name - { - get - { - return this._name; - } - set - { - this._name = value; - OnPropertyChanged("Name"); - } - } - public int? Id - { - get - { - return this._id; - } - set - { - this._id = value; - OnPropertyChanged("Id"); - } - } - public event PropertyChangedEventHandler PropertyChanged; - protected virtual void OnPropertyChanged(string propertyName) - { - if (PropertyChanged != null) - { - PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); - } - } -} -```` -````VB.NET -Public Sub InitializeNullableSpinEditor() - Me.RadSpinEditor1.EnableNullValueInput = True - AddHandler Me.RadSpinEditor1.NullableValueChanged, AddressOf radSpinEditor1_NullableValueChanged - Dim item As New Item("Apple", 2) - Me.RadSpinEditor1.DataBindings.Add("NullableValue", item, "Id", True, Windows.Forms.DataSourceUpdateMode.OnPropertyChanged) -End Sub -Private Sub radSpinEditor1_NullableValueChanged(sender As Object, e As EventArgs) - RadMessageBox.Show("NullableValue is changed " & Me.RadSpinEditor1.NullableValue) -End Sub -Public Class Item - Implements System.ComponentModel.INotifyPropertyChanged - Private _name As String - Private _id As System.Nullable(Of Integer) - Public Sub New(name As String, id As System.Nullable(Of Integer)) - Me._name = name - Me._id = id - End Sub - Public Property Name() As String - Get - Return Me._name - End Get - Set(value As String) - Me._name = value - OnPropertyChanged("Name") - End Set - End Property - Public Property Id() As System.Nullable(Of Integer) - Get - Return Me._id - End Get - Set(value As System.Nullable(Of Integer)) - Me._id = value - OnPropertyChanged("Id") - End Set - End Property - Public Event PropertyChanged As PropertyChangedEventHandler Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged - Protected Overridable Sub OnPropertyChanged(ByVal propertyName As String) - RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName)) - End Sub -End Class - -```` - -{{endregion}} # See Also diff --git a/controls/editors/textbox/adding-buttons-to-radtextbox.md b/controls/editors/textbox/adding-buttons-to-radtextbox.md index 3412a274c..b1e32dd9c 100644 --- a/controls/editors/textbox/adding-buttons-to-radtextbox.md +++ b/controls/editors/textbox/adding-buttons-to-radtextbox.md @@ -25,59 +25,9 @@ In this particular case we are going to add three buttons to RadTextBox: 1\. First, let's create three buttons. In order to arrange them in stacked formation, we need to add them to a [StackLayoutPanel]({%slug winforms/telerik-presentation-framework/layout/predefined-layout-panels%}): -{{source=..\SamplesCS\Editors\TextBoxWithButtons.cs region=creatingButtons}} -{{source=..\SamplesVB\Editors\TextBoxWithButtons.vb region=creatingButtons}} - -````C# -RadButtonElement button = new RadButtonElement(); -button.Click += new EventHandler(button_Click); -button.Padding = new Padding(2, 0, 2, -2); -button.Margin = new Padding(0, 0, 0, 0); -button.Text = "..."; -RadButtonElement button2 = new RadButtonElement(); -button2.Click += new EventHandler(button_Click); -button2.Padding = new Padding(2, 0, 2, -2); -button2.Margin = new Padding(1, 0, 2, 0); -button2.Text = "///"; -RadButtonElement button3 = new RadButtonElement(); -button3.Click += new EventHandler(button_Click); -button3.Padding = new Padding(2, 0, 2, -2); -button3.Margin = new Padding(1, 0, 1, 0); -button3.Text = @"\\\"; -StackLayoutElement stackPanel = new StackLayoutElement(); -stackPanel.Orientation = Orientation.Horizontal; -stackPanel.Margin = new Padding(1, 0, 1, 0); -stackPanel.Children.Add(button); -stackPanel.Children.Add(button2); -stackPanel.Children.Add(button3); - -```` -````VB.NET -Dim button As New RadButtonElement() -AddHandler button.Click, AddressOf button_Click -button.Padding = New Padding(2, 0, 2, -2) -button.Margin = New Padding(0, 0, 0, 0) -button.Text = "..." -Dim button2 As New RadButtonElement() -AddHandler button2.Click, AddressOf button_Click -button2.Padding = New Padding(2, 0, 2, -2) -button2.Margin = New Padding(1, 0, 2, 0) -button2.Text = "///" -Dim button3 As New RadButtonElement() -AddHandler button3.Click, AddressOf button_Click -button3.Padding = New Padding(2, 0, 2, -2) -button3.Margin = New Padding(1, 0, 1, 0) -button3.Text = "\\\" -Dim stackPanel As New StackLayoutElement() -stackPanel.Orientation = Orientation.Horizontal -stackPanel.Margin = New Padding(1, 0, 1, 0) -stackPanel.Children.Add(button) -stackPanel.Children.Add(button2) -stackPanel.Children.Add(button3) - -```` - -{{endregion}} + + + As you can see, we are also setting the __Padding__ of the buttons. This allows us to set some size to these buttons bigger than the default one. In addition, we are setting the __Margin__ of the buttons, so that there is some space between them. @@ -85,76 +35,25 @@ As you can see, we are also setting the __Padding__ of the buttons. This allows 2\. Now we should place the __StackLayoutPanel__ in RadTextBox. In order to achieve the proper layout between the textbox part and the buttons, we need to put the item responsible for the textbox part and the __StackLayoutPanel__ in a __DockLayoutPanel__: -{{source=..\SamplesCS\Editors\TextBoxWithButtons.cs region=dockLayoutPanel}} -{{source=..\SamplesVB\Editors\TextBoxWithButtons.vb region=dockLayoutPanel}} - -````C# -RadTextBoxItem tbItem = this.radTextBox1.TextBoxElement.TextBoxItem; -this.radTextBox1.TextBoxElement.Children.Remove(tbItem); -DockLayoutPanel dockPanel = new DockLayoutPanel(); -dockPanel.Children.Add(stackPanel); -dockPanel.Children.Add(tbItem); -DockLayoutPanel.SetDock(tbItem, Telerik.WinControls.Layouts.Dock.Left); -DockLayoutPanel.SetDock(stackPanel, Telerik.WinControls.Layouts.Dock.Right); -this.radTextBox1.TextBoxElement.Children.Add(dockPanel); - -```` -````VB.NET -Dim tbItem As RadTextBoxItem = Me.RadTextBox1.TextBoxElement.TextBoxItem -Me.RadTextBox1.TextBoxElement.Children.Remove(tbItem) -Dim dockPanel As New DockLayoutPanel() -dockPanel.Children.Add(stackPanel) -dockPanel.Children.Add(tbItem) -DockLayoutPanel.SetDock(tbItem, Telerik.WinControls.Layouts.Dock.Left) -DockLayoutPanel.SetDock(stackPanel, Telerik.WinControls.Layouts.Dock.Right) -Me.RadTextBox1.TextBoxElement.Children.Add(dockPanel) - -```` - -{{endregion}} - + + + -3\. We are setting some __Margin__ and __Padding__ properties to the elements of RadTextBox which centers the buttons and the text vertically: -{{source=..\SamplesCS\Editors\TextBoxWithButtons.cs region=finalPadding}} -{{source=..\SamplesVB\Editors\TextBoxWithButtons.vb region=finalPadding}} +3\. We are setting some __Margin__ and __Padding__ properties to the elements of RadTextBox which centers the buttons and the text vertically: -````C# -this.radTextBox1.TextBoxElement.Padding = new Padding(1, 1, 1, 1); -tbItem.Margin = new Padding(0, 1, 0, 0); + + -```` -````VB.NET -Me.RadTextBox1.TextBoxElement.Padding = New Padding(1, 1, 1, 1) -tbItem.Margin = New Padding(0, 1, 0, 0) -```` -{{endregion}} - 4\. To complete the scenario, here is the event handler implementation for the Click event: -{{source=..\SamplesCS\Editors\TextBoxWithButtons.cs region=clickHandler}} -{{source=..\SamplesVB\Editors\TextBoxWithButtons.vb region=clickHandler}} + + -````C# -void button_Click(object sender, EventArgs e) -{ - RadButtonElement button = sender as RadButtonElement; - RadMessageBox.Show("Clicked! " + button.Text); -} -```` -````VB.NET -Private Sub button_Click(ByVal sender As Object, ByVal e As EventArgs) - Dim button As RadButtonElement = TryCast(sender, RadButtonElement) - RadMessageBox.Show("Clicked! " & button.Text) -End Sub -```` - -{{endregion}} - This is it! Now you have a good-looking RadTextBox with buttons! # See Also diff --git a/controls/editors/textbox/getting-started.md b/controls/editors/textbox/getting-started.md index ff6769420..cd586ee2c 100644 --- a/controls/editors/textbox/getting-started.md +++ b/controls/editors/textbox/getting-started.md @@ -57,11 +57,6 @@ Dim myNewRadTextBox As New RadTextBox() Me.Controls.Add(myNewRadTextBox) ```` - -{{endregion}} - - - ## Telerik UI for WinForms Learning Resources * [Getting Started with Telerik UI for WinForms Components](https://docs.telerik.com/devtools/winforms/getting-started/first-steps) * [Telerik UI for WinForms Setup](https://docs.telerik.com/devtools/winforms/installation-and-upgrades/installing-on-your-computer) diff --git a/controls/editors/textbox/programming-radtextbox.md b/controls/editors/textbox/programming-radtextbox.md index 50a19eead..2629d07a9 100644 --- a/controls/editors/textbox/programming-radtextbox.md +++ b/controls/editors/textbox/programming-radtextbox.md @@ -52,21 +52,10 @@ Since R2 2021 **RadTextBox** supports embedded labels. The embedded label shows #### Example 1: Setting the embedded label -{{source=..\SamplesCS\Editors\TextBox1.cs region=EmbeddedLabel}} -{{source=..\SamplesVB\Editors\TextBox1.vb region=EmbeddedLabel}} + + -````C# -this.radTextBox1.ShowEmbeddedLabel = true; -this.radTextBox1.EmbeddedLabelText = "First Name"; -```` -````VB.NET -Me.RadTextBox1.ShowEmbeddedLabel = True -Me.RadTextBox1.EmbeddedLabelText = "First Name" - -```` - -{{endregion}} ![WinForms RadTextBox Embedded Labels](images/editors-textbox-programming-radtextbox005.gif) diff --git a/controls/editors/textboxcontrol/autocomplete.md b/controls/editors/textboxcontrol/autocomplete.md index e2c1735f6..9012812d0 100644 --- a/controls/editors/textboxcontrol/autocomplete.md +++ b/controls/editors/textboxcontrol/autocomplete.md @@ -65,49 +65,10 @@ To set the __AutoCompleteDisplayMember__ property, first set the data source pro To use auto-completion without specifying a data source, you need to populate the items which will be used for completing the input string in __RadTextBoxControl__, in the __Items__ collection of the control: -{{source=..\SamplesCS\Editors\TextBoxControl.cs region=AddAutoCompleteItems}} -{{source=..\SamplesVB\Editors\TextBoxControl.vb region=AddAutoCompleteItems}} - -````C# - -private void AddAutoCompleteItems() -{ - this.radTextBoxControl1.AutoCompleteMode = AutoCompleteMode.Suggest; - RadListDataItemCollection autoCompleteItems = this.radTextBoxControl1.AutoCompleteItems; - - autoCompleteItems.Add(new RadListDataItem("Luke")); - autoCompleteItems.Add(new RadListDataItem("Max")); - autoCompleteItems.Add(new RadListDataItem("Adam")); - autoCompleteItems.Add(new RadListDataItem("Henry")); - autoCompleteItems.Add(new RadListDataItem("Jack")); - autoCompleteItems.Add(new RadListDataItem("Ben")); - autoCompleteItems.Add(new RadListDataItem("Tyler")); - autoCompleteItems.Add(new RadListDataItem("Ethan")); - autoCompleteItems.Add(new RadListDataItem("David")); - autoCompleteItems.Add(new RadListDataItem("Mike")); -} - -```` -````VB.NET -Private Sub AddAutoCompleteItems() - Me.RadTextBoxControl1.AutoCompleteMode = AutoCompleteMode.Suggest - Dim autoCompleteItems As RadListDataItemCollection = Me.RadTextBoxControl1.AutoCompleteItems - autoCompleteItems.Add(New RadListDataItem("Luke")) - autoCompleteItems.Add(New RadListDataItem("Max")) - autoCompleteItems.Add(New RadListDataItem("Adam")) - autoCompleteItems.Add(New RadListDataItem("Henry")) - autoCompleteItems.Add(New RadListDataItem("Jack")) - autoCompleteItems.Add(New RadListDataItem("Ben")) - autoCompleteItems.Add(New RadListDataItem("Tyler")) - autoCompleteItems.Add(New RadListDataItem("Ethan")) - autoCompleteItems.Add(New RadListDataItem("David")) - autoCompleteItems.Add(New RadListDataItem("Mike")) -End Sub - -```` - -{{endregion}} - + + + + Here is the result of the above code: @@ -119,42 +80,17 @@ Here is the result of the above code: The bellow example shows how you can change the styles of the auto-complete drop down. First you need to subscribe to the __VisualItemFormatting__ event: -{{source=..\SamplesCS\Editors\TextBoxControl.cs region=Subscribe_ItemFormatting}} -{{source=..\SamplesVB\Editors\TextBoxControl.vb region=Subscribe_ItemFormatting}} -````C# -radTextBoxControl1.ListElement.VisualItemFormatting += ListElement_VisualItemFormatting; + + -```` -````VB.NET -AddHandler RadTextBoxControl1.ListElement.VisualItemFormatting, AddressOf ListElement_VisualItemFormatting -```` - -{{endregion}} Then you can change the styles in the event handler: -{{source=..\SamplesCS\Editors\TextBoxControl.cs region=Formatting_AutoComplete}} -{{source=..\SamplesVB\Editors\TextBoxControl.vb region=Formatting_AutoComplete}} -````C# -private void ListElement_VisualItemFormatting(object sender, VisualItemFormattingEventArgs args) -{ - args.VisualItem.BackColor = ColorTranslator.FromHtml("#91c930"); - args.VisualItem.GradientStyle = GradientStyles.Solid; - args.VisualItem.ForeColor = ColorTranslator.FromHtml("#bb2525"); -} - -```` -````VB.NET -Private Sub ListElement_VisualItemFormatting(ByVal sender As Object, ByVal args As VisualItemFormattingEventArgs) - args.VisualItem.BackColor = ColorTranslator.FromHtml("#91c930") - args.VisualItem.GradientStyle = GradientStyles.Solid - args.VisualItem.ForeColor = ColorTranslator.FromHtml("#bb2525") -End Sub - -```` - -{{endregion}} + + + + Here is the result of the above code: diff --git a/controls/editors/textboxcontrol/caret-positioning-and-selection.md b/controls/editors/textboxcontrol/caret-positioning-and-selection.md index 7596cf63a..a82bdbdb7 100644 --- a/controls/editors/textboxcontrol/caret-positioning-and-selection.md +++ b/controls/editors/textboxcontrol/caret-positioning-and-selection.md @@ -25,53 +25,18 @@ The __SelectionLength__ property is a numeric value that sets the width of the i #### Select part of the text using the __SelectionStart__ and __SelectionLenght__ properties. -{{source=..\SamplesCS\Editors\TextBoxControl.cs region=SetSelection}} -{{source=..\SamplesVB\Editors\TextBoxControl.vb region=SetSelection}} - -````C# - -private void SetSelection() -{ - this.radTextBoxControl1.Text = "Hello, John Green"; - this.radTextBoxControl1.SelectionStart = 7; - this.radTextBoxControl1.SelectionLength = 4; -} - -```` -````VB.NET -Private Sub SetSelection() - Me.RadTextBoxControl1.Text = "Hello, John Green" - Me.RadTextBoxControl1.SelectionStart = 7 - Me.RadTextBoxControl1.SelectionLength = 4 -End Sub - -```` - -{{endregion}} - -#### Use the __Select__ method to select the part of the text: + + + -{{source=..\SamplesCS\Editors\TextBoxControl.cs region=Select}} -{{source=..\SamplesVB\Editors\TextBoxControl.vb region=Select}} -````C# -private void SelectText() -{ - this.radTextBoxControl1.Text = "Hello, John Green"; - this.radTextBoxControl1.Select(7, 4); -} +#### Use the __Select__ method to select the part of the text: + + + -```` -````VB.NET -Private Sub SelectText() - Me.RadTextBoxControl1.Text = "Hello, John Green" - Me.RadTextBoxControl1.[Select](7, 4) -End Sub -```` -{{endregion}} - The both approaches produce same result: ![WinForms RadTextBoxControl Caret Position Selection](images/editors-textboxcontrol-caret-positioning-and-selection001.png) diff --git a/controls/editors/textboxcontrol/creating-custom-blocks.md b/controls/editors/textboxcontrol/creating-custom-blocks.md index 39359b43c..d7b2ec7af 100644 --- a/controls/editors/textboxcontrol/creating-custom-blocks.md +++ b/controls/editors/textboxcontrol/creating-custom-blocks.md @@ -20,231 +20,29 @@ You should create a custom text block that inherits from __ITextBlock__ and any First, you should create a button that implements __ITextBlock__ interface: -{{source=..\SamplesCS\Editors\TextBoxControl.cs region=customTextBlock}} -{{source=..\SamplesVB\Editors\TextBoxControl.vb region=customTextBlock}} + + -````C# - -public class ButtonTextBlock : RadButtonElement, ITextBlock -{ - private int index; - private int offset; - public ButtonTextBlock() - { - this.index = 0; - this.offset = 0; - this.MaxSize = new Size(0, 12); - } - - protected override Type ThemeEffectiveType - { - get - { - return typeof(RadButtonElement); - } - } - - public int Index - { - get - { - return this.index; - } - set - { - this.index = value; - } - } - - public int Length - { - get - { - return 1; - } - } - - public int Offset - { - get - { - return this.offset; - } - set - { - this.offset = value; - } - } - - public int GetCharacterIndexFromX(float x) - { - RectangleF bounds = this.ControlBoundingRectangle; - float median = bounds.X + bounds.Width / 2; - return x <= median ? 0 : 1; - } - - public RectangleF GetRectangleFromCharacterIndex(int index, bool trailEdge) - { - Rectangle bounds = this.ControlBoundingRectangle; - - if (index == 1) - { - bounds.X = bounds.Right; - bounds.Width = 0; - } - - return bounds; - } - - protected override void OnClick(EventArgs e) - { - base.OnClick(e); - RadMessageBox.Show("The button is clicked.", "Message"); - } -} -```` -````VB.NET - -Public Class ButtonTextBlock -Inherits RadButtonElement -Implements ITextBlock - Private m_index As Integer - Private m_offset As Integer - Public Sub New() - Me.m_index = 0 - Me.m_offset = 0 - Me.MaxSize = New Size(0, 12) - End Sub - Protected Overrides ReadOnly Property ThemeEffectiveType() As Type - Get - Return GetType(RadButtonElement) - End Get - End Property - Public Property Index() As Integer Implements ITextBlock.Index - Get - Return Me.m_index - End Get - Set(value As Integer) - Me.m_index = value - End Set - End Property - Public ReadOnly Property Length() As Integer Implements ITextBlock.Length - Get - Return 1 - End Get - End Property - Public Property Offset() As Integer Implements ITextBlock.Offset - Get - Return Me.m_offset - End Get - Set(value As Integer) - Me.m_offset = value - End Set - End Property - Public Function GetCharacterIndexFromX(x As Single) As Integer Implements ITextBlock.GetCharacterIndexFromX - Dim bounds As RectangleF = Me.ControlBoundingRectangle - Dim median As Single = bounds.X + bounds.Width / 2 - Return If(x <= median, 0, 1) - End Function - Public Function GetRectangleFromCharacterIndex(index As Integer, trailEdge As Boolean) As RectangleF Implements ITextBlock.GetRectangleFromCharacterIndex - Dim bounds As Rectangle = Me.ControlBoundingRectangle - If index = 1 Then - bounds.X = bounds.Right - bounds.Width = 0 - End If - - Return bounds - End Function - Protected Overrides Sub OnClick(e As EventArgs) - MyBase.OnClick(e) - RadMessageBox.Show("The button is clicked.", "Message") - End Sub - Overloads Sub Measure(availableSize As SizeF) Implements ITextBlock.Measure - MyBase.Measure(availableSize) - End Sub - Overloads Sub Arrange(finalRectangle As RectangleF) Implements ITextBlock.Arrange - MyBase.Arrange(finalRectangle) - End Sub - Overloads ReadOnly Property DesiredSize As SizeF Implements ITextBlock.DesiredSize - Get - Return MyBase.DesiredSize - End Get - End Property - Overloads ReadOnly Property ControlBoundingRectangle As Rectangle Implements ITextBlock.ControlBoundingRectangle - Get - Return MyBase.ControlBoundingRectangle - End Get - End Property - Overloads Property Text As String Implements ITextBlock.Text - Get - Return MyBase.Text - End Get - Set(value As String) - MyBase.Text = value - End Set - End Property -End Class - -```` -{{endregion}} - Then you should subscribe to the __CreateTextBlock__ event before initializing the __Text__ property: -{{source=..\SamplesCS\Editors\TextBoxControl.cs region=applyCustomTextBlock1}} -{{source=..\SamplesVB\Editors\TextBoxControl.vb region=applyCustomTextBlock1}} -````C# - -radTextBoxControl1.CreateTextBlock += new CreateTextBlockEventHandler(radTextBoxControl1_CreateTextBlock); - -```` -````VB.NET -AddHandler RadTextBoxControl1.CreateTextBlock, AddressOf radTextBoxControl1_CreateTextBlock + + -```` -{{endregion}} -{{source=..\SamplesCS\Editors\TextBoxControl.cs region=applyCustomTextBlock2}} -{{source=..\SamplesVB\Editors\TextBoxControl.vb region=applyCustomTextBlock2}} + + -````C# -void radTextBoxControl1_CreateTextBlock(object sender, CreateTextBlockEventArgs e) -{ - if (e.Text == "here") - { - e.TextBlock = new ButtonTextBlock(); - } -} -```` -````VB.NET -Private Sub radTextBoxControl1_CreateTextBlock(sender As Object, e As CreateTextBlockEventArgs) - If e.Text = "here" Then - e.TextBlock = New ButtonTextBlock() - End If -End Sub -```` - -{{endregion}} - Finally, the __Text__ property should be set: -{{source=..\SamplesCS\Editors\TextBoxControl.cs region=applyCustomTextBlock3}} -{{source=..\SamplesVB\Editors\TextBoxControl.vb region=applyCustomTextBlock3}} - -````C# -this.radTextBoxControl1.Text = "Please, click here"; - -```` -````VB.NET -Me.RadTextBoxControl1.Text = "Please, click here" + + -```` -{{endregion}} >caption Figure 1: The "here" word is replaced with a button. diff --git a/controls/editors/textboxcontrol/customizing-appearance/formatting-blocks.md b/controls/editors/textboxcontrol/customizing-appearance/formatting-blocks.md index 5eeb03d22..1181324fe 100644 --- a/controls/editors/textboxcontrol/customizing-appearance/formatting-blocks.md +++ b/controls/editors/textboxcontrol/customizing-appearance/formatting-blocks.md @@ -15,50 +15,16 @@ The RadTextBoxControl allow appearance customization of each instance of __IText #### Subscribing to TextBlockFormatting event -{{source=..\SamplesCS\Editors\TextBoxControl.cs region=Formatting1}} -{{source=..\SamplesVB\Editors\TextBoxControl.vb region=Formatting1}} -````C# - -this.radTextBoxControl1.TextBlockFormatting += this.OnTextBlockFormatting; -this.radTextBoxControl1.Text = "This is important text."; + + -```` -````VB.NET -AddHandler Me.RadTextBoxControl1.TextBlockFormatting, AddressOf Me.OnTextBlockFormatting -Me.RadTextBoxControl1.Text = "This is important text." -```` - -{{endregion}} #### The TextBlockFormatting event handler -{{source=..\SamplesCS\Editors\TextBoxControl.cs region=formatting2}} -{{source=..\SamplesVB\Editors\TextBoxControl.vb region=formatting2}} - -````C# - -private void OnTextBlockFormatting(object sender, Telerik.WinControls.UI.TextBlockFormattingEventArgs e) -{ - TextBlockElement textBlock = e.TextBlock as TextBlockElement; - if (textBlock != null && e.TextBlock.Text == "important") - { - textBlock.ForeColor = Color.Red; - } -} - -```` -````VB.NET -Private Sub OnTextBlockFormatting(sender As Object, e As Telerik.WinControls.UI.TextBlockFormattingEventArgs) - Dim textBlock As TextBlockElement = TryCast(e.TextBlock, TextBlockElement) - If textBlock IsNot Nothing AndAlso e.TextBlock.Text = "important" Then - textBlock.ForeColor = Color.Red - End If -End Sub - -```` + + -{{endregion}} ![WinForms RadTextBoxControl Formatting Blocks](images/editors-textboxcontrol-formatting-blocks001.png) diff --git a/controls/editors/textboxcontrol/getting-started.md b/controls/editors/textboxcontrol/getting-started.md index 2d218373f..4a6c1750a 100644 --- a/controls/editors/textboxcontrol/getting-started.md +++ b/controls/editors/textboxcontrol/getting-started.md @@ -41,107 +41,40 @@ The text displayed by the control resides in the __Text__ property. It can be se The code below sets text in the control at run time: -{{source=..\SamplesCS\Editors\TextBoxControl.cs region=SetText}} -{{source=..\SamplesVB\Editors\TextBoxControl.vb region=SetText}} + + -````C# - -private void SetDefaultText() -{ - this.radTextBoxControl1.Text = "Type your name here."; -} - -```` -````VB.NET -Private Sub SetDefaultText() - Me.RadTextBoxControl1.Text = "Type your name here." -End Sub - -```` -{{endregion}} >caption Figure 1: Set the text at runtime. ![WinForms RadTextBoxControl Text Runtime](images/editors-textboxcontrol-getting-started001.png) You can also define the lines in the text box at run time: -{{source=..\SamplesCS\Editors\TextBoxControl.cs region=Lines}} -{{source=..\SamplesVB\Editors\TextBoxControl.vb region=Lines}} + + + -````C# - -private void SetLines() -{ - string[] lines = new string[] - { - "Dear Sir or Madam,", - "I writing to you regarding your publication in Daily Mail.", - "Could you give me the resources that you have used?" - }; - this.radTextBoxControl1.Lines = lines; -} - -```` -````VB.NET -Private Sub SetLines() - Dim lines As String() = New String() {"Dear Sir or Madam,", "I writing to you regarding your publication in Daily Mail.", "Could you give me the resources that you have used?"} - Me.RadTextBoxControl1.Lines = lines -End Sub - -```` - -{{endregion}} >caption Figure 2: Set the lines of a multiline text box. ![WinForms RadTextBoxControl Multiline](images/editors-textboxcontrol-getting-started002.png) By setting the __NullText__ property, the control will display a custom string when the __Text__ property is empty or null: -{{source=..\SamplesCS\Editors\TextBoxControl.cs region=SetNullText}} -{{source=..\SamplesVB\Editors\TextBoxControl.vb region=SetNullText}} + + -````C# - -private void SetNullText() -{ - this.radTextBoxControl1.NullText = "Type your name..."; -} -```` -````VB.NET -Private Sub SetNullText() - Me.RadTextBoxControl1.NullText = "Type your name..." -End Sub - -```` - -{{endregion}} >caption Figure 3: Setting the null text. ![WinForms RadTextBoxControl Null Text](images/editors-textboxcontrol-getting-started003.png) Based on the value set to the __TextAlign__ property, the control will display its content aligned to the left, center or right: -{{source=..\SamplesCS\Editors\TextBoxControl.cs region=SetTextAlign}} -{{source=..\SamplesVB\Editors\TextBoxControl.vb region=SetTextAlign}} - -````C# - -public void SetTextAlign() -{ - this.radTextBoxControl1.TextAlign = HorizontalAlignment.Left; -} - -```` -````VB.NET -Private Sub SetTextAlign() - Me.RadTextBoxControl1.TextAlign = HorizontalAlignment.Left -End Sub + + -```` -{{endregion}} >caption Figure 4: Aligning the text to different positions. ![WinForms RadTextBoxControl Aligning Text](images/editors-textboxcontrol-getting-started004.png) diff --git a/controls/editors/textboxcontrol/localization.md b/controls/editors/textboxcontrol/localization.md index 4c232c0f9..741b80aa1 100644 --- a/controls/editors/textboxcontrol/localization.md +++ b/controls/editors/textboxcontrol/localization.md @@ -84,9 +84,6 @@ To apply the custom localization provider, instantiate and assign it to the cur TextBoxControlLocalizationProvider.CurrentProvider = New CustomTextBoxControlLocalizationProvider() ```` - -{{endregion}} - # See Also * [AutoComplete]({%slug winforms/editors/textboxcontrol/autocomplete%}) diff --git a/controls/editors/textboxcontrol/properties.md b/controls/editors/textboxcontrol/properties.md index ff8f8ce73..0fabe64f7 100644 --- a/controls/editors/textboxcontrol/properties.md +++ b/controls/editors/textboxcontrol/properties.md @@ -55,23 +55,10 @@ Since R2 2021 **RadTextBoxControl** supports embedded labels. The embedded label #### Example 1: Setting the embedded label -{{source=..\SamplesCS\Editors\TextBoxControl.cs region=EmbeddedLabels}} -{{source=..\SamplesVB\Editors\TextBoxControl.vb region=EmbeddedLabels}} + + -````C# -this.radTextBoxControl1.ShowEmbeddedLabel = true; -this.radTextBoxControl1.AutoSize = true; -this.radTextBoxControl1.EmbeddedLabelText = "First Name"; -```` -````VB.NET -Me.RadTextBoxControl1.ShowEmbeddedLabel = True -Me.RadTextBoxControl1.AutoSize = True -Me.RadTextBoxControl1.EmbeddedLabelText = "First Name" - -```` - -{{endregion}} ![WinForms RadTextBoxControl Embedded Label](images/editors-textboxcontrol-properties-embedded-labels.gif) diff --git a/controls/editors/textboxcontrol/text-editing.md b/controls/editors/textboxcontrol/text-editing.md index 584ffa200..2b4b0b6f5 100644 --- a/controls/editors/textboxcontrol/text-editing.md +++ b/controls/editors/textboxcontrol/text-editing.md @@ -17,29 +17,11 @@ The editing point is determined by the caret position and selection in __RadText You can insert text programmatically at concrete position by using the __Insert__ method. At that case, the text is inserted at the position determined by the __SelectionStart__ property. If the __SelectionLength__ property is greater than zero, the inserted text replaces the selected text. #### Insert string. -{{source=..\SamplesCS\Editors\TextBoxControl.cs region=Insert}} -{{source=..\SamplesVB\Editors\TextBoxControl.vb region=Insert}} - -````C# -private void Insert() -{ - this.radTextBoxControl1.Text = "Green"; - this.radTextBoxControl1.CaretIndex = 0; - this.radTextBoxControl1.Insert("John "); -} - -```` -````VB.NET -Private Sub Insert() - Me.RadTextBoxControl1.Text = "Green" - Me.RadTextBoxControl1.CaretIndex = 0 - Me.RadTextBoxControl1.Insert("John ") -End Sub - -```` - -{{endregion}} - + + + + + >caption Figure 1: The string is inserted at the specified position. ![WinForms RadTextBoxControl Insert String](images/editors-textboxcontrol-text-editing001.png) @@ -47,27 +29,11 @@ End Sub Alternatively, you can insert text at the end of the RadTextBoxControl content by using the __AppendText__ method: ### Append specific string. -{{source=..\SamplesCS\Editors\TextBoxControl.cs region=AppendText}} -{{source=..\SamplesVB\Editors\TextBoxControl.vb region=AppendText}} - -````C# -private void AppendText() -{ - this.radTextBoxControl1.Text = "Samuel"; - this.radTextBoxControl1.AppendText(" Jackson"); -} - -```` -````VB.NET -Private Sub AppendText() - Me.RadTextBoxControl1.Text = "Samuel" - Me.RadTextBoxControl1.AppendText(" Jackson") -End Sub - -```` - -{{endregion}} - + + + + + >caption Figure 2: The string is added at the end of the existing text. ![WinForms RadTextBoxControl Add String At The End](images/editors-textboxcontrol-text-editing002.png) @@ -75,29 +41,11 @@ End Sub You can delete the selected text or character at the caret position by using the __Delete__ method: #### Select and delete a word. -{{source=..\SamplesCS\Editors\TextBoxControl.cs region=Delete}} -{{source=..\SamplesVB\Editors\TextBoxControl.vb region=Delete}} - -````C# -private void DeleteSelection() -{ - this.radTextBoxControl1.Text = "John Green"; - this.radTextBoxControl1.Select(0, 4); - this.radTextBoxControl1.Delete(); -} - -```` -````VB.NET -Private Sub DeleteSelection() - Me.RadTextBoxControl1.Text = "John Green" - Me.RadTextBoxControl1.[Select](0, 4) - Me.RadTextBoxControl1.Delete() -End Sub - -```` - -{{endregion}} - + + + + + >caption Figure 3: The first word is deleted. ![WinForms RadTextBoxControl Delete First Word](images/editors-textboxcontrol-text-editing003.png) @@ -106,25 +54,10 @@ Each editing operation raises the __TextChanging__ and __TextChanged__ events. N #### Cancel the ex changing if the entire text is deleted. -{{source=..\SamplesCS\Editors\TextBoxControl.cs region=TextChanging}} -{{source=..\SamplesVB\Editors\TextBoxControl.vb region=TextChanging}} - -````C# - -private void radTextBoxControl1_TextChanging(object sender, Telerik.WinControls.TextChangingEventArgs e) -{ - e.Cancel = string.IsNullOrEmpty(e.NewValue); -} - -```` -````VB.NET -Private Sub radTextBoxControl1_TextChanging(sender As Object, e As Telerik.WinControls.TextChangingEventArgs) - e.Cancel = String.IsNullOrEmpty(e.NewValue) -End Sub + + -```` -{{endregion}} # See Also diff --git a/controls/editors/timeonlypicker/customizing-appearance/customizing-programatically.md b/controls/editors/timeonlypicker/customizing-appearance/customizing-programatically.md index 476e800fc..1251303d7 100644 --- a/controls/editors/timeonlypicker/customizing-appearance/customizing-programatically.md +++ b/controls/editors/timeonlypicker/customizing-appearance/customizing-programatically.md @@ -96,9 +96,6 @@ Me.RadTimeOnlyPicker1.TimeOnlyPickerElement.PopupContentElement.ClockHeaderEleme Me.RadTimeOnlyPicker1.TimeOnlyPickerElement.PopupContentElement.ClockElement.SecondsArrow.Visibility = Telerik.WinControls.ElementVisibility.Collapsed ```` - -{{endregion}} - ![WinForms RadTimeOnlyPicker Customize Clock Element Appearance](images/editors-timeonlypicker-customization004.png) ## Customize hours and minutes headers @@ -196,9 +193,6 @@ Me.RadTimeOnlyPicker1.TimeOnlyPickerElement.PopupContentElement.MinutesTable.Gra Me.RadTimeOnlyPicker1.TimeOnlyPickerElement.PopupContentElement.MinutesTable.BackColor = Color.Blue ```` - -{{endregion}} - ![WinForms RadTimeOnlyPicker Customize Hours and Minutes Tables](images/editors-timeonlypicker-customization007.png) ## Customize Button Panel diff --git a/controls/editors/timepicker/customizing-appearance/customizing-programatically.md b/controls/editors/timepicker/customizing-appearance/customizing-programatically.md index abd68e63f..d20fcc3ec 100644 --- a/controls/editors/timepicker/customizing-appearance/customizing-programatically.md +++ b/controls/editors/timepicker/customizing-appearance/customizing-programatically.md @@ -18,22 +18,10 @@ Each of the control's elements can be accessed and customized. At the [Structure For example the editable area of the control consist of __RadTextBoxItem__ hosted in __RadMaskedEditBoxElement__. So in order to customize the text box __BackColor__ you need to set both the __BackColor__ of the __RadTextBoxItem__ and of the __RadMaskedEditBoxElement__ `FillPrimitive`: -{{source=..\SamplesCS\Editors\TimePicker1.cs region=CustomizeTextBox}} -{{source=..\SamplesVB\Editors\TimePicker1.vb region=CustomizeTextBox}} + + -````C# -radTimePicker1.TimePickerElement.MaskedEditBox.Fill.BackColor = Color.Red; -radTimePicker1.TimePickerElement.MaskedEditBox.TextBoxItem.BackColor = Color.Red; -```` -````VB.NET -RadTimePicker1.TimePickerElement.MaskedEditBox.Fill.BackColor = Color.Red -RadTimePicker1.TimePickerElement.MaskedEditBox.TextBoxItem.BackColor = Color.Red - -```` - -{{endregion}} - ![WinForms RadDateTimePicker Customize Text Box](images/editors-timepicker-customization001.png) @@ -41,20 +29,10 @@ RadTimePicker1.TimePickerElement.MaskedEditBox.TextBoxItem.BackColor = Color.Red Here is how you can set some left and right padding of the drop down button: -{{source=..\SamplesCS\Editors\TimePicker1.cs region=CustomizeDropDownButton}} -{{source=..\SamplesVB\Editors\TimePicker1.vb region=CustomizeDropDownButton}} - -````C# -radTimePicker1.TimePickerElement.DropDownButton.Padding = new Padding(10,0,10,0); + + -```` -````VB.NET -RadTimePicker1.TimePickerElement.DropDownButton.Padding = New Windows.Forms.Padding(10, 0, 10, 0) -```` - -{{endregion}} - ![WinForms RadDateTimePicker Customize DropDown Button](images/editors-timepicker-customization002.png) @@ -62,25 +40,10 @@ RadTimePicker1.TimePickerElement.DropDownButton.Padding = New Windows.Forms.Padd Here is how to access and set the border color of the arrow buttons: -{{source=..\SamplesCS\Editors\TimePicker1.cs region=CustomizeArrowButtons}} -{{source=..\SamplesVB\Editors\TimePicker1.vb region=CustomizeArrowButtons}} - -````C# -radTimePicker1.TimePickerElement.UpButton.Border.GradientStyle = Telerik.WinControls.GradientStyles.Solid; -radTimePicker1.TimePickerElement.UpButton.Border.ForeColor = Color.Blue; -radTimePicker1.TimePickerElement.DownButton.Border.GradientStyle = Telerik.WinControls.GradientStyles.Solid; -radTimePicker1.TimePickerElement.DownButton.Border.ForeColor = Color.Blue; + + -```` -````VB.NET -RadTimePicker1.TimePickerElement.UpButton.Border.GradientStyle = Telerik.WinControls.GradientStyles.Solid -RadTimePicker1.TimePickerElement.UpButton.Border.ForeColor = Color.Blue -RadTimePicker1.TimePickerElement.DownButton.Border.GradientStyle = Telerik.WinControls.GradientStyles.Solid -RadTimePicker1.TimePickerElement.DownButton.Border.ForeColor = Color.Blue -```` - -{{endregion}} ![WinForms RadDateTimePicker Customize Up/Down Buttons](images/editors-timepicker-customization003.png) @@ -88,29 +51,10 @@ RadTimePicker1.TimePickerElement.DownButton.Border.ForeColor = Color.Blue Here is how to change the clock header background and font and also how to hide the seconds arrow from the clock: -{{source=..\SamplesCS\Editors\TimePicker1.cs region=CustomizeClock}} -{{source=..\SamplesVB\Editors\TimePicker1.vb region=CustomizeClock}} - -````C# -//customize header -radTimePicker1.TimePickerElement.PopupContentElement.ClockHeaderElement.Font = new System.Drawing.Font("Arial", 22); -radTimePicker1.TimePickerElement.PopupContentElement.ClockHeaderElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid; -radTimePicker1.TimePickerElement.PopupContentElement.ClockHeaderElement.BackColor = Color.YellowGreen; -//hide seconds arrow -radTimePicker1.TimePickerElement.PopupContentElement.ClockElement.SecondsArrow.Visibility = Telerik.WinControls.ElementVisibility.Collapsed; + + -```` -````VB.NET - -RadTimePicker1.TimePickerElement.PopupContentElement.ClockHeaderElement.Font = New System.Drawing.Font("Arial", 22) -RadTimePicker1.TimePickerElement.PopupContentElement.ClockHeaderElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid -RadTimePicker1.TimePickerElement.PopupContentElement.ClockHeaderElement.BackColor = Color.YellowGreen - -RadTimePicker1.TimePickerElement.PopupContentElement.ClockElement.SecondsArrow.Visibility = Telerik.WinControls.ElementVisibility.Collapsed -```` - -{{endregion}} ![WinForms RadDateTimePicker Customize Clock Element Appearance](images/editors-timepicker-customization004.png) @@ -118,33 +62,10 @@ RadTimePicker1.TimePickerElement.PopupContentElement.ClockElement.SecondsArrow.V This code snippet demonstrates how to change the hours header back color and the minutes header border appearance: -{{source=..\SamplesCS\Editors\TimePicker1.cs region=CustomizeHoursAndMinutesHeaders}} -{{source=..\SamplesVB\Editors\TimePicker1.vb region=CustomizeHoursAndMinutesHeaders}} - -````C# -//hours header -radTimePicker1.TimePickerElement.PopupContentElement.HoursTable.TableHeader.GradientStyle = Telerik.WinControls.GradientStyles.Solid; -radTimePicker1.TimePickerElement.PopupContentElement.HoursTable.TableHeader.BackColor = Color.Yellow; -//minutes header -radTimePicker1.TimePickerElement.PopupContentElement.MinutesTable.TableHeader.HeaderElement.DrawBorder = true; -radTimePicker1.TimePickerElement.PopupContentElement.MinutesTable.TableHeader.HeaderElement.BorderWidth = 3; -radTimePicker1.TimePickerElement.PopupContentElement.MinutesTable.TableHeader.HeaderElement.BorderColor = Color.Red; -radTimePicker1.TimePickerElement.PopupContentElement.MinutesTable.TableHeader.HeaderElement.BorderGradientStyle = Telerik.WinControls.GradientStyles.Solid; - -```` -````VB.NET - -RadTimePicker1.TimePickerElement.PopupContentElement.HoursTable.TableHeader.GradientStyle = Telerik.WinControls.GradientStyles.Solid -RadTimePicker1.TimePickerElement.PopupContentElement.HoursTable.TableHeader.BackColor = Color.Yellow - -RadTimePicker1.TimePickerElement.PopupContentElement.MinutesTable.TableHeader.HeaderElement.DrawBorder = True -RadTimePicker1.TimePickerElement.PopupContentElement.MinutesTable.TableHeader.HeaderElement.BorderWidth = 3 -RadTimePicker1.TimePickerElement.PopupContentElement.MinutesTable.TableHeader.HeaderElement.BorderColor = Color.Red -RadTimePicker1.TimePickerElement.PopupContentElement.MinutesTable.TableHeader.HeaderElement.BorderGradientStyle = Telerik.WinControls.GradientStyles.Solid + + -```` -{{endregion}} ![WinForms RadDateTimePicker Customize Hours and Minutes Headers](images/editors-timepicker-customization005.png) @@ -152,43 +73,10 @@ RadTimePicker1.TimePickerElement.PopupContentElement.MinutesTable.TableHeader.He The cells in both minutes and hours tables are placed in a GridLayout. To customize the cells, you can use the TimeCellFormatting event of the control: -{{source=..\SamplesCS\Editors\TimePicker1.cs region=CellFormatting}} -{{source=..\SamplesVB\Editors\TimePicker1.vb region=CellFormatting}} - -````C# -void radTimePicker1_TimeCellFormatting(object sender, Telerik.WinControls.UI.TimeCellFormattingEventArgs e) -{ - e.Element.GradientStyle = Telerik.WinControls.GradientStyles.Solid; - e.Element.Margin = new Padding(2); - if (e.IsMinute) - { - //set minute cells specific properties - e.Element.BackColor = Color.Lime; - } - else - { - //set hours cells specific properties - e.Element.BackColor = Color.Green; - } -} - -```` -````VB.NET -Private Sub radTimePicker1_TimeCellFormatting(sender As Object, e As Telerik.WinControls.UI.TimeCellFormattingEventArgs) - e.Element.GradientStyle = Telerik.WinControls.GradientStyles.Solid - e.Element.Margin = New Windows.Forms.Padding(2) - If e.IsMinute Then - - e.Element.BackColor = Color.Lime - Else - - e.Element.BackColor = Color.Green - End If -End Sub - -```` - -{{endregion}} + + + + ![WinForms RadDateTimePicker Customize Hours and Minutes Cells Appearance](images/editors-timepicker-customization006.png) @@ -196,33 +84,10 @@ End Sub This is how you can set the hours and minutes tables background color: -{{source=..\SamplesCS\Editors\TimePicker1.cs region=CustomizeHoursAndMinutesTables}} -{{source=..\SamplesVB\Editors\TimePicker1.vb region=CustomizeHoursAndMinutesTables}} - -````C# -//hours table -radTimePicker1.TimePickerElement.PopupContentElement.HoursTable.DrawFill = true; -radTimePicker1.TimePickerElement.PopupContentElement.HoursTable.GradientStyle = Telerik.WinControls.GradientStyles.Solid; -radTimePicker1.TimePickerElement.PopupContentElement.HoursTable.BackColor = Color.Red; -//minutes table -radTimePicker1.TimePickerElement.PopupContentElement.MinutesTable.DrawFill = true; -radTimePicker1.TimePickerElement.PopupContentElement.MinutesTable.GradientStyle = Telerik.WinControls.GradientStyles.Solid; -radTimePicker1.TimePickerElement.PopupContentElement.MinutesTable.BackColor = Color.Blue; - -```` -````VB.NET - -RadTimePicker1.TimePickerElement.PopupContentElement.HoursTable.DrawFill = True -RadTimePicker1.TimePickerElement.PopupContentElement.HoursTable.GradientStyle = Telerik.WinControls.GradientStyles.Solid -RadTimePicker1.TimePickerElement.PopupContentElement.HoursTable.BackColor = Color.Red - -RadTimePicker1.TimePickerElement.PopupContentElement.MinutesTable.DrawFill = True -RadTimePicker1.TimePickerElement.PopupContentElement.MinutesTable.GradientStyle = Telerik.WinControls.GradientStyles.Solid -RadTimePicker1.TimePickerElement.PopupContentElement.MinutesTable.BackColor = Color.Blue - -```` - -{{endregion}} + + + + ![WinForms RadDateTimePicker Customize Hours and Minutes Tables](images/editors-timepicker-customization007.png) @@ -230,19 +95,10 @@ RadTimePicker1.TimePickerElement.PopupContentElement.MinutesTable.BackColor = Co Here is how to change the BackColor of the FooterPanel: -{{source=..\SamplesCS\Editors\TimePicker1.cs region=CustomizeFooterPanel}} -{{source=..\SamplesVB\Editors\TimePicker1.vb region=CustomizeFooterPanel}} - -````C# -radTimePicker1.TimePickerElement.PopupContentElement.FooterPanel.BackColor = Color.BlanchedAlmond; - -```` -````VB.NET -RadTimePicker1.TimePickerElement.PopupContentElement.FooterPanel.BackColor = Color.BlanchedAlmond + + -```` -{{endregion}} ![WinForms RadDateTimePicker Customize Button Panel](images/editors-timepicker-customization008.png) diff --git a/controls/editors/timepicker/free-form-date-time-parsing.md b/controls/editors/timepicker/free-form-date-time-parsing.md index b759bdcaf..b8e0d63d2 100644 --- a/controls/editors/timepicker/free-form-date-time-parsing.md +++ b/controls/editors/timepicker/free-form-date-time-parsing.md @@ -17,20 +17,9 @@ From Q2 2014 we introduced new MaskType of RadMaskedEditBox that is designed to The embedded text editor of RadTimePicker is RadMaskedEditBox. So if you want to take the advantages from new DateTime parsing logic the only thing that you should to do is to change the MaskType of embedded editor. -{{source=..\SamplesCS\Editors\TimePicker1.cs region=FreeFormDateTimeTimePicker}} -{{source=..\SamplesVB\Editors\TimePicker1.vb region=FreeFormDateTimeTimePicker}} - -````C# - -this.radTimePicker1.TimePickerElement.MaskedEditBox.MaskType = MaskType.FreeFormDateTime; - -```` -````VB.NET -Me.RadTimePicker1.TimePickerElement.MaskedEditBox.MaskType = MaskType.FreeFormDateTime - -```` - -{{endregion}} - - + + + + + ## diff --git a/controls/editors/timepicker/localization.md b/controls/editors/timepicker/localization.md index f6e978cd8..b754863f6 100644 --- a/controls/editors/timepicker/localization.md +++ b/controls/editors/timepicker/localization.md @@ -23,66 +23,20 @@ Below is a sample implementation of an English localization provider: #### Localizing RadTimePicker Strings -{{source=..\SamplesCS\Editors\TimePicker1.cs region=LocalizationProvider}} -{{source=..\SamplesVB\Editors\TimePicker1.vb region=LocalizationProvider}} - -````C# -class MyTimePickerLocalizationProvider : RadTimePickerLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case RadTimePickerStringId.HourHeaderText: return "Hours"; - case RadTimePickerStringId.MinutesHeaderText: return "Minutes"; - case RadTimePickerStringId.CloseButtonText: return "Close"; - default: return string.Empty; - } - } -} - -```` -````VB.NET -Class MyTimePickerLocalizationProvider - Inherits RadTimePickerLocalizationProvider - Public Overrides Function GetLocalizedString(id As String) As String - Select Case id - Case RadTimePickerStringId.HourHeaderText - Return "Hours" - Case RadTimePickerStringId.MinutesHeaderText - Return "Minutes" - Case RadTimePickerStringId.CloseButtonText - Return "Close" - Case Else - Return String.Empty - End Select - End Function -End Class - -```` - -{{endregion}} - - + + + + + To apply the custom localization provider, instantiate and assign it to the current localization provider: #### Assigning the Current Localization Provider -{{source=..\SamplesCS\Editors\TimePicker1.cs region=settingTheLocalizationProvider}} -{{source=..\SamplesVB\Editors\TimePicker1.vb region=settingTheLocalizationProvider}} - -````C# -RadTimePickerLocalizationProvider.CurrentProvider = new MyTimePickerLocalizationProvider(); - -```` -````VB.NET -RadTimePickerLocalizationProvider.CurrentProvider = New MyTimePickerLocalizationProvider() - -```` - -{{endregion}} - - + + + + + The code provided above illustrates the approach to be used to localize the __RadTimePicker__ and is not intended as a full translation. # See Also diff --git a/controls/editors/timespanpicker/customizing-appearance/customizing-appearance.md b/controls/editors/timespanpicker/customizing-appearance/customizing-appearance.md index 1a43d099b..2879ea043 100644 --- a/controls/editors/timespanpicker/customizing-appearance/customizing-appearance.md +++ b/controls/editors/timespanpicker/customizing-appearance/customizing-appearance.md @@ -28,69 +28,10 @@ The drop down consist of several **ListControlElements** which represent the tim #### Formating Items in the Popup -{{source=..\SamplesCS\Editors\TimeSpanCode.cs region=Formatting}} -{{source=..\SamplesVB\Editors\TimeSpanCode.vb region=Formatting}} -````C# -protected override void OnLoad(EventArgs e) -{ - base.OnLoad(e); - radTimeSpanPicker1.PopupContentElement.ComponentsCreated += PopupContentElement_ComponentsCreated; -} -private void PopupContentElement_ComponentsCreated(object sender, EventArgs e) -{ - foreach (ITimeSpanPickerComponent component in radTimeSpanPicker1.PopupContentElement.Components) - { - ListTimeSpanPickerUIComponent listUiCompoinent = component.TimeSpanPickerUIComponent as ListTimeSpanPickerUIComponent; - listUiCompoinent.ListElement.Tag = this.radTimeSpanPicker1.PopupContentElement.Components.IndexOf(component as RadItem); - listUiCompoinent.ListElement.VisualItemFormatting += ListElement_VisualItemFormatting; - } -} -private void ListElement_VisualItemFormatting(object sender, VisualItemFormattingEventArgs args) -{ - int componentIndex = (int)args.VisualItem.Data.Owner.Tag; - if (componentIndex == 1) - { - args.VisualItem.BackColor = ColorTranslator.FromHtml("#f5c020"); - args.VisualItem.ForeColor = ColorTranslator.FromHtml("#008de7"); - args.VisualItem.GradientStyle = GradientStyles.Solid; - } - else - { - args.VisualItem.ResetValue(RadListVisualItem.BackColorProperty, ValueResetFlags.Local); - args.VisualItem.ResetValue(RadListVisualItem.GradientStyleProperty, ValueResetFlags.Local); - args.VisualItem.ResetValue(RadListVisualItem.ForeColorProperty, ValueResetFlags.Local); - } -} - -```` -````VB.NET -Protected Overrides Sub OnLoad(ByVal e As EventArgs) - MyBase.OnLoad(e) - AddHandler radTimeSpanPicker1.PopupContentElement.ComponentsCreated, AddressOf PopupContentElement_ComponentsCreated -End Sub -Private Sub PopupContentElement_ComponentsCreated(ByVal sender As Object, ByVal e As EventArgs) - For Each component As ITimeSpanPickerComponent In radTimeSpanPicker1.PopupContentElement.Components - Dim listUiCompoinent As ListTimeSpanPickerUIComponent = TryCast(component.TimeSpanPickerUIComponent, ListTimeSpanPickerUIComponent) - listUiCompoinent.ListElement.Tag = Me.radTimeSpanPicker1.PopupContentElement.Components.IndexOf(TryCast(component, RadItem)) - AddHandler listUiCompoinent.ListElement.VisualItemFormatting, AddressOf ListElement_VisualItemFormatting - Next component -End Sub -Private Sub ListElement_VisualItemFormatting(ByVal sender As Object, ByVal args As VisualItemFormattingEventArgs) - Dim componentIndex As Integer = CInt(Fix(args.VisualItem.Data.Owner.Tag)) - If componentIndex = 1 Then - args.VisualItem.BackColor = ColorTranslator.FromHtml("#f5c020") - args.VisualItem.ForeColor = ColorTranslator.FromHtml("#008de7") - args.VisualItem.GradientStyle = GradientStyles.Solid - Else - args.VisualItem.ResetValue(RadListVisualItem.BackColorProperty, ValueResetFlags.Local) - args.VisualItem.ResetValue(RadListVisualItem.GradientStyleProperty, ValueResetFlags.Local) - args.VisualItem.ResetValue(RadListVisualItem.ForeColorProperty, ValueResetFlags.Local) - End If -End Sub - -```` - -{{endregion}} + + + + Here is the result. diff --git a/controls/editors/timespanpicker/format-string.md b/controls/editors/timespanpicker/format-string.md index bfc0b0727..e51e3ecfa 100644 --- a/controls/editors/timespanpicker/format-string.md +++ b/controls/editors/timespanpicker/format-string.md @@ -16,18 +16,10 @@ If you want to add a specific content to the string you will need to enclose in #### Using a custom format string -{{source=..\SamplesCS\Editors\TimeSpanCode.cs region=FormatString}} -{{source=..\SamplesVB\Editors\TimeSpanCode.vb region=FormatString}} -````C# -radTimeSpanPicker1.Format = "dd\'days \'hh\'hours \'mm\'minutes \'ss\'seconds \'fff\'milliseconds\'"; + + -```` -````VB.NET -radTimeSpanPicker1.Format = "dd'days 'hh'hours 'mm'minutes 'ss'seconds 'fff'milliseconds'" -```` - -{{endregion}} You can find in the screenshot below the obtained result. diff --git a/controls/editors/timespanpicker/getting-started.md b/controls/editors/timespanpicker/getting-started.md index 77a3b1b04..964902954 100644 --- a/controls/editors/timespanpicker/getting-started.md +++ b/controls/editors/timespanpicker/getting-started.md @@ -42,18 +42,10 @@ This topic will walk you through the process of creating of __RadTimeSpanPicker_ 2\. In the code behind set the value of the control. -{{source=..\SamplesCS\Editors\TimeSpanCode.cs region=getting-started}} -{{source=..\SamplesVB\Editors\TimeSpanCode.vb region=getting-started}} -````C# -this.radTimeSpanPicker1.Value = TimeSpan.FromDays(5); + + -```` -````VB.NET -Me.radTimeSpanPicker1.Value = TimeSpan.FromDays(5) -```` - -{{endregion}} 3\. You can start the application and enter a new value. diff --git a/controls/editors/timespanpicker/localization.md b/controls/editors/timespanpicker/localization.md index b187662b8..461f68106 100644 --- a/controls/editors/timespanpicker/localization.md +++ b/controls/editors/timespanpicker/localization.md @@ -21,70 +21,14 @@ To localize __RadTimeSpanPicker__ to display any text and messages in a specific Below is a sample implementation of an English localization provider: -{{source=..\SamplesCS\Editors\TimeSpanCode.cs region=Localization}} -{{source=..\SamplesVB\Editors\TimeSpanCode.vb region=Localization}} -````C# -class MyRadTimeSpanPickerLocalizationProvider : RadTimeSpanPickerLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case RadTimeSpanPickerStringId.NullText: return "Select time span"; - case RadTimeSpanPickerStringId.DaysText: return "Days"; - case RadTimeSpanPickerStringId.HoursText: return "Hours"; - case RadTimeSpanPickerStringId.MinutesText: return "Minutes"; - case RadTimeSpanPickerStringId.SecondsText: return "Seconds"; - case RadTimeSpanPickerStringId.MillisecondsText: return "Milliseconds"; - case RadTimeSpanPickerStringId.CloseButtonText: return "Close"; - } - return base.GetLocalizedString(id); - } -} + + -```` -````VB.NET -Friend Class MyRadTimeSpanPickerLocalizationProvider - Inherits RadTimeSpanPickerLocalizationProvider - Public Overrides Function GetLocalizedString(ByVal id As String) As String - Select Case id - Case RadTimeSpanPickerStringId.NullText - Return "Select time span" - Case RadTimeSpanPickerStringId.DaysText - Return "Days" - Case RadTimeSpanPickerStringId.HoursText - Return "Hours" - Case RadTimeSpanPickerStringId.MinutesText - Return "Minutes" - Case RadTimeSpanPickerStringId.SecondsText - Return "Seconds" - Case RadTimeSpanPickerStringId.MillisecondsText - Return "Milliseconds" - Case RadTimeSpanPickerStringId.CloseButtonText - Return "Close" - End Select - Return MyBase.GetLocalizedString(id) - End Function -End Class -```` - -{{endregion}} To apply the custom localization provider, instantiate and assign it to the current localization provider: #### Assigning the Current Localization Provider -{{source=..\SamplesCS\Editors\TimeSpanCode.cs region=ChangeProvider}} -{{source=..\SamplesVB\Editors\TimeSpanCode.vb region=ChangeProvider}} -````C# -RadTimeSpanPickerLocalizationProvider.CurrentProvider = new MyRadTimeSpanPickerLocalizationProvider(); - -```` -````VB.NET -RadTimeSpanPickerLocalizationProvider.CurrentProvider = New MyRadTimeSpanPickerLocalizationProvider() - -```` - -{{endregion}} - + + \ No newline at end of file diff --git a/controls/file-dialogs/dialog-controls/radopenfiledialog.md b/controls/file-dialogs/dialog-controls/radopenfiledialog.md index 6ccd1e78a..04c4d4c1d 100644 --- a/controls/file-dialogs/dialog-controls/radopenfiledialog.md +++ b/controls/file-dialogs/dialog-controls/radopenfiledialog.md @@ -25,31 +25,10 @@ To show the dialog call its **ShowDialog** method. If a valid file is opened whe #### Example 1: Show an open file dialog -{{source=..\SamplesCS\FileDialogs\FileDialogsEditingOptions.cs region=OpenFileDialogExample}} -{{source=..\SamplesVB\FileDialogs\FileDialogsEditingOptions.vb region=OpenFileDialogExample}} + + -````C# -RadOpenFileDialog openFileDialog = new RadOpenFileDialog(); -DialogResult dr = openFileDialog.ShowDialog(); -if (dr == System.Windows.Forms.DialogResult.OK) -{ - string fileName = openFileDialog.FileName; -} - -```` -````VB.NET - -Dim openFileDialog As RadOpenFileDialog = New RadOpenFileDialog() -Dim dr As DialogResult = openFileDialog.ShowDialog() - -If dr = System.Windows.Forms.DialogResult.OK Then - Dim fileName As String = openFileDialog.FileName -End If - -```` - -{{endregion}} ## Opening the Selected File @@ -57,31 +36,10 @@ You can open a read-only file stream for the selected file using the OpenFile me #### Example 2: Open a file stream -{{source=..\SamplesCS\FileDialogs\FileDialogsEditingOptions.cs region=OpenFileStreamExample}} -{{source=..\SamplesVB\FileDialogs\FileDialogsEditingOptions.vb region=OpenFileStreamExample}} - -````C# - -RadOpenFileDialog openFileDialog = new RadOpenFileDialog(); -DialogResult dr = openFileDialog.ShowDialog(); -if (dr == System.Windows.Forms.DialogResult.OK) -{ - Stream fileStream = openFileDialog.OpenFile(); -} - -```` -````VB.NET - -Dim openFileDialog As RadOpenFileDialog = New RadOpenFileDialog() -Dim dr As DialogResult = openFileDialog.ShowDialog() + + -If dr = System.Windows.Forms.DialogResult.OK Then - Dim fileStream As Stream = openFileDialog.OpenFile() -End If -```` - -{{endregion}} ## Enabling Multiple Selection @@ -89,24 +47,10 @@ The dialog supports single and multiple selection modes. By default, you can sel #### Example 3: Enable multiple selection -{{source=..\SamplesCS\FileDialogs\FileDialogsEditingOptions.cs region=MultipleSelectionExample}} -{{source=..\SamplesVB\FileDialogs\FileDialogsEditingOptions.vb region=MultipleSelectionExample}} - -````C# - -RadOpenFileDialog openFileDialog = new RadOpenFileDialog(); -openFileDialog.MultiSelect = true; - -```` -````VB.NET - -Dim openFileDialog As RadOpenFileDialog = New RadOpenFileDialog() -openFileDialog.MultiSelect = True + + -```` - -{{endregion}} >caption Figure 2: Multiple selection @@ -121,39 +65,10 @@ You can get only the name of the selected files, without the full path, via the #### Example 4: Get the selected file names -{{source=..\SamplesCS\FileDialogs\FileDialogsEditingOptions.cs region=SelectedFileNames}} -{{source=..\SamplesVB\FileDialogs\FileDialogsEditingOptions.vb region=SelectedFileNames}} - -````C# - -RadOpenFileDialog openFileDialog = new RadOpenFileDialog(); -openFileDialog.MultiSelect = true; -DialogResult dr = openFileDialog.ShowDialog(); -if (dr == System.Windows.Forms.DialogResult.OK) -{ - string filePath = openFileDialog.FileName; - IEnumerable filePaths = openFileDialog.FileNames; - IEnumerable fileNames = openFileDialog.SafeFileNames; -} - + + -```` -````VB.NET -Dim openFileDialog As RadOpenFileDialog = New RadOpenFileDialog() -openFileDialog.MultiSelect = True -Dim dr As DialogResult = openFileDialog.ShowDialog() - -If dr = System.Windows.Forms.DialogResult.OK Then - Dim filePath As String = openFileDialog.FileName - Dim filePaths As IEnumerable(Of String) = openFileDialog.FileNames - Dim fileNames As IEnumerable(Of String) = openFileDialog.SafeFileNames -End If - - -```` - -{{endregion}} The **FileName** property can be set manually. This will change the value displayed in the selected file auto-complete box area. Note that setting this won't change the selected item in the list with the files. @@ -163,23 +78,10 @@ You can save the last used directory by setting the **RestoreDirectory** propert #### Example 5: Set RestoreDirectory property -{{source=..\SamplesCS\FileDialogs\FileDialogsEditingOptions.cs region=RestoreDirectoryPropertyExample}} -{{source=..\SamplesVB\FileDialogs\FileDialogsEditingOptions.vb region=RestoreDirectoryPropertyExample}} - -````C# + + -RadOpenFileDialog openFileDialog = new RadOpenFileDialog(); -openFileDialog.RestoreDirectory = true; -```` -````VB.NET - -Dim openFileDialog As RadOpenFileDialog = New RadOpenFileDialog() -openFileDialog.RestoreDirectory = True - -```` - -{{endregion}} >important Note that the directory restoring feature works per dialog instance and only in memory. This means that the previously selected directory will be stored in a private string field of the RadOpenFolderDialog instance. In other words, to use the feature the following requirements should be met: * The same dialog instance should be used every time you open the dialog. @@ -192,27 +94,10 @@ You can display a checkbox to control whether the file should be opened in reado #### Example 6: Enabling the ReadOnly CheckBox -{{source=..\SamplesCS\FileDialogs\FileDialogsEditingOptions.cs region=EnablingReadOnlyCheckBoxExample}} -{{source=..\SamplesVB\FileDialogs\FileDialogsEditingOptions.vb region=EnablingReadOnlyCheckBoxExample}} - -````C# + + -RadOpenFileDialog openFileDialog = new RadOpenFileDialog(); -openFileDialog.ShowReadOnly = true; -openFileDialog.ReadOnlyChecked = true; -DialogResult dr = openFileDialog.ShowDialog(); -```` -````VB.NET - -Dim openFileDialog As RadOpenFileDialog = New RadOpenFileDialog() -openFileDialog.ShowReadOnly = True -openFileDialog.ReadOnlyChecked = True -Dim dr As DialogResult = openFileDialog.ShowDialog() - -```` - -{{endregion}} >caption Figure 3: RadOpenFileDialog with Checked ReadOnly CheckBox @@ -224,37 +109,10 @@ Dim dr As DialogResult = openFileDialog.ShowDialog() #### Example 7: Using the DereferenceLinks property -{{source=..\SamplesCS\FileDialogs\FileDialogsEditingOptions.cs region=UsingDereferenceLinksPropertyExample}} -{{source=..\SamplesVB\FileDialogs\FileDialogsEditingOptions.vb region=UsingDereferenceLinksPropertyExample}} - -````C# - -RadOpenFileDialog openFileDialog = new RadOpenFileDialog(); -openFileDialog.DereferenceLinks = true; -DialogResult dr = openFileDialog.ShowDialog(); -if (dr == System.Windows.Forms.DialogResult.OK) -{ - string filePath = openFileDialog.FileName; - // If the selected file was C:\Users\\Desktop\Shortcut.lnk, for example, - // the FileName property will now contain the actual location of the file, - // for example - C:\Program Files\Program\Shortcut.exe. -} - - -```` -````VB.NET - - Dim openFileDialog As RadOpenFileDialog = New RadOpenFileDialog() - openFileDialog.DereferenceLinks = True - Dim dr As DialogResult = openFileDialog.ShowDialog() - - If dr = System.Windows.Forms.DialogResult.OK Then - Dim filePath As String = openFileDialog.FileName - End If + + -```` -{{endregion}} >important If in multiple or single selection the first selected item is a link to a directory and **DereferenceLinks** is set to *True*, clicking the `Open` button will actually navigate to this directory. diff --git a/controls/file-dialogs/dialog-controls/radopenfolderdialog.md b/controls/file-dialogs/dialog-controls/radopenfolderdialog.md index 0b9e3e32e..96de51098 100644 --- a/controls/file-dialogs/dialog-controls/radopenfolderdialog.md +++ b/controls/file-dialogs/dialog-controls/radopenfolderdialog.md @@ -24,32 +24,10 @@ To show the dialog call its **ShowDialog** method. If a valid folder is opened w #### Example 1: Show a open folder dialog -{{source=..\SamplesCS\FileDialogs\FileDialogsEditingOptions.cs region=OpenFolderDialogExample}} -{{source=..\SamplesVB\FileDialogs\FileDialogsEditingOptions.vb region=OpenFolderDialogExample}} + + -````C# -RadOpenFolderDialog openFolderDialog = new RadOpenFolderDialog(); -DialogResult dr = openFolderDialog.ShowDialog(); -if (dr == System.Windows.Forms.DialogResult.OK) -{ - string folderName = openFolderDialog.FileName; -} - - -```` -````VB.NET - -Dim openFolderDialog As RadOpenFolderDialog = New RadOpenFolderDialog() -Dim dr As DialogResult = openFolderDialog.ShowDialog() - -If dr = System.Windows.Forms.DialogResult.OK Then - Dim folderName As String = openFolderDialog.FileName -End If - -```` - -{{endregion}} ## Enabling Multiple Selection @@ -57,23 +35,10 @@ The dialog supports single and multiple selection modes. By default, you can sel #### Example 2: Multiple selection -{{source=..\SamplesCS\FileDialogs\FileDialogsEditingOptions.cs region=MultipleSelection}} -{{source=..\SamplesVB\FileDialogs\FileDialogsEditingOptions.vb region=MultipleSelection}} - -````C# - -RadOpenFolderDialog openFolderDialog = new RadOpenFolderDialog(); -openFolderDialog.Multiselect = true; - -```` -````VB.NET - -Dim openFolderDialog As RadOpenFolderDialog = New RadOpenFolderDialog() -openFolderDialog.Multiselect = True + + -```` -{{endregion}} >caption Figure 2: Multiple Selection @@ -87,38 +52,10 @@ You can get only the name of the selected folders, without the full path, via th #### Example 3: Get the selected folder names -{{source=..\SamplesCS\FileDialogs\FileDialogsEditingOptions.cs region=SelectedFolderNames}} -{{source=..\SamplesVB\FileDialogs\FileDialogsEditingOptions.vb region=SelectedFolderNames}} + + -````C# -RadOpenFolderDialog openFolderDialog = new RadOpenFolderDialog(); -openFolderDialog.Multiselect = true; -DialogResult dr = openFolderDialog.ShowDialog(); -if (dr == System.Windows.Forms.DialogResult.OK) -{ - string folderPath = openFolderDialog.FileName; - IEnumerable folderPaths = openFolderDialog.FileNames; - IEnumerable folderNames = openFolderDialog.SafeFileNames; -} - - -```` -````VB.NET - -Dim openFolderDialog As RadOpenFolderDialog = New RadOpenFolderDialog() -openFolderDialog.Multiselect = True -Dim dr As DialogResult = openFolderDialog.ShowDialog() - -If dr = System.Windows.Forms.DialogResult.OK Then - Dim folderPath As String = openFolderDialog.FileName - Dim folderPaths As IEnumerable(Of String) = openFolderDialog.FileNames - Dim folderNames As IEnumerable(Of String) = openFolderDialog.SafeFileNames -End If - -```` - -{{endregion}} ## Saving the Last Used Directory @@ -126,23 +63,10 @@ You can save the last used directory by setting the **RestoreDirectory** propert #### Example 4: Set RestoreDirectory property -{{source=..\SamplesCS\FileDialogs\FileDialogsEditingOptions.cs region=RestoreDirectoryProperty}} -{{source=..\SamplesVB\FileDialogs\FileDialogsEditingOptions.vb region=RestoreDirectoryProperty}} - -````C# - -RadOpenFolderDialog openFolderDialog = new RadOpenFolderDialog(); -openFolderDialog.RestoreDirectory = true; - -```` -````VB.NET - -Dim openFolderDialog As RadOpenFolderDialog = New RadOpenFolderDialog() -openFolderDialog.RestoreDirectory = True + + -```` -{{endregion}} After setting this property to *True* and opening a folder the **InitialDirectory** of this **RadOpenFolderDialog** instance will be set to the parent of the opened folder. diff --git a/controls/file-dialogs/dialog-controls/radsavefiledialog.md b/controls/file-dialogs/dialog-controls/radsavefiledialog.md index 56557cc24..b5491617e 100644 --- a/controls/file-dialogs/dialog-controls/radsavefiledialog.md +++ b/controls/file-dialogs/dialog-controls/radsavefiledialog.md @@ -25,31 +25,10 @@ To show the dialog call its **ShowDialog** method. If a valid file is selected w #### Example 1: Show a save file dialog -{{source=..\SamplesCS\FileDialogs\FileDialogsEditingOptions.cs region=SaveFileDialogExample}} -{{source=..\SamplesVB\FileDialogs\FileDialogsEditingOptions.vb region=SaveFileDialogExample}} + + -````C# -RadSaveFileDialog saveFileDialog = new RadSaveFileDialog(); -DialogResult dr = saveFileDialog.ShowDialog(); -if (dr == System.Windows.Forms.DialogResult.OK) -{ - string selectedFileName = saveFileDialog.FileName; -} - -```` -````VB.NET - -Dim saveFileDialog As RadSaveFileDialog = New RadSaveFileDialog() -Dim dr As DialogResult = saveFileDialog.ShowDialog() - -If dr = System.Windows.Forms.DialogResult.OK Then - Dim selectedFileName As String = saveFileDialog.FileName -End If - -```` - -{{endregion}} ## Creating a stream for the selected file @@ -57,30 +36,10 @@ You can open a read-write file stream for the selected file using the **OpenFile #### Example 2: Open a file stream -{{source=..\SamplesCS\FileDialogs\FileDialogsEditingOptions.cs region=OpenFileStreamExample}} -{{source=..\SamplesVB\FileDialogs\FileDialogsEditingOptions.vb region=OpenFileStreamExample}} - -````C# + + -RadSaveFileDialog saveFileDialog = new RadSaveFileDialog(); -DialogResult dr = saveFileDialog.ShowDialog(); -if (dr == System.Windows.Forms.DialogResult.OK) -{ - Stream fileStream = saveFileDialog.OpenFile(); -} -```` -````VB.NET - -Dim saveFileDialog As RadSaveFileDialog = New RadSaveFileDialog() -Dim dr As DialogResult = saveFileDialog.ShowDialog() -If dr = System.Windows.Forms.DialogResult.OK Then - Dim fileStream As Stream = saveFileDialog.OpenFile() -End If - -```` - -{{endregion}} ## Working with the selected file @@ -90,26 +49,10 @@ The **FileName** property can be set manually. This will change the value displa #### Example 3: Set the file name -{{source=..\SamplesCS\FileDialogs\FileDialogsEditingOptions.cs region=SetFileNameExample}} -{{source=..\SamplesVB\FileDialogs\FileDialogsEditingOptions.vb region=SetFileNameExample}} - -````C# -RadSaveFileDialog saveFileDialog = new RadSaveFileDialog(); -saveFileDialog.InitialDirectory = @"C:\Program Files\Internet Explorer\"; -saveFileDialog.FileName = @"C:\Program Files\Internet Explorer\iexplore.exe"; -DialogResult dr = saveFileDialog.ShowDialog(); - -```` -````VB.NET - -Dim saveFileDialog As RadSaveFileDialog = New RadSaveFileDialog() -saveFileDialog.InitialDirectory = "C:\Program Files\Internet Explorer\" -saveFileDialog.FileName = "C:\Program Files\Internet Explorer\iexplore.exe" -Dim dr As DialogResult = saveFileDialog.ShowDialog() + + -```` -{{endregion}} >caption Figure 2: Setting the File Name diff --git a/controls/file-dialogs/features/context-menu.md b/controls/file-dialogs/features/context-menu.md index 05d041a70..5cef37fa5 100644 --- a/controls/file-dialogs/features/context-menu.md +++ b/controls/file-dialogs/features/context-menu.md @@ -21,44 +21,8 @@ The **ShellContextMenuOpening** event occurs when the context menu is about to o #### Modify ShellContextMenu -{{source=..\SamplesCS\FileDialogs\FileDialogsEditingOptions.cs region=Menu}} -{{source=..\SamplesVB\FileDialogs\FileDialogsEditingOptions.vb region=Menu}} + + -````C# - private void RadForm_Load(object sender, EventArgs e) - { - RadOpenFolderDialog openFolderDialog = new RadOpenFolderDialog(); - openFolderDialog.OpenFolderDialogForm.ExplorerControl.ShellContextMenuOpening += ExplorerControl_ShellContextMenuOpening; - } - private void ExplorerControl_ShellContextMenuOpening(object sender, Telerik.WinControls.FileDialogs.ContextMenuOpeningEventArgs e) - { - e.Cancel = true; - - if (e.IsOpeningOnEmptySpace) - { - e.Cancel = false; - e.ShortContextMenuOptions = ShortContextMenuOptions.NewFolder | ShortContextMenuOptions.View; - } - } - -```` -````VB.NET - Private Sub RadForm_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load - Dim openFolderDialog As RadOpenFolderDialog = New RadOpenFolderDialog() - AddHandler openFolderDialog.OpenFolderDialogForm.ExplorerControl.ShellContextMenuOpening, AddressOf ExplorerControl_ShellContextMenuOpening - End Sub - - Private Sub ExplorerControl_ShellContextMenuOpening(ByVal sender As Object, ByVal e As Telerik.WinControls.FileDialogs.ContextMenuOpeningEventArgs) - e.Cancel = True - - If e.IsOpeningOnEmptySpace Then - e.Cancel = False - e.ShortContextMenuOptions = ShortContextMenuOptions.NewFolder Or ShortContextMenuOptions.View - End If - End Sub - -```` - -{{endregion}} diff --git a/controls/file-dialogs/features/editing-options.md b/controls/file-dialogs/features/editing-options.md index 4b3ca0751..af167b626 100644 --- a/controls/file-dialogs/features/editing-options.md +++ b/controls/file-dialogs/features/editing-options.md @@ -30,88 +30,28 @@ The available **EditingOptions** are listed below: #### Set multiple EditinOptions limitations -{{source=..\SamplesCS\FileDialogs\FileDialogsEditingOptions.cs region=Limit}} -{{source=..\SamplesVB\FileDialogs\FileDialogsEditingOptions.vb region=Limit}} + + -````C# - RadOpenFolderDialog openFolderDialog = new RadOpenFolderDialog(); - openFolderDialog.EditingOptions = Telerik.WinControls.FileDialogs.EditingOptions.All; - openFolderDialog.EditingOptions ^= (EditingOptions.NewFolder | EditingOptions.Rename); - openFolderDialog.ShowDialog(); -```` -````VB.NET - Dim openFolderDialog As RadOpenFolderDialog = New RadOpenFolderDialog() - openFolderDialog.EditingOptions = Telerik.WinControls.FileDialogs.EditingOptions.All - openFolderDialog.EditingOptions = openFolderDialog.EditingOptions Xor (EditingOptions.NewFolder Or EditingOptions.Rename) - openFolderDialog.ShowDialog() - -```` - -{{endregion}} Even though you specify the **EditingOptions**, the end-user is still allowed to drag and drop the files. If you want to disable drag and drop operations you should set explicitly the **IsDragDropEnabled** property of the **ExplorerControl** to *false*. #### Disable drag and drop operations -{{source=..\SamplesCS\FileDialogs\FileDialogsEditingOptions.cs region=DisableDragDrop}} -{{source=..\SamplesVB\FileDialogs\FileDialogsEditingOptions.vb region=DisableDragDrop}} - -````C# - openFolderDialog.OpenFolderDialogForm.ExplorerControl.IsDragDropEnabled = false; + + -```` -````VB.NET - openFolderDialog.OpenFolderDialogForm.ExplorerControl.IsDragDropEnabled = False -```` - -{{endregion}} You cannot modify files/folders context menu but you can choose to cancel its opening. You can, however, modify the empty space context menu items as follows: #### Modify ShellContextMenu -{{source=..\SamplesCS\FileDialogs\FileDialogsEditingOptions.cs region=Menu}} -{{source=..\SamplesVB\FileDialogs\FileDialogsEditingOptions.vb region=Menu}} - -````C# - private void RadForm_Load(object sender, EventArgs e) - { - RadOpenFolderDialog openFolderDialog = new RadOpenFolderDialog(); - openFolderDialog.OpenFolderDialogForm.ExplorerControl.ShellContextMenuOpening += ExplorerControl_ShellContextMenuOpening; - } - - private void ExplorerControl_ShellContextMenuOpening(object sender, Telerik.WinControls.FileDialogs.ContextMenuOpeningEventArgs e) - { - e.Cancel = true; - - if (e.IsOpeningOnEmptySpace) - { - e.Cancel = false; - e.ShortContextMenuOptions = ShortContextMenuOptions.NewFolder | ShortContextMenuOptions.View; - } - } - -```` -````VB.NET - Private Sub RadForm_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load - Dim openFolderDialog As RadOpenFolderDialog = New RadOpenFolderDialog() - AddHandler openFolderDialog.OpenFolderDialogForm.ExplorerControl.ShellContextMenuOpening, AddressOf ExplorerControl_ShellContextMenuOpening - End Sub - - Private Sub ExplorerControl_ShellContextMenuOpening(ByVal sender As Object, ByVal e As Telerik.WinControls.FileDialogs.ContextMenuOpeningEventArgs) - e.Cancel = True - - If e.IsOpeningOnEmptySpace Then - e.Cancel = False - e.ShortContextMenuOptions = ShortContextMenuOptions.NewFolder Or ShortContextMenuOptions.View - End If - End Sub - -```` - -{{endregion}} + + + + diff --git a/controls/file-dialogs/getting-started.md b/controls/file-dialogs/getting-started.md index f5f0d6e24..6c406e7b9 100644 --- a/controls/file-dialogs/getting-started.md +++ b/controls/file-dialogs/getting-started.md @@ -41,83 +41,10 @@ The following tutorial demonstrates how to specify a file name by using a **RadS #### How to use the file dialogs -{{source=..\SamplesCS\FileDialogs\FileDialogsEditingOptions.cs region=GettingStartedExample}} -{{source=..\SamplesVB\FileDialogs\FileDialogsEditingOptions.vb region=GettingStartedExample}} - -````C# - - private void radButton1_Click(object sender, EventArgs e) - { - RadOpenFolderDialog openFolderDialog = new RadOpenFolderDialog(); - openFolderDialog.ShowDialog(); - if (openFolderDialog.OpenFolderDialogForm.DialogResult == System.Windows.Forms.DialogResult.OK) - { - string folderName = openFolderDialog.FileName; - this.radLabel1.Text = folderName; - } - } - - private void radButton2_Click(object sender, EventArgs e) - { - RadOpenFileDialog openFileDialog = new RadOpenFileDialog(); - openFileDialog.ShowDialog(); - - if (openFileDialog.OpenFileDialogForm.DialogResult == System.Windows.Forms.DialogResult.OK) - { - string fileName = openFileDialog.FileName; - this.radLabel2.Text = fileName; - } - } - - private void radButton3_Click(object sender, EventArgs e) - { - RadSaveFileDialog saveFileDialog = new RadSaveFileDialog(); - saveFileDialog.ShowDialog(); - if (saveFileDialog.SaveFileDialogForm.DialogResult == System.Windows.Forms.DialogResult.OK) - { - string selectedFileName = saveFileDialog.FileName; - this.radLabel3.Text = selectedFileName; - } - } - - -```` -````VB.NET - - Private Sub radButton1_Click(ByVal sender As Object, ByVal e As EventArgs) - Dim openFolderDialog As RadOpenFolderDialog = New RadOpenFolderDialog() - openFolderDialog.ShowDialog() - - If openFolderDialog.OpenFolderDialogForm.DialogResult = System.Windows.Forms.DialogResult.OK Then - Dim folderName As String = openFolderDialog.FileName - Me.radLabel1.Text = folderName - End If - End Sub - - Private Sub radButton2_Click(ByVal sender As Object, ByVal e As EventArgs) - Dim openFileDialog As RadOpenFileDialog = New RadOpenFileDialog() - openFileDialog.ShowDialog() - - If openFileDialog.OpenFileDialogForm.DialogResult = System.Windows.Forms.DialogResult.OK Then - Dim fileName As String = openFileDialog.FileName - Me.radLabel2.Text = fileName - End If - End Sub - - Private Sub radButton3_Click(ByVal sender As Object, ByVal e As EventArgs) - Dim saveFileDialog As RadSaveFileDialog = New RadSaveFileDialog() - saveFileDialog.ShowDialog() - - If saveFileDialog.SaveFileDialogForm.DialogResult = System.Windows.Forms.DialogResult.OK Then - Dim selectedFileName As String = saveFileDialog.FileName - Me.radLabel3.Text = selectedFileName - End If - End Sub - - -```` - -{{endregion}} + + + + This is it! Now you can select a file name or open a folder. diff --git a/controls/filter-view/filter-view-changing-default-editors.md b/controls/filter-view/filter-view-changing-default-editors.md index 968131122..ba14d4e3d 100644 --- a/controls/filter-view/filter-view-changing-default-editors.md +++ b/controls/filter-view/filter-view-changing-default-editors.md @@ -29,37 +29,10 @@ For the boolean fields in the applied DataSource, **RadFilterView** generates a The **CategoryCreating** event gives you the possibility to replace the default **FilterViewBooleanCategoryElement** with another one, e.g. **FilterViewTextCategoryElement** with radio buttons: -{{source=..\SamplesCS\FilterView\FilterViewGettingStarted.cs region=ReplaceCategory}} -{{source=..\SamplesVB\FilterView\FilterViewGettingStarted.vb region=ReplaceCategory}} - -````C# - -private void RadFilterView_CategoryCreating(object sender, FilterViewCategoryCreatingEventArgs e) -{ - if (e.Category.PropertyName == "Discontinued") - { - FilterViewTextCategoryElement textCategory = new FilterViewTextCategoryElement(); - textCategory.PropertyName = e.Category.PropertyName; - textCategory.ItemType = FilterViewTextCategoryItemType.RadioButton; - e.Category = textCategory; - } -} - -```` -````VB.NET - -Private Sub RadFilterView_CategoryCreating(ByVal sender As Object, ByVal e As FilterViewCategoryCreatingEventArgs) - If e.Category.PropertyName = "Discontinued" Then - Dim textCategory As FilterViewTextCategoryElement = New FilterViewTextCategoryElement() - textCategory.PropertyName = e.Category.PropertyName - textCategory.ItemType = FilterViewTextCategoryItemType.RadioButton - e.Category = textCategory - End If -End Sub - -```` - -{{endregion}} + + + + ![WinForms RadFilterView FilterViewTextCategoryElement](images/filter-view-changing-default-editors003.png) @@ -67,33 +40,10 @@ End Sub By default, the **FilterViewTextCategoryElement** auto-generates a set of check boxes for each string value. You can switch to creating a set of radio buttons and thus allowing only a single text value to be selected: -{{source=..\SamplesCS\FilterView\FilterViewGettingStarted.cs region=SwitchToRadioButtons}} -{{source=..\SamplesVB\FilterView\FilterViewGettingStarted.vb region=SwitchToRadioButtons}} - -````C# - -private void RadFilterView1_CategoryCreating(object sender, FilterViewCategoryCreatingEventArgs e) -{ - if (e.Category.PropertyName == "ProductName") - { - FilterViewTextCategoryElement textCategory = e.Category as FilterViewTextCategoryElement; - textCategory.ItemType = FilterViewTextCategoryItemType.RadioButton; - } -} - -```` -````VB.NET - -Private Sub RadFilterView1_CategoryCreating(ByVal sender As Object, ByVal e As FilterViewCategoryCreatingEventArgs) - If e.Category.PropertyName = "ProductName" Then - Dim textCategory As FilterViewTextCategoryElement = TryCast(e.Category, FilterViewTextCategoryElement) - textCategory.ItemType = FilterViewTextCategoryItemType.RadioButton - End If -End Sub + + -```` -{{endregion}} ![WinForms RadFilterView Default ItemType](images/filter-view-changing-default-editors002.png) @@ -107,223 +57,17 @@ You may want to replace them with two **RadCalendar** controls. The following ex ![WinForms RadFilterView Replace RadCalendar](images/filter-view-changing-default-editors005.png) -{{source=..\SamplesCS\FilterView\FilterViewGettingStarted.cs region=CalendarCategory}} -{{source=..\SamplesVB\FilterView\FilterViewGettingStarted.vb region=CalendarCategory}} - -````C# -public class FilterViewCalendarCategoryElement : FilterViewDateTimeCategoryElement -{ - - RadCalendar minValueCalendar; - RadCalendar maxValueCalendar; - - public FilterViewCalendarCategoryElement(string propertyName) : base(propertyName) - { - - } - - protected override void CreateChildElements() - { - base.CreateChildElements(); - this.MinValueDateTimePicker.Visibility = ElementVisibility.Collapsed; - this.MaxValueDateTimePicker.Visibility = ElementVisibility.Collapsed; - this.minValueCalendar = new RadCalendar(); - minValueCalendar.AllowMultipleSelect = false; - this.minValueCalendar.SelectedDate = this.minValue; - RadHostItem minHost = new RadHostItem(this.minValueCalendar); - minHost.MinSize = new Size(0, 150); - this.minValueCalendar.SelectionChanged += Calendar_SelectionChanged; - this.minValueCalendar.Margin = new Padding(2); - this.EditorsStack.Children.Insert(1, minHost); - this.minValueCalendar.SelectedDate = this.minValue; - - this.maxValueCalendar = new RadCalendar(); - maxValueCalendar.AllowMultipleSelect = false; - this.maxValueCalendar.SelectedDate = this.maxValue; - this.maxValueCalendar.SelectionChanged += Calendar_SelectionChanged; - RadHostItem maxHost = new RadHostItem(this.maxValueCalendar); - maxHost.MinSize = new Size(0, 150); - maxHost.StretchHorizontally = true; - this.maxValueCalendar.Margin = new Padding(2); - this.EditorsStack.Children.Add(maxHost); - } - - protected override void DisposeManagedResources() - { - base.DisposeManagedResources(); - this.minValueCalendar.SelectionChanged -= Calendar_SelectionChanged; - this.maxValueCalendar.SelectionChanged -= Calendar_SelectionChanged; - } - public override void CreateItems(ICollection values) - { - base.CreateItems(values); - this.minValueCalendar.SelectionChanged -= Calendar_SelectionChanged; - this.maxValueCalendar.SelectionChanged -= Calendar_SelectionChanged; - minValueCalendar.SelectedDate = this.minValue; - minValueCalendar.FocusedDate = this.minValue; - maxValueCalendar.SelectedDate = this.maxValue; - maxValueCalendar.FocusedDate = this.maxValue; - this.minValueCalendar.SelectionChanged += Calendar_SelectionChanged; - this.maxValueCalendar.SelectionChanged += Calendar_SelectionChanged; - } - - private void Calendar_SelectionChanged(object sender, EventArgs e) - { - this.ItemFilterChanged(null); - } - - protected override DateTime? GetMinEditorValue() - { - return this.minValueCalendar.SelectedDate; - } - - protected override DateTime? GetMaxEditorValue() - { - return this.maxValueCalendar.SelectedDate; - } - - protected override void SetMinEditorValue(DateTime? newValue) - { - base.SetMinEditorValue(newValue); - if (newValue != null) - { - this.minValueCalendar.SelectedDate = (DateTime)newValue; - this.minValueCalendar.FocusedDate = this.minValueCalendar.SelectedDate; - } - } - - protected override void SetMaxEditorValue(DateTime? newValue) - { - base.SetMaxEditorValue(newValue); - if (newValue != null) - { - this.maxValueCalendar.SelectedDate = (DateTime)newValue; - this.maxValueCalendar.FocusedDate = this.maxValueCalendar.SelectedDate; - } - } -} - - -```` -````VB.NET - -Public Class FilterViewCalendarCategoryElement - Inherits FilterViewDateTimeCategoryElement - - Private minValueCalendar As RadCalendar - Private maxValueCalendar As RadCalendar - - Public Sub New(ByVal propertyName As String) - MyBase.New(propertyName) - End Sub - - Protected Overrides Sub CreateChildElements() - MyBase.CreateChildElements() - Me.MinValueDateTimePicker.Visibility = ElementVisibility.Collapsed - Me.MaxValueDateTimePicker.Visibility = ElementVisibility.Collapsed - Me.minValueCalendar = New RadCalendar() - minValueCalendar.AllowMultipleSelect = False - Me.minValueCalendar.SelectedDate = Me.minValue - Dim minHost As RadHostItem = New RadHostItem(Me.minValueCalendar) - minHost.MinSize = New Size(0, 150) - AddHandler Me.minValueCalendar.SelectionChanged, AddressOf Calendar_SelectionChanged - Me.minValueCalendar.Margin = New Padding(2) - Me.EditorsStack.Children.Insert(1, minHost) - Me.minValueCalendar.SelectedDate = Me.minValue - Me.maxValueCalendar = New RadCalendar() - maxValueCalendar.AllowMultipleSelect = False - Me.maxValueCalendar.SelectedDate = Me.maxValue - AddHandler Me.maxValueCalendar.SelectionChanged, AddressOf Calendar_SelectionChanged - Dim maxHost As RadHostItem = New RadHostItem(Me.maxValueCalendar) - maxHost.MinSize = New Size(0, 150) - maxHost.StretchHorizontally = True - Me.maxValueCalendar.Margin = New Padding(2) - Me.EditorsStack.Children.Add(maxHost) - End Sub - - Protected Overrides Sub DisposeManagedResources() - MyBase.DisposeManagedResources() - RemoveHandler Me.minValueCalendar.SelectionChanged, AddressOf Calendar_SelectionChanged - RemoveHandler Me.maxValueCalendar.SelectionChanged, AddressOf Calendar_SelectionChanged - End Sub - - Public Overrides Sub CreateItems(ByVal values As ICollection(Of Object)) - MyBase.CreateItems(values) - RemoveHandler Me.minValueCalendar.SelectionChanged, AddressOf Calendar_SelectionChanged - RemoveHandler Me.maxValueCalendar.SelectionChanged, AddressOf Calendar_SelectionChanged - minValueCalendar.SelectedDate = Me.minValue - minValueCalendar.FocusedDate = Me.minValue - maxValueCalendar.SelectedDate = Me.maxValue - maxValueCalendar.FocusedDate = Me.maxValue - AddHandler Me.minValueCalendar.SelectionChanged, AddressOf Calendar_SelectionChanged - AddHandler Me.maxValueCalendar.SelectionChanged, AddressOf Calendar_SelectionChanged - End Sub - - Private Sub Calendar_SelectionChanged(ByVal sender As Object, ByVal e As EventArgs) - Me.ItemFilterChanged(Nothing) - End Sub - - Protected Overrides Function GetMinEditorValue() As DateTime? - Return Me.minValueCalendar.SelectedDate - End Function - - Protected Overrides Function GetMaxEditorValue() As DateTime? - Return Me.maxValueCalendar.SelectedDate - End Function - - Protected Overrides Sub SetMinEditorValue(ByVal newValue As DateTime?) - MyBase.SetMinEditorValue(newValue) - - If newValue IsNot Nothing Then - Me.minValueCalendar.SelectedDate = CType(newValue, DateTime) - Me.minValueCalendar.FocusedDate = Me.minValueCalendar.SelectedDate - End If - End Sub - - Protected Overrides Sub SetMaxEditorValue(ByVal newValue As DateTime?) - MyBase.SetMaxEditorValue(newValue) - - If newValue IsNot Nothing Then - Me.maxValueCalendar.SelectedDate = CType(newValue, DateTime) - Me.maxValueCalendar.FocusedDate = Me.maxValueCalendar.SelectedDate - End If - End Sub -End Class - - -```` - -{{endregion}} + + -Then, apply the custom category element in the **CategoryCreating** event: - -{{source=..\SamplesCS\FilterView\FilterViewGettingStarted.cs region=CustomCategory}} -{{source=..\SamplesVB\FilterView\FilterViewGettingStarted.vb region=CustomCategory}} - -````C# -private void RadFilterViewCategoryCreating(object sender, FilterViewCategoryCreatingEventArgs e) -{ - if (e.Category is FilterViewDateTimeCategoryElement) - { - FilterViewCalendarCategoryElement calendarCategory = new FilterViewCalendarCategoryElement(e.Category.PropertyName); - e.Category = calendarCategory; - } -} -```` -````VB.NET +Then, apply the custom category element in the **CategoryCreating** event: -Private Sub RadFilterViewCategoryCreating(ByVal sender As Object, ByVal e As FilterViewCategoryCreatingEventArgs) - If TypeOf e.Category Is FilterViewDateTimeCategoryElement Then - Dim calendarCategory As FilterViewCalendarCategoryElement = New FilterViewCalendarCategoryElement(e.Category.PropertyName) - e.Category = calendarCategory - End If -End Sub + + -```` -{{endregion}} >note It is possible to either use the **CategoryCreating** event or a custom **FilterViewCategoriesFactory** to replace one of the default category elements with your custom one. @@ -331,71 +75,18 @@ End Sub Create a derivative of the **FilterViewCategoriesFactory** element and override its **CreateCategory** method. This is the default logic for generating the category elements considering the property data type. It is possible to plug into the creation process and adjust it according to any custom requirements: -{{source=..\SamplesCS\FilterView\FilterViewGettingStarted.cs region=CustomFactory}} -{{source=..\SamplesVB\FilterView\FilterViewGettingStarted.vb region=CustomFactory}} - -````C# -public class CustomFilterViewCategoriesFactory : Telerik.WinControls.UI.FilterView.FilterViewCategoriesFactory -{ - public override BaseFilterViewCategoryElement CreateCategory(string propertyName, Type propertyType, string displayName = "") - { - if (TelerikHelper.IsNumericType(propertyType)) - { - return new FilterViewNumericCategoryElement(propertyName, propertyType, displayName); - } - else if (propertyType == typeof(DateTime)) - { - return new FilterViewDateTimeCategoryElement(propertyName, propertyType, displayName); - } - else if (propertyType == typeof(bool)) - { - return new FilterViewBooleanCategoryElement(propertyName, propertyType, displayName); - } - - return new FilterViewTextCategoryElement(propertyName, propertyType, displayName); - } -} - -```` -````VB.NET - -Public Class CustomFilterViewCategoriesFactory - Inherits Telerik.WinControls.UI.FilterView.FilterViewCategoriesFactory - - Public Overrides Function CreateCategory(ByVal propertyName As String, ByVal propertyType As Type, - ByVal Optional displayName As String = "") As BaseFilterViewCategoryElement - If TelerikHelper.IsNumericType(propertyType) Then - Return New FilterViewNumericCategoryElement(propertyName, propertyType, displayName) - ElseIf propertyType = GetType(DateTime) Then - Return New FilterViewDateTimeCategoryElement(propertyName, propertyType, displayName) - ElseIf propertyType = GetType(Boolean) Then - Return New FilterViewBooleanCategoryElement(propertyName, propertyType, displayName) - End If - - Return New FilterViewTextCategoryElement(propertyName, propertyType, displayName) - End Function -End Class - -```` - -{{endregion}} + + -Then, apply the custom factory: -{{source=..\SamplesCS\FilterView\FilterViewGettingStarted.cs region=ChangeFactory}} -{{source=..\SamplesVB\FilterView\FilterViewGettingStarted.vb region=ChangeFactory}} -````C# +Then, apply the custom factory: -this.radFilterView1.CategoriesFactory = new CustomFilterViewCategoriesFactory(); + + -```` -````VB.NET -Me.RadFilterView1.CategoriesFactory = New CustomFilterViewCategoriesFactory() -```` -{{endregion}} # See Also diff --git a/controls/filter-view/filter-view-getting-started.md b/controls/filter-view/filter-view-getting-started.md index bf46b3501..f3c82a66b 100644 --- a/controls/filter-view/filter-view-getting-started.md +++ b/controls/filter-view/filter-view-getting-started.md @@ -57,24 +57,10 @@ That's it. You can now filter the grid by using the automatically generated cate Steps 3-5 can also be performed programmatically: -{{source=..\SamplesCS\FilterView\FilterViewGettingStarted.cs region=GettingStarted}} -{{source=..\SamplesVB\FilterView\FilterViewGettingStarted.vb region=GettingStarted}} + + -````C# -this.radGridView1.DataSource = this.productsBindingSource; -this.radGridView1.EnableFiltering = true; -this.radFilterView1.AssociatedControl = this.radGridView1; - -```` -````VB.NET -Me.RadGridView1.DataSource = Me.ProductsBindingSource -Me.RadGridView1.EnableFiltering = True -Me.RadFilterView1.AssociatedControl = Me.RadGridView1 - -```` - -{{endregion}} # See Also diff --git a/controls/filter-view/filter-view-localization.md b/controls/filter-view/filter-view-localization.md index 36dc79fe8..2a316397f 100644 --- a/controls/filter-view/filter-view-localization.md +++ b/controls/filter-view/filter-view-localization.md @@ -22,82 +22,19 @@ Below is a sample implementation of an English localization provider: #### Localizing RadFilterView Strings -{{source=..\SamplesCS\FilterView\FilterViewLocalization.cs region=EnglishProvider}} -{{source=..\SamplesVB\FilterView\FilterViewLocalization.vb region=EnglishProvider}} - -````C# - -public class EnglishFilterViewLocalizationProvider : Telerik.WinControls.UI.FilterView.RadFilterViewLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case RadFilterViewStringId.ClearCategoryFilterMenuItem: return "Clear Filter"; - case RadFilterViewStringId.ClearAllFiltersMenuItem: return "Clear All Filters"; - - case RadFilterViewStringId.BooleanCategoryTrue: return "True"; - case RadFilterViewStringId.BooleanCategoryFalse: return "False"; - - case RadFilterViewStringId.NumericCategoryFrom: return "From:"; - case RadFilterViewStringId.NumericCategoryTo: return "To:"; - - default: return base.GetLocalizedString(id); - } - } -} - -```` -````VB.NET - -Public Class EnglishFilterViewLocalizationProvider - Inherits Telerik.WinControls.UI.FilterView.RadFilterViewLocalizationProvider - - Public Overrides Function GetLocalizedString(ByVal id As String) As String - Select Case id - Case RadFilterViewStringId.ClearCategoryFilterMenuItem - Return "Clear Filter" - Case RadFilterViewStringId.ClearAllFiltersMenuItem - Return "Clear All Filters" - Case RadFilterViewStringId.BooleanCategoryTrue - Return "True" - Case RadFilterViewStringId.BooleanCategoryFalse - Return "False" - Case RadFilterViewStringId.NumericCategoryFrom - Return "From:" - Case RadFilterViewStringId.NumericCategoryTo - Return "To:" - Case Else - Return MyBase.GetLocalizedString(id) - End Select - End Function -End Class - -```` - -{{endregion}} + + -To apply the custom localization provider, instantiate and assign it to the current localization provider: - -#### Assigning the Current Localization Provider -{{source=..\SamplesCS\FilterView\FilterViewLocalization.cs region=ApplyProvider}} -{{source=..\SamplesVB\FilterView\FilterViewLocalization.vb region=ApplyProvider}} -````C# - -RadFilterViewLocalizationProvider.CurrentProvider = new EnglishFilterViewLocalizationProvider(); -InitializeComponent(); +To apply the custom localization provider, instantiate and assign it to the current localization provider: -```` -````VB.NET +#### Assigning the Current Localization Provider -RadFilterViewLocalizationProvider.CurrentProvider = New EnglishFilterViewLocalizationProvider() -InitializeComponent() + + -```` -{{endregion}} # See Also diff --git a/controls/filter-view/unbound_mode.md b/controls/filter-view/unbound_mode.md index 0c4c6fae6..604186591 100644 --- a/controls/filter-view/unbound_mode.md +++ b/controls/filter-view/unbound_mode.md @@ -17,131 +17,19 @@ For the purpose of this article, we are going to use RadGridView in unbound mode 2\. Then we can create our columns and create some dummy data. 3\. The next step is to set the AssociatedControl property of the RadFilterView to the RadGridView. -{{source=..\SamplesCS\FilterView\FilterViewUnboundMode.cs region=PopulateGridView}} -{{source=..\SamplesVB\FilterView\FilterViewUnboundMode.vb region=PopulateGridView}} + + -````C# -public RadForm1() -{ - InitializeComponent(); - GridViewDecimalColumn decimalColumn = new GridViewDecimalColumn("Id"); - this.radGridView1.Columns.Add(decimalColumn); - - GridViewDateTimeColumn dateColumn = new GridViewDateTimeColumn("Date"); - this.radGridView1.Columns.Add(dateColumn); - - GridViewTextBoxColumn textColumn = new GridViewTextBoxColumn("Title"); - this.radGridView1.Columns.Add(textColumn); - - for (int i = 5; i < 15; i++) - { - this.radGridView1.Rows.Add(i, DateTime.Now.AddDays(i), "Item" + i); - } - this.radFilterView1.AssociatedControl = this.radGridView1; -} - -```` -````VB.NET -Public Partial Class FilterViewUnboundMode - Inherits Form - - Public Sub New() - InitializeComponent() - Dim decimalColumn As GridViewDecimalColumn = New GridViewDecimalColumn("Id") - Me.radGridView1.Columns.Add(decimalColumn) - Dim dateColumn As GridViewDateTimeColumn = New GridViewDateTimeColumn("Date") - Me.radGridView1.Columns.Add(dateColumn) - Dim textColumn As GridViewTextBoxColumn = New GridViewTextBoxColumn("Title") - Me.radGridView1.Columns.Add(textColumn) - - For i As Integer = 5 To 15 - 1 - Me.radGridView1.Rows.Add(i, DateTime.Now.AddDays(i), "Item" & i) - Next - Me.radFilterView1.AssociatedControl = Me.radGridView1 - End Sub -End Class - -```` - -{{endregion}} ![WinForms RadFilterView Unbound Mode](images/filter-view-unbound-mode001.png) If we run the example, we can see that the __RadGridView__ is populated correctly, but the __RadFilterView__ will remain empty. As the __DataSource__ of the __RadGridView__ is null, the __RadFilterView__ control won't be aware which filter categories need to be created. Upon checking the RadGridView we can create 3 filter categories for the following ID,Date and Title columns. -{{source=..\SamplesCS\FilterView\FilterViewUnboundMode.cs region=CreateFilterViewCategories}} -{{source=..\SamplesVB\FilterView\FilterViewUnboundMode.vb region=CreateFilterViewCategories}} - -````C# -ICollection numericValues = new List(); -ICollection dateTimeValues = new List(); -ICollection textValues = new List(); - -FilterViewNumericCategoryElement numericFilterCategory = new FilterViewNumericCategoryElement(); -numericFilterCategory.PropertyName = "Id"; -foreach (var item in decimalColumn.DistinctValues) -{ - numericValues.Add(item); -} -numericFilterCategory.CreateItems(numericValues); -this.radFilterView1.Categories.Add(numericFilterCategory); - -FilterViewDateTimeCategoryElement dateTimeFilterCategory = new FilterViewDateTimeCategoryElement(); -dateTimeFilterCategory.PropertyName = "Date"; -foreach (var item in dateColumn.DistinctValues) -{ - dateTimeValues.Add(item); -} -dateTimeFilterCategory.CreateItems(dateTimeValues); -this.radFilterView1.Categories.Add(dateTimeFilterCategory); - -FilterViewTextCategoryElement stringFilterCategory = new FilterViewTextCategoryElement(); -stringFilterCategory.PropertyName = "Title"; -foreach (var item in textColumn.DistinctValues) -{ - textValues.Add(item); -} -stringFilterCategory.CreateItems(textValues); -this.radFilterView1.Categories.Add(stringFilterCategory); - -```` -````VB.NET -Private numericValues As ICollection(Of Object) = New List(Of Object)() -Private dateTimeValues As ICollection(Of Object) = New List(Of Object)() -Private textValues As ICollection(Of Object) = New List(Of Object)() - -Dim numericFilterCategory As FilterViewNumericCategoryElement = New FilterViewNumericCategoryElement() -numericFilterCategory.PropertyName = "Id" - -For Each item In decimalColumn.DistinctValues - numericValues.Add(item) -Next - -numericFilterCategory.CreateItems(numericValues) -Me.radFilterView1.Categories.Add(numericFilterCategory) -Dim dateTimeFilterCategory As FilterViewDateTimeCategoryElement = New FilterViewDateTimeCategoryElement() -dateTimeFilterCategory.PropertyName = "Date" - -For Each item In dateColumn.DistinctValues - dateTimeValues.Add(item) -Next - -dateTimeFilterCategory.CreateItems(dateTimeValues) -Me.radFilterView1.Categories.Add(dateTimeFilterCategory) -Dim stringFilterCategory As FilterViewTextCategoryElement = New FilterViewTextCategoryElement() -stringFilterCategory.PropertyName = "Title" - -For Each item In textColumn.DistinctValues - textValues.Add(item) -Next - -stringFilterCategory.CreateItems(textValues) -Me.radFilterView1.Categories.Add(stringFilterCategory) + + -```` -{{endregion}} 4\. In the above code snippet we are creating FilterViewNumericCategoryElement, FilterViewDateTimeCategoryElement and FilterViewTextCategoryElement filter categories. You can observe that the CreateItems() method of these categories need to be called. The DistinctValues collection property can be pass as a parameter. That collection will be use to create the filter values for each filter category. @@ -151,118 +39,11 @@ Me.radFilterView1.Categories.Add(stringFilterCategory) Here is the complete code snippet. -{{source=..\SamplesCS\FilterView\FilterViewUnboundMode.cs region=CompleteCodeSnippetExample}} -{{source=..\SamplesVB\FilterView\FilterViewUnboundMode.vb region=CompleteCodeSnippetExample}} - -````C# -public partial class RadForm1 : Telerik.WinControls.UI.RadForm -{ - ICollection numericValues = new List(); - ICollection dateTimeValues = new List(); - ICollection textValues = new List(); - - public RadForm1() - { - InitializeComponent(); - - GridViewDecimalColumn decimalColumn = new GridViewDecimalColumn("Id"); - this.radGridView1.Columns.Add(decimalColumn); - - GridViewDateTimeColumn dateColumn = new GridViewDateTimeColumn("Date"); - this.radGridView1.Columns.Add(dateColumn); - - GridViewTextBoxColumn textColumn = new GridViewTextBoxColumn("Title"); - this.radGridView1.Columns.Add(textColumn); - - for (int i = 5; i < 15; i++) - { - this.radGridView1.Rows.Add(i, DateTime.Now.AddDays(i), "Item" + i); - } - - FilterViewNumericCategoryElement numericFilterCategory = new FilterViewNumericCategoryElement(); - numericFilterCategory.PropertyName = "Id"; - foreach (var item in decimalColumn.DistinctValues) - { - numericValues.Add(item); - } - numericFilterCategory.CreateItems(numericValues); - this.radFilterView1.Categories.Add(numericFilterCategory); - - FilterViewDateTimeCategoryElement dateTimeFilterCategory = new FilterViewDateTimeCategoryElement(); - dateTimeFilterCategory.PropertyName = "Date"; - foreach (var item in dateColumn.DistinctValues) - { - dateTimeValues.Add(item); - } - dateTimeFilterCategory.CreateItems(dateTimeValues); - this.radFilterView1.Categories.Add(dateTimeFilterCategory); - - FilterViewTextCategoryElement stringFilterCategory = new FilterViewTextCategoryElement(); - stringFilterCategory.PropertyName = "Title"; - foreach (var item in textColumn.DistinctValues) - { - textValues.Add(item); - } - stringFilterCategory.CreateItems(textValues); - this.radFilterView1.Categories.Add(stringFilterCategory); - - this.radFilterView1.AssociatedControl = this.radGridView1; - } -} - -```` -````VB.NET -Partial Public Class FilterViewUnboundMode - Inherits Form - - Private numericValues As ICollection(Of Object) = New List(Of Object)() - Private dateTimeValues As ICollection(Of Object) = New List(Of Object)() - Private textValues As ICollection(Of Object) = New List(Of Object)() - - Public Sub New() - Dim decimalColumn As GridViewDecimalColumn = New GridViewDecimalColumn("Id") - Me.radGridView1.Columns.Add(decimalColumn) - Dim dateColumn As GridViewDateTimeColumn = New GridViewDateTimeColumn("Date") - Me.radGridView1.Columns.Add(dateColumn) - Dim textColumn As GridViewTextBoxColumn = New GridViewTextBoxColumn("Title") - Me.radGridView1.Columns.Add(textColumn) - - For i As Integer = 5 To 15 - 1 - Me.radGridView1.Rows.Add(i, DateTime.Now.AddDays(i), "Item" & i) - Next - - Dim numericFilterCategory As FilterViewNumericCategoryElement = New FilterViewNumericCategoryElement() - numericFilterCategory.PropertyName = "Id" - - For Each item In decimalColumn.DistinctValues - numericValues.Add(item) - Next - - numericFilterCategory.CreateItems(numericValues) - Me.radFilterView1.Categories.Add(numericFilterCategory) - Dim dateTimeFilterCategory As FilterViewDateTimeCategoryElement = New FilterViewDateTimeCategoryElement() - dateTimeFilterCategory.PropertyName = "Date" - - For Each item In dateColumn.DistinctValues - dateTimeValues.Add(item) - Next - - dateTimeFilterCategory.CreateItems(dateTimeValues) - Me.radFilterView1.Categories.Add(dateTimeFilterCategory) - Dim stringFilterCategory As FilterViewTextCategoryElement = New FilterViewTextCategoryElement() - stringFilterCategory.PropertyName = "Title" + + - For Each item In textColumn.DistinctValues - textValues.Add(item) - Next - stringFilterCategory.CreateItems(textValues) - Me.radFilterView1.Categories.Add(stringFilterCategory) - Me.radFilterView1.AssociatedControl = Me.radGridView1 - End Sub -End Class -```` # See Also diff --git a/controls/forms-and-dialogs/colordialog/custom-colors.md b/controls/forms-and-dialogs/colordialog/custom-colors.md index a79118204..fe44e2194 100644 --- a/controls/forms-and-dialogs/colordialog/custom-colors.md +++ b/controls/forms-and-dialogs/colordialog/custom-colors.md @@ -20,34 +20,8 @@ The RadColorSelector.**CustomColorsConfigLocationNeeded** event fires when custo The following code snippet demonstrates how to change the default location of the file and file name that stores the custom colors: -{{source=..\SamplesCS\Forms and Dialogs\ColorDialog1.cs region=CustomColors}} -{{source=..\SamplesVB\Forms and Dialogs\ColorDialog1.vb region=CustomColors}} - -````C# - public void CustomColorsSubscription() - { - RadColorSelector colorSelector = this.radColorDialog1 .ColorDialogForm .RadColorSelector as RadColorSelector; - colorSelector.CustomColorsConfigLocationNeeded += colorSelector_CustomColorsConfigLocationNeeded; - } - private void colorSelector_CustomColorsConfigLocationNeeded(object sender, Telerik.WinControls.Themes.ColorDialog.CustomColorsEventArgs args) - { - args.ConfigFilename = "my file"; - args.ConfigLocation = "my folder"; - } - -```` -````VB.NET - Public Sub CustomColorsSubscription() - Dim colorSelector As RadColorSelector = TryCast(Me.RadColorDialog1.ColorDialogForm.RadColorSelector, RadColorSelector) - AddHandler colorSelector.CustomColorsConfigLocationNeeded, AddressOf colorSelector_CustomColorsConfigLocationNeeded - End Sub - - Private Sub colorSelector_CustomColorsConfigLocationNeeded(ByVal sender As Object, ByVal args As Telerik.WinControls.Themes.ColorDialog.CustomColorsEventArgs) - args.ConfigFilename = "my file" - args.ConfigLocation = "my folder" - End Sub - -```` - -{{endregion}} + + + + diff --git a/controls/forms-and-dialogs/colordialog/getting-started.md b/controls/forms-and-dialogs/colordialog/getting-started.md index 7a2f0454e..42bc02376 100644 --- a/controls/forms-and-dialogs/colordialog/getting-started.md +++ b/controls/forms-and-dialogs/colordialog/getting-started.md @@ -58,26 +58,10 @@ The following tutorial demonstrates configuring the __RadColorDialog__, localizi #### Check the selected values in RadColorDialog -{{source=..\SamplesCS\Forms and Dialogs\ColorDialog1.cs region=getTheSelectedColors}} -{{source=..\SamplesVB\Forms and Dialogs\ColorDialog1.vb region=getTheSelectedColors}} - -````C# -if (radColorDialog1.ShowDialog() == DialogResult.OK) -{ - Color color = radColorDialog1.SelectedColor; - HslColor hslColor = radColorDialog1.SelectedHslColor; -} - -```` -````VB.NET -If RadColorDialog1.ShowDialog() = DialogResult.OK Then - Dim color As Color = RadColorDialog1.SelectedColor - Dim hslColor As Telerik.WinControls.HslColor = RadColorDialog1.SelectedHslColor -End If - -```` - -{{endregion}} + + + + 9\. Press __F5__ to run the application. diff --git a/controls/forms-and-dialogs/colordialog/localizattion.md b/controls/forms-and-dialogs/colordialog/localizattion.md index aaed4003e..59f4006a9 100644 --- a/controls/forms-and-dialogs/colordialog/localizattion.md +++ b/controls/forms-and-dialogs/colordialog/localizattion.md @@ -21,96 +21,19 @@ Below is a sample implementation of a custom localization provider, which return #### Localizing RadColorDialog strings -{{source=..\SamplesCS\Forms and Dialogs\ColorDialog1.cs region=localization1}} -{{source=..\SamplesVB\Forms and Dialogs\ColorDialog1.vb region=localization1}} + + -````C# -public class CustomColorDialogLocalizationProvider : ColorDialogLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - //localizing the static strings - case ColorDialogStringId.ColorDialogProfessionalTab: return "Localized Professional"; - case ColorDialogStringId.ColorDialogWebTab: return "Localized Web"; - case ColorDialogStringId.ColorDialogSystemTab: return "Localized System"; - case ColorDialogStringId.ColorDialogBasicTab: return "Localized Basic"; - case ColorDialogStringId.ColorDialogAddCustomColorButton: return "Localized Add Custom Color"; - case ColorDialogStringId.ColorDialogOKButton: return "Localized OK"; - case ColorDialogStringId.ColorDialogCancelButton: return "Localized Cancel"; - case ColorDialogStringId.ColorDialogNewColorLabel: return "Localized New"; - case ColorDialogStringId.ColorDialogCurrentColorLabel: return "Localized Current"; - case ColorDialogStringId.ColorDialogCaption: return "Localized Color dialog"; - //you can also localize the names of the colors - case "Black": return "Localized Black"; - case "Blue": return "Localized Blue"; - case "Aqua": return "Localized Aqua"; - } - return base.GetLocalizedString(id); - } -} - -```` -````VB.NET -Public Class CustomColorDialogLocalizationProvider - Inherits ColorDialogLocalizationProvider - Public Overrides Function GetLocalizedString(id As String) As String - Select Case id - 'localizing the static strings - Case ColorDialogStringId.ColorDialogProfessionalTab - Return "Localized Professional" - Case ColorDialogStringId.ColorDialogWebTab - Return "Localized Web" - Case ColorDialogStringId.ColorDialogSystemTab - Return "Localized System" - Case ColorDialogStringId.ColorDialogBasicTab - Return "Localized Basic" - Case ColorDialogStringId.ColorDialogAddCustomColorButton - Return "Localized Add Custom Color" - Case ColorDialogStringId.ColorDialogOKButton - Return "Localized OK" - Case ColorDialogStringId.ColorDialogCancelButton - Return "Localized Cancel" - Case ColorDialogStringId.ColorDialogNewColorLabel - Return "Localized New" - Case ColorDialogStringId.ColorDialogCurrentColorLabel - Return "Localized Current" - Case ColorDialogStringId.ColorDialogCaption - Return "Localized Color dialog" - 'you can also localize the names of the colors - Case "Black" - Return "Localized Black" - Case "Blue" - Return "Localized Blue" - Case "Aqua" - Return "Localized Aqua" - End Select - Return MyBase.GetLocalizedString(id) - End Function -End Class - -```` - -{{endregion}} + To apply the custom localization provider, instantiate and assign it to the current localization provider: #### Using the custom localization provider -{{source=..\SamplesCS\Forms and Dialogs\ColorDialog1.cs region=localization2}} -{{source=..\SamplesVB\Forms and Dialogs\ColorDialog1.vb region=localization2}} + + -````C# -ColorDialogLocalizationProvider.CurrentProvider = new CustomColorDialogLocalizationProvider(); - -```` -````VB.NET -ColorDialogLocalizationProvider.CurrentProvider = New CustomColorDialogLocalizationProvider() - -```` - -{{endregion}} + The code provided above illustrates the approach to be used to localize the __RadColorDialog__ and is not intended as a full translation. diff --git a/controls/forms-and-dialogs/colordialog/properties-methods-events.md b/controls/forms-and-dialogs/colordialog/properties-methods-events.md index 123eebc18..33d921b1a 100644 --- a/controls/forms-and-dialogs/colordialog/properties-methods-events.md +++ b/controls/forms-and-dialogs/colordialog/properties-methods-events.md @@ -45,35 +45,10 @@ You can find below how to enlist all custom colors in __RadColorDialog__: #### Enlist the current custom colors in RadColorDialog -{{source=..\SamplesCS\Forms and Dialogs\ColorDialog1.cs region=enlistTheCustomColors}} -{{source=..\SamplesVB\Forms and Dialogs\ColorDialog1.vb region=enlistTheCustomColors}} - -````C# -private void radButton1_Click(object sender, EventArgs e) -{ - StringBuilder sb = new StringBuilder(); - foreach (Color color in radColorDialog1.CustomColors) - { - sb.Append(color.ToString()); - sb.Append(System.Environment.NewLine); - } - MessageBox.Show(sb.ToString()); -} - -```` -````VB.NET -Private Sub RadButton1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadButton1.Click - Dim sb As New StringBuilder() - For Each color As Color In RadColorDialog1.CustomColors - sb.Append(color.ToString()) - sb.Append(System.Environment.NewLine) - Next - MessageBox.Show(sb.ToString()) -End Sub - -```` - -{{endregion}} + + + + # Methods diff --git a/controls/forms-and-dialogs/form/accessing-radform-elements.md b/controls/forms-and-dialogs/form/accessing-radform-elements.md index 500544ec0..e580f17b0 100644 --- a/controls/forms-and-dialogs/form/accessing-radform-elements.md +++ b/controls/forms-and-dialogs/form/accessing-radform-elements.md @@ -19,28 +19,10 @@ The __RadFormTitleBarElement__ is positioned on the top of the form and its defa #### Accessing RadForm elements -{{source=..\SamplesCS\Forms and Dialogs\Form1.cs region=accessingRadFormElements}} -{{source=..\SamplesVB\Forms and Dialogs\Form1.vb region=accessingRadFormElements}} + + -````C# -void Form1_Shown(object sender, EventArgs e) -{ - this.FormElement.TitleBar.MaximizeButton.Enabled = false; - this.FormElement.TitleBar.MinimizeButton.Enabled = false; - this.FormElement.TitleBar.HelpButton.Visibility = Telerik.WinControls.ElementVisibility.Visible; -} - -```` -````VB.NET -Private Sub Form1_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown - Me.FormElement.TitleBar.MaximizeButton.Enabled = False - Me.FormElement.TitleBar.MinimizeButton.Enabled = False - Me.FormElement.TitleBar.HelpButton.Visibility = Telerik.WinControls.ElementVisibility.Visible -End Sub - -```` - -{{endregion}} + >caption Figure 1: TitleBar @@ -57,28 +39,10 @@ You can easily extend the __RadFormTitleBarElement__ 's functionality by adding #### Adding new button to the title bar -{{source=..\SamplesCS\Forms and Dialogs\Form1.cs region=addingNewButtonToTheTitleBar}} -{{source=..\SamplesVB\Forms and Dialogs\Form1.vb region=addingNewButtonToTheTitleBar}} + + -````C# -void Form1_Load(object sender, EventArgs e) -{ - RadButtonElement buttonElement = new RadButtonElement(); - buttonElement.Text = "TitleBar Button"; - this.FormElement.TitleBar.Children[2].Children[0].Children.Insert(0, buttonElement); -} - -```` -````VB.NET -Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load - Dim buttonElement As New RadButtonElement() - buttonElement.Text = "TitleBar Button" - Me.FormElement.TitleBar.Children(2).Children(0).Children.Insert(0, buttonElement) -End Sub - -```` - -{{endregion}} + ## Accessing the Form Borders @@ -91,19 +55,10 @@ The __FormBorderPrimitive__ represents the outer thin border that surrounds a __ #### Accessing the FormBorderPrimitive -{{source=..\SamplesCS\Forms and Dialogs\Form1.cs region=accessingTheFormBorderPrimitive}} -{{source=..\SamplesVB\Forms and Dialogs\Form1.vb region=accessingTheFormBorderPrimitive}} + + -````C# -this.FormElement.Border.ForeColor = System.Drawing.Color.Green; - -```` -````VB.NET -Me.FormElement.Border.ForeColor = System.Drawing.Color.Green - -```` - -{{endregion}} + >note The visual appearance of the border and also for the whole RadForm control can be designed in the Visual Style Builder. @@ -118,19 +73,10 @@ The following code snippet demonstrates how to set the __BackColor__ of the __Fo #### Accessing the FormImageBorderPrimitive -{{source=..\SamplesCS\Forms and Dialogs\Form1.cs region=accessingTheFormImageBorderPrimitive}} -{{source=..\SamplesVB\Forms and Dialogs\Form1.vb region=accessingTheFormImageBorderPrimitive}} + + -````C# -this.FormElement.ImageBorder.BackColor = Color.Lime; - -```` -````VB.NET -Me.FormElement.ImageBorder.BackColor = Color.Lime - -```` - -{{endregion}} + >note More information on how to use the __FormImageBorderPrimitive__ can be found in the separate topic: [Using the FormImageBorderPrimitive]({%slug winforms/forms-and-dialogs/form/using-the-formimageborderprimitive%}). diff --git a/controls/forms-and-dialogs/form/detect-theme-change.md b/controls/forms-and-dialogs/form/detect-theme-change.md index 05707bc38..8d976e64e 100644 --- a/controls/forms-and-dialogs/form/detect-theme-change.md +++ b/controls/forms-and-dialogs/form/detect-theme-change.md @@ -14,50 +14,10 @@ As of **R1 2022 SP1** RadForm offers the **WindowsThemeChanged** event which can >note The WindowsSettings.**CurrentWindowsTheme** can be used to detect the currently active windows theme. -{{source=..\SamplesCS\Forms and Dialogs\Form1.cs region=OSThemeChange}} -{{source=..\SamplesVB\Forms and Dialogs\Form1.vb region=OSThemeChange}} + + -````C# - -private void RadForm_WindowsThemeChanged(object sender, Telerik.WinControls.WindowsThemeChangedEventArgs e) -{ - WindowsTheme newTheme = e.CurrentTheme; - if (newTheme == WindowsTheme.Light) - { - this.BackColor = Color.LightBlue; - } - else if (newTheme == WindowsTheme.Dark) - { - this.BackColor = Color.DarkBlue; - } - else if (newTheme == WindowsTheme.HighContrast) - { - this.BackColor = Color.Black; - } - - this.Text = "Windows Theme is " + newTheme.ToString(); -} - -```` -````VB.NET - -Private Sub RadForm_WindowsThemeChanged(sender As Object, e As WindowsThemeChangedEventArgs) - Dim newTheme As WindowsTheme = e.CurrentTheme - - If newTheme = WindowsTheme.Light Then - Me.BackColor = Color.LightBlue - ElseIf newTheme = WindowsTheme.Dark Then - Me.BackColor = Color.DarkBlue - ElseIf newTheme = WindowsTheme.HighContrast Then - Me.BackColor = Color.Black - End If - - Me.Text = "Windows Theme is " & newTheme.ToString() -End Sub - -```` -{{endregion}} diff --git a/controls/forms-and-dialogs/form/mdi.md b/controls/forms-and-dialogs/form/mdi.md index d6025d03e..916109ad3 100644 --- a/controls/forms-and-dialogs/form/mdi.md +++ b/controls/forms-and-dialogs/form/mdi.md @@ -23,52 +23,11 @@ The following code snippet adds three __RadForm__ instances to a MDI container a #### Adding RadForm MDI children to RadForm -{{source=..\SamplesCS\Forms and Dialogs\Form1.cs region=addingMDIChildFormsToAForm}} -{{source=..\SamplesVB\Forms and Dialogs\Form1.vb region=addingMDIChildFormsToAForm}} - -````C# -this.IsMdiContainer = true; -  -RadForm form = new RadForm(); -form.Text = "MDI Child 1"; -form.MdiParent = this; -form.ThemeName = "Desert"; -form.Show(); -  -form = new RadForm(); -form.Text = "MDI Child 2"; -form.MdiParent = this; -form.ThemeName = "Office2007Black"; -form.Show(); -  -form = new RadForm(); -form.Text = "MDI Child 3"; -form.MdiParent = this; -form.ThemeName = "TelerikMetro"; -form.Show(); - -```` -````VB.NET -Me.IsMdiContainer = True -Dim form As New RadForm() -form.Text = "MDI Child 1" -form.MdiParent = Me -form.ThemeName = "Desert" -form.Show() -form = New RadForm() -form.Text = "MDI Child 2" -form.MdiParent = Me -form.ThemeName = "Office2007Black" -form.Show() -form = New RadForm() -form.Text = "MDI Child 3" -form.MdiParent = Me -form.ThemeName = "TelerikMetro" -form.Show() - -```` - -{{endregion}} + + + + + ## Default MDI Menu Strip diff --git a/controls/forms-and-dialogs/form/themes.md b/controls/forms-and-dialogs/form/themes.md index 951881e27..611d88443 100644 --- a/controls/forms-and-dialogs/form/themes.md +++ b/controls/forms-and-dialogs/form/themes.md @@ -25,20 +25,10 @@ This section shows how to apply the __Office2007Black__ theme to a __RadForm__ i #### Changing WinForms form to Telerik RadForm -{{source=..\SamplesCS\Forms and Dialogs\Form1.Designer.cs region=radForm}} -{{source=..\SamplesVB\Forms and Dialogs\Form1.Designer.vb region=radForm}} + + -````C# -partial class Form1 : Telerik.WinControls.UI.RadForm - -```` -````VB.NET -Partial Class Form1 - Inherits Telerik.WinControls.UI.RadForm - -```` - -{{endregion}} + 2\. Open the __Design View__ of the Form and open the Visual Studio Toolbox. diff --git a/controls/forms-and-dialogs/messagebox/getting-started.md b/controls/forms-and-dialogs/messagebox/getting-started.md index b391147f3..a8a34a380 100644 --- a/controls/forms-and-dialogs/messagebox/getting-started.md +++ b/controls/forms-and-dialogs/messagebox/getting-started.md @@ -44,48 +44,20 @@ The following tutorial will show you a simple usage of __RadMessageBox__: 4\. Make sure that you import/use the following namespaces -{{source=..\SamplesCS\Forms and Dialogs\MessageBox1.cs region=namespace}} -{{source=..\SamplesVB\Forms and Dialogs\MessageBox1.vb region=namespace}} + + -````C# -using Telerik.WinControls; - -```` -````VB.NET -Imports Telerik.WinControls - -```` - -{{endregion}} + 5\. In the RadButton.__Click__ event handler, first set the theme of the __RadMessageBox__ and then call its static __Show__ method of the __RadMessageBox__ class, passing the appropriate parameters. Set the RadMessageBox.__Show__ method to a __DialogResult__ variable: #### Setting a theme and showing RadMessageBox -{{source=..\SamplesCS\Forms and Dialogs\MessageBox1.cs region=workingWithRadMessageBox}} -{{source=..\SamplesVB\Forms and Dialogs\MessageBox1.vb region=workingWithRadMessageBox}} + + -````C# -private void radButton1_Click(object sender, EventArgs e) -{ - RadMessageBox.SetThemeName("Desert"); - - DialogResult ds = RadMessageBox.Show(this, "Are you sure?", "Title", MessageBoxButtons.YesNo, RadMessageIcon.Question); - this.Text = ds.ToString(); -} - -```` -````VB.NET -Private Sub RadButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadButton1.Click - RadMessageBox.SetThemeName("Desert") - Dim ds As DialogResult = RadMessageBox.Show(Me, "Are you sure?", "Title", MessageBoxButtons.YesNo, RadMessageIcon.Question) - Me.Text = ds.ToString() -End Sub - -```` - -{{endregion}} + 6\. The result RadMessageBox is shown below: diff --git a/controls/forms-and-dialogs/messagebox/localization.md b/controls/forms-and-dialogs/messagebox/localization.md index 1babeaf99..8f709d9dd 100644 --- a/controls/forms-and-dialogs/messagebox/localization.md +++ b/controls/forms-and-dialogs/messagebox/localization.md @@ -1,92 +1,35 @@ ---- -title: Localization -page_title: Localization - WinForms MessageBox -description: WinForms MessageBox provides localization of its buttons text via RadMessageLocalizationProvider. -slug: winforms/forms-and-dialogs/messagebox/localization -tags: localization -published: True -position: 5 -previous_url: forms-and-dialogs-messagebox-localization ---- - -# Localization - -__RadMessageBox__ provides localization of its buttons text via __RadMessageLocalizationProvider__: - -1\. Start by creating a descendant of the __RadGridLocalizationSettings__ class. Then, override the __GetLocalizedString(string id)__ method, and in its implementation, provide a translation for the label and user messages. If one is not provided, the default value will be returned - this is guaranteed by the call to the base __GetLocalizedString__ method in the default clause of the switch statement. - -#### Creating a custom localization provider - -{{source=..\SamplesCS\Forms and Dialogs\MessageBox1.cs region=LocalizationProvider}} -{{source=..\SamplesVB\Forms and Dialogs\MessageBox1.vb region=LocalizationProvider}} - -````C# -public class MyRadMessageLocalizationProvider : RadMessageLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case RadMessageStringID.AbortButton: return "Abbruch"; - case RadMessageStringID.CancelButton: return "Löschen"; - case RadMessageStringID.IgnoreButton: return "Ignorieren"; - case RadMessageStringID.NoButton: return "Nein"; - case RadMessageStringID.OKButton: return "OK"; - case RadMessageStringID.RetryButton: return "Wiederholung"; - case RadMessageStringID.YesButton: return "Ja"; - default: - return base.GetLocalizedString(id); - } - } -} - -```` -````VB.NET -Public Class MyRadMessageLocalizationProvider - Inherits RadMessageLocalizationProvider - Public Overloads Overrides Function GetLocalizedString(ByVal id As String) As String - Select Case id - Case RadMessageStringID.AbortButton - Return "Abbruch" - Case RadMessageStringID.CancelButton - Return "Löschen" - Case RadMessageStringID.IgnoreButton - Return "Ignorieren" - Case RadMessageStringID.NoButton - Return "Nein" - Case RadMessageStringID.OKButton - Return "OK" - Case RadMessageStringID.RetryButton - Return "Wiederholung" - Case RadMessageStringID.YesButton - Return "Ja" - Case Else - Return MyBase.GetLocalizedString(id) - End Select - End Function -End Class - -```` - -{{endregion}} - -2\. To apply the custom localization provider, instantiate and assign it to the current localization provider: - -#### Setting the custom localization provider to RadMessageBox - -{{source=..\SamplesCS\Forms and Dialogs\MessageBox1.cs region=settingTheLocalizationProvider}} -{{source=..\SamplesVB\Forms and Dialogs\MessageBox1.vb region=settingTheLocalizationProvider}} - -````C# -RadMessageLocalizationProvider.CurrentProvider = new MyRadMessageLocalizationProvider(); - -```` -````VB.NET -RadMessageLocalizationProvider.CurrentProvider = New MyRadMessageLocalizationProvider() - -```` - -{{endregion}} - - - +--- +title: Localization +page_title: Localization - WinForms MessageBox +description: WinForms MessageBox provides localization of its buttons text via RadMessageLocalizationProvider. +slug: winforms/forms-and-dialogs/messagebox/localization +tags: localization +published: True +position: 5 +previous_url: forms-and-dialogs-messagebox-localization +--- + +# Localization + +__RadMessageBox__ provides localization of its buttons text via __RadMessageLocalizationProvider__: + +1\. Start by creating a descendant of the __RadGridLocalizationSettings__ class. Then, override the __GetLocalizedString(string id)__ method, and in its implementation, provide a translation for the label and user messages. If one is not provided, the default value will be returned - this is guaranteed by the call to the base __GetLocalizedString__ method in the default clause of the switch statement. + +#### Creating a custom localization provider + + + + + + +2\. To apply the custom localization provider, instantiate and assign it to the current localization provider: + +#### Setting the custom localization provider to RadMessageBox + + + + + + + + diff --git a/controls/forms-and-dialogs/messagebox/parameters.md b/controls/forms-and-dialogs/messagebox/parameters.md index 1855519f9..6aeefc539 100644 --- a/controls/forms-and-dialogs/messagebox/parameters.md +++ b/controls/forms-and-dialogs/messagebox/parameters.md @@ -17,19 +17,10 @@ You can easily set the __ThemeName__ of the __RadMessageBox__ by calling the __S #### Setting a theme in RadMessageBox -{{source=..\SamplesCS\Forms and Dialogs\MessageBox1.cs region=SetThemeName}} -{{source=..\SamplesVB\Forms and Dialogs\MessageBox1.vb region=SetThemeName}} + + -````C# -RadMessageBox.SetThemeName("Desert"); - -```` -````VB.NET -RadMessageBox.SetThemeName("Desert") - -```` - -{{endregion}} + ## Show method @@ -91,46 +82,10 @@ The __Show__ method displays a __RadMessageBox__. It returns a __DialogResult__ As of Q2 2014 __RadMessageBox__ supports details section. This section can be shown by just specifying the details text in the __Show__ method parameters: -{{source=..\SamplesCS\Forms and Dialogs\MessageBox1.cs region=details}} -{{source=..\SamplesVB\Forms and Dialogs\MessageBox1.vb region=details}} - -````C# -RadMessageBox.Show("Message", "Caption Text", MessageBoxButtons.AbortRetryIgnore, "Details Text"); - -```` -````VB.NET -RadMessageBox.Show("Message", "Caption Text", MessageBoxButtons.AbortRetryIgnore, "Details Text") -'#End Region -End Sub -s - "LocalizationProvider" -lass MyRadMessageLocalizationProvider -Inherits RadMessageLocalizationProvider -Public Overloads Overrides Function GetLocalizedString(ByVal id As String) As String -Select Case id - Case RadMessageStringID.AbortButton - Return "Abbruch" - Case RadMessageStringID.CancelButton - Return "Löschen" - Case RadMessageStringID.IgnoreButton - Return "Ignorieren" - Case RadMessageStringID.NoButton - Return "Nein" - Case RadMessageStringID.OKButton - Return "OK" - Case RadMessageStringID.RetryButton - Return "Wiederholung" - Case RadMessageStringID.YesButton - Return "Ja" - Case Else - Return MyBase.GetLocalizedString(id) -End Select -End Function -s - -```` - -{{endregion}} + + + + The result looks like this: diff --git a/controls/forms-and-dialogs/radtitlebar/detecting-when-the-user-drags-the-radtitlebar.md b/controls/forms-and-dialogs/radtitlebar/detecting-when-the-user-drags-the-radtitlebar.md index baf16b13a..b341e3e9a 100644 --- a/controls/forms-and-dialogs/radtitlebar/detecting-when-the-user-drags-the-radtitlebar.md +++ b/controls/forms-and-dialogs/radtitlebar/detecting-when-the-user-drags-the-radtitlebar.md @@ -15,33 +15,10 @@ The following example, demonstrates how to detect when the user drags the title #### Detecting when the TitleBar is dragged -{{source=..\SamplesCS\Forms and Dialogs\ShapedForm1.cs region=detectTitleBarDragging}} -{{source=..\SamplesVB\Forms and Dialogs\ShapedForm1.vb region=detectTitleBarDragging}} - -````C# -public const int WM_WINDOWPOSCHANGED = 0x47; -protected override void WndProc(ref Message m) -{ - if (m.Msg == WM_WINDOWPOSCHANGED) - { - this.Text = Control.MousePosition.ToString(); - } - base.WndProc(ref m); -} - -```` -````VB.NET -Public Const WM_WINDOWPOSCHANGED As Integer = 71 -Protected Overloads Overrides Sub WndProc(ByRef m As Message) - If m.Msg = WM_WINDOWPOSCHANGED Then - Me.Text = Control.MousePosition.ToString() - End If - MyBase.WndProc(m) -End Sub - -```` - -{{endregion}} + + + + diff --git a/controls/forms-and-dialogs/radtitlebar/help-button.md b/controls/forms-and-dialogs/radtitlebar/help-button.md index 2be795b80..c8508c501 100644 --- a/controls/forms-and-dialogs/radtitlebar/help-button.md +++ b/controls/forms-and-dialogs/radtitlebar/help-button.md @@ -20,56 +20,10 @@ An alternative solution is to set its Visibility property to ElementVisibility.* You can find below a sample code snippet: #### Customize selected item appearance -{{source=..\SamplesCS\Forms And Dialogs\TitleBarHelpButton.cs region=HelpButton}} -{{source=..\SamplesVB\Forms And Dialogs\TitleBarHelpButton.vb region=HelpButton}} + + -````C# - -public TitleBarHelpButton() -{ - InitializeComponent(); - this.HelpButton = true; - this.MaximizeBox = false; - this.MinimizeBox = false; - this.HelpButtonClicked += ShapedForm1_HelpButtonClicked; - this.radButton1.HelpRequested += radButton1_HelpRequested; -} - -private void ShapedForm1_HelpButtonClicked(object sender, CancelEventArgs e) -{ - if (RadMessageBox.Show("Do you need help?", "Confirmation", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No) - { - e.Cancel = true; - } -} - -private void radButton1_HelpRequested(object sender, HelpEventArgs hlpevent) -{ - RadMessageBox.Show("This is RadButton."); -} -```` -````VB.NET -Public Sub New() - InitializeComponent() - Me.HelpButton = True - Me.MaximizeBox = False - Me.MinimizeBox = False - AddHandler Me.HelpButtonClicked, AddressOf ShapedForm1_HelpButtonClicked - AddHandler Me.RadButton1.HelpRequested, AddressOf radButton1_HelpRequested -End Sub -Private Sub ShapedForm1_HelpButtonClicked(sender As Object, e As CancelEventArgs) - If RadMessageBox.Show("Do you need help?", "Confirmation", MessageBoxButtons.YesNo) = System.Windows.Forms.DialogResult.No Then - e.Cancel = True - End If -End Sub -Private Sub radButton1_HelpRequested(sender As Object, hlpevent As HelpEventArgs) - RadMessageBox.Show("This is RadButton.") -End Sub - -```` - -{{endregion}} diff --git a/controls/forms-and-dialogs/ribbonform/customizing-appearance/accessing-and-customizing-elements.md b/controls/forms-and-dialogs/ribbonform/customizing-appearance/accessing-and-customizing-elements.md index 50d6ae2f4..d0f3f9302 100644 --- a/controls/forms-and-dialogs/ribbonform/customizing-appearance/accessing-and-customizing-elements.md +++ b/controls/forms-and-dialogs/ribbonform/customizing-appearance/accessing-and-customizing-elements.md @@ -29,18 +29,7 @@ You can customize the nested elements at run time as well: #### Customize elements -{{source=..\SamplesCS\Forms And Dialogs\RadRibbonForm1.cs region=RibbonForm}} -{{source=..\SamplesVB\Forms And Dialogs\RadRibbonForm1.vb region=RibbonForm}} + + -````C# -this.AllowAero = false; -this.RibbonBar.RibbonBarElement.CaptionFill.BackColor = Color.Lime; - -```` -````VB.NET -Me.AllowAero = False -Me.RibbonBar.RibbonBarElement.CaptionFill.BackColor = Color.Lime - -```` - -{{endregion}} + diff --git a/controls/forms-and-dialogs/shapedform/customizing-shapedform.md b/controls/forms-and-dialogs/shapedform/customizing-shapedform.md index e277163ac..50f8cd00d 100644 --- a/controls/forms-and-dialogs/shapedform/customizing-shapedform.md +++ b/controls/forms-and-dialogs/shapedform/customizing-shapedform.md @@ -21,19 +21,10 @@ Almost all properties of _ShapedForm__ are the same as a standard Windows Form. #### Setting a theme to a ShapedForm -{{source=..\SamplesCS\Forms and Dialogs\ShapedForm1.cs region=ThemeName}} -{{source=..\SamplesVB\Forms and Dialogs\ShapedForm1.vb region=ThemeName}} + + -````C# -this.ThemeName = "Breeze"; -```` -````VB.NET -Me.ThemeName = "Breeze" - -```` - -{{endregion}} diff --git a/controls/forms-and-dialogs/shapedform/getting-started.md b/controls/forms-and-dialogs/shapedform/getting-started.md index 0f851f5fb..28c042dac 100644 --- a/controls/forms-and-dialogs/shapedform/getting-started.md +++ b/controls/forms-and-dialogs/shapedform/getting-started.md @@ -61,21 +61,10 @@ To add a __ShapedForm__ to your project: #### Changing WinForms form to Telerik ShapedForm -{{source=..\SamplesCS\Forms and Dialogs\ShapedForm1.Designer.cs region=shapedForm}} -{{source=..\SamplesVB\Forms and Dialogs\ShapedForm1.Designer.vb region=shapedForm}} + + -````C# -partial class ShapedForm1 : Telerik.WinControls.UI.ShapedForm -```` -````VB.NET - _ -Partial Class ShapedForm1 - Inherits Telerik.WinControls.UI.ShapedForm - -```` - -{{endregion}} 10\. Return to the design view of the form. Visual Studio will repaint the form without a title bar, indicating that it is now being derived from the __ShapedForm__ class. diff --git a/controls/forms-and-dialogs/statusstrip/adding-items.md b/controls/forms-and-dialogs/statusstrip/adding-items.md index 54fa0d95f..83b01b16a 100644 --- a/controls/forms-and-dialogs/statusstrip/adding-items.md +++ b/controls/forms-and-dialogs/statusstrip/adding-items.md @@ -57,60 +57,10 @@ Add items at run time by creating __RadElement__ instances and adding them to th #### Adding Elements to RadStatusStrip -{{source=..\SamplesCS\Forms and Dialogs\StatusStrip1.cs region=addingElementsToRadStatusStrip}} -{{source=..\SamplesVB\Forms and Dialogs\StatusStrip1.vb region=addingElementsToRadStatusStrip}} - -````C# -private void StatusStrip1_Load(object sender, EventArgs e) -{ - RadLabelElement labelElement = new RadLabelElement(); - labelElement.Text = "My LabelElement"; - RadButtonElement buttonElement = new RadButtonElement(); - buttonElement.Text = "My ButtonElement"; - buttonElement.Click += new EventHandler(buttonElement_Click); - RadRepeatButtonElement repeatButtonElement = new RadRepeatButtonElement(); - repeatButtonElement.Text = "My Repeat button"; - repeatButtonElement.Click += new EventHandler(repeatButtonElement_Click); - CommandBarSeparator separator = new CommandBarSeparator(); - RadProgressBarElement progressBarElement = new RadProgressBarElement(); - progressBarElement.Text = "My Progress Bar"; - radStatusStrip1.Items.AddRange(new RadItem[] {labelElement, buttonElement, repeatButtonElement, separator, progressBarElement}); -} -void repeatButtonElement_Click(object sender, EventArgs e) -{ - (radStatusStrip1.Items[0] as RadLabelElement).Text = "Clicked repeat button on " + DateTime.Now.ToLongTimeString(); -} -void buttonElement_Click(object sender, EventArgs e) -{ - MessageBox.Show("Clicked on ButtonElement"); -} - -```` -````VB.NET -Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load - Dim labelElement As New RadLabelElement() - labelElement.Text = "My LabelElement" - Dim buttonElement As New RadButtonElement() - buttonElement.Text = "My ButtonElement" - AddHandler buttonElement.Click, AddressOf buttonElement_Click - Dim repeatButtonElement As New RadRepeatButtonElement() - repeatButtonElement.Text = "My Repeat button" - AddHandler repeatButtonElement.Click, AddressOf repeatButtonElement_Click - Dim separator As New CommandBarSeparator() - Dim progressBarElement As New RadProgressBarElement() - progressBarElement.Text = "My Progress Bar" - RadStatusStrip1.Items.AddRange(New RadItem() {labelElement, buttonElement, repeatButtonElement, separator, progressBarElement}) -End Sub -Sub repeatButtonElement_Click(ByVal sender As Object, ByVal e As EventArgs) - TryCast(RadStatusStrip1.Items(0), RadLabelElement).Text = "Clicked repeat button on " + DateTime.Now.ToLongTimeString() -End Sub -Sub buttonElement_Click(ByVal sender As Object, ByVal e As EventArgs) - MessageBox.Show("Clicked on ButtonElement") -End Sub - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/forms-and-dialogs/statusstrip/gettingstarted.md b/controls/forms-and-dialogs/statusstrip/gettingstarted.md index 8b2006afc..31f7e83d4 100644 --- a/controls/forms-and-dialogs/statusstrip/gettingstarted.md +++ b/controls/forms-and-dialogs/statusstrip/gettingstarted.md @@ -72,31 +72,10 @@ The following tutorial demonstrates configuring __RadStatusStrip__ at design-tim 7\. Double-click "btnStatus" to create a __Click__ event handler. Add the code below to replace the event handler. This code block bumps the list control selected index until the end of the list is reached, and then moves the index back to the first item in the list. -{{source=..\SamplesCS\Forms And Dialogs\StatusStripGettingStarted.cs region=statusClick}} -{{source=..\SamplesVB\Forms And Dialogs\StatusStripGettingStarted.vb region=statusClick}} - -````C# -private void btnStatus_Click(object sender, EventArgs e) -{ - if (radListControl1.SelectedIndex >= radListControl1.Items.Count - 1) - radListControl1.SelectedIndex = 0; - else - radListControl1.SelectedIndex += 1; -} - -```` -````VB.NET -Private Sub btnStatus_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStatus.Click - If RadListControl1.SelectedIndex >= RadListControl1.Items.Count - 1 Then - RadListControl1.SelectedIndex = 0 - Else - RadListControl1.SelectedIndex += 1 - End If -End Sub - -```` - -{{endregion}} + + + + 8\. In the __Properties Window__ for the __RadListControl:__ @@ -119,66 +98,17 @@ End Sub 11\. Paste the following code to the __SelectedIndexChanged__ event handler.  *The code retrieves the selected item and assigns the text and image for the selected item to the status bar label and image elements. Then the progress bar element mimics an operation against the newly selected item.* -{{source=..\SamplesCS\Forms And Dialogs\StatusStripGettingStarted.cs region=selectedIndexChanged}} -{{source=..\SamplesVB\Forms And Dialogs\StatusStripGettingStarted.vb region=selectedIndexChanged}} - -````C# -void radListControl1_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e) -{ - RadListElement listControl = (sender as RadListElement); - RadListDataItem item = listControl.SelectedItem; - lblStatus.Text = item.Text; - imgStatus.Image = item.Image; - pbStatus.Visibility = Telerik.WinControls.ElementVisibility.Visible; - for (int i = 0; i < 100; i++) - { - pbStatus.Value1 = i; - pbStatus.Text = item.Text + "..."; - radStatusStrip1.Refresh(); - Thread.Sleep(5); - } - pbStatus.Visibility = Telerik.WinControls.ElementVisibility.Collapsed; -} - -```` -````VB.NET -Private Sub RadListControl1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As Telerik.WinControls.UI.Data.PositionChangedEventArgs) Handles RadListControl1.SelectedIndexChanged - Dim listControl As RadListElement = TryCast(sender, RadListElement) - Dim item As RadListDataItem = listControl.SelectedItem - lblStatus.Text = item.Text - imgStatus.Image = item.Image - pbStatus.Visibility = Telerik.WinControls.ElementVisibility.Visible - Dim i As Integer = 0 - While i < 100 - pbStatus.Value1 = i - pbStatus.Text = item.Text + "..." - Thread.Sleep(5) - System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1) - End While - pbStatus.Visibility = Telerik.WinControls.ElementVisibility.Hidden -End Sub - -```` - -{{endregion}} + + -12\. Add __Telerik.WinControls.UI__ and __System.Threading__ references to the "using" (C#) or Imports (VB) section of the code. - -{{source=..\SamplesCS\Forms And Dialogs\StatusStripGettingStarted.cs region=namespaces}} -{{source=..\SamplesVB\Forms And Dialogs\StatusStripGettingStarted.vb region=namespaces}} -````C# -using Telerik.WinControls.UI; -using System.Threading; -```` -````VB.NET -Imports Telerik.WinControls.UI -Imports System.Threading +12\. Add __Telerik.WinControls.UI__ and __System.Threading__ references to the "using" (C#) or Imports (VB) section of the code. + + + -```` -{{endregion}} 13\. Press __F5__ to run the application. Press the "Go!" button to see the status bar react to list control changes. diff --git a/controls/forms-and-dialogs/tabbedform/customizing-appearance/customizing-appearance.md b/controls/forms-and-dialogs/tabbedform/customizing-appearance/customizing-appearance.md index 7eed3aa4b..9a5e3aaac 100644 --- a/controls/forms-and-dialogs/tabbedform/customizing-appearance/customizing-appearance.md +++ b/controls/forms-and-dialogs/tabbedform/customizing-appearance/customizing-appearance.md @@ -21,18 +21,10 @@ The following example demonstrates how you can access the visual item of the tab ### Access the tab visual element -{{source=..\SamplesCS\Forms and Dialogs\TabbedFormCode.cs region=Appearance}} -{{source=..\SamplesVB\Forms and Dialogs\TabbedFormCode.vb region=Appearance}} -````C# -this.TabbedFormControl.Tabs[0].Item.BackColor = Color.Red; + + -```` -````VB.NET -Me.TabbedFormControl.Tabs(0).Item.BackColor = Color.Red -```` - -{{endregion}} # See Also diff --git a/controls/forms-and-dialogs/tabbedform/features/context-menu.md b/controls/forms-and-dialogs/tabbedform/features/context-menu.md index d73d7fe18..2f8010d68 100644 --- a/controls/forms-and-dialogs/tabbedform/features/context-menu.md +++ b/controls/forms-and-dialogs/tabbedform/features/context-menu.md @@ -20,44 +20,9 @@ The following example demonstrates how one can use the __ContextMenuOpening__ ev #### Using the ContextMenuOpening event -{{source=..\SamplesCS\Forms and Dialogs\TabbedFormCode.cs region=ModifyContextMenu}} -{{source=..\SamplesVB\Forms and Dialogs\TabbedFormCode.vb region=ModifyContextMenu}} -````C# -private void TabbedFormCode_Load(object sender, EventArgs e) -{ - this.TabbedFormControl.ContextMenuOpening += TabbedFormControl_ContextMenuOpening; -} -private void TabbedFormControl_ContextMenuOpening(object sender, RadTabbedFormControlItemConextMenuOpeningEventArgs e) -{ - if (e.TabItem.Text == "Tab 1") - { - //remove first item - e.ContextMenu.Items[0].Visibility = ElementVisibility.Collapsed; - } - else if (e.TabItem.Text == "Tab 2") - { - //disable the context menu - e.Cancel = true; - } -} - -```` -````VB.NET -Private Sub TabbedFormCode_Load(ByVal sender As Object, ByVal e As EventArgs) - AddHandler Me.TabbedFormControl.ContextMenuOpening, AddressOf TabbedFormControl_ContextMenuOpening -End Sub -Private Sub TabbedFormControl_ContextMenuOpening(ByVal sender As Object, ByVal e As RadTabbedFormControlItemConextMenuOpeningEventArgs) - If e.TabItem.Text = "Tab 1" Then - 'remove first item - e.ContextMenu.Items(0).Visibility = ElementVisibility.Collapsed - ElseIf e.TabItem.Text = "Tab 2" Then - 'disable the context menu - e.Cancel = True - End If -End Sub - -```` - -{{endregion}} + + + + diff --git a/controls/forms-and-dialogs/tabbedform/features/drag-and-drop.md b/controls/forms-and-dialogs/tabbedform/features/drag-and-drop.md index eb5080c2b..90518b709 100644 --- a/controls/forms-and-dialogs/tabbedform/features/drag-and-drop.md +++ b/controls/forms-and-dialogs/tabbedform/features/drag-and-drop.md @@ -21,24 +21,10 @@ position: 0 #### RadTabbedFormDragDropService -{{source=..\SamplesCS\Forms and Dialogs\TabbedFormCode.cs region=DragDropService}} -{{source=..\SamplesVB\Forms and Dialogs\TabbedFormCode.vb region=DragDropService}} -````C# -RadTabbedFormDragDropService dragDropService = this.TabbedFormControl.TabbedFormControlElement.ItemDragService; -dragDropService.TabbedFormCreating += DragDropService_TabbedFormCreating; -dragDropService.TabbedFormShown += DragDropService_TabbedFormShown; + + -```` -````VB.NET -Dim dragDropService As RadTabbedFormDragDropService = Me.TabbedFormControl.TabbedFormControlElement.ItemDragService -AddHandler dragDropService.TabbedFormCreating, AddressOf DragDropService_TabbedFormCreating -AddHandler dragDropService.TabbedFormShown, AddressOf DragDropService_TabbedFormShown -```` - - - -{{endregion}} ## Reordering via Drag and Drop @@ -75,18 +61,10 @@ There are three drag modes that are currently supported: #### Setting the Drag Drop Mode -{{source=..\SamplesCS\Forms and Dialogs\TabbedFormCode.cs region=DragDropMode}} -{{source=..\SamplesVB\Forms and Dialogs\TabbedFormCode.vb region=DragDropMode}} -````C# -this.TabbedFormControl.ItemDragMode = TabItemDragMode.Preview; - -```` -````VB.NET -Me.TabbedFormControl.ItemDragMode = TabItemDragMode.Preview + + -```` -{{endregion}} ![WinForms RadTabbedForm Drag Drop Mode](images/radtabbedform-drag-drop004.gif) diff --git a/controls/forms-and-dialogs/tabbedform/features/navigation.md b/controls/forms-and-dialogs/tabbedform/features/navigation.md index c7f0d3df9..ad9c90878 100644 --- a/controls/forms-and-dialogs/tabbedform/features/navigation.md +++ b/controls/forms-and-dialogs/tabbedform/features/navigation.md @@ -22,17 +22,8 @@ If you set the __MinimumTabWidth__ property, it will affect when the navigation #### Set MinTabWidth -{{source=..\SamplesCS\Forms And Dialogs\TabbedFormCode.cs region=SetMinWidth}} -{{source=..\SamplesVB\Forms And Dialogs\TabbedFormCode.vb region=SetMinWidth}} -````C# -this.TabbedFormControl.MinimumTabWidth = 150; + + -```` -````VB.NET -Me.TabbedFormControl.MinimumTabWidth = 150 -```` - - -{{endregion}} diff --git a/controls/forms-and-dialogs/tabbedform/features/pinned-tabs.md b/controls/forms-and-dialogs/tabbedform/features/pinned-tabs.md index dd95b345d..f9b93aea8 100644 --- a/controls/forms-and-dialogs/tabbedform/features/pinned-tabs.md +++ b/controls/forms-and-dialogs/tabbedform/features/pinned-tabs.md @@ -27,18 +27,10 @@ First you need to show the pin button. Set the **ShowTabPinButton** property to #### Show Pin Button -{{source=..\SamplesCS\Forms And Dialogs\TabbedFormCode.cs region=PinProp}} -{{source=..\SamplesVB\Forms And Dialogs\TabbedFormCode.vb region=PinProp}} -````C# -this.TabbedFormControl.Tabs[0].Item.IsPinned = true; + + -```` -````VB.NET -Me.TabbedFormControl.Tabs(0).Item.IsPinned = True -```` - -{{endregion}} >caption Figure 2: Pin Tabs by Using the Pin Button @@ -52,17 +44,9 @@ You can use the following code to pin a tab. #### Pin with code -{{source=..\SamplesCS\Forms and Dialogs\TabbedFormCode.cs region=PinTab}} -{{source=..\SamplesVB\Forms and Dialogs\TabbedFormCode.vb region=PinTab}} -````C# -this.TabbedFormControl.Tabs[0].Item.IsPinned = true; - -```` -````VB.NET -Me.TabbedFormControl.Tabs(0).Item.IsPinned = True + + -```` -{{endregion}} diff --git a/controls/forms-and-dialogs/tabbedform/features/quick-actions.md b/controls/forms-and-dialogs/tabbedform/features/quick-actions.md index a0a2093a7..f6758d225 100644 --- a/controls/forms-and-dialogs/tabbedform/features/quick-actions.md +++ b/controls/forms-and-dialogs/tabbedform/features/quick-actions.md @@ -32,20 +32,10 @@ You can add the buttons in the code behind as well. This is demonstrated in the #### Adding Buttons Programmatically -{{source=..\SamplesCS\Forms and Dialogs\TabbedFormCode.cs region=Buttons}} -{{source=..\SamplesVB\Forms and Dialogs\TabbedFormCode.vb region=Buttons}} -````C# -this.TabbedFormControl.LeftItems.Add(new RadButtonElement { Text = "button1" }); -this.TabbedFormControl.RightItems.Add(new RadButtonElement { Text = "button2" }); + + -```` -````VB.NET -Me.TabbedFormControl.LeftItems.Add(New RadButtonElement With {.Text = "button1"}) -Me.TabbedFormControl.RightItems.Add(New RadButtonElement With {.Text = "button2"}) -```` - -{{endregion}} >caption Figure 1:Adding Buttons Programmatically. diff --git a/controls/forms-and-dialogs/tabbedform/features/tab-settings.md b/controls/forms-and-dialogs/tabbedform/features/tab-settings.md index 315be3ad3..32c085cb2 100644 --- a/controls/forms-and-dialogs/tabbedform/features/tab-settings.md +++ b/controls/forms-and-dialogs/tabbedform/features/tab-settings.md @@ -50,32 +50,10 @@ position: 0 #### Apply Settings -{{source=..\SamplesCS\Forms and Dialogs\TabbedFormCode.cs region=ApplyTabSettings}} -{{source=..\SamplesVB\Forms and Dialogs\TabbedFormCode.vb region=ApplyTabSettings}} -````C# -this.AllowAero = false; -this.ShowIcon = true; -this.TabbedFormControl.ShowText = true; -this.TabbedFormControl.CaptionHeight = 65; -this.TabbedFormControl.TabHeight = 32; -this.TabbedFormControl.TabWidth = 180; -this.TabbedFormControl.TabSpacing = 12; - -```` -````VB.NET -Me.AllowAero = False -Me.ShowIcon = True -Me.TabbedFormControl.ShowText = True -Me.TabbedFormControl.CaptionHeight = 65 -Me.TabbedFormControl.TabHeight = 32 -Me.TabbedFormControl.TabWidth = 180 -Me.TabbedFormControl.TabSpacing = 12 - -```` - - - -{{endregion}} + + + + The below image demonstrates the result after applying the above code in the TelerikMetro theme. diff --git a/controls/forms-and-dialogs/tabbedform/features/titlebar-style.md b/controls/forms-and-dialogs/tabbedform/features/titlebar-style.md index e9d719d38..b18afe7e6 100644 --- a/controls/forms-and-dialogs/tabbedform/features/titlebar-style.md +++ b/controls/forms-and-dialogs/tabbedform/features/titlebar-style.md @@ -12,18 +12,10 @@ position: 0 The Tabbed Form supports the standard Windows title bar style. This setting is controlled by the __AllowAero__ property. -{{source=..\SamplesCS\Forms and Dialogs\TabbedFormCode.cs region=Aero}} -{{source=..\SamplesVB\Forms and Dialogs\TabbedFormCode.vb region=Aero}} -````C# -this.AllowAero = false; + + -```` -````VB.NET -Me.AllowAero = False -```` - -{{endregion}} >caption Figure 1: AllowAero = false on Windows 10 diff --git a/controls/forms-and-dialogs/tabbedform/localization.md b/controls/forms-and-dialogs/tabbedform/localization.md index dae209df3..f9ca17170 100644 --- a/controls/forms-and-dialogs/tabbedform/localization.md +++ b/controls/forms-and-dialogs/tabbedform/localization.md @@ -20,66 +20,16 @@ To localize __RadTabbedForm__ to display any text and messages in a specific lan Below is a sample implementation of an English localization provider: -{{source=..\SamplesCS\Forms and Dialogs\TabbedFormCode.cs region=Localization}} -{{source=..\SamplesVB\Forms and Dialogs\TabbedFormCode.vb region=Localization}} -````C# -class MyRadTabbedFormControlLocalizationProvider : RadTabbedFormControlLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case RadTabbedFormControlStringId.NewTabMenuTtem: return "New tab"; - case RadTabbedFormControlStringId.PinTabMenuTtem: return "Pin tab"; - case RadTabbedFormControlStringId.CloseTabMenuTtem: return "Close tab"; - case RadTabbedFormControlStringId.CloseOtherTabsMenuTtem: return "Close other tabs"; - case RadTabbedFormControlStringId.CloseRightTabsMenuTtem: return "Close tabs to the right"; - case RadTabbedFormControlStringId.UnpinTabMenuTtem: return "Unpin tab"; - } - return base.GetLocalizedString(id); - } -} + + -```` -````VB.NET -Friend Class MyRadTabbedFormControlLocalizationProvider - Inherits RadTabbedFormControlLocalizationProvider - Public Overrides Function GetLocalizedString(ByVal id As String) As String - Select Case id - Case RadTabbedFormControlStringId.NewTabMenuTtem - Return "New tab" - Case RadTabbedFormControlStringId.PinTabMenuTtem - Return "Pin tab" - Case RadTabbedFormControlStringId.CloseTabMenuTtem - Return "Close tab" - Case RadTabbedFormControlStringId.CloseOtherTabsMenuTtem - Return "Close other tabs" - Case RadTabbedFormControlStringId.CloseRightTabsMenuTtem - Return "Close tabs to the right" - Case RadTabbedFormControlStringId.UnpinTabMenuTtem - Return "Unpin tab" - End Select - Return MyBase.GetLocalizedString(id) - End Function -End Class -```` - -{{endregion}} To apply the custom localization provider, instantiate and assign it to the current localization provider: #### Assigning the Current Localization Provider -{{source=..\SamplesCS\Forms and Dialogs\TabbedFormCode.cs region=ChangeProvider}} -{{source=..\SamplesVB\Forms and Dialogs\TabbedFormCode.vb region=ChangeProvider}} -````C# -RadTabbedFormControlLocalizationProvider.CurrentProvider = new MyRadTabbedFormControlLocalizationProvider(); - -```` -````VB.NET -RadTabbedFormControlLocalizationProvider.CurrentProvider = New MyRadTabbedFormControlLocalizationProvider() + + -```` -{{endregion}} diff --git a/controls/forms-and-dialogs/toolbarform/adding-items-programmatically.md b/controls/forms-and-dialogs/toolbarform/adding-items-programmatically.md index 0561488f4..596c5b494 100644 --- a/controls/forms-and-dialogs/toolbarform/adding-items-programmatically.md +++ b/controls/forms-and-dialogs/toolbarform/adding-items-programmatically.md @@ -14,142 +14,10 @@ position: 4 ![WinForms RadToolbarForm Add Items](images/toolbarform-adding-items-programmatically001.png) -{{source=..\SamplesCS\Forms and Dialogs\RadToolbarForm1.cs region=AddItems}} -{{source=..\SamplesVB\Forms and Dialogs\RadToolbarForm1.vb region=AddItems}} + + -````C# - -RadDropDownButtonElement dropDownBtn = new RadDropDownButtonElement() { Text = "Progress Corporation" }; -dropDownBtn.Items.Add(new RadMenuItem("UI for WinForms")); -dropDownBtn.Items.Add(new RadMenuItem("UI for WPF")); -this.ToolbarFormControl.NearItems.Add(dropDownBtn); - -RadToggleSwitchElement toggleSwitch = new RadToggleSwitchElement() { MinSize = new Size(40, 0), Margin = new Padding(1) }; -this.ToolbarFormControl.NearItems.Add(toggleSwitch); - -RadButtonElement generalBtn = new RadButtonElement() -{ - Text = "General", - SvgImageXml = Properties.Resources.document_text_table, - TextImageRelation = TextImageRelation.ImageAboveText, - ImageAlignment = ContentAlignment.TopCenter, - Margin = new Padding(10) -}; -this.ToolbarFormControl.CenterItems.Add(generalBtn); - -RadButtonElement securityBtn = new RadButtonElement() -{ - Text = "Security", - SvgImageXml = Properties.Resources.document_flag, - TextImageRelation = TextImageRelation.ImageAboveText, - ImageAlignment = ContentAlignment.TopCenter, - Margin = new Padding(10) -}; -this.ToolbarFormControl.CenterItems.Add(securityBtn); - -RadButtonElement profileBtn = new RadButtonElement() -{ - Text = "Profile", - SvgImageXml = Properties.Resources.document_text, - TextImageRelation = TextImageRelation.ImageAboveText, - ImageAlignment = ContentAlignment.TopCenter, - Margin = new Padding(10) -}; -this.ToolbarFormControl.CenterItems.Add(profileBtn); - -RadButtonElement projectBtn = new RadButtonElement() -{ - Text = "Project", - SvgImageXml = Properties.Resources.document_pdf, - TextImageRelation = TextImageRelation.ImageAboveText, - ImageAlignment = ContentAlignment.TopCenter, - Margin = new Padding(10) -}; -this.ToolbarFormControl.CenterItems.Add(projectBtn); - -RadButtonElement settingsBtn = new RadButtonElement() -{ - Text = "Settings", - SvgImageXml = Properties.Resources.tool_wrench, - TextImageRelation = TextImageRelation.ImageAboveText, - ImageAlignment = ContentAlignment.TopCenter, - Margin = new Padding(10) -}; -this.ToolbarFormControl.CenterItems.Add(settingsBtn); - -this.ToolbarFormControl.FarItems.Add(new RadLabelElement() { Text = "Dess" }); -this.ToolbarFormControl.FarItems.Add(new RadButtonElement() -{ - Image = Properties.Resources.dess_avatar32, - DisplayStyle = DisplayStyle.Image -}); - - -```` -````VB.NET - -Dim dropDownBtn As RadDropDownButtonElement = New RadDropDownButtonElement() With { -Text = "Progress Corporation"} -dropDownBtn.Items.Add(New RadMenuItem("UI for WinForms")) -dropDownBtn.Items.Add(New RadMenuItem("UI for WPF")) -Me.ToolbarFormControl.NearItems.Add(dropDownBtn) - -Dim toggleSwitch As RadToggleSwitchElement = New RadToggleSwitchElement() With { - .MinSize = New Size(40, 0), - .Margin = New Padding(1) -} -Me.ToolbarFormControl.NearItems.Add(toggleSwitch) -Dim generalBtn As RadButtonElement = New RadButtonElement() With { - .Text = "General", - .SvgImageXml = My.Resources.document_text_table, - .TextImageRelation = TextImageRelation.ImageAboveText, - .ImageAlignment = ContentAlignment.TopCenter, - .Margin = New Padding(10) -} -Me.ToolbarFormControl.CenterItems.Add(generalBtn) -Dim securityBtn As RadButtonElement = New RadButtonElement() With { - .Text = "Security", - .SvgImageXml = My.Resources.document_flag, - .TextImageRelation = TextImageRelation.ImageAboveText, - .ImageAlignment = ContentAlignment.TopCenter, - .Margin = New Padding(10) -} -Me.ToolbarFormControl.CenterItems.Add(securityBtn) -Dim profileBtn As RadButtonElement = New RadButtonElement() With { - .Text = "Profile", - .SvgImageXml = My.Resources.document_text, - .TextImageRelation = TextImageRelation.ImageAboveText, - .ImageAlignment = ContentAlignment.TopCenter, - .Margin = New Padding(10) -} -Me.ToolbarFormControl.CenterItems.Add(profileBtn) -Dim projectBtn As RadButtonElement = New RadButtonElement() With { - .Text = "Project", - .SvgImageXml = My.Resources.document_pdf, - .TextImageRelation = TextImageRelation.ImageAboveText, - .ImageAlignment = ContentAlignment.TopCenter, - .Margin = New Padding(10) -} -Me.ToolbarFormControl.CenterItems.Add(projectBtn) -Dim settingsBtn As RadButtonElement = New RadButtonElement() With { - .Text = "Settings", - .SvgImageXml = My.Resources.tool_wrench, - .TextImageRelation = TextImageRelation.ImageAboveText, - .ImageAlignment = ContentAlignment.TopCenter, - .Margin = New Padding(10) -} -Me.ToolbarFormControl.CenterItems.Add(settingsBtn) -Me.ToolbarFormControl.FarItems.Add(New RadLabelElement() With { - .Text = "Dess" -}) -Me.ToolbarFormControl.FarItems.Add(New RadButtonElement() With { - .Image = My.Resources.dess_avatar32, - .DisplayStyle = DisplayStyle.Image -}) - -```` - -{{endregion}} + ## See Also diff --git a/controls/forms-and-dialogs/toolbarform/customizing-appearance.md b/controls/forms-and-dialogs/toolbarform/customizing-appearance.md index 7f6f06e76..7d8d7e1af 100644 --- a/controls/forms-and-dialogs/toolbarform/customizing-appearance.md +++ b/controls/forms-and-dialogs/toolbarform/customizing-appearance.md @@ -20,25 +20,10 @@ You can access and modify the style for the different elements in the **RadToolb The following example demonstrates how you can access the **CaptionFill** and change its back color. -{{source=..\SamplesCS\Forms and Dialogs\RadToolbarForm1.cs region=CustomizeStyle}} -{{source=..\SamplesVB\Forms and Dialogs\RadToolbarForm1.vb region=CustomizeStyle}} + + -````C# - -this.ToolbarFormControl.ToolbarFormControlElement.CaptionFill.BackColor = Color.Red; -this.ToolbarFormControl.ToolbarFormControlElement.CaptionFill.GradientStyle = GradientStyles.Solid; -this.ToolbarFormControl.ToolbarFormControlElement.CaptionTextElement.ForeColor = Color.White; - -```` -````VB.NET - -Me.ToolbarFormControl.ToolbarFormControlElement.CaptionFill.BackColor = Color.Red -Me.ToolbarFormControl.ToolbarFormControlElement.CaptionFill.GradientStyle = GradientStyles.Solid -Me.ToolbarFormControl.ToolbarFormControlElement.CaptionTextElement.ForeColor = Color.White - -```` - -{{endregion}} + ![WinForms RadToolbarForm Change CaptionFill](images/toolbarform-customizing-appearance002.png) diff --git a/controls/forms-and-dialogs/toolbarform/features/item-alignment.md b/controls/forms-and-dialogs/toolbarform/features/item-alignment.md index 7509cf723..c30fae700 100644 --- a/controls/forms-and-dialogs/toolbarform/features/item-alignment.md +++ b/controls/forms-and-dialogs/toolbarform/features/item-alignment.md @@ -12,22 +12,10 @@ position: 3 In general case, there could be a requirement to increase the size of the title bar part of the RadToolBarForm. In this case, RadToolBarForm provides a mechanism to customize the alignment of the elements inside it. The height of the title bar can be changed by setting the __CaptionHeight__ property. -{{source=..\SamplesCS\Forms and Dialogs\RadToolbarForm1.cs region=CaptionHeight}} -{{source=..\SamplesVB\Forms and Dialogs\RadToolbarForm1.vb region=CaptionHeight}} + + -````C# - -this.radToolbarFormControl1.CaptionHeight = 60; - - -```` -````VB.NET - -Me.ToolbarFormControl.CaptionHeight = 60 - -```` - -{{endregion}} + >caption Figure 1: CaptionHeight Property @@ -36,26 +24,10 @@ Me.ToolbarFormControl.CaptionHeight = 60 In __Figure 1__ the default alignment of all three parts (near, center, far) of the toolbar form are Top. Their alignment can be controled throught the __NearItemsVerticalAligment__, __CenterItemsVerticalAlignment__, __FarItemsVerticalAligment__ properties. -{{source=..\SamplesCS\Forms and Dialogs\RadToolbarForm1.cs region=VerticalAlignment}} -{{source=..\SamplesVB\Forms and Dialogs\RadToolbarForm1.vb region=VerticalAlignment}} - -````C# - -this.radToolbarFormControl1.NearItemsVerticalAlignment = RadVerticalAlignment.Bottom; -this.radToolbarFormControl1.CenterItemsVerticalAlignment = RadVerticalAlignment.Center; -this.radToolbarFormControl1.FarItemsVerticalAlignment = RadVerticalAlignment.Stretch; - - -```` -````VB.NET - -Me.ToolbarFormControl.NearItemsVerticalAlignment = RadVerticalAlignment.Bottom -Me.ToolbarFormControl.CenterItemsVerticalAlignment = RadVerticalAlignment.Center -Me.ToolbarFormControl.FarItemsVerticalAlignment = RadVerticalAlignment.Stretch + + -```` -{{endregion}} >caption Figure 2: Vertical Alignment @@ -65,22 +37,10 @@ Me.ToolbarFormControl.FarItemsVerticalAlignment = RadVerticalAlignment.Stretch The text position in the title bar of the control can be change throught the __TextPosition__ property of the __RadToolbarFormControl__. This property is enumeration and expose four values: __Near__ (default), __CenterBefore__, __CenterAfter__, __Far__. -{{source=..\SamplesCS\Forms and Dialogs\RadToolbarForm1.cs region=TextPosition}} -{{source=..\SamplesVB\Forms and Dialogs\RadToolbarForm1.vb region=TextPosition}} + + -````C# -this.radToolbarFormControl1.TextPosition = ToolbarTextPosition.CenterAfter; - - -```` -````VB.NET - -Me.ToolbarFormControl.TextPosition = ToolbarTextPosition.CenterAfter - -```` - -{{endregion}} __Figure 3__ shows how the text will be visualize in all four options of the __TextPosition__ property. @@ -92,26 +52,10 @@ __Figure 3__ shows how the text will be visualize in all four options of the __T The RadToolbarFormControl exposes three properties to control the margins of its items sections: __NearItemsMargin__, __CenterItemsMargin__, __FarItemsMargin__. Their default value is: __0,8,0,8__. You can use these properties to adjust the items per your needs. -{{source=..\SamplesCS\Forms and Dialogs\RadToolbarForm1.cs region=Margins}} -{{source=..\SamplesVB\Forms and Dialogs\RadToolbarForm1.vb region=Margins}} - -````C# - -this.radToolbarFormControl1.NearItemsMargin = new Padding(0,8,0,0); -this.radToolbarFormControl1.CenterItemsMargin = new Padding(100,8,0,0); -this.radToolbarFormControl1.FarItemsMargin = new Padding(0,0,0,8); - -```` -````VB.NET - -Me.ToolbarFormControl.NearItemsMargin = New Padding(0,8,0,0) -Me.ToolbarFormControl.CenterItemsMargin = New Padding(100,8,0,0) -Me.ToolbarFormControl.FarItemsMargin = New Padding(0,0,0,8) - + + -```` -{{endregion}} >caption Figure 4: Margins diff --git a/controls/forms-and-dialogs/toolbarform/features/wrap-mode.md b/controls/forms-and-dialogs/toolbarform/features/wrap-mode.md index 91a944551..ea91a8f30 100644 --- a/controls/forms-and-dialogs/toolbarform/features/wrap-mode.md +++ b/controls/forms-and-dialogs/toolbarform/features/wrap-mode.md @@ -26,27 +26,10 @@ When using ToolbarWrapMode.**Weight**, it is possible to specify the weight for * **FarItemsWrapWeight** - Gets or sets the wrap weight while performing the layout of the **FarItems** container. The property is only relevant in the ToolbarWrapMode.Weight wrap mode. The value is in percentage and determines what part of the available space is dedicated to the container. -{{source=..\SamplesCS\Forms and Dialogs\RadToolbarForm1.cs region=Wrap}} -{{source=..\SamplesVB\Forms and Dialogs\RadToolbarForm1.vb region=Wrap}} + + -````C# - -this.ToolbarFormControl.WrapMode = ToolbarWrapMode.Weight; -this.ToolbarFormControl.NearItemsWrapWeight = 20; -this.ToolbarFormControl.CenterItemsWrapWeight = 60; -this.ToolbarFormControl.FarItemsWrapWeight = 20; - -```` -````VB.NET - -Me.ToolbarFormControl.WrapMode = ToolbarWrapMode.Weight -Me.ToolbarFormControl.NearItemsWrapWeight = 20 -Me.ToolbarFormControl.CenterItemsWrapWeight = 60 -Me.ToolbarFormControl.FarItemsWrapWeight = 20 - -```` - -{{endregion}} + ## See Also diff --git a/controls/ganttview/context-menu/data-item-context-menu.md b/controls/ganttview/context-menu/data-item-context-menu.md index 528b1e435..3f7282dbf 100644 --- a/controls/ganttview/context-menu/data-item-context-menu.md +++ b/controls/ganttview/context-menu/data-item-context-menu.md @@ -13,37 +13,10 @@ previous_url: ganttview-context-menu-item-context-menu __RadGanttView__ allows you to assign an individual context menu on each data item. This context menu is with higher priority than the default context menu so if you have assigned such a context menu it will be displayed even if you have not disabled the default context menu. -{{source=..\SamplesCS\GanttView\ContextMenus\ItemContextMenu.cs region=ItemContextMenu}} -{{source=..\SamplesVB\GanttView\ContextMenus\ItemContextMenu.vb region=ItemContextMenu}} - -````C# -RadContextMenu contextMenu1 = new RadContextMenu(); -contextMenu1.Items.Add(new GanttViewMenuItem("complete", "Mark as complete")); -contextMenu1.Items.Add(new GanttViewMenuItem("started", "Mark as started")); -contextMenu1.Items.Add(new GanttViewMenuItem("important", "Make important")); -RadContextMenu contextMenu2 = new RadContextMenu(); -contextMenu2.Items.Add(new GanttViewMenuItem("high", "Set high priority")); -contextMenu2.Items.Add(new GanttViewMenuItem("normal", "Set normal priority")); -contextMenu2.Items.Add(new GanttViewMenuItem("low", "Set low priority")); -this.radGanttView1.Items[0].ContextMenu = contextMenu1; -this.radGanttView1.Items[0].Items[0].ContextMenu = contextMenu2; - -```` -````VB.NET -Dim ContextMenu1 As RadContextMenu = New RadContextMenu() -ContextMenu1.Items.Add(New GanttViewMenuItem("complete", "Mark as complete")) -ContextMenu1.Items.Add(New GanttViewMenuItem("started", "Mark as started")) -ContextMenu1.Items.Add(New GanttViewMenuItem("important", "Make important")) -Dim ContextMenu2 As RadContextMenu = New RadContextMenu() -contextMenu2.Items.Add(New GanttViewMenuItem("high", "Set high priority")) -contextMenu2.Items.Add(New GanttViewMenuItem("normal", "Set normal priority")) -contextMenu2.Items.Add(New GanttViewMenuItem("low", "Set low priority")) -Me.radGanttView1.Items(0).ContextMenu = ContextMenu1 -Me.radGanttView1.Items(0).Items(0).ContextMenu = ContextMenu2 - -```` - -{{endregion}} + + + + ![WinForms RadGanttView Default ContextMenu](images/ganttview-context-menu-item-context-menu001.png) diff --git a/controls/ganttview/context-menu/modifying-context-menu.md b/controls/ganttview/context-menu/modifying-context-menu.md index a8da1a2b3..3aaf85901 100644 --- a/controls/ganttview/context-menu/modifying-context-menu.md +++ b/controls/ganttview/context-menu/modifying-context-menu.md @@ -23,31 +23,10 @@ The event arguments have the following properties: Here is an example which demonstrates how to change the progress step of the default context menu. -{{source=..\SamplesCS\GanttView\ContextMenus\ModifyingContextMenu.cs region=ModifyingContextMenu}} -{{source=..\SamplesVB\GanttView\ContextMenus\ModifyingContextMenu.vb region=ModifyingContextMenu}} - -````C# -private void radGanttView1_ContextMenuOpening(object sender, GanttViewContextMenuOpeningEventArgs e) -{ - GanttViewDefaultContextMenu menu = e.Menu as GanttViewDefaultContextMenu; - if (menu != null) - { - menu.ProgressStep = 25; - } -} - -```` -````VB.NET -Private Sub radGanttView1_ContextMenuOpening(sender As Object, e As GanttViewContextMenuOpeningEventArgs) - Dim menu As GanttViewDefaultContextMenu = TryCast(e.Menu, GanttViewDefaultContextMenu) - If menu IsNot Nothing Then - menu.ProgressStep = 25 - End If -End Sub - -```` - -{{endregion}} + + + + ![WinForms RadGanttView Modifying Context Menu](images/ganttview-context-menu-modifying-context-menu001.png) diff --git a/controls/ganttview/custom-items/data-cells.md b/controls/ganttview/custom-items/data-cells.md index 065ecf9eb..f5d003744 100644 --- a/controls/ganttview/custom-items/data-cells.md +++ b/controls/ganttview/custom-items/data-cells.md @@ -18,83 +18,8 @@ position: 1 #### Custom Cell Implementation -{{source=..\SamplesCS\GanttView\CustomItems\GanttCheckBoxForm.cs region=CustomCellClass}} -{{source=..\SamplesVB\GanttView\CustomItems\GanttCheckBoxForm.vb region=CustomCellClass}} -````C# -public class CustomGanttViewTextViewCellElement : GanttViewTextViewCellElement -{ - private RadCheckBoxElement checkBox; - public CustomGanttViewTextViewCellElement(GanttViewTextItemElement owner, GanttViewTextViewColumn column) - : base(owner, column) - { } - protected override Type ThemeEffectiveType - { - get { return typeof(GanttViewTextViewCellElement); } - } - - public override bool IsCompatible(GanttViewTextViewColumn data, object context) - { - return data.FieldName == "Check"; - } - - protected override void CreateChildElements() - { - base.CreateChildElements(); - this.checkBox = new RadCheckBoxElement(); - this.checkBox.CheckStateChanged += CheckBox_CheckStateChanged; - this.Children.Add(this.checkBox); - } - protected override SizeF ArrangeOverride(SizeF finalSize) - { - SizeF size = base.ArrangeOverride(finalSize); - this.checkBox.Arrange(new RectangleF(new PointF((size.Width - this.checkBox.CheckMarkPrimitive.Size.Width) / 2, 0), this.checkBox.Size)); - return size; - } - private void CheckBox_CheckStateChanged(object sender, EventArgs e) - { - GanttViewTextItemElement owner = this.Owner as GanttViewTextItemElement; - owner.Data.Tag = this.checkBox.Checked; - } -} - -```` -````VB.NET -Public Class CustomGanttViewTextViewCellElement - Inherits GanttViewTextViewCellElement - Private checkBox As RadCheckBoxElement - Public Sub New(owner As GanttViewTextItemElement, column As GanttViewTextViewColumn) - MyBase.New(owner, column) - End Sub - Protected Overrides ReadOnly Property ThemeEffectiveType() As Type - Get - Return GetType(GanttViewTextViewCellElement) - End Get - End Property - Public Overrides Function IsCompatible(data As GanttViewTextViewColumn, context As Object) As Boolean - Return data.FieldName = "Check" - End Function - Protected Overrides Sub CreateChildElements() - MyBase.CreateChildElements() - Me.checkBox = New RadCheckBoxElement() - AddHandler Me.checkBox.CheckStateChanged, AddressOf CheckBox_CheckStateChanged - Me.Children.Add(Me.checkBox) - End Sub - Protected Overrides Function ArrangeOverride(finalSize As SizeF) As SizeF - Dim size As SizeF = MyBase.ArrangeOverride(finalSize) - Me.checkBox.Arrange(New RectangleF(New PointF((size.Width - Me.checkBox.CheckMarkPrimitive.Size.Width) / 2, 0), Me.checkBox.Size)) - Return size - End Function - Private Sub CheckBox_CheckStateChanged(sender As Object, e As EventArgs) - Dim owner As GanttViewTextItemElement = TryCast(Me.Owner, GanttViewTextItemElement) - owner.Data.Tag = Me.checkBox.Checked - End Sub -End Class - -```` - - - -{{endregion}} + + The events which need to be handled are: @@ -103,145 +28,15 @@ The events which need to be handled are: #### Handling Events -{{source=..\SamplesCS\GanttView\CustomItems\GanttCheckBoxForm.cs region=HandleEvents}} -{{source=..\SamplesVB\GanttView\CustomItems\GanttCheckBoxForm.vb region=HandleEvents}} -````C# -private void GanttViewElement_ItemEditing(object sender, GanttViewItemEditingEventArgs e) -{ - if (e.Column.FieldName == "Check") - { - e.Cancel = true; - } -} -private void radGanttView1_DataCellElementCreating(object sender, GanttViewDataCellElementCreatingEventArgs e) -{ - if (e.CellElement.Data.HeaderText == "Check") - { - e.CellElement = new CustomGanttViewTextViewCellElement(e.CellElement.Owner, e.CellElement.Column); - } -} - -```` -````VB.NET -Private Sub GanttViewElement_ItemEditing(sender As Object, e As GanttViewItemEditingEventArgs) - If e.Column.FieldName = "Check" Then - e.Cancel = True - End If -End Sub -Private Sub radGanttView1_DataCellElementCreating(sender As Object, e As GanttViewDataCellElementCreatingEventArgs) - If e.CellElement.Data.HeaderText = "Check" Then - e.CellElement = New CustomGanttViewTextViewCellElement(e.CellElement.Owner, e.CellElement.Column) - End If -End Sub - -```` - - - -{{endregion}} + + The data can be added to the control in the **OnLoad** method of the form. It is important to also add "*Check*" column in which the custom cell will be displayed. #### Initial Setup -{{source=..\SamplesCS\GanttView\CustomItems\GanttCheckBoxForm.cs region=InitialSetup}} -{{source=..\SamplesVB\GanttView\CustomItems\GanttCheckBoxForm.vb region=InitialSetup}} -````C# -protected override void OnLoad(EventArgs e) -{ - base.OnLoad(e); - this.radGanttView1.GanttViewElement.ItemEditing += GanttViewElement_ItemEditing; - this.radGanttView1.DataCellElementCreating += radGanttView1_DataCellElementCreating; - this.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineStart = new DateTime(2017, 10, 9); - this.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineEnd = new DateTime(2017, 10, 20); - this.BindData(); -} -private void BindData() -{ - GanttViewDataItem item1 = new GanttViewDataItem(); - item1.Start = new DateTime(2017, 10, 10); - item1.End = new DateTime(2017, 10, 13); - item1.Progress = 30m; - item1.Title = "Summary task.1. title"; - GanttViewDataItem subitem11 = new GanttViewDataItem(); - subitem11.Start = new DateTime(2017, 10, 10); - subitem11.End = new DateTime(2017, 10, 12); - subitem11.Tag = "Custom"; - subitem11.Progress = 10m; - subitem11.Title = "Sub-task.1.1 title"; - GanttViewDataItem subitem12 = new GanttViewDataItem(); - subitem12.Start = new DateTime(2017, 10, 12); - subitem12.End = new DateTime(2017, 10, 13); - subitem12.Progress = 20m; - subitem12.Title = "Sub-task.1.2 title"; - item1.Items.Add(subitem11); - item1.Items.Add(subitem12); - this.radGanttView1.Items.Add(item1); - GanttViewLinkDataItem link1 = new GanttViewLinkDataItem(); - link1.StartItem = subitem11; - link1.EndItem = subitem12; - link1.LinkType = TasksLinkType.FinishToStart; - this.radGanttView1.Links.Add(link1); - GanttViewTextViewColumn titleColumn = new GanttViewTextViewColumn("Title"); - GanttViewTextViewColumn startColumn = new GanttViewTextViewColumn("Start"); - GanttViewTextViewColumn endColumn = new GanttViewTextViewColumn("End"); - GanttViewTextViewColumn checkColumn = new GanttViewTextViewColumn("Check"); - this.radGanttView1.GanttViewElement.Columns.Add(titleColumn); - this.radGanttView1.GanttViewElement.Columns.Add(startColumn); - this.radGanttView1.GanttViewElement.Columns.Add(endColumn); - this.radGanttView1.GanttViewElement.Columns.Add(checkColumn); -} - -```` -````VB.NET -Protected Overrides Sub OnLoad(e As EventArgs) - MyBase.OnLoad(e) - AddHandler Me.radGanttView1.GanttViewElement.ItemEditing, AddressOf GanttViewElement_ItemEditing - AddHandler Me.radGanttView1.DataCellElementCreating, AddressOf radGanttView1_DataCellElementCreating - Me.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineStart = New DateTime(2017, 10, 9) - Me.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineEnd = New DateTime(2017, 10, 20) - Me.BindData() -End Sub -Private Sub BindData() - Dim item1 As New GanttViewDataItem() - item1.Start = New DateTime(2017, 10, 10) - item1.[End] = New DateTime(2017, 10, 13) - item1.Progress = 30D - item1.Title = "Summary task.1. title" - Dim subitem11 As New GanttViewDataItem() - subitem11.Start = New DateTime(2017, 10, 10) - subitem11.[End] = New DateTime(2017, 10, 12) - subitem11.Tag = "Custom" - subitem11.Progress = 10D - subitem11.Title = "Sub-task.1.1 title" - Dim subitem12 As New GanttViewDataItem() - subitem12.Start = New DateTime(2017, 10, 12) - subitem12.[End] = New DateTime(2017, 10, 13) - subitem12.Progress = 20D - subitem12.Title = "Sub-task.1.2 title" - item1.Items.Add(subitem11) - item1.Items.Add(subitem12) - Me.radGanttView1.Items.Add(item1) - Dim link1 As New GanttViewLinkDataItem() - link1.StartItem = subitem11 - link1.EndItem = subitem12 - link1.LinkType = TasksLinkType.FinishToStart - Me.radGanttView1.Links.Add(link1) - Dim titleColumn As New GanttViewTextViewColumn("Title") - Dim startColumn As New GanttViewTextViewColumn("Start") - Dim endColumn As New GanttViewTextViewColumn("End") - Dim checkColumn As New GanttViewTextViewColumn("Check") - Me.radGanttView1.GanttViewElement.Columns.Add(titleColumn) - Me.radGanttView1.GanttViewElement.Columns.Add(startColumn) - Me.radGanttView1.GanttViewElement.Columns.Add(endColumn) - Me.radGanttView1.GanttViewElement.Columns.Add(checkColumn) -End Sub - -```` - - - -{{endregion}} + + # See Also diff --git a/controls/ganttview/custom-items/data-items.md b/controls/ganttview/custom-items/data-items.md index 9eea25492..6f1a65cf4 100644 --- a/controls/ganttview/custom-items/data-items.md +++ b/controls/ganttview/custom-items/data-items.md @@ -22,281 +22,22 @@ The example in this article will handle a scenario of a *Duration* column displa #### Setup the Control and Add Data -{{source=..\SamplesCS\GanttView\CustomItems\GanttDataItemForm.cs region=SetupGantt}} -{{source=..\SamplesVB\GanttView\CustomItems\GanttDataItemForm.vb region=SetupGantt}} -````C# -public GanttDataItemForm() -{ - InitializeComponent(); - this.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineStart = new DateTime(2010, 10, 9); - this.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineEnd = new DateTime(2010, 10, 19); - //setup data items - MyGanttViewDataItem item1 = new MyGanttViewDataItem(); - item1.Start = new DateTime(2010, 10, 10); - item1.End = new DateTime(2010, 10, 15); - item1.Progress = 30m; - item1.Title = "Summary task.1. title"; - MyGanttViewDataItem subitem11 = new MyGanttViewDataItem(); - subitem11.Start = new DateTime(2010, 10, 10); - subitem11.End = new DateTime(2010, 10, 12); - subitem11.Progress = 10m; - subitem11.Title = "Sub-task.1.1 title"; - MyGanttViewDataItem subitem12 = new MyGanttViewDataItem(); - subitem12.Start = new DateTime(2010, 10, 12); - subitem12.End = new DateTime(2010, 10, 15); - subitem12.Progress = 20m; - subitem12.Title = "Sub-task.1.2 title"; - //add subitems - item1.Items.Add(subitem11); - item1.Items.Add(subitem12); - this.radGanttView1.Items.Add(item1); - MyGanttViewDataItem item2 = new MyGanttViewDataItem(); - item2.Start = new DateTime(2010, 10, 12); - item2.End = new DateTime(2010, 10, 18); - item2.Progress = 40m; - item2.Title = "Summary task.2. title"; - MyGanttViewDataItem subitem21 = new MyGanttViewDataItem(); - subitem21.Start = new DateTime(2010, 10, 12); - subitem21.End = new DateTime(2010, 10, 13); - subitem21.Progress = 10m; - subitem21.Title = "Sub-task.2.1 title"; - MyGanttViewDataItem subitem22 = new MyGanttViewDataItem(); - subitem22.Start = new DateTime(2010, 10, 13); - subitem22.End = new DateTime(2010, 10, 18); - subitem22.Progress = 30m; - subitem22.Title = "Sub-task.2.2 title"; - MyGanttViewDataItem subitem23 = new MyGanttViewDataItem(); - subitem23.Start = new DateTime(2010, 10, 18); - subitem23.End = new DateTime(2010, 10, 18); - subitem23.Title = "Sub-task.2.3 title"; - //add subitems - item2.Items.Add(subitem21); - item2.Items.Add(subitem22); - item2.Items.Add(subitem23); - this.radGanttView1.Items.Add(item2); - //add links between items - GanttViewLinkDataItem link1 = new GanttViewLinkDataItem(); - link1.StartItem = subitem11; - link1.EndItem = subitem12; - link1.LinkType = TasksLinkType.FinishToStart; - this.radGanttView1.Links.Add(link1); - GanttViewLinkDataItem link2 = new GanttViewLinkDataItem(); - link2.StartItem = subitem21; - link2.EndItem = subitem22; - link2.LinkType = TasksLinkType.StartToStart; - this.radGanttView1.Links.Add(link2); - GanttViewLinkDataItem link3 = new GanttViewLinkDataItem(); - link3.StartItem = subitem22; - link3.EndItem = subitem23; - link3.LinkType = TasksLinkType.FinishToStart; - this.radGanttView1.Links.Add(link3); - GanttViewTextViewColumn titleColumn = new GanttViewTextViewColumn("Title"); - GanttViewTextViewColumn startColumn = new GanttViewTextViewColumn("Start"); - GanttViewTextViewColumn endColumn = new GanttViewTextViewColumn("End"); - GanttViewTextViewColumn durationColumn = new GanttViewTextViewColumn("Duration"); - this.radGanttView1.GanttViewElement.Columns.Add(titleColumn); - this.radGanttView1.GanttViewElement.Columns.Add(startColumn); - this.radGanttView1.GanttViewElement.Columns.Add(endColumn); - this.radGanttView1.GanttViewElement.Columns.Add(durationColumn); - this.radGanttView1.GanttViewElement.EditorInitialized += GanttViewElement_EditorInitialized; -} - -```` -````VB.NET -Public Sub New() - InitializeComponent() - Me.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineStart = New DateTime(2010, 10, 9) - Me.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineEnd = New DateTime(2010, 10, 19) - Dim item1 As MyGanttViewDataItem = New MyGanttViewDataItem() - item1.Start = New DateTime(2010, 10, 10) - item1.[End] = New DateTime(2010, 10, 15) - item1.Progress = 30D - item1.Title = "Summary task.1. title" - Dim subitem11 As MyGanttViewDataItem = New MyGanttViewDataItem() - subitem11.Start = New DateTime(2010, 10, 10) - subitem11.[End] = New DateTime(2010, 10, 12) - subitem11.Progress = 10D - subitem11.Title = "Sub-task.1.1 title" - Dim subitem12 As MyGanttViewDataItem = New MyGanttViewDataItem() - subitem12.Start = New DateTime(2010, 10, 12) - subitem12.[End] = New DateTime(2010, 10, 15) - subitem12.Progress = 20D - subitem12.Title = "Sub-task.1.2 title" - item1.Items.Add(subitem11) - item1.Items.Add(subitem12) - Me.radGanttView1.Items.Add(item1) - Dim item2 As MyGanttViewDataItem = New MyGanttViewDataItem() - item2.Start = New DateTime(2010, 10, 12) - item2.[End] = New DateTime(2010, 10, 18) - item2.Progress = 40D - item2.Title = "Summary task.2. title" - Dim subitem21 As MyGanttViewDataItem = New MyGanttViewDataItem() - subitem21.Start = New DateTime(2010, 10, 12) - subitem21.[End] = New DateTime(2010, 10, 13) - subitem21.Progress = 10D - subitem21.Title = "Sub-task.2.1 title" - Dim subitem22 As MyGanttViewDataItem = New MyGanttViewDataItem() - subitem22.Start = New DateTime(2010, 10, 13) - subitem22.[End] = New DateTime(2010, 10, 18) - subitem22.Progress = 30D - subitem22.Title = "Sub-task.2.2 title" - Dim subitem23 As MyGanttViewDataItem = New MyGanttViewDataItem() - subitem23.Start = New DateTime(2010, 10, 18) - subitem23.[End] = New DateTime(2010, 10, 18) - subitem23.Title = "Sub-task.2.3 title" - item2.Items.Add(subitem21) - item2.Items.Add(subitem22) - item2.Items.Add(subitem23) - Me.radGanttView1.Items.Add(item2) - Dim link1 As GanttViewLinkDataItem = New GanttViewLinkDataItem() - link1.StartItem = subitem11 - link1.EndItem = subitem12 - link1.LinkType = TasksLinkType.FinishToStart - Me.radGanttView1.Links.Add(link1) - Dim link2 As GanttViewLinkDataItem = New GanttViewLinkDataItem() - link2.StartItem = subitem21 - link2.EndItem = subitem22 - link2.LinkType = TasksLinkType.StartToStart - Me.radGanttView1.Links.Add(link2) - Dim link3 As GanttViewLinkDataItem = New GanttViewLinkDataItem() - link3.StartItem = subitem22 - link3.EndItem = subitem23 - link3.LinkType = TasksLinkType.FinishToStart - Me.radGanttView1.Links.Add(link3) - Dim titleColumn As GanttViewTextViewColumn = New GanttViewTextViewColumn("Title") - Dim startColumn As GanttViewTextViewColumn = New GanttViewTextViewColumn("Start") - Dim endColumn As GanttViewTextViewColumn = New GanttViewTextViewColumn("End") - Dim durationColumn As GanttViewTextViewColumn = New GanttViewTextViewColumn("Duration") - Me.radGanttView1.GanttViewElement.Columns.Add(titleColumn) - Me.radGanttView1.GanttViewElement.Columns.Add(startColumn) - Me.radGanttView1.GanttViewElement.Columns.Add(endColumn) - Me.radGanttView1.GanttViewElement.Columns.Add(durationColumn) - AddHandler Me.radGanttView1.GanttViewElement.EditorInitialized, AddressOf GanttViewElement_EditorInitialized -End Sub - -```` - - - -{{endregion}} + + Our implementation of the custom **GanttViewDataItem** class will add an integer **Duration** property. This property will be calculated whenever the Start or the End of a task changes. #### Custom Data Item Implementation -{{source=..\SamplesCS\GanttView\CustomItems\GanttDataItemForm.cs region=CustomDataItem}} -{{source=..\SamplesVB\GanttView\CustomItems\GanttDataItemForm.vb region=CustomDataItem}} -````C# -public class MyGanttViewDataItem : GanttViewDataItem -{ - private int duration; - private bool shouldUpdate; - public MyGanttViewDataItem() - { } - public int Duration - { - get - { - return this.duration; - } - private set - { - if (this.duration != value) - { - this.duration = value; - this.OnNotifyPropertyChanged("Duration"); - } - } - } - - protected override void OnNotifyPropertyChanged(string propertyName) - { - base.OnNotifyPropertyChanged(propertyName); - if (propertyName == "Duration" && this.shouldUpdate) - { - TimeSpan span = this.End - this.End.Date; - this.End = this.Start.AddDays(this.Duration).Add(span); - } - if (propertyName == "Start" || propertyName == "End") - { - this.shouldUpdate = false; - this.Duration = (this.End - this.Start).Days; - } - this.shouldUpdate = true; - } -} - -```` -````VB.NET -Public Class MyGanttViewDataItem - Inherits GanttViewDataItem - Private _duration As Integer - Private shouldUpdate As Boolean - Public Sub New() - End Sub - Public Property Duration As Integer - Get - Return Me._duration - End Get - Private Set(ByVal value As Integer) - If Me._duration <> value Then - Me._duration = value - Me.OnNotifyPropertyChanged("Duration") - End If - End Set - End Property - Protected Overrides Sub OnNotifyPropertyChanged(ByVal propertyName As String) - MyBase.OnNotifyPropertyChanged(propertyName) - If propertyName = "Duration" AndAlso Me.shouldUpdate Then - Dim span As TimeSpan = Me.[End] - Me.[End].Date - Me.[End] = Me.Start.AddDays(Me.Duration).Add(span) - End If - If propertyName = "Start" OrElse propertyName = "End" Then - Me.shouldUpdate = False - Me.Duration = (Me.[End] - Me.Start).Days - End If - Me.shouldUpdate = True - End Sub -End Class - -```` - - - -{{endregion}} + + The *Duration* column will be working with a **GanttViewSpinEditor** and considering our scenario, we will need to change the **MaxValue** property of the editor. This can be accomplished by handling the RadGanttView.GanttViewElement.**EditorInitialized** event. #### Handling the EditorInitialized event -{{source=..\SamplesCS\GanttView\CustomItems\GanttDataItemForm.cs region=EditorInitializedEvent}} -{{source=..\SamplesVB\GanttView\CustomItems\GanttDataItemForm.vb region=EditorInitializedEvent}} -````C# -private void GanttViewElement_EditorInitialized(object sender, GanttViewItemEditorInitializedEventArgs e) -{ - GanttViewSpinEditor editor = e.Editor as GanttViewSpinEditor; - decimal totalDays = (decimal)(this.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineEnd - this.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineStart).TotalDays; - if (editor != null && editor.MaxValue != totalDays) - { - editor.MaxValue = totalDays; - } -} - -```` -````VB.NET -Private Sub GanttViewElement_EditorInitialized(ByVal sender As Object, ByVal e As GanttViewItemEditorInitializedEventArgs) - Dim editor As GanttViewSpinEditor = TryCast(e.Editor, GanttViewSpinEditor) - Dim totalDays As Decimal = CDec((Me.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineEnd - Me.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineStart).TotalDays) - If editor IsNot Nothing AndAlso editor.MaxValue <> totalDays Then - editor.MaxValue = totalDays - End If -End Sub - -```` - - - -{{endregion}} + + # See Also diff --git a/controls/ganttview/custom-items/task-elements.md b/controls/ganttview/custom-items/task-elements.md index 4777078c5..eec85a245 100644 --- a/controls/ganttview/custom-items/task-elements.md +++ b/controls/ganttview/custom-items/task-elements.md @@ -23,194 +23,15 @@ The methods which need to be overridden in the derived custom class are: #### Custom Task Element Implementation -{{source=..\SamplesCS\GanttView\CustomItems\GanttTaskElementForm.cs region=CustomTaskElementClass}} -{{source=..\SamplesVB\GanttView\CustomItems\GanttTaskElementForm.vb region=CustomTaskElementClass}} -````C# -public class MyGanttViewTaskItemElement : GanttViewTaskItemElement -{ - private int dayCount; - public MyGanttViewTaskItemElement(GanttViewGraphicalViewElement ganttViewBaseViewElement, int dayCount) - : base(ganttViewBaseViewElement) - { - this.dayCount = dayCount; - } - internal int DayCount - { - get - { - return this.dayCount; - } - } - protected override Type ThemeEffectiveType - { - get - { - return typeof(GanttViewTaskItemElement); - } - } - protected override GanttGraphicalViewBaseTaskElement CreateTaskElement() - { - return new MyGanttViewTaskElement(); - } -} -public class MyGanttViewTaskElement : GanttViewTaskElement -{ - private LightVisualElement start; - private LightVisualElement end; - protected override Type ThemeEffectiveType - { - get - { - return typeof(GanttViewTaskElement); - } - } - protected override void CreateChildElements() - { - base.CreateChildElements(); - this.DrawFill = false; - this.start = new LightVisualElement(); - this.start.ShouldHandleMouseInput = false; - this.start.GradientStyle = Telerik.WinControls.GradientStyles.Solid; - this.start.BackColor = Color.FromArgb(75, Color.Red); - this.start.DrawFill = true; - this.end = new LightVisualElement(); - this.end.ShouldHandleMouseInput = false; - this.end.GradientStyle = Telerik.WinControls.GradientStyles.Solid; - this.end.DrawFill = true; - this.end.BackColor = Color.FromArgb(75, Color.Blue); - this.Children.Add(start); - this.Children.Add(end); - } - protected override SizeF ArrangeOverride(SizeF finalSize) - { - SizeF size = base.ArrangeOverride(finalSize); - RectangleF rect = this.GetClientRectangle(finalSize); - int dayCount = ((MyGanttViewTaskItemElement)this.Parent).DayCount; - GanttViewDataItem data = ((GanttViewBaseItemElement)this.Parent).Data; - if ((data.End - data.Start).TotalDays > dayCount) - { - double span = (data.End - data.Start).TotalSeconds; - double pivot = (data.Start.AddDays(dayCount) - data.Start).TotalSeconds; - double res = pivot / span; - float desiredWidth = rect.Width * (float)res; - RectangleF startRect = new RectangleF(rect.X, 0, desiredWidth, rect.Height); - this.start.Arrange(startRect); - RectangleF endRect = new RectangleF(rect.X + desiredWidth, 0, rect.Width - desiredWidth, rect.Height); - this.end.Arrange(endRect); - } - else - { - this.start.Arrange(rect); - this.end.Arrange(RectangleF.Empty); - } - return size; - } -} - -```` -````VB.NET -Public Class MyGanttViewTaskItemElement - Inherits GanttViewTaskItemElement - Private m_dayCount As Integer - Public Sub New(ganttViewBaseViewElement As GanttViewGraphicalViewElement, dayCount As Integer) - MyBase.New(ganttViewBaseViewElement) - Me.m_dayCount = dayCount - End Sub - Friend ReadOnly Property DayCount() As Integer - Get - Return Me.m_dayCount - End Get - End Property - Protected Overrides ReadOnly Property ThemeEffectiveType() As Type - Get - Return GetType(GanttViewTaskItemElement) - End Get - End Property - Protected Overrides Function CreateTaskElement() As GanttGraphicalViewBaseTaskElement - Return New MyGanttViewTaskElement() - End Function -End Class -Public Class MyGanttViewTaskElement - Inherits GanttViewTaskElement - Private start As LightVisualElement - Private [end] As LightVisualElement - Protected Overrides ReadOnly Property ThemeEffectiveType() As Type - Get - Return GetType(GanttViewTaskElement) - End Get - End Property - Protected Overrides Sub CreateChildElements() - MyBase.CreateChildElements() - Me.DrawFill = False - Me.start = New LightVisualElement() - Me.start.ShouldHandleMouseInput = False - Me.start.GradientStyle = Telerik.WinControls.GradientStyles.Solid - Me.start.BackColor = Color.FromArgb(75, Color.Red) - Me.start.DrawFill = True - Me.[end] = New LightVisualElement() - Me.[end].ShouldHandleMouseInput = False - Me.[end].GradientStyle = Telerik.WinControls.GradientStyles.Solid - Me.[end].DrawFill = True - Me.[end].BackColor = Color.FromArgb(75, Color.Blue) - Me.Children.Add(start) - Me.Children.Add([end]) - End Sub - Protected Overrides Function ArrangeOverride(finalSize As SizeF) As SizeF - Dim size As SizeF = MyBase.ArrangeOverride(finalSize) - Dim rect As RectangleF = Me.GetClientRectangle(finalSize) - Dim dayCount As Integer = DirectCast(Me.Parent, MyGanttViewTaskItemElement).DayCount - Dim data As GanttViewDataItem = DirectCast(Me.Parent, GanttViewBaseItemElement).Data - If (data.[End] - data.Start).TotalDays > dayCount Then - Dim span As Double = (data.[End] - data.Start).TotalSeconds - Dim pivot As Double = (data.Start.AddDays(dayCount) - data.Start).TotalSeconds - Dim res As Double = pivot / span - Dim desiredWidth As Single = rect.Width * CSng(res) - Dim startRect As New RectangleF(rect.X, 0, desiredWidth, rect.Height) - Me.start.Arrange(startRect) - Dim endRect As New RectangleF(rect.X + desiredWidth, 0, rect.Width - desiredWidth, rect.Height) - Me.[end].Arrange(endRect) - Else - Me.start.Arrange(rect) - Me.[end].Arrange(RectangleF.Empty) - End If - Return size - End Function -End Class - -```` - - - -{{endregion}} + + The custom elements can be initialized in the handler of the RadGanttView.**ItemElementCreating** event. This event is part of API allowing the default elements to be substituted with custom ones. #### Handling Events -{{source=..\SamplesCS\GanttView\CustomItems\GanttTaskElementForm.cs region=HandleEvents}} -{{source=..\SamplesVB\GanttView\CustomItems\GanttTaskElementForm.vb region=HandleEvents}} -````C# -private void RadGanttView1_ItemElementCreating(object sender, GanttViewItemElementCreatingEventArgs e) -{ - if (e.Item.Items.Count == 0 && e.ViewElement is GanttViewGraphicalViewElement) - { - e.ItemElement = new MyGanttViewTaskItemElement((GanttViewGraphicalViewElement)e.ViewElement, 3); - } -} - -```` -````VB.NET -Private Sub RadGanttView1_ItemElementCreating(sender As Object, e As GanttViewItemElementCreatingEventArgs) - If e.Item.Items.Count = 0 AndAlso TypeOf e.ViewElement Is GanttViewGraphicalViewElement Then - e.ItemElement = New MyGanttViewTaskItemElement(DirectCast(e.ViewElement, GanttViewGraphicalViewElement), 3) - End If -End Sub - -```` - - - -{{endregion}} + + # See Also diff --git a/controls/ganttview/editing/creating-custom-editor.md b/controls/ganttview/editing/creating-custom-editor.md index 7ee104ebb..731573a02 100644 --- a/controls/ganttview/editing/creating-custom-editor.md +++ b/controls/ganttview/editing/creating-custom-editor.md @@ -13,140 +13,17 @@ previous_url: ganttview-editing-creating-a-custom-editor __RadGanttView__ allows you to replace the standard editors with a custom ones. The following examples demonstrates how to replace the spin editor with a track bar editor. All editors inherit from __BaseInputEditor__. So, you have to inherit from this class and override several methods: -{{source=..\SamplesCS\GanttView\Editing\CustomEditor.cs region=CustomTrackBarEditor}} -{{source=..\SamplesVB\GanttView\Editing\CustomEditor.vb region=CustomTrackBarEditor}} + + -````C# -public class GanttViewTrackBarEditor : BaseInputEditor -{ - public override object Value - { - get - { - RadTrackBarElement editor = (RadTrackBarElement)this.EditorElement; - return editor.Value; - } - set - { - RadTrackBarElement editor = (RadTrackBarElement)this.EditorElement; - if (value != null && value != DBNull.Value) - { - editor.Value = Convert.ToInt32(value); - } - else - { - editor.Value = 0; - } - } - } - public override void BeginEdit() - { - base.BeginEdit(); - this.EditorElement.Focus(); - ((RadTrackBarElement)this.EditorElement).ValueChanged += new EventHandler(TrackBarEditor_ValueChanged); - } - void TrackBarEditor_ValueChanged(object sender, EventArgs e) - { - this.OnValueChanged(); - } - public override bool EndEdit() - { - ((RadTrackBarElement)this.EditorElement).ValueChanged -= TrackBarEditor_ValueChanged; - return base.EndEdit(); - } - protected override RadElement CreateEditorElement() - { - RadTrackBarElement element = new RadTrackBarElement(); - element.Minimum = 0; - element.Maximum = 100; - element.TickStyle = Telerik.WinControls.Enumerations.TickStyles.Both; - element.SmallTickFrequency = 10; - element.LargeTickFrequency = 0; - element.BodyElement.ScaleContainerElement.TrackBarLineElement.Margin = new Padding(0, 3, 0, 3); - return element; - } - public override Type DataType - { - get { return typeof(int); } - } -} -```` -````VB.NET -Public Class GanttViewTrackBarEditor - Inherits BaseInputEditor - Public Overrides Property Value() As Object - Get - Dim editor As RadTrackBarElement = DirectCast(Me.EditorElement, RadTrackBarElement) - Return editor.Value - End Get - Set(value As Object) - Dim editor As RadTrackBarElement = DirectCast(Me.EditorElement, RadTrackBarElement) - If value IsNot Nothing AndAlso value IsNot DBNull.Value Then - editor.Value = Convert.ToInt32(value) - Else - editor.Value = 0 - End If - End Set - End Property - Public Overrides Sub BeginEdit() - MyBase.BeginEdit() - Me.EditorElement.Focus() - AddHandler DirectCast(Me.EditorElement, RadTrackBarElement).ValueChanged, AddressOf TrackBarEditor_ValueChanged - End Sub - Private Sub TrackBarEditor_ValueChanged(sender As Object, e As EventArgs) - Me.OnValueChanged() - End Sub - Public Overrides Function EndEdit() As Boolean - RemoveHandler DirectCast(Me.EditorElement, RadTrackBarElement).ValueChanged, AddressOf TrackBarEditor_ValueChanged - Return MyBase.EndEdit() - End Function - Protected Overrides Function CreateEditorElement() As RadElement - Dim element As New RadTrackBarElement() - element.Minimum = 0 - element.Maximum = 100 - element.TickStyle = Telerik.WinControls.Enumerations.TickStyles.Both - element.SmallTickFrequency = 10 - element.LargeTickFrequency = 0 - element.BodyElement.ScaleContainerElement.TrackBarLineElement.Margin = New Padding(0, 3, 0, 3) - Return element - End Function - Public Overrides ReadOnly Property DataType() As Type - Get - Return GetType(Integer) - End Get - End Property -End Class - -```` - -{{endregion}} In the __EditorRequired__ event you can replace the default editor: -{{source=..\SamplesCS\GanttView\Editing\CustomEditor.cs region=CustomEditorReplace}} -{{source=..\SamplesVB\GanttView\Editing\CustomEditor.vb region=CustomEditorReplace}} - -````C# -private void GanttViewElement_EditorRequired(object sender, GanttViewEditorRequiredEventArgs e) -{ - if (e.EditorType == typeof(GanttViewSpinEditor)) - { - e.EditorType = typeof(GanttViewTrackBarEditor); - } -} - -```` -````VB.NET -Private Sub GanttViewElement_EditorRequired(sender As Object, e As GanttViewEditorRequiredEventArgs) - If (e.EditorType = GetType(GanttViewSpinEditor)) Then - e.EditorType = GetType(GanttViewTrackBarEditor) - End If -End Sub + + -```` -{{endregion}} ![WinForms RadGanttView Custom Editor](images/ganttview-editing-creating-a-custom-editor001.png) diff --git a/controls/ganttview/editing/customizing-editor.md b/controls/ganttview/editing/customizing-editor.md index 1752934cb..936136ce3 100644 --- a/controls/ganttview/editing/customizing-editor.md +++ b/controls/ganttview/editing/customizing-editor.md @@ -1,86 +1,33 @@ ---- -title: Customizing editor -page_title: Customizing editor - WinForms GanttView Control -description: Learn how the appearance and behavior of ganttview editors can be changed programmatically. -slug: winforms/ganttview-/editing/customizing-editor -tags: customizing,editor -published: True -position: 2 -previous_url: ganttview-editing-customizing-editor ---- - -# Customizing Editor - -The appearance and behavior of property grid editors can be changed programmatically. This can be done in the __EditorInitialized__ event. __EditorInitialized__ is fired when the editor is created and initialized with a predefined set of properties. - -The following sample demonstrates how to change the default font of a __BaseTextBoxEditor__ in RadGanttView: - -{{source=..\SamplesCS\GanttView\Editing\CustomizingEditor.cs region=CustomizingEditor}} -{{source=..\SamplesVB\GanttView\Editing\CustomizingEditor.vb region=CustomizingEditor}} - -````C# -private void GanttViewElement_EditorInitialized(object sender, GanttViewItemEditorInitializedEventArgs e) -{ - BaseTextBoxEditor editor = e.Editor as BaseTextBoxEditor; - if (editor != null) - { - ((RadTextBoxElement)editor.EditorElement).Font = new Font(FontFamily.Families[12], 12, FontStyle.Bold); - } -} - -```` -````VB.NET -Private Sub GanttViewElement_EditorInitialized(sender As Object, e As GanttViewItemEditorInitializedEventArgs) - Dim editor As BaseTextBoxEditor = TryCast(e.Editor, BaseTextBoxEditor) - If editor IsNot Nothing Then - DirectCast(editor.EditorElement, RadTextBoxElement).Font = New Font(FontFamily.Families(12), 12, FontStyle.Bold) - End If -End Sub - -```` - -{{endregion}} - -## Mask Editor - -The following sample demonstrates how to change the default font of a __GanttViewDateTimeEditor__ in RadGanttView and apply __MaskDateTimeProvider__ with a custom format for time: - -{{source=..\SamplesCS\GanttView\Editing\CustomizingEditor.cs region=CustomizingEditor_Mask}} -{{source=..\SamplesVB\GanttView\Editing\CustomizingEditor.vb region=CustomizingEditor_Mask}} - -````C# - -private void GanttViewElement_MaskEditorInitialized(object sender, GanttViewItemEditorInitializedEventArgs e) -{ - GanttViewDateTimeEditor dtEditor = e.Editor as GanttViewDateTimeEditor; - if (dtEditor != null) - { - dtEditor.CustomFormat = "hh/mm/ss"; - MaskDateTimeProvider dtprovider = ((BaseDateTimeEditorElement)dtEditor.EditorElement).TextBoxElement.Provider as MaskDateTimeProvider; - dtprovider.AutoSelectNextPart = true; - } -} - -```` -````VB.NET - -Private Sub GanttViewElement_MaskEditorInitialized(ByVal sender As Object, ByVal e As GanttViewItemEditorInitializedEventArgs) - Dim dtEditor As GanttViewDateTimeEditor = TryCast(e.Editor, GanttViewDateTimeEditor) - - If dtEditor IsNot Nothing Then - dtEditor.CustomFormat = "hh/mm/ss" - Dim dtprovider As MaskDateTimeProvider = TryCast((CType(dtEditor.EditorElement, BaseDateTimeEditorElement)).TextBoxElement.Provider, MaskDateTimeProvider) - dtprovider.AutoSelectNextPart = True - End If -End Sub - -```` - -{{endregion}} - -# See Also - -* [Creating custom editor]({%slug winforms/ganttview-/editing/creating-custom-editor%}) -* [Editing Graphical View]({%slug winforms/ganttview-/editing/editing-graphical-view%}) -* [Editing Text View]({%slug winforms/ganttview-/editing/editing-text-view%}) - +--- +title: Customizing editor +page_title: Customizing editor - WinForms GanttView Control +description: Learn how the appearance and behavior of ganttview editors can be changed programmatically. +slug: winforms/ganttview-/editing/customizing-editor +tags: customizing,editor +published: True +position: 2 +previous_url: ganttview-editing-customizing-editor +--- + +# Customizing Editor + +The appearance and behavior of property grid editors can be changed programmatically. This can be done in the __EditorInitialized__ event. __EditorInitialized__ is fired when the editor is created and initialized with a predefined set of properties. + +The following sample demonstrates how to change the default font of a __BaseTextBoxEditor__ in RadGanttView: + + + + +## Mask Editor + +The following sample demonstrates how to change the default font of a __GanttViewDateTimeEditor__ in RadGanttView and apply __MaskDateTimeProvider__ with a custom format for time: + + + + +# See Also + +* [Creating custom editor]({%slug winforms/ganttview-/editing/creating-custom-editor%}) +* [Editing Graphical View]({%slug winforms/ganttview-/editing/editing-graphical-view%}) +* [Editing Text View]({%slug winforms/ganttview-/editing/editing-text-view%}) + diff --git a/controls/ganttview/formatting/custom-painting.md b/controls/ganttview/formatting/custom-painting.md index f42798475..f1b622b5e 100644 --- a/controls/ganttview/formatting/custom-painting.md +++ b/controls/ganttview/formatting/custom-painting.md @@ -17,91 +17,29 @@ Since all the elements in the graphical view of the control are arranged along t The following example demonstrates how to draw an image which appears exactly 12 hours after each task which has a duration longer than 12 hours. -{{source=..\SamplesCS\GanttView\Formatting\CustomPainting.cs region=FormattingEventSubscribe1}} -{{source=..\SamplesVB\GanttView\Formatting\CustomPainting.vb region=FormattingEventSubscribe1}} -````C# -this.radGanttView1.EnableCustomPainting = true; -this.radGanttView1.ItemPaint += radGanttView1_ItemPaint1; - -```` -````VB.NET -Me.radGanttView1.EnableCustomPainting = True -AddHandler Me.radGanttView1.ItemPaint, AddressOf radGanttView1_ItemPaint1 - -```` - -{{endregion}} - -{{source=..\SamplesCS\GanttView\Formatting\CustomPainting.cs region=FormattingPaintEvent1}} -{{source=..\SamplesVB\GanttView\Formatting\CustomPainting.vb region=FormattingPaintEvent1}} -````C# -private void radGanttView1_ItemPaint1(object sender, GanttViewItemPaintEventArgs e) -{ - if (e.Element.Data.Items.Count == 0 && e.Element.Data.End - e.Element.Data.Start > new TimeSpan(12, 0, 0)) - { - RectangleF rect = this.radGanttView1.GanttViewElement.GraphicalViewElement.GetDrawRectangle(e.Element.Data, e.Element.Data.End.AddHours(12)); - rect.Width = rect.Height; - e.Graphics.DrawImage(prizeImage, rect); - } -} - -```` -````VB.NET -Private Sub radGanttView1_ItemPaint1(sender As Object, e As GanttViewItemPaintEventArgs) - If (e.Element.Data.Items.Count = 0 AndAlso e.Element.Data.End - e.Element.Data.Start > New TimeSpan(12, 0, 0)) Then - Dim rect As RectangleF = Me.radGanttView1.GanttViewElement.GraphicalViewElement.GetDrawRectangle(e.Element.Data, e.Element.Data.End.AddHours(12)) - rect.Width = rect.Height - e.Graphics.DrawImage(prizeImage, rect) - End If -End Sub - -```` - -{{endregion}} + + + + + + + + + ![WinForms RadGanttView Custom Painting](images/ganttview-formatting-custom-paiting001.png) Another example demonstrating how to draw a colored rectangle which would be 10 hours in duration and will "start" 18 hours before each summary task. -{{source=..\SamplesCS\GanttView\Formatting\CustomPainting.cs region=FormattingEventSubscribe2}} -{{source=..\SamplesVB\GanttView\Formatting\CustomPainting.vb region=FormattingEventSubscribe2}} -````C# -this.radGanttView1.ItemPaint += radGanttView1_ItemPaint2; - -```` -````VB.NET -AddHandler Me.radGanttView1.ItemPaint, AddressOf radGanttView1_ItemPaint2 - -```` - -{{endregion}} - -{{source=..\SamplesCS\GanttView\Formatting\CustomPainting.cs region=FormattingPaintEvent2}} -{{source=..\SamplesVB\GanttView\Formatting\CustomPainting.vb region=FormattingPaintEvent2}} -````C# -private void radGanttView1_ItemPaint2(object sender, GanttViewItemPaintEventArgs e) -{ - if (e.Element.Data.Items.Count > 0) - { - DateTime start = e.Element.Data.Start.AddHours(-18); - RectangleF rect = this.radGanttView1.GanttViewElement.GraphicalViewElement.GetDrawRectangle(e.Element.Data, start, start.AddHours(10)); - e.Graphics.FillRectangle(Brushes.LightBlue, rect); - } -} - -```` -````VB.NET -Private Sub radGanttView1_ItemPaint2(sender As Object, e As GanttViewItemPaintEventArgs) - If (e.Element.Data.Items.Count > 0) Then - Dim start As DateTime = e.Element.Data.Start.AddHours(-18) - Dim rect As RectangleF = Me.radGanttView1.GanttViewElement.GraphicalViewElement.GetDrawRectangle(e.Element.Data, start, start.AddHours(10)) - e.Graphics.FillRectangle(Brushes.LightBlue, rect) - End If -End Sub - -```` - -{{endregion}} + + + + + + + + + ![WinForms RadGanttView Draw Rectangle](images/ganttview-formatting-custom-paiting002.png) diff --git a/controls/ganttview/formatting/graphicalview-item-formatting.md b/controls/ganttview/formatting/graphicalview-item-formatting.md index 128e0354f..3c9cdb5d0 100644 --- a/controls/ganttview/formatting/graphicalview-item-formatting.md +++ b/controls/ganttview/formatting/graphicalview-item-formatting.md @@ -13,35 +13,10 @@ previous_url: ganttview-formatting-graphicalviewitem-formatting The __GraphicalViewItemFormatting__ event allows you to change the style and looks of the items displayed in the graphical view. The following example demonstrates how to format all tasks that involve some selection e.g. their title starts with "Select". -{{source=..\SamplesCS\GanttView\Formatting\GraphicalViewItemFormatting.cs region=GraphicalViewItemFormatting}} -{{source=..\SamplesVB\GanttView\Formatting\GraphicalViewItemFormatting.vb region=GraphicalViewItemFormatting}} - -````C# -private void radGanttView1_GraphicalViewItemFormatting(object sender, GanttViewGraphicalViewItemFormattingEventArgs e) -{ - if (e.Item.Title.StartsWith("Select")) - { - e.ItemElement.TaskElement.BackColor = Color.Lime; - } - else - { - e.ItemElement.TaskElement.ResetValue(LightVisualElement.BackColorProperty, Telerik.WinControls.ValueResetFlags.Local); - } -} - -```` -````VB.NET -Private Sub radGanttView1_GraphicalViewItemFormatting(sender As Object, e As GanttViewGraphicalViewItemFormattingEventArgs) - If (e.Item.Title.StartsWith("Select")) Then - e.ItemElement.TaskElement.BackColor = Color.Lime - Else - e.ItemElement.TaskElement.ResetValue(LightVisualElement.BackColorProperty, Telerik.WinControls.ValueResetFlags.Local) - End If -End Sub - -```` - -{{endregion}} + + + + ![WinForms RadGanttView GraphicalView Item Formatting](images/ganttview-formatting-graphicalviewitem-formatting001.png) diff --git a/controls/ganttview/formatting/graphicalview-link-item-formatting.md b/controls/ganttview/formatting/graphicalview-link-item-formatting.md index 27d098bce..39d2b7512 100644 --- a/controls/ganttview/formatting/graphicalview-link-item-formatting.md +++ b/controls/ganttview/formatting/graphicalview-link-item-formatting.md @@ -13,75 +13,10 @@ previous_url: ganttview-formatting-graphical-view-link-item-formatting __RadGanttView__ allows formatting of individual links through the __GraphicalViewLinkItemFormatting__ event. The following example demonstrates how to format links based on their type. -{{source=..\SamplesCS\GanttView\Formatting\GraphicalViewLinkItemFormatting.cs region=GraphicalViewLinkItemFormatting}} -{{source=..\SamplesVB\GanttView\Formatting\GraphicalViewLinkItemFormatting.vb region=GraphicalViewLinkItemFormatting}} + + -````C# -private void radGanttView1_GraphicalViewLinkItemFormatting(object sender, GanttViewLinkItemFormattingEventArgs e) -{ - Color color = Color.Black; - DashStyle dash = DashStyle.Solid; - switch (e.Link.LinkType) - { - case TasksLinkType.FinishToFinish: - dash = DashStyle.DashDotDot; - color = Color.Red; - break; - case TasksLinkType.FinishToStart: - dash = DashStyle.Dash; - color = Color.Green; - break; - case TasksLinkType.StartToFinish: - dash = DashStyle.DashDot; - color = Color.Blue; - break; - case TasksLinkType.StartToStart: - dash = DashStyle.Dot; - color = Color.Black; - break; - } - Pen pen = new Pen(color); - pen.DashStyle = dash; - pen.Width = 3; - pen.LineJoin = LineJoin.Bevel; - pen.EndCap = LineCap.ArrowAnchor; - e.Pen = pen; -} -```` -````VB.NET -Private Sub RadGanttView1_GraphicalViewLinkItemFormatting(sender As Object, e As Telerik.WinControls.UI.GanttViewLinkItemFormattingEventArgs) - Dim penColor As Color = Color.Black - Dim dash As DashStyle = DashStyle.Solid - Select Case e.Link.LinkType - Case TasksLinkType.FinishToFinish - dash = DashStyle.DashDotDot - penColor = Color.Red - Exit Select - Case TasksLinkType.FinishToStart - dash = DashStyle.Dash - penColor = Color.Green - Exit Select - Case TasksLinkType.StartToFinish - dash = DashStyle.DashDot - penColor = Color.Blue - Exit Select - Case TasksLinkType.StartToStart - dash = DashStyle.Dot - penColor = Color.Black - Exit Select - End Select - Dim pen As New Pen(penColor) - pen.DashStyle = dash - pen.Width = 3 - pen.LineJoin = LineJoin.Bevel - pen.EndCap = LineCap.ArrowAnchor - e.Pen = pen -End Sub - -```` - -{{endregion}} ![WinForms RadGanttView GraphicalView Link Item Formatting](images/ganttview-formatting-graphical-view-item-formatting001.png) diff --git a/controls/ganttview/formatting/textview-item-formatting.md b/controls/ganttview/formatting/textview-item-formatting.md index ad8c315d4..9e724b1f8 100644 --- a/controls/ganttview/formatting/textview-item-formatting.md +++ b/controls/ganttview/formatting/textview-item-formatting.md @@ -15,88 +15,20 @@ __RadGanttView__ offers two events for formatting the text view part. The __Text Here is an example demonstrating how to use the event to make all summary items have a green back color and all tasks a yellow one. -{{source=..\SamplesCS\GanttView\Formatting\TextViewItemCellFormatting.cs region=TextViewItemFormatting}} -{{source=..\SamplesVB\GanttView\Formatting\TextViewItemCellFormatting.vb region=TextViewItemFormatting}} + + -````C# -private void radGanttView1_TextViewItemFormatting(object sender, GanttViewTextViewItemFormattingEventArgs e) -{ - if (e.Item.Items.Count > 0) - { - e.ItemElement.DrawFill = true; - e.ItemElement.BackColor = Color.LightGreen; - e.ItemElement.GradientStyle = GradientStyles.Solid; - } - else if (e.Item.Start != e.Item.End) - { - e.ItemElement.DrawFill = true; - e.ItemElement.BackColor = Color.Yellow; - e.ItemElement.GradientStyle = GradientStyles.Solid; - } - else - { - e.ItemElement.ResetValue(LightVisualElement.DrawBorderProperty, ValueResetFlags.Local); - e.ItemElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local); - e.ItemElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local); - } -} -```` -````VB.NET -Private Sub radGanttView1_TextViewItemFormatting(sender As Object, e As GanttViewTextViewItemFormattingEventArgs) - If (e.Item.Items.Count > 0) Then - e.ItemElement.DrawFill = True - e.ItemElement.BackColor = Color.LightGreen - e.ItemElement.GradientStyle = GradientStyles.Solid - ElseIf (e.Item.Start <> e.Item.End) Then - e.ItemElement.DrawFill = True - e.ItemElement.BackColor = Color.Yellow - e.ItemElement.GradientStyle = GradientStyles.Solid - Else - e.ItemElement.ResetValue(LightVisualElement.DrawBorderProperty, ValueResetFlags.Local) - e.ItemElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local) - e.ItemElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local) - End If -End Sub - -```` - -{{endregion}} ![WinForms RadGanttView TextView Item Formatting](images/ganttview-formatting-textviewitem-cellformatting001.png) Another example showing how to change the fore color of the cells in the `Title` column for all types of tasks that start on an even day of the month. -{{source=..\SamplesCS\GanttView\Formatting\TextViewItemCellFormatting.cs region=TextViewCellFormatting}} -{{source=..\SamplesVB\GanttView\Formatting\TextViewItemCellFormatting.vb region=TextViewCellFormatting}} - -````C# -private void radGanttView1_TextViewCellFormatting(object sender, GanttViewTextViewCellFormattingEventArgs e) -{ - if (e.Item.Start.Day % 2 == 0 && e.Column.Name == "Title") - { - e.CellElement.ForeColor = Color.Red; - } - else - { - e.CellElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local); - } -} - -```` -````VB.NET -Private Sub radGanttView1_TextViewCellFormatting(sender As Object, e As GanttViewTextViewCellFormattingEventArgs) - If (e.Item.Start.Day Mod 2 = 0 AndAlso e.Column.Name = "Title") Then - e.CellElement.ForeColor = Color.Red - Else - e.CellElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local) - End If -End Sub + + -```` -{{endregion}} ![WinForms RadGanttView Cells Color](images/ganttview-formatting-textviewitem-cellformatting002.png) diff --git a/controls/ganttview/formatting/timeline-item-formatting.md b/controls/ganttview/formatting/timeline-item-formatting.md index 1f3076d09..a730221c2 100644 --- a/controls/ganttview/formatting/timeline-item-formatting.md +++ b/controls/ganttview/formatting/timeline-item-formatting.md @@ -13,60 +13,10 @@ previous_url: ganttview-formatting-timelineviewitem-formatting The __TimelineItemFormatting__ event allows you to format the style and look of the items in the timeline container. The following example demonstrates how to make the timeline appear as a checkered flag. -{{source=..\SamplesCS\GanttView\Formatting\TimelineItemFormatting.cs region=TimelineItemFormatting}} -{{source=..\SamplesVB\GanttView\Formatting\TimelineItemFormatting.vb region=TimelineItemFormatting}} + + -````C# -private void radGanttView1_TimelineItemFormatting(object sender, GanttViewTimelineItemFormattingEventArgs e) -{ - CultureInfo currentCulture = CultureInfo.CurrentCulture; - int weekNo = currentCulture.Calendar.GetWeekOfYear(e.Item.Start, currentCulture.DateTimeFormat.CalendarWeekRule, currentCulture.DateTimeFormat.FirstDayOfWeek); - Color color1 = Color.Black; - Color color2 = Color.White; - if (weekNo % 2 == 0) - { - color1 = Color.White; - color2 = Color.Black; - } - e.ItemElement.TopElement.DrawFill = true; - e.ItemElement.TopElement.DrawBorder = false; - e.ItemElement.TopElement.GradientStyle = GradientStyles.Solid; - e.ItemElement.TopElement.BackColor = color1; - e.ItemElement.TopElement.ForeColor = color2; - foreach (LightVisualElement element in e.ItemElement.BottomElement.Children) - { - element.BackColor = color2; - element.ForeColor = color1; - element.DrawBorder = false; - } -} -```` -````VB.NET -Private Sub radGanttView1_TimelineItemFormatting(sender As Object, e As GanttViewTimelineItemFormattingEventArgs) - Dim currentCulture As CultureInfo = CultureInfo.CurrentCulture - Dim weekNo As Integer = currentCulture.Calendar.GetWeekOfYear(e.Item.Start, currentCulture.DateTimeFormat.CalendarWeekRule, currentCulture.DateTimeFormat.FirstDayOfWeek) - Dim color1 As Color = Color.Black - Dim color2 As Color = Color.White - If weekNo Mod 2 = 0 Then - color1 = Color.White - color2 = Color.Black - End If - e.ItemElement.TopElement.DrawFill = True - e.ItemElement.TopElement.DrawBorder = False - e.ItemElement.TopElement.GradientStyle = GradientStyles.Solid - e.ItemElement.TopElement.BackColor = color1 - e.ItemElement.TopElement.ForeColor = color2 - For Each element As LightVisualElement In e.ItemElement.BottomElement.Children - element.BackColor = color2 - element.ForeColor = color1 - element.DrawBorder = False - Next -End Sub - -```` - -{{endregion}} ![WinForms RadGanttView Timeline Item Formatting](images/ganttview-formatting-timelineviewitem-formatting001.png) diff --git a/controls/ganttview/integration.md b/controls/ganttview/integration.md index 7564b54b9..caa2ed294 100644 --- a/controls/ganttview/integration.md +++ b/controls/ganttview/integration.md @@ -17,41 +17,18 @@ This example will demonstrate how __RadGanttView__ integrates with __RadSchedule In the case of __RadScheduler__ we have implemented a component (called __GanttViewIntegrationProvider__) which implements the interface and allows for two way notifications between the controls. Here is how to use it: -{{source=..\SamplesCS\GanttView\SchedulerIntegration\SchedulerIntegration.cs region=Integration}} -{{source=..\SamplesVB\GanttView\SchedulerIntegration\SchedulerIntegration.vb region=Integration}} + + -````C# -this.radGanttView1.DataProvider = new GanttViewIntegrationProvider(this.radScheduler1); - -```` -````VB.NET -Me.radGanttView1.DataProvider = New GanttViewIntegrationProvider(Me.radScheduler1) - -```` - -{{endregion}} + Two things you need to note. The first is that __RadGanttView__ requires a unique id for each item in it. You can read more on how to provide such an "id" in the section on ["Adding new items"]({%slug winforms/ganttview-/working-with-data/adding-new-items%}). The other thing you need to be aware is the ids __RadScheduler__ assigns to its appointments. They are of type __EventId__ and need a `Guid` when constructed. Summing these two together gives the following code: -{{source=..\SamplesCS\GanttView\SchedulerIntegration\SchedulerIntegration.cs region=TrickyPart}} -{{source=..\SamplesVB\GanttView\SchedulerIntegration\SchedulerIntegration.vb region=TrickyPart}} + + -````C# -private void radGanttView1_ItemChildIdNeeded(object sender, GanttViewItemChildIdNeededEventArgs e) -{ - e.ChildId = new EventId(Guid.NewGuid()); -} - -```` -````VB.NET -Private Sub radGanttView1_ItemChildIdNeeded(sender As Object, e As Telerik.WinControls.UI.GanttViewItemChildIdNeededEventArgs) Handles radGanttView1.ItemChildIdNeeded - e.ChildId = New EventId(Guid.NewGuid()) -End Sub - -```` - -{{endregion}} + ![WinForms RadGanttView Integration](images/ganttview-integration001.png) diff --git a/controls/ganttview/localization.md b/controls/ganttview/localization.md index 47baf13e4..3bd54f24d 100644 --- a/controls/ganttview/localization.md +++ b/controls/ganttview/localization.md @@ -1,93 +1,35 @@ ---- -title: Localization -page_title: Localization - WinForms GanttView Control -description: Learn how you can localize WinForms GanttView to display control text and messages in a specific language. -slug: winforms/ganttview-/localization -tags: localization -published: True -position: 16 -previous_url: ganttview-localizaton ---- - -# Localization - -To localize __RadGanttView__ to display control text and messages in a specific language: - -1. Start by creating a descendant of the __GanttViewLocalizationProvider__ class. - -1. Override the __GetLocalizedString(string id)__ method and provide a translation for the texts. If a translation is not provided, the default value will be returned. This behavior is guaranteed by the call to the __base GetLocalizedString__ method in the default clause of the switch statement in the example. - -Below is a sample implementation of an English localization provider: - -{{source=..\SamplesCS\GanttView\Localization\LocalizationProvider.cs region=LocalizationProvider}} -{{source=..\SamplesVB\GanttView\Localization\LocalizationProvider.vb region=LocalizationProvider}} - -````C# -public class MyEnglishGanttViewLocalizationProvider : GanttViewLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case GanttViewStringId.ContextMenuAdd: - return "&Add"; - case GanttViewStringId.ContextMenuAddChild: - return "Add &Child"; - case GanttViewStringId.ContextMenuAddSibling: - return "Add &Sibling"; - case GanttViewStringId.ContextMenuDelete: - return "&Delete"; - case GanttViewStringId.ContextMenuProgress: - return "&Progress"; - case "TimelineWeek": - return "Week"; - } - return string.Empty; - } -} - -```` -````VB.NET -Public Class MyEnglishGanttViewLocalizationProvider - Inherits GanttViewLocalizationProvider - Public Overrides Function GetLocalizedString(id As String) As String - Select Case id - Case GanttViewStringId.ContextMenuAdd - Return "&Add" - Case GanttViewStringId.ContextMenuAddChild - Return "Add &Child" - Case GanttViewStringId.ContextMenuAddSibling - Return "Add &Sibling" - Case GanttViewStringId.ContextMenuDelete - Return "&Delete" - Case GanttViewStringId.ContextMenuProgress - Return "&Progress" - Case "TimelineWeek" - Return "Week" - End Select - Return String.Empty - End Function -End Class - -```` - -{{endregion}} - -To apply the custom localization provider, instantiate and assign it to the current localization provider: - -{{source=..\SamplesCS\GanttView\Localization\LocalizationProvider.cs region=ApplyLocalizationProvider}} -{{source=..\SamplesVB\GanttView\Localization\LocalizationProvider.vb region=ApplyLocalizationProvider}} - -````C# -GanttViewLocalizationProvider.CurrentProvider = new MyEnglishGanttViewLocalizationProvider(); - -```` -````VB.NET -GanttViewLocalizationProvider.CurrentProvider = New MyEnglishGanttViewLocalizationProvider() - -```` - -{{endregion}} - - - +--- +title: Localization +page_title: Localization - WinForms GanttView Control +description: Learn how you can localize WinForms GanttView to display control text and messages in a specific language. +slug: winforms/ganttview-/localization +tags: localization +published: True +position: 16 +previous_url: ganttview-localizaton +--- + +# Localization + +To localize __RadGanttView__ to display control text and messages in a specific language: + +1. Start by creating a descendant of the __GanttViewLocalizationProvider__ class. + +1. Override the __GetLocalizedString(string id)__ method and provide a translation for the texts. If a translation is not provided, the default value will be returned. This behavior is guaranteed by the call to the __base GetLocalizedString__ method in the default clause of the switch statement in the example. + +Below is a sample implementation of an English localization provider: + + + + + + +To apply the custom localization provider, instantiate and assign it to the current localization provider: + + + + + + + + diff --git a/controls/ganttview/printing-support/printing-events.md b/controls/ganttview/printing-support/printing-events.md index 007770fc7..eb51665e7 100644 --- a/controls/ganttview/printing-support/printing-events.md +++ b/controls/ganttview/printing-support/printing-events.md @@ -17,69 +17,10 @@ You can customize the print output through the __PrintElementFormatting__ and __ The following example demonstrates how you can use the __PrintContext__ property to determine what element is being printed and to change the styling accordingly. -{{source=..\SamplesCS\GanttView\PrintingEvents\PrintingEvents.cs region=PrintFormatting}} -{{source=..\SamplesVB\GanttView\PrintingEvents\PrintingEvents.vb region=PrintFormatting}} + + -````C# -private void radGanttView1_PrintElementFormatting(object sender, GanttViewPrintElementFormattingEventArgs e) -{ - switch (e.PrintContext) - { - case GanttViewPrintElementContext.HeaderCell: - e.PrintElement.BackColor = Color.LightBlue; - break; - case GanttViewPrintElementContext.DataCell: - e.PrintElement.BorderColor = Color.Cyan; - break; - case GanttViewPrintElementContext.TaskElement: - e.PrintElement.ForeColor = Color.Green; - break; - case GanttViewPrintElementContext.SummaryTaskElement: - e.PrintElement.BorderColor = Color.Red; - break; - case GanttViewPrintElementContext.MilestoneElement: - e.PrintElement.BackColor = Color.Orange; - break; - case GanttViewPrintElementContext.TimelineUpperElement: - e.PrintElement.BackColor = Color.LightCoral; - break; - case GanttViewPrintElementContext.TimelineBottomElement: - e.PrintElement.BackColor = Color.LightGray; - break; - } -} - -```` -````VB.NET -Private Sub GanttViewPrintElementFormattingEventArgs(sender As Object, e As GanttViewPrintElementFormattingEventArgs) - Select Case e.PrintContext - Case GanttViewPrintElementContext.HeaderCell - e.PrintElement.BackColor = Color.LightBlue - Exit Select - Case GanttViewPrintElementContext.DataCell - e.PrintElement.BorderColor = Color.Cyan - Exit Select - Case GanttViewPrintElementContext.TaskElement - e.PrintElement.ForeColor = Color.Green - Exit Select - Case GanttViewPrintElementContext.SummaryTaskElement - e.PrintElement.BorderColor = Color.Red - Exit Select - Case GanttViewPrintElementContext.MilestoneElement - e.PrintElement.BackColor = Color.Orange - Exit Select - Case GanttViewPrintElementContext.TimelineUpperElement - e.PrintElement.BackColor = Color.LightCoral - Exit Select - Case GanttViewPrintElementContext.TimelineBottomElement - e.PrintElement.BackColor = Color.LightGray - Exit Select - End Select -End Sub - -```` - -{{endregion}} + ![WinForms RadGanttView Text Part](images/ganttview-printing-printing-events001.png)![WinForms RadGanttView Graphics Part](images/ganttview-printing-printing-events002.png) @@ -87,37 +28,10 @@ End Sub This example demonstrates how you can paint the text of summary items next to the printed graphical representation. -{{source=..\SamplesCS\GanttView\PrintingEvents\PrintingEvents.cs region=PrintPaint}} -{{source=..\SamplesVB\GanttView\PrintingEvents\PrintingEvents.vb region=PrintPaint}} + + -````C# -private void radGanttView1_PrintElementPaint(object sender, GanttViewPrintElementPaintEventArgs e) -{ - if (e.PrintContext == GanttViewPrintElementContext.SummaryTaskElement) - { - GanttViewDataItem dataItem = e.DataContext as GanttViewDataItem; - SizeF textSize = e.Graphics.MeasureString(dataItem.Title, this.radGanttView1.Font); - RectangleF rect = new RectangleF(e.Rectangle.Right + 10, e.Rectangle.Y, textSize.Width, e.Rectangle.Height); - e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit; - e.Graphics.DrawString(dataItem.Title, this.radGanttView1.Font, Brushes.Black, rect); - } -} - -```` -````VB.NET -Private Sub radGanttView1_PrintElementPaint(sender As Object, e As GanttViewPrintElementPaintEventArgs) - If e.PrintContext = GanttViewPrintElementContext.SummaryTaskElement Then - Dim dataItem As GanttViewDataItem = TryCast(e.DataContext, GanttViewDataItem) - Dim textSize As SizeF = e.Graphics.MeasureString(dataItem.Title, Me.radGanttView1.Font) - Dim rect As New RectangleF(e.Rectangle.Right + 10, e.Rectangle.Y, textSize.Width, e.Rectangle.Height) - e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit - e.Graphics.DrawString(dataItem.Title, Me.radGanttView1.Font, Brushes.Black, rect) - End If -End Sub - -```` - -{{endregion}} + ![WinForms RadGanttView Customized Graphics Path While Printing](images/ganttview-printing-printing-events003.png) diff --git a/controls/ganttview/timeline/custom-timeline.md b/controls/ganttview/timeline/custom-timeline.md index 898bfe472..32c6aa22f 100644 --- a/controls/ganttview/timeline/custom-timeline.md +++ b/controls/ganttview/timeline/custom-timeline.md @@ -18,273 +18,43 @@ __RadGanttView__ offers a number of built-in *TimeRange* settings which allow us 1\. First you need to set the __TimelineRange__ property of the gantt view graphical element to *Custom*. If you want you can override and modify the default views as well but for this example we will use the custom value. -{{source=..\SamplesCS\GanttView\CustomTimeline\DecadesTimeline.cs region=TimeRangeCustom}} -{{source=..\SamplesVB\GanttView\CustomTimeline\DecadesTimeline.vb region=TimeRangeCustom}} + + -````C# -this.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineRange = TimeRange.Custom; - -```` -````VB.NET -Me.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineRange = TimeRange.Custom - -```` - -{{endregion}} 2\. Next you need to create a custom timeline behavior class and assign it to the graphical view. In this class you will add the logic for the new decades view. -{{source=..\SamplesCS\GanttView\CustomTimeline\DecadesTimeline.cs region=CustomBehavior}} -{{source=..\SamplesVB\GanttView\CustomTimeline\DecadesTimeline.vb region=CustomBehavior}} - -````C# -this.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineBehavior = new DecadesGanttViewTimelineBehavior(); - -```` -````VB.NET -Me.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineBehavior = New DecadesGanttViewTimelineBehavior() - -```` - -{{endregion}} + + 3\. Now you can fill the class with the code that will create the view. You should note that because we want to preserve the built-in views throughout the example we will check whether the time range is Custom and only handle this case. * First you have to override the __AdjustedTimelineStart__ and __AdjustedTimelineEnd__ properties. What these properties do is to enlarge the timeline start and end to allow only whole timeline cells to be displayed. Here is an example. Imagine you use a view with quarters and your __TimelineStart__ property is set to 15.05.2013. This date is somewhere in the middle of the year’s second quarter. The __AdjustedTimelineStart__ property takes this date and the fact you use quarters and returns an adjusted date which is the actual start of the quarter. In this particular case the property will return 03.04.2013 which is the start date of the quarter that contains the __TimelineStart__ date. The __AdjustedTimelineEnd__ property does the same for the end of the timeline. For the decades view this properties will adjust the start and end dates to years: -{{source=..\SamplesCS\GanttView\CustomTimeline\DecadesTimeline.cs region=AdjustedStartAndEnd}} -{{source=..\SamplesVB\GanttView\CustomTimeline\DecadesTimeline.vb region=AdjustedStartAndEnd}} - -````C# -public override DateTime AdjustedTimelineStart -{ - get - { - if (this.GraphicalViewElement.TimelineRange != TimeRange.Custom) - { - return base.AdjustedTimelineStart; - } - return new DateTime(this.GraphicalViewElement.TimelineStart.Year, 1, 1); - } -} -public override DateTime AdjustedTimelineEnd -{ - get - { - if (this.GraphicalViewElement.TimelineRange != TimeRange.Custom) - { - return base.AdjustedTimelineEnd; - } - return new DateTime(this.GraphicalViewElement.TimelineEnd.Year + 1, 1, 1); - } -} - -```` -````VB.NET -Public Overrides ReadOnly Property AdjustedTimelineStart() As DateTime - Get - If Me.GraphicalViewElement.TimelineRange <> TimeRange.[Custom] Then - Return MyBase.AdjustedTimelineStart - End If - Return New DateTime(Me.GraphicalViewElement.TimelineStart.Year, 1, 1) - End Get -End Property -Public Overrides ReadOnly Property AdjustedTimelineEnd As DateTime - Get - If Me.GraphicalViewElement.TimelineRange <> TimeRange.[Custom] Then - Return MyBase.AdjustedTimelineEnd - End If - Return New DateTime(Me.GraphicalViewElement.TimelineEnd.Year + 1, 1, 1) - End Get -End Property - -```` + + -{{endregion}} * Next you should override the __BuildTimelineDataItems__ method. The method returns a list of __GanttViewTimelineDataItems__. Each data item will represent a decade. -{{source=..\SamplesCS\GanttView\CustomTimeline\DecadesTimeline.cs region=GanttViewTimelineDataItems}} -{{source=..\SamplesVB\GanttView\CustomTimeline\DecadesTimeline.vb region=GanttViewTimelineDataItems}} + + -````C# -public override IList BuildTimelineDataItems(TimeRange range) -{ - if (range != TimeRange.Custom) - { - return base.BuildTimelineDataItems(range); - } - return this.BuildTimelineDataItemsForDecadesRange(); -} -public IList BuildTimelineDataItemsForDecadesRange() -{ - List result = new List(); - DateTime adjustedStart = this.AdjustedTimelineStart; - DateTime adjustedEnd = this.AdjustedTimelineEnd; - DateTime currentDate = adjustedStart.Date; - int currentYearNumber = currentDate.Year; - int newYearNumber = currentYearNumber; - GanttViewTimelineDataItem item = new GanttViewTimelineDataItem(currentDate.Date, currentDate.AddYears(1), this.GraphicalViewElement.TimelineRange, this.GraphicalViewElement.OnePixelTime); - result.Add(item); - while (currentDate < adjustedEnd) - { - item.End = currentDate.AddYears(1); - currentDate = currentDate.AddYears(1); - newYearNumber = currentDate.Year; - if (newYearNumber != currentYearNumber && newYearNumber % 10 == 0 && currentDate <= adjustedEnd) - { - currentYearNumber = newYearNumber; - item = new GanttViewTimelineDataItem(currentDate, currentDate, this.GraphicalViewElement.TimelineRange, this.GraphicalViewElement.OnePixelTime); - result.Add(item); - } - } - return result; -} - -```` -````VB.NET -Public Overrides Function BuildTimelineDataItems(range As TimeRange) As IList(Of GanttViewTimelineDataItem) -If range <> TimeRange.[Custom] Then - Return MyBase.BuildTimelineDataItems(range) -End If -Return Me.BuildTimelineDataItemsForDecadesRange() -End Function -Public Function BuildTimelineDataItemsForDecadesRange() As IList(Of GanttViewTimelineDataItem) -Dim result As New List(Of GanttViewTimelineDataItem)() -Dim adjustedStart As DateTime = Me.AdjustedTimelineStart -Dim adjustedEnd As DateTime = Me.AdjustedTimelineEnd -Dim currentDate As DateTime = adjustedStart.[Date] -Dim currentYearNumber As Integer = currentDate.Year -Dim newYearNumber As Integer = currentYearNumber -Dim item As New GanttViewTimelineDataItem(currentDate.[Date], currentDate.AddYears(1), Me.GraphicalViewElement.TimelineRange, Me.GraphicalViewElement.OnePixelTime) -result.Add(item) -While currentDate < adjustedEnd - item.[End] = currentDate.AddYears(1) - currentDate = currentDate.AddYears(1) - newYearNumber = currentDate.Year - If newYearNumber <> currentYearNumber AndAlso newYearNumber Mod 10 = 0 AndAlso currentDate <= adjustedEnd Then - currentYearNumber = newYearNumber - item = New GanttViewTimelineDataItem(currentDate, currentDate, Me.GraphicalViewElement.TimelineRange, Me.GraphicalViewElement.OnePixelTime) - result.Add(item) - End If -End While -Return result -End Function - -```` - -{{endregion}} * Next we have to calculate the timeline cells for each timeline data item. To this we override the __GetTimelineCellInfoForItem__ method. The method returns an instance of the __GanttTimelineCellsInfo__ struct. This struct contains two properties. The first one, __NumberOfcells__, indicates how many cells the given timeline data item will display. The second one, __StartIndex__, is useful in the case where you use repeatable cell items e.g. quarters, halves, thirds etc. The property is useful when the start of the timeline is not the first item in the repeatable values collection. Here is an example. Imagine the timeline starts is the third quarter of the year with this property you will later be able to set the proper text to the cell item. If you do not have this info your cells will always start at 0 or 1. Since in this example the start is the third quarter starting at 0 or 1 would be wrong. In our example we have continuous data so we will not use this property: -{{source=..\SamplesCS\GanttView\CustomTimeline\DecadesTimeline.cs region=GanttTimelineCellsInfo}} -{{source=..\SamplesVB\GanttView\CustomTimeline\DecadesTimeline.vb region=GanttTimelineCellsInfo}} - -````C# -public override GanttTimelineCellsInfo GetTimelineCellInfoForItem(GanttViewTimelineDataItem item, TimeRange timeRange) -{ - if (timeRange != TimeRange.Custom) - { - return base.GetTimelineCellInfoForItem(item, timeRange); - } - return this.GetTimelineCellInfoForDecadeRange(item); -} -public GanttTimelineCellsInfo GetTimelineCellInfoForDecadeRange(GanttViewTimelineDataItem item) -{ - int years = 10; - if (item.Start == this.AdjustedTimelineStart) - { - if (item.Start.Year % 10 > 0) - { - years = 10 - (item.Start.Year % 10); - } - } - if (item.End == this.AdjustedTimelineEnd) - { - if (item.End.Year % 10 > 0) - { - years = item.End.Year % 10; - } - } - return new GanttTimelineCellsInfo(years); -} - -```` -````VB.NET -Public Overrides Function GetTimelineCellInfoForItem(item As GanttViewTimelineDataItem, range As TimeRange) As GanttTimelineCellsInfo - If range <> TimeRange.[Custom] Then - Return MyBase.GetTimelineCellInfoForItem(item, range) - End If - Return Me.GetTimelineCellInfoForDecadeRange(item) -End Function -Public Function GetTimelineCellInfoForDecadeRange(item As GanttViewTimelineDataItem) As GanttTimelineCellsInfo - Dim years As Integer = 10 - If item.Start = Me.AdjustedTimelineStart Then - If item.Start.Year Mod 10 > 0 Then - years = 10 - (item.Start.Year Mod 10) - End If - End If - If item.[End] = Me.AdjustedTimelineEnd Then - If item.[End].Year Mod 10 > 0 Then - years = item.[End].Year Mod 10 - End If - End If - Return New GanttTimelineCellsInfo(years) -End Function + + -```` - -{{endregion}} * Finally we want to have a proper text inside our decade timeline items. For this purpose we override the __GetTimelineTopElementText__ and __GetTimelineBottomElementText__ methods. -{{source=..\SamplesCS\GanttView\CustomTimeline\DecadesTimeline.cs region=TimelineElementsText}} -{{source=..\SamplesVB\GanttView\CustomTimeline\DecadesTimeline.vb region=TimelineElementsText}} - -````C# -public override string GetTimelineTopElementText(GanttViewTimelineDataItem item) -{ - if (item.Range != TimeRange.Custom) - { - return base.GetTimelineTopElementText(item); - } - string format = "{0:yyyy} - {1:yyyy}"; - return string.Format(System.Threading.Thread.CurrentThread.CurrentUICulture, format, item.Start, item.End.AddYears(-1)); -} -public override string GetTimelineBottomElementText(GanttViewTimelineDataItem item, int index) -{ - if (item.Range != TimeRange.Custom) - { - return base.GetTimelineBottomElementText(item, index); - } - string format = "{0:yyyy}"; - return string.Format(System.Threading.Thread.CurrentThread.CurrentCulture, format, new DateTime(item.Start.Year + index, 1, 1)); -} - -```` -````VB.NET - Public Overrides Function GetTimelineTopElementText(item As GanttViewTimelineDataItem) As String - If item.Range <> TimeRange.[Custom] Then - Return MyBase.GetTimelineTopElementText(item) - End If - Dim format As String = "{0:yyyy} - {1:yyyy}" - Return String.Format(System.Threading.Thread.CurrentThread.CurrentUICulture, format, item.Start, item.[End].AddYears(-1)) -End Function -Public Overrides Function GetTimelineBottomElementText(item As GanttViewTimelineDataItem, index As Integer) As String - If item.Range <> TimeRange.[Custom] Then - Return MyBase.GetTimelineBottomElementText(item, index) - End If - Dim format As String = "{0:yyyy}" - Return String.Format(System.Threading.Thread.CurrentThread.CurrentCulture, format, New DateTime(item.Start.Year + index, 1, 1)) -End Function - -```` - -{{endregion}} + + # See Also diff --git a/controls/ganttview/timeline/timeline-views.md b/controls/ganttview/timeline/timeline-views.md index d565cba45..e244aeb6d 100644 --- a/controls/ganttview/timeline/timeline-views.md +++ b/controls/ganttview/timeline/timeline-views.md @@ -19,130 +19,53 @@ All built-in views can be found in the *TimeRange* enumeration. Here are the dif * __TimeRange.Week__ : Each element of the upper row represents one week. The elements on the lower row represent days. -{{source=..\SamplesCS\GanttView\TimelineViews\GanttTimelineViews.cs region=TimeRangeWeek}} -{{source=..\SamplesVB\GanttView\TimelineViews\GanttTimelineViews.vb region=TimeRangeWeek}} - -````C# -this.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineRange = TimeRange.Week; - -```` -````VB.NET -Me.RadGanttView1.GanttViewElement.GraphicalViewElement.TimelineRange = TimeRange.Week - -```` - -{{endregion}} + + ![WinForms RadGanttView TimeRange Week](images/ganttview-timeline-timeline-views001.png) * __TimeRange.Month:__ Each element of the upper row represents one month. The elements on the lower row represent days. -{{source=..\SamplesCS\GanttView\TimelineViews\GanttTimelineViews.cs region=TimeRangeMonth}} -{{source=..\SamplesVB\GanttView\TimelineViews\GanttTimelineViews.vb region=TimeRangeMonth}} - -````C# -this.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineRange = TimeRange.Month; - -```` -````VB.NET -Me.RadGanttView1.GanttViewElement.GraphicalViewElement.TimelineRange = TimeRange.Month - -```` - -{{endregion}} + + ![WinForms RadGanttView __TimeRange Month](images/ganttview-timeline-timeline-views002.png) * __TimeRange.Year:__ Each element of the upper row represents one year. The elements on the lower row represent months. -{{source=..\SamplesCS\GanttView\TimelineViews\GanttTimelineViews.cs region=TimeRangeYear}} -{{source=..\SamplesVB\GanttView\TimelineViews\GanttTimelineViews.vb region=TimeRangeYear}} - -````C# -this.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineRange = TimeRange.Year; - -```` -````VB.NET -Me.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineRange = TimeRange.Year - -```` - -{{endregion}} + + ![WinForms RadGanttView TimeRange Year](images/ganttview-timeline-timeline-views003.png) * __TimeRange.YearHalves:__ Each element of the upper row represents one year. The elements on the lower row represent half year periods (roughly six months). -{{source=..\SamplesCS\GanttView\TimelineViews\GanttTimelineViews.cs region=TimeRangeYearHalves}} -{{source=..\SamplesVB\GanttView\TimelineViews\GanttTimelineViews.vb region=TimeRangeYearHalves}} - -````C# -this.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineRange = TimeRange.YearHalves; - -```` -````VB.NET -Me.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineRange = TimeRange.YearHalves - -```` - -{{endregion}} + + ![WinForms RadGanttView TimeRange YearHalves](images/ganttview-timeline-timeline-views004.png) * __TimeRange.YearQuarters:__ Each element of the upper row represents one year. The elements on the lower row represent quarter year periods (roughly three months). -{{source=..\SamplesCS\GanttView\TimelineViews\GanttTimelineViews.cs region=TimeRangeYearQuarters}} -{{source=..\SamplesVB\GanttView\TimelineViews\GanttTimelineViews.vb region=TimeRangeYearQuarters}} - -````C# -this.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineRange = TimeRange.YearQuarters; - -```` -````VB.NET -Me.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineRange = TimeRange.YearQuarters - -```` - -{{endregion}} + + ![WinForms RadGanttView TimeRange YearQuarters](images/ganttview-timeline-timeline-views005.png) * __TimeRange.Day__ – Each element of the upper row represents one day. The elements on the lower row represent hours. -{{source=..\SamplesCS\GanttView\TimelineViews\GanttTimelineViews.cs region=TimeRangeDay}} -{{source=..\SamplesVB\GanttView\TimelineViews\GanttTimelineViews.vb region=TimeRangeDay}} - -````C# -this.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineRange = TimeRange.Day; - -```` -````VB.NET -Me.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineRange = TimeRange.Day - -```` - -{{endregion}} + + ![WinForms RadGanttView TimeRange Day](images/ganttview-timeline-timeline-views006.png) * __TimeRange.DayHalfHours:__ Each element of the upper row represents one day. The elements on the lower row represent half hours (30 minutes period). -{{source=..\SamplesCS\GanttView\TimelineViews\GanttTimelineViews.cs region=TimeRangeDayHalfHours}} -{{source=..\SamplesVB\GanttView\TimelineViews\GanttTimelineViews.vb region=TimeRangeDayHalfHours}} - -````C# -this.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineRange = TimeRange.DayHalfHours; - -```` -````VB.NET -Me.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineRange = TimeRange.DayHalfHours - -```` - -{{endregion}} + + ![WinForms RadGanttView TimeRange DayHalfHours](images/ganttview-timeline-timeline-views007.png) @@ -150,38 +73,16 @@ Me.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineRange = TimeRange * __TimeRange.DayQuarterHours:__ Each element of the upper row represents one day. The elements on the lower row represent quarter hours (15 minutes period). -{{source=..\SamplesCS\GanttView\TimelineViews\GanttTimelineViews.cs region=TimeRangeDayQuarterHours}} -{{source=..\SamplesVB\GanttView\TimelineViews\GanttTimelineViews.vb region=TimeRangeDayQuarterHours}} - -````C# -this.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineRange = TimeRange.DayQuarterHours; - -```` -````VB.NET -Me.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineRange = TimeRange.DayQuarterHours - -```` - -{{endregion}} + + ![WinForms RadGanttView TimeRange DayQuarterHours](images/ganttview-timeline-timeline-views008.png) * __TimeRange.Hour:__ Each element of the upper row represents one hour. The elements on the lower row represent minutes. -{{source=..\SamplesCS\GanttView\TimelineViews\GanttTimelineViews.cs region=TimeRangeHour}} -{{source=..\SamplesVB\GanttView\TimelineViews\GanttTimelineViews.vb region=TimeRangeHour}} - -````C# -this.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineRange = TimeRange.Hour; - -```` -````VB.NET -Me.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineRange = TimeRange.Hour - -```` - -{{endregion}} + + ![WinForms RadGanttView TimeRange Hour](images/ganttview-timeline-timeline-views009.png) diff --git a/controls/ganttview/today-indicator.md b/controls/ganttview/today-indicator.md index 4f6b22f3e..fde524761 100644 --- a/controls/ganttview/today-indicator.md +++ b/controls/ganttview/today-indicator.md @@ -19,29 +19,10 @@ You can control which one is visible through the __ShowTodayIndicator__ and the You can also directly access the two indicators: -{{source=..\SamplesCS\GanttView\TodayIndicator\TodayIndicator.cs region=IndicatorsAccess}} -{{source=..\SamplesVB\GanttView\TodayIndicator\TodayIndicator.vb region=IndicatorsAccess}} - -````C# -GanttViewTodayIndicatorElement todayIndicator = this.radGanttView1.GanttViewElement.GraphicalViewElement.TodayIndicatorElement; -todayIndicator.BackColor = Color.Red; -todayIndicator.BackColor2 = Color.Red; -GanttViewTimelineTodayIndicatorElement timelineTodayIndicator = this.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineTodayIndicatorElement; -timelineTodayIndicator.BackColor = Color.Green; -timelineTodayIndicator.BackColor2 = Color.Green; - -```` -````VB.NET -Dim todayIndicator As GanttViewTodayIndicatorElement = Me.radGanttView1.GanttViewElement.GraphicalViewElement.TodayIndicatorElement -todayIndicator.BackColor = Color.Red -todayIndicator.BackColor2 = Color.Red -Dim timelineTodayIndicator As GanttViewTimelineTodayIndicatorElement = Me.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineTodayIndicatorElement -timelineTodayIndicator.BackColor = Color.Green -timelineTodayIndicator.BackColor2 = Color.Green - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/ganttview/tooltip.md b/controls/ganttview/tooltip.md index 14f983675..5e0a2dc3f 100644 --- a/controls/ganttview/tooltip.md +++ b/controls/ganttview/tooltip.md @@ -16,74 +16,12 @@ To set a ToolTip value to the RadGanttView elements, we can use the __ToolTipTex ![WinForms RadGanttView Tooltip](images/ganttview-tooltip001.png) -{{source=..\SamplesCS\GanttView\TodayIndicator\TodayIndicator.cs region=ToolTip}} -{{source=..\SamplesVB\GanttView\TodayIndicator\TodayIndicator.vb region=ToolTip}} + + -The code snippet below demonstrates how you can use ToolTipTextNeeded event handler to set ToolTipText for the given element. -````C# -private void radGanttView1_ToolTipTextNeeded(object sender, ToolTipTextNeededEventArgs e) -{ - GanttViewTaskElement taskElement = sender as GanttViewTaskElement; - GanttViewMilestoneElement mileStone = sender as GanttViewMilestoneElement; - GanttViewSummaryElement summaryItem = sender as GanttViewSummaryElement; - - if (mileStone != null) - { - GanttViewMilestoneItemElement itemElement = mileStone.Parent as GanttViewMilestoneItemElement; - - e.ToolTipText = itemElement.Data.Title + " : " + itemElement.Data.Start.ToShortDateString() + " - " + itemElement.Data.End.ToShortDateString(); - } - - if (summaryItem != null) - { - GanttGraphicalViewBaseItemElement itemElement = summaryItem.Parent as GanttGraphicalViewBaseItemElement; - - e.ToolTipText = itemElement.Data.Title + " : " + itemElement.Data.Start.ToShortDateString() + " - " + itemElement.Data.End.ToShortDateString(); - } - - if (taskElement != null) - { - GanttGraphicalViewBaseItemElement itemElement = taskElement.Parent as GanttGraphicalViewBaseItemElement; - - if (itemElement != null) - e.ToolTipText = itemElement.Data.Title + " : " + itemElement.Data.Start.ToShortDateString() + " - " + itemElement.Data.End.ToShortDateString(); - } -} - -```` -````VB.NET -Private Sub radGanttView1_ToolTipTextNeeded(sender As Object, e As ToolTipTextNeededEventArgs) - Dim taskElement As GanttViewTaskElement = TryCast(sender, GanttViewTaskElement) - Dim mileStone As GanttViewMilestoneElement = TryCast(sender, GanttViewMilestoneElement) - Dim summaryItem As GanttViewSummaryElement = TryCast(sender, GanttViewSummaryElement) - - - If mileStone IsNot Nothing Then - Dim itemElement As GanttViewMilestoneItemElement = TryCast(mileStone.Parent, GanttViewMilestoneItemElement) - - e.ToolTipText = itemElement.Data.Title & " : " & itemElement.Data.Start.ToShortDateString() & " - " + itemElement.Data.[End].ToShortDateString() - End If - - If summaryItem IsNot Nothing Then - Dim itemElement As GanttGraphicalViewBaseItemElement = TryCast(summaryItem.Parent, GanttGraphicalViewBaseItemElement) - - e.ToolTipText = itemElement.Data.Title & " : " & itemElement.Data.Start.ToShortDateString() & " - " + itemElement.Data.[End].ToShortDateString() - End If - - If taskElement IsNot Nothing Then - Dim itemElement As GanttGraphicalViewBaseItemElement = TryCast(taskElement.Parent, GanttGraphicalViewBaseItemElement) - - If itemElement IsNot Nothing Then - e.ToolTipText = itemElement.Data.Title & " : " & itemElement.Data.Start.ToShortDateString() & " - " + itemElement.Data.[End].ToShortDateString() - End If - End If - End Sub - -```` - -{{endregion}} +The code snippet below demonstrates how you can use ToolTipTextNeeded event handler to set ToolTipText for the given element. # See Also diff --git a/controls/ganttview/working-with-data/adding-new-items.md b/controls/ganttview/working-with-data/adding-new-items.md index 76a183582..53c655355 100644 --- a/controls/ganttview/working-with-data/adding-new-items.md +++ b/controls/ganttview/working-with-data/adding-new-items.md @@ -15,27 +15,10 @@ __RadGanttView__ uses its data source to create a hierarchical data structure. T Here is an example of how to provide ids using the __ItemChildIdNeeded__ event. The event is fired every time a new item is created and is about to be added to the data source. -{{source=..\SamplesCS\GanttView\WorkingWithData\AddingNewItems.cs region=AddingNewItems}} -{{source=..\SamplesVB\GanttView\WorkingWithData\AddingNewItems.vb region=AddingNewItems}} - -````C# -int integerIdCounter = 100; -private void radGanttView1_ItemChildIdNeeded(object sender, GanttViewItemChildIdNeededEventArgs e) -{ - e.ChildId = this.integerIdCounter++; -} - -```` -````VB.NET -Dim integerIdCounter As Integer = 100 -Private Sub radGanttView1_ItemChildIdNeeded(sender As Object, e As GanttViewItemChildIdNeededEventArgs) - Me.integerIdCounter += 1 - e.ChildId = Me.integerIdCounter -End Sub - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/ganttview/working-with-data/binding-to-database.md b/controls/ganttview/working-with-data/binding-to-database.md index 02f2f6d6a..af3faef21 100644 --- a/controls/ganttview/working-with-data/binding-to-database.md +++ b/controls/ganttview/working-with-data/binding-to-database.md @@ -49,21 +49,10 @@ __RadGanttView__ supports binding to Database data. Levels are created using the 1. Finally add this code to the form load event handler to specify the timeline range: -{{source=..\SamplesCS\GanttView\WorkingWithData\BindingToDatabase.cs region=BindingToDatabase}} -{{source=..\SamplesVB\GanttView\WorkingWithData\BindingToDatabase.vb region=BindingToDatabase}} + + -````C# -this.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineStart = new DateTime(2006, 8, 2); -this.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineEnd = new DateTime(2007, 4, 2); -```` -````VB.NET -Me.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineStart = New DateTime(2006, 8, 2) -Me.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineEnd = New DateTime(2007, 4, 2) - -```` - -{{endregion}} ![WinForms RadGanttView Bound Mode](images/ganttview-working-with-data-binding-to-database006.png) diff --git a/controls/ganttview/working-with-data/data-binding-basics.md b/controls/ganttview/working-with-data/data-binding-basics.md index bf12015ec..bf11c4720 100644 --- a/controls/ganttview/working-with-data/data-binding-basics.md +++ b/controls/ganttview/working-with-data/data-binding-basics.md @@ -53,114 +53,27 @@ The following example demonstrates a sample data with all the code needed to bin 1\. First we define the schema of the data. -{{source=..\SamplesCS\GanttView\WorkingWithData\DataBindingBasics.cs region=DataSchema}} -{{source=..\SamplesVB\GanttView\WorkingWithData\DataBindingBasics.vb region=DataSchema}} - -````C# -DataTable tasks = new DataTable("Tasks"); -tasks.Columns.Add("Id", typeof(int)); -tasks.Columns.Add("ParentId", typeof(int)); -tasks.Columns.Add("Title", typeof(string)); -tasks.Columns.Add("Start", typeof(DateTime)); -tasks.Columns.Add("End", typeof(DateTime)); -tasks.Columns.Add("Progress", typeof(decimal)); -DataTable links = new DataTable("Links"); -links.Columns.Add("StartId", typeof(int)); -links.Columns.Add("EndId", typeof(int)); -links.Columns.Add("LinkType", typeof(int)); -DataSet data = new DataSet(); -data.Tables.Add(tasks); -data.Tables.Add(links); - -```` -````VB.NET -Dim tasks As New DataTable("Tasks") -tasks.Columns.Add("Id", GetType(Integer)) -tasks.Columns.Add("ParentId", GetType(Integer)) -tasks.Columns.Add("Title", GetType(String)) -tasks.Columns.Add("Start", GetType(DateTime)) -tasks.Columns.Add("End", GetType(DateTime)) -tasks.Columns.Add("Progress", GetType(Decimal)) -Dim links As New DataTable("Links") -links.Columns.Add("StartId", GetType(Integer)) -links.Columns.Add("EndId", GetType(Integer)) -links.Columns.Add("LinkType", GetType(Integer)) -Dim data As New DataSet() -data.Tables.Add(tasks) -data.Tables.Add(links) - -```` - -{{endregion}} + + + + + 2\. USe the following snippet to populate with data. -{{source=..\SamplesCS\GanttView\WorkingWithData\DataBindingBasics.cs region=SampleData}} -{{source=..\SamplesVB\GanttView\WorkingWithData\DataBindingBasics.vb region=SampleData}} - -````C# -tasks.Rows.Add(1, 0, "Summary task title", new DateTime(2010, 10, 10), new DateTime(2010, 10, 15), 30m); -tasks.Rows.Add(2, 1, "First child task title", new DateTime(2010, 10, 10), new DateTime(2010, 10, 12), 10); -tasks.Rows.Add(3, 1, "Second child task title", new DateTime(2010, 10, 12), new DateTime(2010, 10, 15), 20m); -tasks.Rows.Add(4, 1, "Milestone", new DateTime(2010, 10, 15), new DateTime(2010, 10, 15), 0m); -links.Rows.Add(2, 3, 1); -links.Rows.Add(3, 4, 1); - -```` -````VB.NET -tasks.Rows.Add(1, 0, "Summary task title", New DateTime(2010, 10, 10), New DateTime(2010, 10, 15), 30D) -tasks.Rows.Add(2, 1, "First child task title", New DateTime(2010, 10, 10), New DateTime(2010, 10, 12), 10) -tasks.Rows.Add(3, 1, "Second child task title", New DateTime(2010, 10, 12), New DateTime(2010, 10, 15), 20D) -tasks.Rows.Add(4, 1, "Milestone", New DateTime(2010, 10, 15), New DateTime(2010, 10, 15), 0D) -links.Rows.Add(2, 3, 1) -links.Rows.Add(3, 4, 1) - -```` - -{{endregion}} + + + + + 3\. Set all the aforementioned properties. -{{source=..\SamplesCS\GanttView\WorkingWithData\DataBindingBasics.cs region=SetupAndBinding}} -{{source=..\SamplesVB\GanttView\WorkingWithData\DataBindingBasics.vb region=SetupAndBinding}} - -````C# -this.radGanttView1.GanttViewElement.TaskDataMember = "Tasks"; -this.radGanttView1.GanttViewElement.ChildMember = "Id"; -this.radGanttView1.GanttViewElement.ParentMember = "ParentId"; -this.radGanttView1.GanttViewElement.TitleMember = "Title"; -this.radGanttView1.GanttViewElement.StartMember = "Start"; -this.radGanttView1.GanttViewElement.EndMember = "End"; -this.radGanttView1.GanttViewElement.ProgressMember = "Progress"; -this.radGanttView1.GanttViewElement.LinkDataMember = "Links"; -this.radGanttView1.GanttViewElement.LinkStartMember = "StartId"; -this.radGanttView1.GanttViewElement.LinkEndMember = "EndId"; -this.radGanttView1.GanttViewElement.LinkTypeMember = "LinkType"; -this.radGanttView1.GanttViewElement.DataSource = data; -this.radGanttView1.Columns.Add("Start"); -this.radGanttView1.Columns.Add("End"); - -```` -````VB.NET -Me.RadGanttView1.GanttViewElement.TaskDataMember = "Tasks" -Me.RadGanttView1.GanttViewElement.ChildMember = "Id" -Me.RadGanttView1.GanttViewElement.ParentMember = "ParentId" -Me.RadGanttView1.GanttViewElement.TitleMember = "Title" -Me.RadGanttView1.GanttViewElement.StartMember = "Start" -Me.RadGanttView1.GanttViewElement.EndMember = "End" -Me.RadGanttView1.GanttViewElement.ProgressMember = "Progress" -Me.RadGanttView1.GanttViewElement.LinkDataMember = "Links" -Me.RadGanttView1.GanttViewElement.LinkStartMember = "StartId" -Me.RadGanttView1.GanttViewElement.LinkEndMember = "EndId" -Me.RadGanttView1.GanttViewElement.LinkTypeMember = "LinkType" -Me.RadGanttView1.GanttViewElement.DataSource = data -Me.RadGanttView1.Columns.Add("Start") -Me.RadGanttView1.Columns.Add("End") - -```` - -{{endregion}} + + + + >important If you don't see the tasks, it is most probably because the graphical view is not scrolled to the tasks' date. Feel free to set the **TimelineStart** and **TimelineEnd** properties of the GanttViewElement.**GraphicalViewElement**. diff --git a/controls/ganttview/working-with-data/importing-xml-from-ms-project.md b/controls/ganttview/working-with-data/importing-xml-from-ms-project.md index bfbd17c3a..c7a02dc42 100644 --- a/controls/ganttview/working-with-data/importing-xml-from-ms-project.md +++ b/controls/ganttview/working-with-data/importing-xml-from-ms-project.md @@ -13,306 +13,19 @@ previous_url: ganttview-working-with-data-importing-xml-from-msproject Although __RadGanttView__ does not support direct binding or importing of MS Project files we have prepared a class that would help you import an MS Project saved as xml. -{{source=..\SamplesCS\GanttView\WorkingWithData\ImportXmlFromMsProject.cs region=MsProjectImport}} -{{source=..\SamplesVB\GanttView\WorkingWithData\ImportXmlFromMsProject.vb region=MsProjectImport}} + + -````C# -public class MsProjectImporter -{ - private Dictionary> tasksByLevel; - private DataSet dataSet; - public DataSet GetData(TextReader reader) - { - XmlDocument doc = new XmlDocument(); - doc.Load(reader); - this.InitializeDataStructures(); - this.ExtractTasks(doc); - ImporterNode root = this.BuildTasksHierarchy(); - this.SaveTasksDataTable(root); - this.SaveLinksDataTable(doc); - return this.dataSet; - } - private void InitializeDataStructures() - { - this.tasksByLevel = new Dictionary>(); - DataTable tasks = new DataTable("Tasks"); - tasks.Columns.Add("Id", typeof(int)); - tasks.Columns.Add("ParentId", typeof(int)); - tasks.Columns.Add("Title", typeof(string)); - tasks.Columns.Add("Start", typeof(DateTime)); - tasks.Columns.Add("End", typeof(DateTime)); - tasks.Columns.Add("Progress", typeof(decimal)); - tasks.Columns.Add("Outline", typeof(string)); - DataTable links = new DataTable("Links"); - links.Columns.Add("StartId", typeof(int)); - links.Columns.Add("EndId", typeof(int)); - links.Columns.Add("LinkType", typeof(int)); - this.dataSet = new DataSet(); - this.dataSet.Tables.Add(tasks); - this.dataSet.Tables.Add(links); - } - private ImporterNode BuildTasksHierarchy() - { - ImporterNode root = null; - foreach (int key in this.tasksByLevel.Keys) - { - if (key == 0) - { - root = new ImporterNode(); - root.Row = this.tasksByLevel[key][0]; - continue; - } - foreach (DataRow row in this.tasksByLevel[key]) - { - List outlineIndexes = new List(row["Outline"].ToString().Split('.')); - ImporterNode parent = root; - while (outlineIndexes.Count > 1) - { - parent = parent.Children[int.Parse(outlineIndexes[0]) - 1]; - outlineIndexes.RemoveAt(0); - } - ImporterNode newNode = new ImporterNode(); - newNode.Row = row; - newNode.Row["ParentId"] = parent.Row["Id"]; - parent.Children.Add(newNode); - } - } - return root; - } - private void ExtractTasks(XmlDocument doc) - { - foreach (XmlNode node in doc.DocumentElement["Tasks"].ChildNodes) - { - if (node["OutlineNumber"] == null) - { - continue; - } - DataRow row = this.dataSet.Tables["Tasks"].NewRow(); - int outlineLevel = int.Parse(node["OutlineLevel"].InnerText); - int id = int.Parse(node["UID"].InnerText); - row["Id"] = id; - row["ParentId"] = 0; - row["Title"] = node["Name"].InnerText; - row["Start"] = DateTime.Parse(node["Start"].InnerText); - row["End"] = DateTime.Parse(node["Finish"].InnerText); - row["Progress"] = decimal.Parse(node["PercentComplete"].InnerText); - row["Outline"] = node["OutlineNumber"].InnerText; - if (this.tasksByLevel.ContainsKey(outlineLevel)) - { - this.tasksByLevel[outlineLevel].Add(row); - } - else - { - this.tasksByLevel.Add(outlineLevel, new List() { row }); - } - } - } - private void SaveTasksDataTable(ImporterNode root) - { - Queue queue = new Queue(); - foreach (ImporterNode node in root.Children) - { - queue.Enqueue(node); - } - while (queue.Count > 0) - { - ImporterNode node = queue.Dequeue(); - foreach (ImporterNode item in node.Children) - { - queue.Enqueue(item); - } - this.dataSet.Tables["Tasks"].Rows.Add(node.Row); - } - dataSet.Tables["Tasks"].Columns.Remove("Outline"); - } - private void SaveLinksDataTable(XmlDocument doc) - { - foreach (XmlNode node in doc.DocumentElement["Tasks"].ChildNodes) - { - XmlNode predecessor = node["PredecessorLink"]; - if (predecessor != null) - { - int id = int.Parse(node["UID"].InnerText); - int startId = int.Parse(predecessor["PredecessorUID"].InnerText); - int linkType = int.Parse(predecessor["Type"].InnerText); - this.dataSet.Tables["Links"].Rows.Add(startId, id, linkType); - } - } - } -} -public class ImporterNode -{ - private DataRow row; - private List children; - public ImporterNode() - { - this.children = new List(); - } - public DataRow Row - { - get { return row; } - set { row = value; } - } - public List Children - { - get { return children; } - } -} -```` -````VB.NET -Public Class MsProjectImporter - Private tasksByLevel As Dictionary(Of Integer, List(Of DataRow)) - Private dataSet As DataSet - Public Function GetData(reader As TextReader) As DataSet - Dim doc As New XmlDocument() - doc.Load(reader) - Me.InitializeDataStructures() - Me.ExtractTasks(doc) - Dim root As ImporterNode = Me.BuildTasksHierarchy() - Me.SaveTasksDataTable(root) - Me.SaveLinksDataTable(doc) - Return Me.dataSet - End Function - Private Sub InitializeDataStructures() - Me.tasksByLevel = New Dictionary(Of Integer, List(Of DataRow))() - Dim tasks As New DataTable("Tasks") - tasks.Columns.Add("Id", GetType(Integer)) - tasks.Columns.Add("ParentId", GetType(Integer)) - tasks.Columns.Add("Title", GetType(String)) - tasks.Columns.Add("Start", GetType(DateTime)) - tasks.Columns.Add("End", GetType(DateTime)) - tasks.Columns.Add("Progress", GetType(Decimal)) - tasks.Columns.Add("Outline", GetType(String)) - Dim links As New DataTable("Links") - links.Columns.Add("StartId", GetType(Integer)) - links.Columns.Add("EndId", GetType(Integer)) - links.Columns.Add("LinkType", GetType(Integer)) - Me.dataSet = New DataSet() - Me.dataSet.Tables.Add(tasks) - Me.dataSet.Tables.Add(links) - End Sub - Private Function BuildTasksHierarchy() As ImporterNode - Dim root As ImporterNode = Nothing - For Each key As Integer In Me.tasksByLevel.Keys - If key = 0 Then - root = New ImporterNode() - root.Row = Me.tasksByLevel(key)(0) - Continue For - End If - For Each row As DataRow In Me.tasksByLevel(key) - Dim outlineIndexes As New List(Of String)(row("Outline").ToString().Split("."c)) - Dim parent As ImporterNode = root - While outlineIndexes.Count > 1 - parent = parent.Children(Integer.Parse(outlineIndexes(0)) - 1) - outlineIndexes.RemoveAt(0) - End While - Dim newNode As New ImporterNode() - newNode.Row = row - newNode.Row("ParentId") = parent.Row("Id") - parent.Children.Add(newNode) - Next - Next - Return root - End Function - Private Sub ExtractTasks(doc As XmlDocument) - For Each node As XmlNode In doc.DocumentElement("Tasks").ChildNodes - If node("OutlineNumber") Is Nothing Then - Continue For - End If - Dim row As DataRow = Me.dataSet.Tables("Tasks").NewRow() - Dim outlineLevel As Integer = Integer.Parse(node("OutlineLevel").InnerText) - Dim id As Integer = Integer.Parse(node("UID").InnerText) - row("Id") = id - row("ParentId") = 0 - row("Title") = node("Name").InnerText - row("Start") = DateTime.Parse(node("Start").InnerText) - row("End") = DateTime.Parse(node("Finish").InnerText) - row("Progress") = Decimal.Parse(node("PercentComplete").InnerText) - row("Outline") = node("OutlineNumber").InnerText - If Me.tasksByLevel.ContainsKey(outlineLevel) Then - Me.tasksByLevel(outlineLevel).Add(row) - Else - Me.tasksByLevel.Add(outlineLevel, New List(Of DataRow)() From { _ - row _ - }) - End If - Next - End Sub - Private Sub SaveTasksDataTable(root As ImporterNode) - Dim queue As New Queue(Of ImporterNode)() - For Each node As ImporterNode In root.Children - queue.Enqueue(node) - Next - While queue.Count > 0 - Dim node As ImporterNode = queue.Dequeue() - For Each item As ImporterNode In node.Children - queue.Enqueue(item) - Next - Me.dataSet.Tables("Tasks").Rows.Add(node.Row) - End While - dataSet.Tables("Tasks").Columns.Remove("Outline") - End Sub - Private Sub SaveLinksDataTable(doc As XmlDocument) - For Each node As XmlNode In doc.DocumentElement("Tasks").ChildNodes - Dim predecessor As XmlNode = node("PredecessorLink") - If predecessor IsNot Nothing Then - Dim id As Integer = Integer.Parse(node("UID").InnerText) - Dim startId As Integer = Integer.Parse(predecessor("PredecessorUID").InnerText) - Dim linkType As Integer = Integer.Parse(predecessor("Type").InnerText) - Me.dataSet.Tables("Links").Rows.Add(startId, id, linkType) - End If - Next - End Sub -End Class -Public Class ImporterNode - Private m_row As DataRow - Private m_children As List(Of ImporterNode) - Public Sub New() - Me.m_children = New List(Of ImporterNode)() - End Sub - Public Property Row() As DataRow - Get - Return m_row - End Get - Set(value As DataRow) - m_row = value - End Set - End Property - Public ReadOnly Property Children() As List(Of ImporterNode) - Get - Return m_children - End Get - End Property -End Class -```` - -{{endregion}} After you have this code in your project you can load the data from the xml into __RadGanttView__ like this: -{{source=..\SamplesCS\GanttView\WorkingWithData\ImportXmlFromMsProject.cs region=ImportXmlIntoGanttView}} -{{source=..\SamplesVB\GanttView\WorkingWithData\ImportXmlFromMsProject.vb region=ImportXmlIntoGanttView}} - -````C# -string fileLocation = @"C:\file.xml"; -MsProjectImporter importer = new MsProjectImporter(); -StringReader reader = new StringReader(fileLocation); -DataSet dataSet = importer.GetData(reader); -this.radGanttView1.DataSource = dataSet; - -```` -````VB.NET -Dim fileLocation As String = "C:\file.xml" -Dim importer As New MsProjectImporter() -Dim reader As New StringReader(fileLocation) -Dim dataSet As DataSet = importer.GetData(reader) + + -```` -{{endregion}} # See Also diff --git a/controls/ganttview/working-with-data/link-type-converter.md b/controls/ganttview/working-with-data/link-type-converter.md index 90319cf98..a69b745b1 100644 --- a/controls/ganttview/working-with-data/link-type-converter.md +++ b/controls/ganttview/working-with-data/link-type-converter.md @@ -41,98 +41,18 @@ This will work fine if your mapping is the same but if you store your link types * “SS” translates to TasksLinkType. StartToStart -{{source=..\SamplesCS\GanttView\WorkingWithData\LinkTypeConverterExample.cs region=CustomLinkTypeConverter}} -{{source=..\SamplesVB\GanttView\WorkingWithData\LinkTypeConverterExample.vb region=CustomLinkTypeConverter}} - -````C# -public class MyLinkTypeConverter : LinkTypeConverter -{ - public override TasksLinkType ConvertToLinkType(object value) - { - string stringVlaue = Convert.ToString(value); - switch (stringVlaue) - { - case "FF": - return TasksLinkType.FinishToFinish; - case "FS": - return TasksLinkType.FinishToStart; - case "SF": - return TasksLinkType.StartToFinish; - case "SS": - return TasksLinkType.StartToStart; - } - return base.ConvertToLinkType(value); - } - public override object ConvertFromLinkType(TasksLinkType linkType) - { - switch (linkType) - { - case TasksLinkType.FinishToFinish: - return "FF"; - case TasksLinkType.FinishToStart: - return "FS"; - case TasksLinkType.StartToFinish: - return "SF"; - case TasksLinkType.StartToStart: - return "SS"; - } - return base.ConvertFromLinkType(linkType); - } -} - -```` -````VB.NET -Public Class MyLinkTypeConverter - Inherits LinkTypeConverter - Public Overrides Function ConvertToLinkType(value As Object) As TasksLinkType - Dim stringVlaue As String = Convert.ToString(value) - Select Case stringVlaue - Case "FF" - Return TasksLinkType.FinishToFinish - Case "FS" - Return TasksLinkType.FinishToStart - Case "SF" - Return TasksLinkType.StartToFinish - Case "SS" - Return TasksLinkType.StartToStart - End Select - Return MyBase.ConvertToLinkType(value) - End Function - Public Overrides Function ConvertFromLinkType(linkType As TasksLinkType) As Object - Select Case linkType - Case TasksLinkType.FinishToFinish - Return "FF" - Case TasksLinkType.FinishToStart - Return "FS" - Case TasksLinkType.StartToFinish - Return "SF" - Case TasksLinkType.StartToStart - Return "SS" - End Select - Return MyBase.ConvertFromLinkType(linkType) - End Function -End Class - -```` - -{{endregion}} + + - -Now to use the converter you should assign it to the __LinkTypeConverter__ property of __RadGanttView__. -{{source=..\SamplesCS\GanttView\WorkingWithData\LinkTypeConverterExample.cs region=AssignLinkTypeConverter}} -{{source=..\SamplesVB\GanttView\WorkingWithData\LinkTypeConverterExample.vb region=AssignLinkTypeConverter}} -````C# -this.radGanttView1.LinkTypeConverter = new MyLinkTypeConverter(); + +Now to use the converter you should assign it to the __LinkTypeConverter__ property of __RadGanttView__. -```` -````VB.NET -Me.RadGanttView1.LinkTypeConverter = New MyLinkTypeConverter() + + -```` -{{endregion}} # See Also diff --git a/controls/ganttview/working-with-data/populating-with-data-programmatically.md b/controls/ganttview/working-with-data/populating-with-data-programmatically.md index 1dc1a7c3f..030b5b3bc 100644 --- a/controls/ganttview/working-with-data/populating-with-data-programmatically.md +++ b/controls/ganttview/working-with-data/populating-with-data-programmatically.md @@ -14,187 +14,20 @@ previous_url: ganttview-working-with-data-populating-with-data-programmatically __RadGanttview__ supports unbound mode as well, which means that you can manually populate it with the summary items, task items and milestone items (if needed). Then just set up the links between tasks and you have your gantt setup. The following example starts by setting the desired start and end range of the graphical element and then we are adding a few task items with sub items. At the end we are adding the links between the items. -{{source=..\SamplesCS\GanttView\WorkingWithData\PopulatingWithDataProgrammatically.cs region=PopulateData}} -{{source=..\SamplesVB\GanttView\WorkingWithData\PopulatingWithDataProgrammatically.vb region=PopulateData}} + + -````C# - -this.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineStart = new DateTime(2010, 10, 9); -this.radGanttView1.GanttViewElement.GraphicalViewElement.TimelineEnd = new DateTime(2010, 12, 10); - -//setup data items -GanttViewDataItem item1 = new GanttViewDataItem(); -item1.Start = new DateTime(2010, 10, 10); -item1.End = new DateTime(2010, 10, 15); -item1.Progress = 30m; -item1.Title = "Summary task.1. title"; - -GanttViewDataItem subitem11 = new GanttViewDataItem(); -subitem11.Start = new DateTime(2010, 10, 10); -subitem11.End = new DateTime(2010, 10, 12); -subitem11.Progress = 10m; -subitem11.Title = "Sub-task.1.1 title"; - -GanttViewDataItem subitem12 = new GanttViewDataItem(); -subitem12.Start = new DateTime(2010, 10, 12); -subitem12.End = new DateTime(2010, 10, 15); -subitem12.Progress = 20m; -subitem12.Title = "Sub-task.1.2 title"; - -//add subitems -item1.Items.Add(subitem11); -item1.Items.Add(subitem12); - -this.radGanttView1.Items.Add(item1); - -GanttViewDataItem item2 = new GanttViewDataItem(); -item2.Start = new DateTime(2010, 10, 12); -item2.End = new DateTime(2010, 10, 18); -item2.Progress = 40m; -item2.Title = "Summary task.2. title"; - -GanttViewDataItem subitem21 = new GanttViewDataItem(); -subitem21.Start = new DateTime(2010, 10, 12); -subitem21.End = new DateTime(2010, 10, 13); -subitem21.Progress = 10m; -subitem21.Title = "Sub-task.2.1 title"; - -GanttViewDataItem subitem22 = new GanttViewDataItem(); -subitem22.Start = new DateTime(2010, 10, 13); -subitem22.End = new DateTime(2010, 10, 18); -subitem22.Progress = 30m; -subitem22.Title = "Sub-task.2.2 title"; - -GanttViewDataItem subitem23 = new GanttViewDataItem(); -subitem23.Start = new DateTime(2010, 10, 18); -subitem23.End = new DateTime(2010, 10, 18); -subitem23.Title = "Sub-task.2.3 title"; - -//add subitems -item2.Items.Add(subitem21); -item2.Items.Add(subitem22); -item2.Items.Add(subitem23); - -this.radGanttView1.Items.Add(item2); - -//add links between items -GanttViewLinkDataItem link1 = new GanttViewLinkDataItem(); -link1.StartItem = subitem11; -link1.EndItem = subitem12; -link1.LinkType = TasksLinkType.FinishToStart; -this.radGanttView1.Links.Add(link1); - -GanttViewLinkDataItem link2 = new GanttViewLinkDataItem(); -link2.StartItem = subitem21; -link2.EndItem = subitem22; -link2.LinkType = TasksLinkType.StartToStart; -this.radGanttView1.Links.Add(link2); - -GanttViewLinkDataItem link3 = new GanttViewLinkDataItem(); -link3.StartItem = subitem22; -link3.EndItem = subitem23; -link3.LinkType = TasksLinkType.FinishToStart; -this.radGanttView1.Links.Add(link3); -```` -````VB.NET -Me.RadGanttView1.GanttViewElement.GraphicalViewElement.TimelineStart = New DateTime(2010, 10, 9) -Me.RadGanttView1.GanttViewElement.GraphicalViewElement.TimelineEnd = New DateTime(2010, 12, 10) -'setup data items -Dim item1 As New GanttViewDataItem() -item1.Start = New DateTime(2010, 10, 10) -item1.[End] = New DateTime(2010, 10, 15) -item1.Progress = 30D -item1.Title = "Summary task.1. title" -Dim subitem11 As New GanttViewDataItem() -subitem11.Start = New DateTime(2010, 10, 10) -subitem11.[End] = New DateTime(2010, 10, 12) -subitem11.Progress = 10D -subitem11.Title = "Sub-task.1.1 title" -Dim subitem12 As New GanttViewDataItem() -subitem12.Start = New DateTime(2010, 10, 12) -subitem12.[End] = New DateTime(2010, 10, 15) -subitem12.Progress = 20D -subitem12.Title = "Sub-task.1.2 title" -'add subitems -item1.Items.Add(subitem11) -item1.Items.Add(subitem12) -Me.RadGanttView1.Items.Add(item1) -Dim item2 As New GanttViewDataItem() -item2.Start = New DateTime(2010, 10, 12) -item2.[End] = New DateTime(2010, 10, 18) -item2.Progress = 40D -item2.Title = "Summary task.2. title" -Dim subitem21 As New GanttViewDataItem() -subitem21.Start = New DateTime(2010, 10, 12) -subitem21.[End] = New DateTime(2010, 10, 13) -subitem21.Progress = 10D -subitem21.Title = "Sub-task.2.1 title" -Dim subitem22 As New GanttViewDataItem() -subitem22.Start = New DateTime(2010, 10, 13) -subitem22.[End] = New DateTime(2010, 10, 18) -subitem22.Progress = 30D -subitem22.Title = "Sub-task.2.2 title" -Dim subitem23 As New GanttViewDataItem() -subitem23.Start = New DateTime(2010, 10, 18) -subitem23.[End] = New DateTime(2010, 10, 18) -subitem23.Title = "Sub-task.2.3 title" -'add subitems -item2.Items.Add(subitem21) -item2.Items.Add(subitem22) -item2.Items.Add(subitem23) -Me.RadGanttView1.Items.Add(item2) -'add links between items -Dim link1 As New GanttViewLinkDataItem() -link1.StartItem = subitem11 -link1.EndItem = subitem12 -link1.LinkType = TasksLinkType.FinishToStart -Me.RadGanttView1.Links.Add(link1) -Dim link2 As New GanttViewLinkDataItem() -link2.StartItem = subitem21 -link2.EndItem = subitem22 -link2.LinkType = TasksLinkType.StartToStart -Me.RadGanttView1.Links.Add(link2) -Dim link3 As New GanttViewLinkDataItem() -link3.StartItem = subitem22 -link3.EndItem = subitem23 -link3.LinkType = TasksLinkType.FinishToStart -Me.RadGanttView1.Links.Add(link3) - -```` - -{{endregion}} ![WinForms RadGanttView ganttview-working-with-data-populating-with-data-programmatically 001](images/ganttview-working-with-data-populating-with-data-programmatically001.png) Now we can just add the desired columns to be displayed in __GanttViewTextViewElement__. During the column initialization we will pass a string to specify the __FieldName__ so the column will know which fields of the tasks to display. In addition this string will also be used as header text. -{{source=..\SamplesCS\GanttView\WorkingWithData\PopulatingWithDataProgrammatically.cs region=AddColumns}} -{{source=..\SamplesVB\GanttView\WorkingWithData\PopulatingWithDataProgrammatically.vb region=AddColumns}} - -````C# - -GanttViewTextViewColumn titleColumn = new GanttViewTextViewColumn("Title"); -GanttViewTextViewColumn startColumn = new GanttViewTextViewColumn("Start"); -GanttViewTextViewColumn endColumn = new GanttViewTextViewColumn("End"); - -this.radGanttView1.GanttViewElement.Columns.Add(titleColumn); -this.radGanttView1.GanttViewElement.Columns.Add(startColumn); -this.radGanttView1.GanttViewElement.Columns.Add(endColumn); - -```` -````VB.NET -Dim titleColumn As New GanttViewTextViewColumn("Title") -Dim startColumn As New GanttViewTextViewColumn("Start") -Dim endColumn As New GanttViewTextViewColumn("End") -Me.RadGanttView1.GanttViewElement.Columns.Add(titleColumn) -Me.RadGanttView1.GanttViewElement.Columns.Add(startColumn) -Me.RadGanttView1.GanttViewElement.Columns.Add(endColumn) + + -```` -{{endregion}} ![WinForms RadGanttView Populating Data Programmatically](images/ganttview-working-with-data-populating-with-data-programmatically002.png) diff --git a/controls/gauges/bulletgraph/getting-started.md b/controls/gauges/bulletgraph/getting-started.md index 887675e87..ea4367836 100644 --- a/controls/gauges/bulletgraph/getting-started.md +++ b/controls/gauges/bulletgraph/getting-started.md @@ -54,50 +54,10 @@ Once the control is added to the form you just need to synchronize the __Feature #### Update Properties -{{source=..\SamplesCS\Gauges\BulletGraphCode.cs region=test}} -{{source=..\SamplesVB\Gauges\BulletGraphCode.vb region=test}} -````C# -Timer timer; -Random rand; - -public BulletGraphCode() -{ - InitializeComponent(); - timer = new Timer(); - rand = new Random(); - timer.Interval = 1000; - timer.Tick += timer_Tick; - timer.Start(); -} - -void timer_Tick(object sender, EventArgs e) -{ - this.radBulletGraph1.FeaturedMeasure = rand.Next(100); - this.radBulletGraph1.ComparativeMeasure = rand.Next(100); -} - -```` -````VB.NET -Private timer As Timer -Private rand As Random -Public Sub New() - InitializeComponent() - timer = New Timer() - rand = New Random() - timer.Interval = 1000 - AddHandler timer.Tick, AddressOf timer_Tick - timer.Start() -End Sub -Private Sub timer_Tick(ByVal sender As Object, ByVal e As EventArgs) - radBulletGraph1.FeaturedMeasure = rand.Next(100) - radBulletGraph1.ComparativeMeasure = rand.Next(100) -End Sub - -```` - - - -{{endregion}} + + + + >important Please note that when you select the style all elements will be automatically created and you can directly access them. You can create the control in code as well. More information is available in the following article:[Getting Started]({%slug winforms/gauges/lineargauge/getting-started%}) > diff --git a/controls/gauges/bulletgraph/save-and-load-layout.md b/controls/gauges/bulletgraph/save-and-load-layout.md index beaa228bb..2a0015022 100644 --- a/controls/gauges/bulletgraph/save-and-load-layout.md +++ b/controls/gauges/bulletgraph/save-and-load-layout.md @@ -25,26 +25,8 @@ You can save/load the layout in code as well. #### Save/Load Layout -{{source=..\SamplesCS\Gauges\BulletGraphCode.cs region=SaveLoadLayout}} -{{source=..\SamplesVB\Gauges\BulletGraphCode.vb region=SaveLoadLayout}} - -````C# -private void SaveLoadLayout() -{ - this.radBulletGraph1.SaveLayout(@"..\..\gauge-layout.xml"); - this.radBulletGraph1.LoadLayout(@"..\..\gauge-layout.xml"); -} - -```` -````VB.NET -Private Sub SaveLoadLayout() - Me.radBulletGraph1.SaveLayout("..\..\gauge-layout.xml") - Me.radBulletGraph1.LoadLayout("..\..\gauge-layout.xml") -End Sub - -```` - -{{endregion}} + + # See Also diff --git a/controls/gauges/lineargauge/getting-started.md b/controls/gauges/lineargauge/getting-started.md index 8e5a5dc9a..116ddbe9e 100644 --- a/controls/gauges/lineargauge/getting-started.md +++ b/controls/gauges/lineargauge/getting-started.md @@ -60,91 +60,8 @@ This example demonstrates how to programmatically setup a linear gauge. #### Add Items -{{source=..\SamplesCS\Gauges\LinearGauge\LinearGuageGettingStarted.cs region=add}} -{{source=..\SamplesVB\Gauges\LinearGauge\LinearGuageGettingStarted.vb region=add}} - -````C# -RadLinearGauge radLinearGauge1 = new RadLinearGauge(); -radLinearGauge1.Location = new Point(20, 20); -radLinearGauge1.Padding = new System.Windows.Forms.Padding(0, 10, 0, 10); -radLinearGauge1.RangeEnd = 100F; -radLinearGauge1.Size = new System.Drawing.Size(70, 384); -radLinearGauge1.Value = 70F; -radLinearGauge1.BackColor = Color.White; -radLinearGauge1.Vertical = true; -this.Controls.Add(radLinearGauge1); -LinearGaugeBar linearGaugeBar1 = new LinearGaugeBar(); -linearGaugeBar1.BackColor = Color.DarkGray; -linearGaugeBar1.BackColor2 = Color.LightGray; -linearGaugeBar1.BindEndRange = true; -linearGaugeBar1.Offset = 35F; -linearGaugeBar1.RangeEnd = 100F; -LinearGaugeLine linearGaugeLine1 = new LinearGaugeLine(); -linearGaugeLine1.AutoSize = false; -linearGaugeLine1.Bounds = new System.Drawing.Rectangle(0, 0, 60, 384); -linearGaugeLine1.Offset = 35F; -linearGaugeLine1.Padding = new System.Windows.Forms.Padding(0); -linearGaugeLine1.RangeEnd = 100F; -linearGaugeLine1.Width = 1F; -LinearGaugeTicks linearGaugeTicks1 = new LinearGaugeTicks(); -linearGaugeTicks1.Padding = new System.Windows.Forms.Padding(0); -linearGaugeTicks1.TicksCount = 10; -linearGaugeTicks1.TicksLenghtPercentage = 10F; -linearGaugeTicks1.TicksLocationPercentage = 35F; -linearGaugeTicks1.TickThickness = 0.5F; -LinearGaugeLabels linearGaugeLabels1 = new LinearGaugeLabels(); -linearGaugeLabels1.LabelFontSize = 3F; -linearGaugeLabels1.LabelLocationPercentage = 15F; -linearGaugeLabels1.LabelsCount = 10; -linearGaugeLabels1.LabelStartVisibleRange = 0F; -radLinearGauge1.Items.Add(linearGaugeBar1); -radLinearGauge1.Items.Add(linearGaugeLine1); -radLinearGauge1.Items.Add(linearGaugeTicks1); -radLinearGauge1.Items.Add(linearGaugeLabels1); - -```` -````VB.NET -Dim radLinearGauge1 As New RadLinearGauge() -radLinearGauge1.Location = New System.Drawing.Point(20, 20) -radLinearGauge1.Padding = New System.Windows.Forms.Padding(0, 10, 0, 10) -radLinearGauge1.RangeEnd = 100.0F -radLinearGauge1.Size = New System.Drawing.Size(70, 384) -radLinearGauge1.Value = 70.0F -radLinearGauge1.BackColor = Color.White -radLinearGauge1.Vertical = True -Me.Controls.Add(radLinearGauge1) -Dim linearGaugeBar1 As New LinearGaugeBar() -linearGaugeBar1.BackColor = Color.DarkGray -linearGaugeBar1.BackColor2 = Color.LightGray -linearGaugeBar1.BindEndRange = True -linearGaugeBar1.Offset = 35.0F -linearGaugeBar1.RangeEnd = 100.0F -Dim linearGaugeLine1 As New LinearGaugeLine() -linearGaugeLine1.AutoSize = False -linearGaugeLine1.Bounds = New System.Drawing.Rectangle(0, 0, 60, 384) -linearGaugeLine1.Offset = 35.0F -linearGaugeLine1.Padding = New System.Windows.Forms.Padding(0) -linearGaugeLine1.RangeEnd = 100.0F -linearGaugeLine1.Width = 1.0F -Dim linearGaugeTicks1 As New LinearGaugeTicks() -linearGaugeTicks1.Padding = New System.Windows.Forms.Padding(0) -linearGaugeTicks1.TicksCount = 10 -linearGaugeTicks1.TicksLenghtPercentage = 10.0F -linearGaugeTicks1.TicksLocationPercentage = 35.0F -linearGaugeTicks1.TickThickness = 0.5F -Dim linearGaugeLabels1 As New LinearGaugeLabels() -linearGaugeLabels1.LabelFontSize = 3.0F -linearGaugeLabels1.LabelLocationPercentage = 15.0F -linearGaugeLabels1.LabelsCount = 10 -linearGaugeLabels1.LabelStartVisibleRange = 0.0F -radLinearGauge1.Items.Add(linearGaugeBar1) -radLinearGauge1.Items.Add(linearGaugeLine1) -radLinearGauge1.Items.Add(linearGaugeTicks1) -radLinearGauge1.Items.Add(linearGaugeLabels1) - -```` - -{{endregion}} + + ## See Also diff --git a/controls/gauges/lineargauge/properties-and-events.md b/controls/gauges/lineargauge/properties-and-events.md index 549819721..f4597578c 100644 --- a/controls/gauges/lineargauge/properties-and-events.md +++ b/controls/gauges/lineargauge/properties-and-events.md @@ -30,30 +30,9 @@ The __ValueChanged__ event fires when the __Value__ of the control is changed. F #### ValueChanged Event -{{source=..\SamplesCS\Gauges\LinearGauge\LinearGuageGettingStarted.cs region=value}} -{{source=..\SamplesVB\Gauges\LinearGauge\LinearGuageGettingStarted.vb region=value}} - -````C# -void radLinearGauge2_ValueChanged(object sender, EventArgs e) -{ - if ( radLinearGauge2.Value > radLinearGauge2.RangeEnd - 10) - { - RadMessageBox.Show("Detected value that is close to the maximum!"); - } -} - -```` -````VB.NET -Private Sub radLinearGauge1_ValueChanged(ByVal sender As Object, ByVal e As EventArgs) - If radLinearGauge2.Value > radLinearGauge2.RangeEnd - 10 Then - RadMessageBox.Show("Detected value that is close to the maximum!") - End If -End Sub - -```` - -{{endregion}} - + + + # See Also * [Properties](https://docs.telerik.com/devtools/winforms/api/telerik.wincontrols.ui.gauges.radlineargauge.html#properties) diff --git a/controls/gauges/lineargauge/save-and-load-layout.md b/controls/gauges/lineargauge/save-and-load-layout.md index 7cd34e318..2742e5c88 100644 --- a/controls/gauges/lineargauge/save-and-load-layout.md +++ b/controls/gauges/lineargauge/save-and-load-layout.md @@ -27,21 +27,8 @@ You can save/load the layout in code as well. #### Save/Load Layout -{{source=..\SamplesCS\Gauges\LinearGauge\LinearGuageGettingStarted.cs region=code}} -{{source=..\SamplesVB\Gauges\LinearGauge\LinearGuageGettingStarted.vb region=code}} - -````C# -radLinearGauge1.SaveLayout("Layout.xml"); -radLinearGauge1.LoadLayout("Layout.xml"); - -```` -````VB.NET -radLinearGauge1.SaveLayout("Layout.xml") -radLinearGauge1.LoadLayout("Layout.xml") - -```` - -{{endregion}} + + # See Also diff --git a/controls/gauges/radialgauge/getting-started.md b/controls/gauges/radialgauge/getting-started.md index 26e79e906..f61f6a77a 100644 --- a/controls/gauges/radialgauge/getting-started.md +++ b/controls/gauges/radialgauge/getting-started.md @@ -60,66 +60,9 @@ You can create your own gauge's style programmatically from the scratch by addin #### Add Items -{{source=..\SamplesCS\Gauges\RadialGauge\RadialGaugeGettingStarted.cs region=AddItemsProgrammatically}} -{{source=..\SamplesVB\Gauges\RadialGauge\RadialGaugeGettingStarted.vb region=AddItemsProgrammatically}} - -````C# - -RadialGaugeLabels labels = new RadialGaugeLabels(); -RadialGaugeTicks smallTicks = new RadialGaugeTicks(); -RadialGaugeTicks bigTicks = new RadialGaugeTicks(); -RadialGaugeNeedle needle = new RadialGaugeNeedle(); -RadialGaugeArc arc = new RadialGaugeArc(); -labels.LabelFontSize = 4; -smallTicks.TickColor = Color.Red; -smallTicks.TickThickness = 0.5f; -smallTicks.TicksCount = 30; -smallTicks.TickStartIndexVisibleRange = 15; -bigTicks.TickColor = Color.DimGray; -bigTicks.TickThickness = 1f; -bigTicks.TicksCount = 10; -bigTicks.TicksLenghtPercentage = 20; -bigTicks.TicksRadiusPercentage = 80; -needle.LenghtPercentage = 60; -arc.Width = 0.5f; -arc.BackColor = Color.Gray; -radRadialGauge1.Items.Add(labels); -radRadialGauge1.Items.Add(smallTicks); -radRadialGauge1.Items.Add(bigTicks); -radRadialGauge1.Items.Add(needle); -radRadialGauge1.Items.Add(arc); - -```` -````VB.NET -Dim labels As New RadialGaugeLabels() -Dim smallTicks As New RadialGaugeTicks() -Dim bigTicks As New RadialGaugeTicks() -Dim needle As New RadialGaugeNeedle() -Dim arc As New RadialGaugeArc() -labels.LabelFontSize = 4 -smallTicks.TickColor = Color.Red -smallTicks.TickThickness = 0.5F -smallTicks.TicksCount = 30 -smallTicks.TickStartIndexVisibleRange = 15 -bigTicks.TickColor = Color.DimGray -bigTicks.TickThickness = 1.0F -bigTicks.TicksCount = 10 -bigTicks.TicksLenghtPercentage = 20 -bigTicks.TicksRadiusPercentage = 80 -needle.LenghtPercentage = 60 -arc.Width = 0.5F -arc.BackColor = Color.Gray -radRadialGauge1.Items.Add(labels) -radRadialGauge1.Items.Add(smallTicks) -radRadialGauge1.Items.Add(bigTicks) -radRadialGauge1.Items.Add(needle) -radRadialGauge1.Items.Add(arc) - -```` - -{{endregion}} - - + + + ## Adding Additional Elements Drag a __RadRadialGauge__ from the Toolbox and drop it onto the form. The gauge gallery will offer you to pick up the desired type. Select the first gauge type. Now, we will customize the gauge in order to obtain the result illustrated on the screen-shot below: @@ -129,198 +72,9 @@ Drag a __RadRadialGauge__ from the Toolbox and drop it onto the form. The gauge #### Additional Element -{{source=..\SamplesCS\Gauges\RadialGauge\RadialGaugeGettingStarted.cs region=AdvancedExample}} -{{source=..\SamplesVB\Gauges\RadialGauge\RadialGaugeGettingStarted.vb region=AdvancedExample}} - -````C# - -Timer timer = new Timer(); -float step = 0f; - -private void AdvancedExample() -{ - this.AVGRadialGauge1.RangeStart = 0; - this.AVGRadialGauge1.RangeEnd = 9; - this.AVGRadialGauge1.ValueChanged += AVGRadialGauge1_ValueChanged; - step = -(float)(AVGRadialGauge1.RangeEnd - AVGRadialGauge1.RangeStart) / 10f; - - this.radialGaugeLabels1.LabelFormat = "#,##0.00#"; - this.radialGaugeLabels1.LabelRadiusPercentage = 70; - this.radialGaugeLabels1.LabelEndVisibleRange = 5; - this.radialGaugeLabels2.LabelRadiusPercentage = 70; - this.radialGaugeLabels2.LabelFormat = "#,##0.00#"; - this.radialGaugeLabels2.LabelStartVisibleRange=6; - - this.radialGaugeNeedle1.Visibility = ElementVisibility.Collapsed; - this.radialGaugeNeedle2.Value = 4.25f; - this.radialGaugeNeedle2.BackColor = Color.Black; - this.radialGaugeNeedle2.BackColor2 = Color.Black; - this.radialGaugeNeedle2.BackLenghtPercentage = 0; - this.radialGaugeNeedle2.Thickness = 0.2f; - this.radialGaugeNeedle2.BindValue = true; - - RadialGaugeTicks firstCircleTick = new RadialGaugeTicks(); - this.AVGRadialGauge1.Items.Add(firstCircleTick); - - firstCircleTick.TicksCount = 18; - firstCircleTick.TickStartIndexVisibleRange = 5; - firstCircleTick.TickEndIndexVisibleRange = 5; - firstCircleTick.TicksLenghtPercentage = 3; - firstCircleTick.TicksRadiusPercentage = 115; - firstCircleTick.CircleTicks = true; - firstCircleTick.TickThickness = 1; - firstCircleTick.TickColor = Color.DimGray; - - RadialGaugeTicks firstTick = new RadialGaugeTicks(); - this.AVGRadialGauge1.Items.Add(firstTick); - - firstTick.TicksCount = 18; - firstTick.TickStartIndexVisibleRange = 5; - firstTick.TickEndIndexVisibleRange = 5; - firstTick.TicksRadiusPercentage = 103; - firstTick.CircleTicks = false; - firstTick.TickThickness = 1; - firstTick.TickColor = Color.DimGray; - - RadialGaugeTicks secondCircleTick = new RadialGaugeTicks(); - this.AVGRadialGauge1.Items.Add(secondCircleTick); - - secondCircleTick.TicksCount = 18; - secondCircleTick.TickStartIndexVisibleRange = 9; - secondCircleTick.TickEndIndexVisibleRange = 9; - secondCircleTick.TicksLenghtPercentage = 3; - secondCircleTick.TicksRadiusPercentage = 115; - secondCircleTick.CircleTicks = true; - secondCircleTick.TickThickness = 1; - secondCircleTick.TickColor = Color.DimGray; - - RadialGaugeTicks secondTick = new RadialGaugeTicks(); - this.AVGRadialGauge1.Items.Add(secondTick); - - secondTick.TicksCount = 18; - secondTick.TickStartIndexVisibleRange = 9; - secondTick.TickEndIndexVisibleRange = 9; - secondTick.TicksRadiusPercentage = 103; - secondTick.CircleTicks = false; - secondTick.TickThickness = 1; - secondTick.TickColor = Color.DimGray; - - timer.Interval = 1000; - timer.Tick += timer_Tick; - timer.Start(); -} -private void AVGRadialGauge1_ValueChanged(object sender, EventArgs e) -{ - if (this.AVGRadialGauge1.Value >= 6f) - { - this.radialGaugeNeedle2.BackColor = Color.FromArgb(224, 90, 90); - this.radialGaugeNeedle2.BackColor2 = Color.FromArgb(224, 90, 90); - } - else - { - this.radialGaugeNeedle2.BackColor = Color.Black; - this.radialGaugeNeedle2.BackColor2 = Color.Black; - } -} - -private void timer_Tick(object sender, EventArgs e) -{ - if (AVGRadialGauge1.Value + step > AVGRadialGauge1.RangeEnd || AVGRadialGauge1.Value + step < AVGRadialGauge1.RangeStart) - { - step = -step; - } - AnimatedPropertySetting setting = new AnimatedPropertySetting(RadRadialGaugeElement.ValueProperty, - AVGRadialGauge1.Value, AVGRadialGauge1.Value + step, 12, 40); - setting.ApplyEasingType = RadEasingType.OutBounce; - setting.ApplyValue(AVGRadialGauge1.GaugeElement); -} - -```` -````VB.NET -Private timer As New Timer() -Private [step] As Single = 0.0F -Private Sub AdvancedExample() - Me.AVGRadialGauge1.RangeStart = 0 - Me.AVGRadialGauge1.RangeEnd = 9 - AddHandler Me.AVGRadialGauge1.ValueChanged, AddressOf AVGRadialGauge1_ValueChanged - [step] = -CSng(AVGRadialGauge1.RangeEnd - AVGRadialGauge1.RangeStart) / 10.0F - Me.RadialGaugeLabels1.LabelFormat = "#,##0.00#" - Me.RadialGaugeLabels1.LabelRadiusPercentage = 70 - Me.RadialGaugeLabels1.LabelEndVisibleRange = 5 - Me.RadialGaugeLabels2.LabelRadiusPercentage = 70 - Me.RadialGaugeLabels2.LabelFormat = "#,##0.00#" - Me.RadialGaugeLabels2.LabelStartVisibleRange = 6 - Me.RadialGaugeNeedle1.Visibility = ElementVisibility.Collapsed - Me.RadialGaugeNeedle2.Value = 4.25F - Me.RadialGaugeNeedle2.BackColor = Color.Black - Me.RadialGaugeNeedle2.BackColor2 = Color.Black - Me.RadialGaugeNeedle2.BackLenghtPercentage = 0 - Me.RadialGaugeNeedle2.Thickness = 0.2F - Me.RadialGaugeNeedle2.BindValue = True - Dim firstCircleTick As New RadialGaugeTicks() - Me.AVGRadialGauge1.Items.Add(firstCircleTick) - firstCircleTick.TicksCount = 18 - firstCircleTick.TickStartIndexVisibleRange = 5 - firstCircleTick.TickEndIndexVisibleRange = 5 - firstCircleTick.TicksLenghtPercentage = 3 - firstCircleTick.TicksRadiusPercentage = 115 - firstCircleTick.CircleTicks = True - firstCircleTick.TickThickness = 1 - firstCircleTick.TickColor = Color.DimGray - Dim firstTick As New RadialGaugeTicks() - Me.AVGRadialGauge1.Items.Add(firstTick) - firstTick.TicksCount = 18 - firstTick.TickStartIndexVisibleRange = 5 - firstTick.TickEndIndexVisibleRange = 5 - firstTick.TicksRadiusPercentage = 103 - firstTick.CircleTicks = False - firstTick.TickThickness = 1 - firstTick.TickColor = Color.DimGray - Dim secondCircleTick As New RadialGaugeTicks() - Me.AVGRadialGauge1.Items.Add(secondCircleTick) - secondCircleTick.TicksCount = 18 - secondCircleTick.TickStartIndexVisibleRange = 9 - secondCircleTick.TickEndIndexVisibleRange = 9 - secondCircleTick.TicksLenghtPercentage = 3 - secondCircleTick.TicksRadiusPercentage = 115 - secondCircleTick.CircleTicks = True - secondCircleTick.TickThickness = 1 - secondCircleTick.TickColor = Color.DimGray - Dim secondTick As New RadialGaugeTicks() - Me.AVGRadialGauge1.Items.Add(secondTick) - secondTick.TicksCount = 18 - secondTick.TickStartIndexVisibleRange = 9 - secondTick.TickEndIndexVisibleRange = 9 - secondTick.TicksRadiusPercentage = 103 - secondTick.CircleTicks = False - secondTick.TickThickness = 1 - secondTick.TickColor = Color.DimGray - timer.Interval = 1000 - AddHandler timer.Tick, AddressOf timer_Tick - timer.Start() -End Sub -Private Sub AVGRadialGauge1_ValueChanged(sender As Object, e As EventArgs) - If Me.AVGRadialGauge1.Value >= 6.0F Then - Me.RadialGaugeNeedle2.BackColor = Color.FromArgb(224, 90, 90) - Me.RadialGaugeNeedle2.BackColor2 = Color.FromArgb(224, 90, 90) - Else - Me.RadialGaugeNeedle2.BackColor = Color.Black - Me.RadialGaugeNeedle2.BackColor2 = Color.Black - End If -End Sub -Private Sub timer_Tick(sender As Object, e As EventArgs) - If AVGRadialGauge1.Value + [step] > AVGRadialGauge1.RangeEnd OrElse AVGRadialGauge1.Value + [step] < AVGRadialGauge1.RangeStart Then - [step] = -[step] - End If - Dim setting As New AnimatedPropertySetting(RadRadialGaugeElement.ValueProperty, AVGRadialGauge1.Value, AVGRadialGauge1.Value + [step], 12, 40) - setting.ApplyEasingType = RadEasingType.OutBounce - setting.ApplyValue(AVGRadialGauge1.GaugeElement) -End Sub - -```` - -{{endregion}} - + + + ## Clock Example The following code snippet is purposed to demonstrate how to create a simple clock. For this purpose we will add the necessary clock's elements to the RadRadialGauge.__Items__ collection. Afterwards, we need to drag a timer from the Toolbox and drop it onto the form. Set the timer's __Interval__ property to *1000*. Subscribe to its __Tick__ event where we should update the time. @@ -330,140 +84,8 @@ The following code snippet is purposed to demonstrate how to create a simple clo #### Clock -{{source=..\SamplesCS\Gauges\RadialGauge\RadialGaugeGettingStarted.cs region=Clock}} -{{source=..\SamplesVB\Gauges\RadialGauge\RadialGaugeGettingStarted.vb region=Clock}} - -````C# - -RadialGaugeNeedle hoursNeedle ; -RadialGaugeNeedle minutesNeedle; -RadialGaugeNeedle secondsNeedle; - -private void RadialGaugeGettingStarted_Load(object sender, EventArgs e) -{ - RadialGaugeLabels hoursLabels = new RadialGaugeLabels(); - RadialGaugeTicks minutesTicks = new RadialGaugeTicks(); - RadialGaugeTicks bigTicks = new RadialGaugeTicks(); - - hoursNeedle = new RadialGaugeNeedle(); - minutesNeedle = new RadialGaugeNeedle(); - secondsNeedle = new RadialGaugeNeedle(); - - RadialGaugeArc arc = new RadialGaugeArc(); - - hoursLabels.LabelFontSize = 4; - bigTicks.TickColor = Color.DimGray; - bigTicks.TickThickness = 1f; - bigTicks.TicksCount = 12; - bigTicks.TicksLenghtPercentage = 20; - bigTicks.TicksRadiusPercentage = 80; - - minutesTicks.TicksCount = 60; - minutesTicks.TickColor = Color.Black; - minutesTicks.TickThickness = 0.5f; - - hoursNeedle.LenghtPercentage = 40; - hoursNeedle.BackColor = Color.Gray; - hoursNeedle.BackColor2 = Color.Gray; - minutesNeedle.LenghtPercentage = 60; - minutesNeedle.BackColor = Color.Gray; - minutesNeedle.BackColor2 = Color.Gray; - secondsNeedle.LenghtPercentage = 80; - secondsNeedle.BackColor = Color.CadetBlue; - secondsNeedle.BackColor2 = Color.CadetBlue; - - arc.Width = 0.5f; - arc.BackColor = Color.Gray; - - radRadialGauge1.StartAngle = 270; - radRadialGauge1.SweepAngle = 360; - radRadialGauge1.RangeStart = 0; - radRadialGauge1.RangeEnd = 12; - hoursLabels.LabelStartVisibleRange = 1; - hoursLabels.LabelFormat = "N0"; - hoursLabels.LabelsCount = 12; - - radRadialGauge1.Items.Add(hoursLabels); - radRadialGauge1.Items.Add(minutesTicks); - radRadialGauge1.Items.Add(bigTicks); - - radRadialGauge1.Items.Add(hoursNeedle); - radRadialGauge1.Items.Add(minutesNeedle); - radRadialGauge1.Items.Add(secondsNeedle); - - radRadialGauge1.Items.Add(arc); - - this.timer1.Start(); -} - -private void timer1_Tick(object sender, EventArgs e) -{ - float angleHour = (float)(DateTime.Now.Hour * 30 + DateTime.Now.Minute * 0.5); - hoursNeedle.Value = angleHour % 360 / 360 * 12 ; - minutesNeedle.Value = 12 * ((float)DateTime.Now.Minute / 60); - secondsNeedle.Value = 12 * ((float)DateTime.Now.Second / 60); -} - -```` -````VB.NET -Private hoursNeedle As RadialGaugeNeedle -Private minutesNeedle As RadialGaugeNeedle -Private secondsNeedle As RadialGaugeNeedle -Private Sub RadialGaugeGettingStarted_Load(sender As Object, e As EventArgs) Handles MyBase.Load - Dim hoursLabels As New RadialGaugeLabels() - Dim minutesTicks As New RadialGaugeTicks() - Dim bigTicks As New RadialGaugeTicks() - - hoursNeedle = New RadialGaugeNeedle() - minutesNeedle = New RadialGaugeNeedle() - secondsNeedle = New RadialGaugeNeedle() - Dim arc As New RadialGaugeArc() - hoursLabels.LabelFontSize = 4 - bigTicks.TickColor = Color.DimGray - bigTicks.TickThickness = 1.0F - bigTicks.TicksCount = 12 - bigTicks.TicksLenghtPercentage = 20 - bigTicks.TicksRadiusPercentage = 80 - minutesTicks.TicksCount = 60 - minutesTicks.TickColor = Color.Black - minutesTicks.TickThickness = 0.5F - hoursNeedle.LenghtPercentage = 40 - hoursNeedle.BackColor = Color.Gray - hoursNeedle.BackColor2 = Color.Gray - minutesNeedle.LenghtPercentage = 60 - minutesNeedle.BackColor = Color.Gray - minutesNeedle.BackColor2 = Color.Gray - secondsNeedle.LenghtPercentage = 80 - secondsNeedle.BackColor = Color.CadetBlue - secondsNeedle.BackColor2 = Color.CadetBlue - arc.Width = 0.5F - arc.BackColor = Color.Gray - radRadialGauge1.StartAngle = 270 - radRadialGauge1.SweepAngle = 360 - radRadialGauge1.RangeStart = 0 - radRadialGauge1.RangeEnd = 12 - hoursLabels.LabelStartVisibleRange = 1 - hoursLabels.LabelFormat = "N0" - hoursLabels.LabelsCount = 12 - radRadialGauge1.Items.Add(hoursLabels) - radRadialGauge1.Items.Add(minutesTicks) - radRadialGauge1.Items.Add(bigTicks) - radRadialGauge1.Items.Add(hoursNeedle) - radRadialGauge1.Items.Add(minutesNeedle) - radRadialGauge1.Items.Add(secondsNeedle) - radRadialGauge1.Items.Add(arc) - Me.Timer1.Start() -End Sub -Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick - Dim angleHour As Single = CSng(DateTime.Now.Hour * 30 + DateTime.Now.Minute * 0.5) - hoursNeedle.Value = (angleHour Mod 360) / 360 * 12 - minutesNeedle.Value = 12 * (CSng(DateTime.Now.Minute) / 60) - secondsNeedle.Value = 12 * (CSng(DateTime.Now.Second) / 60) -End Sub - -```` - -{{endregion}} + + # See Also diff --git a/controls/gauges/radialgauge/properties-and-events.md b/controls/gauges/radialgauge/properties-and-events.md index 6fa7a0947..e33ef09be 100644 --- a/controls/gauges/radialgauge/properties-and-events.md +++ b/controls/gauges/radialgauge/properties-and-events.md @@ -37,88 +37,8 @@ The __ValueChanged__ event fires when the value is modified. You can perform cha #### Change Value -{{source=..\SamplesCS\Gauges\RadialGauge\RadialGaugePropertiesAndEvents.cs region=ValueChanged}} -{{source=..\SamplesVB\Gauges\RadialGauge\RadialGaugePropertiesAndEvents.vb region=ValueChanged}} - -````C# - -Timer timer1 = new Timer(); -float step = 0f; - -public RadialGaugePropertiesAndEvents() -{ - InitializeComponent(); - - step = -(float)(radRadialGauge1.RangeEnd - radRadialGauge1.RangeStart) / 10f; - this.radRadialGauge1.ValueChanged += radRadialGauge1_ValueChanged; - timer1.Interval = 1000; - timer1.Tick += timer1_Tick; - timer1.Start(); -} - -private void radRadialGauge1_ValueChanged(object sender, EventArgs e) -{ - if (this.radRadialGauge1.Value >= 120) - { - this.radialGaugeNeedle1.BackColor = Color.FromArgb(224, 90, 90); - this.radialGaugeNeedle1.BackColor2 = Color.FromArgb(224, 90, 90); - this.radialGaugeSingleLabel1.ForeColor = Color.FromArgb(224, 90, 90); - } - else - { - this.radialGaugeNeedle1.BackColor = Color.Black; - this.radialGaugeNeedle1.BackColor2 = Color.Black; - this.radialGaugeSingleLabel1.ForeColor = Color.Black; - } -} - -private void timer1_Tick(object sender, EventArgs e) -{ - if (radRadialGauge1.Value + step > radRadialGauge1.RangeEnd || radRadialGauge1.Value + step < radRadialGauge1.RangeStart) - { - step = -step; - } - AnimatedPropertySetting setting = new AnimatedPropertySetting(RadRadialGaugeElement.ValueProperty, - this.radRadialGauge1.Value, radRadialGauge1.Value + step, 12, 40); - setting.ApplyEasingType = RadEasingType.OutBounce; - setting.ApplyValue(radRadialGauge1.GaugeElement); -} - -```` -````VB.NET -Private timer1 As New Timer() -Private [step] As Single = 0.0F -Public Sub New() - InitializeComponent() - [step] = -CSng(RadRadialGauge1.RangeEnd - RadRadialGauge1.RangeStart) / 10.0F - AddHandler Me.RadRadialGauge1.ValueChanged, AddressOf radRadialGauge1_ValueChanged - timer1.Interval = 1000 - AddHandler timer1.Tick, AddressOf timer1_Tick - timer1.Start() -End Sub -Private Sub radRadialGauge1_ValueChanged(sender As Object, e As EventArgs) - If Me.RadRadialGauge1.Value >= 120 Then - Me.RadialGaugeNeedle1.BackColor = Color.FromArgb(224, 90, 90) - Me.RadialGaugeNeedle1.BackColor2 = Color.FromArgb(224, 90, 90) - Me.RadialGaugeSingleLabel1.ForeColor = Color.FromArgb(224, 90, 90) - Else - Me.RadialGaugeNeedle1.BackColor = Color.Black - Me.RadialGaugeNeedle1.BackColor2 = Color.Black - Me.RadialGaugeSingleLabel1.ForeColor = Color.Black - End If -End Sub -Private Sub timer1_Tick(sender As Object, e As EventArgs) - If RadRadialGauge1.Value + [step] > RadRadialGauge1.RangeEnd OrElse RadRadialGauge1.Value + [step] < RadRadialGauge1.RangeStart Then - [step] = -[step] - End If - Dim setting As New AnimatedPropertySetting(RadRadialGaugeElement.ValueProperty, Me.RadRadialGauge1.Value, RadRadialGauge1.Value + [step], 12, 40) - setting.ApplyEasingType = RadEasingType.OutBounce - setting.ApplyValue(RadRadialGauge1.GaugeElement) -End Sub - -```` - -{{endregion}} + + # See Also diff --git a/controls/gauges/radialgauge/save-and-load-layout.md b/controls/gauges/radialgauge/save-and-load-layout.md index b0a3f9ad8..6e85c2dd4 100644 --- a/controls/gauges/radialgauge/save-and-load-layout.md +++ b/controls/gauges/radialgauge/save-and-load-layout.md @@ -26,27 +26,8 @@ You can save/load the layout in code as well. #### Save/Load Layout -{{source=..\SamplesCS\Gauges\RadialGauge\RadialGaugePropertiesAndEvents.cs region=SaveLoadLayout}} -{{source=..\SamplesVB\Gauges\RadialGauge\RadialGaugePropertiesAndEvents.vb region=SaveLoadLayout}} -````C# -private void SaveLoadLayout() -{ - this.radRadialGauge1.SaveLayout(@"..\..\gauge-layout.xml"); - this.radRadialGauge1.LoadLayout(@"..\..\gauge-layout.xml"); -} - -```` -````VB.NET -Private Sub SaveLoadLayout() - Me.RadRadialGauge1.SaveLayout("..\..\gauge-layout.xml") - Me.RadRadialGauge1.LoadLayout("..\..\gauge-layout.xml") -End Sub - -```` - - - -{{endregion}} + + # See Also diff --git a/controls/gridview/features/caption.md b/controls/gridview/features/caption.md index b4b5b535d..e7729a2a6 100644 --- a/controls/gridview/features/caption.md +++ b/controls/gridview/features/caption.md @@ -18,23 +18,8 @@ Since R3 2018 SP1 RadGridView supports displaying a Title(Caption). By default t To show the title just set the __TitleText__ property. In addition the following snippet shows how you can set the font and the ForeColor. -{{source=..\SamplesCS\GridView\GridTitle\GridTitle.cs region=ShowTitle}} -{{source=..\SamplesVB\GridView\GridTitle\GridTitle.vb region=ShowTitle}} - -````C# -radGridView1.TitleText = "Customers"; -radGridView1.GridViewElement.TitleLabelElement.ForeColor = Color.DarkRed; -radGridView1.GridViewElement.TitleLabelElement.Font = new Font("Consolas", 12, FontStyle.Bold); - -```` -````VB.NET -radGridView1.TitleText = "Customers" -radGridView1.GridViewElement.TitleLabelElement.ForeColor = Color.DarkRed -radGridView1.GridViewElement.TitleLabelElement.Font = New Font("Consolas", 12, FontStyle.Bold) - -```` - -{{endregion}} + + >note If the **TitleText** is set to an empty string, the GridViewElement.**TitleLabelElement** is collapsed. Otherwise, it is always shown and if you need to hide it, it is necessary to manage the GridViewElement.TitleLabelElement.**Visibility** property. @@ -43,23 +28,8 @@ radGridView1.GridViewElement.TitleLabelElement.Font = New Font("Consolas", 12, F To change the position you can use the __TitlePosition__ property. In addition you can set the __FlipText__ property. The __TitleLabelElement__ property allows you to access the actual label element. This element is a [LightVisualElement]({%slug winforms/telerik-presentation-framework/primitives/lightvisualelement%}) which is capable of displaying text and image. -{{source=..\SamplesCS\GridView\GridTitle\GridTitle.cs region=Position}} -{{source=..\SamplesVB\GridView\GridTitle\GridTitle.vb region=Position}} -````C# -radGridView1.TitlePosition = Telerik.WinControls.Layouts.Dock.Left; -radGridView1.GridViewElement.TitleLabelElement.TextOrientation = Orientation.Vertical; -radGridView1.GridViewElement.TitleLabelElement.FlipText = true; - -```` -````VB.NET -radGridView1.TitlePosition = Telerik.WinControls.Layouts.Dock.Left -radGridView1.GridViewElement.TitleLabelElement.TextOrientation = Orientation.Vertical -radGridView1.GridViewElement.TitleLabelElement.FlipText = True - -```` - -{{endregion}} - + + # See Also diff --git a/controls/gridview/features/context-menus/conditional-custom-context-menus.md b/controls/gridview/features/context-menus/conditional-custom-context-menus.md index c47bb7551..449b60317 100644 --- a/controls/gridview/features/context-menus/conditional-custom-context-menus.md +++ b/controls/gridview/features/context-menus/conditional-custom-context-menus.md @@ -22,89 +22,8 @@ In this example, two different context menus are created and attached to cells i Start by creating the context menus, initializing its items, and subscribing to the context menu events that you want to handle. Then in the ContextMenuOpening event handler check the context menu provider and assign the corresponding context menu. -{{source=..\SamplesCS\GridView\ContextMenus\ConditionalCustomContextMenus.cs region=creatingAndChangingContextMenus}} -{{source=..\SamplesVB\GridView\ContextMenus\ConditionalCustomContextMenus.vb region=creatingAndChangingContextMenus}} - -````C# -private RadContextMenu firstContextMenu = new RadContextMenu(); -private RadContextMenu secondContextMenu = new RadContextMenu(); -void Form1_Load(object sender, EventArgs e) -{ - radGridView1.MasterTemplate.BestFitColumns(); - RadMenuItem firstContextMenuItem1 = new RadMenuItem("First menu - Item 1"); - firstContextMenuItem1.ForeColor = Color.Red; - firstContextMenuItem1.Click += new EventHandler(firstContextMenuItem1_Click); - RadMenuItem firstContextMenuItem2 = new RadMenuItem("First menu - Item 2"); - firstContextMenuItem2.Click += new EventHandler(firstContextMenuItem2_Click); - firstContextMenu.Items.Add(firstContextMenuItem1); - firstContextMenu.Items.Add(firstContextMenuItem2); - RadMenuItem secondContextMenuItem1 = new RadMenuItem("Second menu - Item 1"); - secondContextMenuItem1.ForeColor = Color.LightBlue; - secondContextMenuItem1.Click += new EventHandler(secondContextMenuItem1_Click); - RadMenuItem secondContextMenuItem2 = new RadMenuItem("Second menu - Item 2"); - secondContextMenuItem2.Click += new EventHandler(secondContextMenuItem2_Click); - secondContextMenu.Items.Add(secondContextMenuItem1); - secondContextMenu.Items.Add(secondContextMenuItem2); -} -void radGridView1_ContextMenuOpening(object sender, ContextMenuOpeningEventArgs e) -{ - GridDataCellElement cell = e.ContextMenuProvider as GridDataCellElement; - if (cell == null) - { - return; - } - //set the first context menu to be displayed for cells in the second column - if (cell.ColumnIndex == 1) - { - e.ContextMenu = firstContextMenu.DropDown; - } - //set the second context menu to be displayed for cells in the third column - else if (cell.ColumnIndex == 2) - { - e.ContextMenu = secondContextMenu.DropDown; - } -} - -```` -````VB.NET -Private firstContextMenu As New RadContextMenu() -Private secondContextMenu As New RadContextMenu() -Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load - RadGridView1.MasterTemplate.BestFitColumns() - Dim firstContextMenuItem1 As New RadMenuItem("First menu - Item 1") - firstContextMenuItem1.ForeColor = Color.Red - AddHandler firstContextMenuItem1.Click, AddressOf firstContextMenuItem1_Click - Dim firstContextMenuItem2 As New RadMenuItem("First menu - Item 2") - AddHandler firstContextMenuItem2.Click, AddressOf firstContextMenuItem2_Click - firstContextMenu.Items.Add(firstContextMenuItem1) - firstContextMenu.Items.Add(firstContextMenuItem2) - Dim secondContextMenuItem1 As New RadMenuItem("Second menu - Item 1") - secondContextMenuItem1.ForeColor = Color.LightBlue - AddHandler secondContextMenuItem1.Click, AddressOf secondContextMenuItem1_Click - Dim secondContextMenuItem2 As New RadMenuItem("Second menu - Item 2") - AddHandler secondContextMenuItem2.Click, AddressOf secondContextMenuItem2_Click - secondContextMenu.Items.Add(secondContextMenuItem1) - secondContextMenu.Items.Add(secondContextMenuItem2) -End Sub -Private Sub RadGridView1_ContextMenuOpening(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.ContextMenuOpeningEventArgs) Handles RadGridView1.ContextMenuOpening - Dim cell As GridDataCellElement = TryCast(e.ContextMenuProvider, GridDataCellElement) - If cell Is Nothing Then - Return - End If - 'set the first context menu to be displayed for cells in the second column - If cell.ColumnIndex = 1 Then - e.ContextMenu = firstContextMenu.DropDown - ElseIf cell.ColumnIndex = 2 Then - 'set the second context menu to be displayed for cells in the third column - e.ContextMenu = secondContextMenu.DropDown - End If -End Sub - -```` - -{{endregion}} - - + + # See Also * [Custom Context Menus]({%slug winforms/gridview/context-menus/custom-context-menus%}) diff --git a/controls/gridview/features/context-menus/custom-context-menus.md b/controls/gridview/features/context-menus/custom-context-menus.md index f4c093576..5ae00159c 100644 --- a/controls/gridview/features/context-menus/custom-context-menus.md +++ b/controls/gridview/features/context-menus/custom-context-menus.md @@ -21,63 +21,15 @@ Start by creating the context menu, initializing its items, and subscribing for #### Setup the Context Menu -{{source=..\SamplesCS\GridView\ContextMenus\CustomContextMenus.cs region=creatingContextMenu}} -{{source=..\SamplesVB\GridView\ContextMenus\CustomContextMenus.vb region=creatingContextMenu}} - -````C# -private RadContextMenu contextMenu; -private void Form1_Load(object sender, EventArgs e) -{ - contextMenu = new RadContextMenu(); - RadMenuItem menuItem1 = new RadMenuItem("Item 1"); - menuItem1.ForeColor = Color.Red; - menuItem1.Click += new EventHandler(menuItem1_Click); - RadMenuItem menuItem2 = new RadMenuItem("Item 2"); - menuItem2.Click += new EventHandler(menuItem2_Click); - contextMenu.Items.Add(menuItem1); - contextMenu.Items.Add(menuItem2); -} - -```` -````VB.NET -Private contextMenu1 As RadContextMenu -Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load - contextMenu1 = New RadContextMenu() - Dim menuItem1 As New RadMenuItem("Item 1") - menuItem1.ForeColor = Color.Red - AddHandler menuItem1.Click, AddressOf rmi1_Click - Dim menuItem2 As New RadMenuItem("Item 2") - AddHandler menuItem2.Click, AddressOf rmi2_Click - contextMenu1.Items.Add(menuItem1) - contextMenu1.Items.Add(menuItem2) -End Sub - -```` - -{{endregion}} + + Once the menu object has been initialized and populated with menu items, it is ready to be attached to the __RadGridView__. To do that, subscribe to the __ContextMenuOpening__ event and set the context menu to be displayed: #### ContextMenuOpening Event -{{source=..\SamplesCS\GridView\ContextMenus\CustomContextMenus.cs region=changeTheContextMenu}} -{{source=..\SamplesVB\GridView\ContextMenus\CustomContextMenus.vb region=changeTheContextMenu}} - -````C# -void radGridView1_ContextMenuOpening(object sender, ContextMenuOpeningEventArgs e) -{ - e.ContextMenu = contextMenu.DropDown; -} - -```` -````VB.NET -Private Sub RadGridView1_ContextMenuOpening(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.ContextMenuOpeningEventArgs) Handles RadGridView1.ContextMenuOpening - e.ContextMenu = contextMenu1.DropDown -End Sub - -```` - -{{endregion}} + + # See Also diff --git a/controls/gridview/features/context-menus/modifying-the-default-context-menu.md b/controls/gridview/features/context-menus/modifying-the-default-context-menu.md index 2abd10f3c..2e89cfd4a 100644 --- a/controls/gridview/features/context-menus/modifying-the-default-context-menu.md +++ b/controls/gridview/features/context-menus/modifying-the-default-context-menu.md @@ -17,42 +17,8 @@ The default __RadGridView context__ menu can be customized in the ContextMenuOp In order to remove an item, you need to make a loop iterating the __e.ContextMenu.Items__ and check if the __e.ContextMenu.Items[index].Text__ is equal to the text of the menu item that you want to hide. If so, just set the __Visibility__ of the menu item to *Collapsed*: -{{source=..\SamplesCS\GridView\ContextMenus\ModifingTheDefaultContextMenu.cs region=removeContextMenuItem}} -{{source=..\SamplesVB\GridView\ContextMenus\ModifingTheDefaultContextMenu.vb region=removeContextMenuItem}} - -````C# -void radGridView1_ContextMenuOpening(object sender, Telerik.WinControls.UI.ContextMenuOpeningEventArgs e) -{ - for (int i = 0; i < e.ContextMenu.Items.Count; i++) - { - if (e.ContextMenu.Items[i].Text == "Conditional Formatting") - { - // hide the Conditional Formatting option from the header row context menu - e.ContextMenu.Items[i].Visibility = Telerik.WinControls.ElementVisibility.Collapsed; - // hide the separator below the CF option - e.ContextMenu.Items[i + 1].Visibility = Telerik.WinControls.ElementVisibility.Collapsed; - } - } -} - -```` -````VB.NET -Private Sub RadGridView1_ContextMenuOpening(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.ContextMenuOpeningEventArgs) Handles RadGridView1.ContextMenuOpening - Dim i As Integer = 0 - Do While i < e.ContextMenu.Items.Count - If e.ContextMenu.Items(i).Text = "Conditional Formatting" Then - ' hide the Conditional Formatting option from the header row context menu - e.ContextMenu.Items(i).Visibility = Telerik.WinControls.ElementVisibility.Collapsed - ' hide the separator below the CF option - e.ContextMenu.Items(i + 1).Visibility = Telerik.WinControls.ElementVisibility.Collapsed - End If - i += 1 - Loop -End Sub - -```` - -{{endregion}} + + >note If your grid is localized you can get the item text from the localization provider - `if (e.ContextMenu.Items[i].Text == RadGridLocalizationProvider.CurrentProvider.GetLocalizedString(RadGridStringId.ConditionalFormattingMenuItem))' @@ -60,32 +26,8 @@ End Sub In order to add custom menu items to the default context menu, *you should create menu item instances in the ContextMenuOpening event handler* and add them to the __e.ContextMenu.Items:__ -{{source=..\SamplesCS\GridView\ContextMenus\ModifingTheDefaultContextMenu.cs region=addContextMenuOption}} -{{source=..\SamplesVB\GridView\ContextMenus\ModifingTheDefaultContextMenu.vb region=addContextMenuOption}} - -````C# -void radGridView1_ContextMenuOpening1(object sender, Telerik.WinControls.UI.ContextMenuOpeningEventArgs e) -{ - RadMenuItem customMenuItem = new RadMenuItem(); - customMenuItem.Text = "Custom Data Operation"; - RadMenuSeparatorItem separator = new RadMenuSeparatorItem(); - e.ContextMenu.Items.Add(separator); - e.ContextMenu.Items.Add(customMenuItem); -} - -```` -````VB.NET -Private Sub RadGridView1_ContextMenuOpening1(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.ContextMenuOpeningEventArgs) Handles RadGridView1.ContextMenuOpening - Dim customMenuItem As RadMenuItem = New RadMenuItem() - customMenuItem.Text = "Custom Data Operation" - Dim separator As RadMenuSeparatorItem = New RadMenuSeparatorItem() - e.ContextMenu.Items.Add(separator) - e.ContextMenu.Items.Add(customMenuItem) -End Sub - -```` - -{{endregion}} + + >note You can subscribe to the **Click** event of the newly added menu items and thus execute the desired action when a **RadMenuItem** is clicked. diff --git a/controls/gridview/features/copy-paste-cut.md b/controls/gridview/features/copy-paste-cut.md index 95b95ed8b..189b7775f 100644 --- a/controls/gridview/features/copy-paste-cut.md +++ b/controls/gridview/features/copy-paste-cut.md @@ -33,30 +33,8 @@ Copying is a pretty simple operation. After cell/row is selected, right click ov __RadGridView__ introduces __Copying__ event which occurs when the grid has prepared appropriate data formats that represent the copy selection. This event is fired once for each supported format:*Text*, *HTML*, *CommaSeparatedValue*. You can cancel this event if the data is not allowed to be stored to Clipboard in a specific format, e.g. HTML format: -{{source=..\SamplesCS\GridView\CopyPasteBehavior\CopyPasteForm.cs region=Copying}} -{{source=..\SamplesVB\GridView\CopyPasteBehavior\CopyPasteForm.vb region=Copying}} - -````C# -private void radGridView1_Copying(object sender, GridViewClipboardEventArgs e) -{ - if (e.Format == DataFormats.Html) - { - e.Cancel = true; - } -} - -```` -````VB.NET -Private Sub radGridView1_Copying(sender As Object, e As GridViewClipboardEventArgs) - If e.Format = DataFormats.Html Then - e.Cancel = True - End If -End Sub - -```` - -{{endregion}} - + + >note Additionally, you can use the __RadGridView__.__Copy__ method in order to perform programmatically copy functionality. > @@ -67,31 +45,8 @@ The __CopyingCellClipboardContent__ event is fired before each cell is copied. I #### Copy only the time from a DateTime value. -{{source=..\SamplesCS\GridView\CopyPasteBehavior\CopyPasteForm.cs region=CopyEvent}} -{{source=..\SamplesVB\GridView\CopyPasteBehavior\CopyPasteForm.vb region=CopyEvent}} -````C# -private void RadGridView1_CopyingCellClipboardContent(object sender, GridViewCellValueEventArgs e) -{ - if (e.Value is DateTime) - { - var value = (DateTime)e.Value; - e.Value = value.ToShortTimeString(); - } -} - -```` -````VB.NET -Private Sub RadGridView1_CopyingCellClipboardContent(ByVal sender As Object, ByVal e As GridViewCellValueEventArgs) - If TypeOf e.Value Is Date Then - Dim value = CDate(e.Value) - e.Value = value.ToShortTimeString() - End If -End Sub - -```` - -{{endregion}} - + + ## Pasting @@ -113,36 +68,8 @@ RadGridView.__Pasting__ event is appropriate for modifying the Clipboard data be The following example demonstrates how to capitalize the copied string before inserting it in the grid: -{{source=..\SamplesCS\GridView\CopyPasteBehavior\CopyPasteForm.cs region=Pasting}} -{{source=..\SamplesVB\GridView\CopyPasteBehavior\CopyPasteForm.vb region=Pasting}} - -````C# -private void radGridView1_Pasting(object sender, GridViewClipboardEventArgs e) -{ - if (Clipboard.ContainsData(DataFormats.Text)) - { - string data = Clipboard.GetData(DataFormats.Text).ToString(); - if (data != string.Empty) - { - Clipboard.SetData(DataFormats.Text, data.ToUpper()); - } - } -} - -```` -````VB.NET -Private Sub radGridView1_Pasting(sender As Object, e As GridViewClipboardEventArgs) - If Clipboard.ContainsData(DataFormats.Text) Then - Dim data As String = Clipboard.GetData(DataFormats.Text).ToString() - If data <> String.Empty Then - Clipboard.SetData(DataFormats.Text, data.ToUpper()) - End If - End If -End Sub - -```` - -{{endregion}} + + You can cancel this event as well in order to prevent pasting data in some cases. @@ -155,40 +82,8 @@ This event will be fired before the data is pasted in each cell. It allows you c #### Check the values when pasting -{{source=..\SamplesCS\GridView\CopyPasteBehavior\CopyPasteForm.cs region=PasteEvent}} -{{source=..\SamplesVB\GridView\CopyPasteBehavior\CopyPasteForm.vb region=PasteEvent}} -````C# -private void RadGridView1_PastingCellClipboardContent(object sender, GridViewCellValueEventArgs e) -{ - if (e.Column.Name == "Date") - { - DateTime date; - var valid = DateTime.TryParse(e.Value.ToString(), out date); - if (!valid) - { - RadMessageBox.Show("Invalid Date format pasted in the Date column"); - e.Value = DateTime.Now; - } - } -} - -```` -````VB.NET -Private Sub RadGridView1_PastingCellClipboardContent(ByVal sender As Object, ByVal e As GridViewCellValueEventArgs) - If e.Column.Name = "Date" Then - Dim [date] As Date = Nothing - Dim valid = Date.TryParse(e.Value.ToString(), [date]) - If Not valid Then - RadMessageBox.Show("Invalid Date format pasted in the Date column") - e.Value = Date.Now - End If - End If -End Sub - -```` - - -{{endregion}} + + ## Key Combinations diff --git a/controls/gridview/features/drag-and-drop/radgridviewdragdropservice.md b/controls/gridview/features/drag-and-drop/radgridviewdragdropservice.md index 108891a82..de3edc0a7 100644 --- a/controls/gridview/features/drag-and-drop/radgridviewdragdropservice.md +++ b/controls/gridview/features/drag-and-drop/radgridviewdragdropservice.md @@ -46,60 +46,13 @@ As a descendant of [RadDragDropService]({%slug winforms/telerik-presentation-fra 1\. Create a class that inherits **RadGridViewDragDropService** and override its **Name** property: -{{source=..\SamplesCS\GridView\Rows\DragAndDropRadGridForm1.cs region=CustomService}} -{{source=..\SamplesVB\GridView\Rows\DragAndDropRadGridForm1.vb region=CustomService}} - -````C# -public class CustomDragDropService : RadGridViewDragDropService -{ - public CustomDragDropService(RadGridViewElement gridViewElement) - : base(gridViewElement) - { - } - public override string Name - { - get - { - return typeof(RadGridViewDragDropService).Name; - } - } -} - -```` -````VB.NET -Public Class CustomDragDropService - Inherits RadGridViewDragDropService - Public Sub New(gridViewElement As RadGridViewElement) - MyBase.New(gridViewElement) - End Sub - Public Overrides ReadOnly Property Name() As String - Get - Return GetType(RadGridViewDragDropService).Name - End Get - End Property -End Class - -```` - -{{endregion}} + + 2\. After you have already overridden the desired methods in order to achieve the expected behavior register the custom service to **RadGridView**: -{{source=..\SamplesCS\GridView\Rows\DragAndDropRadGridForm1.cs region=RegisterService}} -{{source=..\SamplesVB\GridView\Rows\DragAndDropRadGridForm1.vb region=RegisterService}} - -````C# -CustomDragDropService customService = new CustomDragDropService(radGridView1.GridViewElement); -radGridView1.GridViewElement.RegisterService(customService); - -```` -````VB.NET -Dim customService As New CustomDragDropService(radGridView1.GridViewElement) -radGridView1.GridViewElement.RegisterService(customService) - -```` - -{{endregion}} + + # See Also diff --git a/controls/gridview/features/drag-and-drop/rows-reordering-in-self-reference-hierarchy.md b/controls/gridview/features/drag-and-drop/rows-reordering-in-self-reference-hierarchy.md index 29afaba37..bec4585e1 100644 --- a/controls/gridview/features/drag-and-drop/rows-reordering-in-self-reference-hierarchy.md +++ b/controls/gridview/features/drag-and-drop/rows-reordering-in-self-reference-hierarchy.md @@ -18,216 +18,26 @@ Consider the case you have a bound **RadGridView** with self-reference hierarchi 1\. Populate **RadGridView** with self-reference hierarchical data: -{{source=..\SamplesCS\GridView\DragDrop\RowsReorderInSelfReference.cs region=FillData}} -{{source=..\SamplesVB\GridView\DragDrop\RowsReorderInSelfReference.vb region=FillData}} - -````C# -DataTable dt; -private void RadForm_Load(object sender, EventArgs e) -{ - dt = new DataTable(); - dt.Columns.Add("Id"); - dt.Columns.Add("Name"); - dt.Columns.Add("ParentId"); - FillData(); -} -private void FillData() -{ - this.radGridView1.Relations.AddSelfReference(this.radGridView1.MasterTemplate, "Id", "ParentId"); - for (int i = 1; i <= 3; i++) - { - dt.Rows.Add(i, "Parent" + i, 0); - for (int j = 4; j <= 9; j++) - { - int childIndex = ((i - 1) * 9 + j + i); - dt.Rows.Add(childIndex, "Child" + childIndex, i); - } - } - this.radGridView1.DataSource = dt; -} - -```` -````VB.NET -Private dt As DataTable -Private Sub RadForm_Load(ByVal sender As Object, ByVal e As EventArgs) - dt = New DataTable() - dt.Columns.Add("Id") - dt.Columns.Add("Name") - dt.Columns.Add("ParentId") - FillData() -End Sub -Private Sub FillData() - Me.radGridView1.Relations.AddSelfReference(Me.radGridView1.MasterTemplate, "Id", "ParentId") - For i As Integer = 1 To 3 - dt.Rows.Add(i, "Parent" & i, 0) - For j As Integer = 4 To 9 - Dim childIndex As Integer = ((i - 1) * 9 + j + i) - dt.Rows.Add(childIndex, "Child" & childIndex, i) - Next - Next - Me.radGridView1.DataSource = dt -End Sub - -```` - -{{endregion}} + + 2\. Register a custom [GridHierarchyRowBehavior]({%slug winforms/gridview/rows/row-behaviors%}) which starts the [RadGridViewDragDropService]({%slug winforms/gridview/radgridviewdragdropservice%}) when you click with the left mouse button: #### Register the custom row behavior -{{source=..\SamplesCS\GridView\DragDrop\RowsReorderInSelfReference.cs region=RegisterRowBehavior}} -{{source=..\SamplesVB\GridView\DragDrop\RowsReorderInSelfReference.vb region=RegisterRowBehavior}} - -````C# -BaseGridBehavior gridBehavior = this.radGridView1.GridBehavior as BaseGridBehavior; -gridBehavior.UnregisterBehavior(typeof(GridViewHierarchyRowInfo)); -gridBehavior.RegisterBehavior(typeof(GridViewHierarchyRowInfo), new RowSelectionGridBehavior()); - -```` -````VB.NET -Dim gridBehavior As BaseGridBehavior = TryCast(Me.radGridView1.GridBehavior, BaseGridBehavior) -gridBehavior.UnregisterBehavior(GetType(GridViewHierarchyRowInfo)) -gridBehavior.RegisterBehavior(GetType(GridViewHierarchyRowInfo), New RowSelectionGridBehavior()) - -```` - -{{endregion}} + + Override the **OnMouseDownLeft** method of the **GridHierarchyRowBehavior** and start the service: -{{source=..\SamplesCS\GridView\DragDrop\RowsReorderInSelfReference.cs region=StartService}} -{{source=..\SamplesVB\GridView\DragDrop\RowsReorderInSelfReference.vb region=StartService}} - -````C# -public class RowSelectionGridBehavior : GridHierarchyRowBehavior -{ - protected override bool OnMouseDownLeft(MouseEventArgs e) - { - GridDataRowElement row = this.GetRowAtPoint(e.Location) as GridDataRowElement; - if (row != null) - { - RadGridViewDragDropService svc = this.GridViewElement.GetService(); - svc.Start(row); - } - return base.OnMouseDownLeft(e); - } -} - -```` -````VB.NET -Public Class RowSelectionGridBehavior - Inherits GridHierarchyRowBehavior - Protected Overrides Function OnMouseDownLeft(ByVal e As MouseEventArgs) As Boolean - Dim row As GridDataRowElement = TryCast(Me.GetRowAtPoint(e.Location), GridDataRowElement) - If row IsNot Nothing Then - Dim svc As RadGridViewDragDropService = Me.GridViewElement.GetService(Of RadGridViewDragDropService)() - svc.Start(row) - End If - Return MyBase.OnMouseDownLeft(e) - End Function -End Class - -```` - -{{endregion}} + + 3\. Handle the RadDragDropService.**PreviewDragStart** event in order to indicate that **RadGridView** can start the drag operation. In the RadDragDropService.**PreviewDragOver** event you can control on what targets the row being dragged can be dropped on. In the **PreviewDragDrop** event you can perform the actual reordering of the data bound records. Note that it is important to update the **ParentId** field of the affected record. Thus, you will indicate the new parent record to which the dragged record belongs. -{{source=..\SamplesCS\GridView\DragDrop\RowsReorderInSelfReference.cs region=DoDragDrop}} -{{source=..\SamplesVB\GridView\DragDrop\RowsReorderInSelfReference.vb region=DoDragDrop}} - -````C# -private void SubscribeToDragDropEvents() -{ - RadDragDropService svc = this.radGridView1.GridViewElement.GetService(); - svc.PreviewDragStart += svc_PreviewDragStart; - svc.PreviewDragOver += svc_PreviewDragOver; - svc.PreviewDragDrop += svc_PreviewDragDrop; -} -private void svc_PreviewDragStart(object sender, PreviewDragStartEventArgs e) -{ - e.CanStart = true; -} -private void svc_PreviewDragOver(object sender, RadDragOverEventArgs e) -{ - GridDataRowElement draggedRowElement = e.DragInstance as GridDataRowElement; - if (draggedRowElement == null) - { - e.CanDrop = false; - return; - } - e.CanDrop = true; - draggedRowElement.Visibility = ElementVisibility.Hidden; -} -private void svc_PreviewDragDrop(object sender, RadDropEventArgs e) -{ - GridDataRowElement draggedRowElement = e.DragInstance as GridDataRowElement; - GridDataRowElement targetRowElement = e.HitTarget as GridDataRowElement; - if (draggedRowElement == null) - { - return; - } - DataRowView sourceRowView = draggedRowElement.RowInfo.DataBoundItem as DataRowView; - DataRowView targetRowView = targetRowElement.RowInfo.DataBoundItem as DataRowView; - if (!(targetRowElement.RowInfo.Cells["ParentId"].Equals(draggedRowElement.RowInfo.Cells["ParentId"]))) - { - e.Handled = true; - int targetIndex = dt.Rows.IndexOf(targetRowView.Row); - DataRow newRow = dt.NewRow(); - newRow["ParentId"] = targetRowView.Row["ParentId"]; - newRow["Name"] = sourceRowView.Row["Name"]; - newRow["Id"] = sourceRowView.Row["Id"]; - dt.Rows.Remove(sourceRowView.Row); - dt.Rows.InsertAt(newRow, targetIndex); - } -} - -```` -````VB.NET -Private Sub SubscribeToDragDropEvents() - Dim svc As RadDragDropService = Me.radGridView1.GridViewElement.GetService(Of RadDragDropService)() - AddHandler svc.PreviewDragStart, AddressOf svc_PreviewDragStart - AddHandler svc.PreviewDragOver, AddressOf svc_PreviewDragOver - AddHandler svc.PreviewDragDrop, AddressOf svc_PreviewDragDrop -End Sub -Private Sub svc_PreviewDragStart(ByVal sender As Object, ByVal e As PreviewDragStartEventArgs) - e.CanStart = True -End Sub -Private Sub svc_PreviewDragOver(ByVal sender As Object, ByVal e As RadDragOverEventArgs) - Dim draggedRowElement As GridDataRowElement = TryCast(e.DragInstance, GridDataRowElement) - If draggedRowElement Is Nothing Then - e.CanDrop = False - Return - End If - e.CanDrop = True - draggedRowElement.Visibility = ElementVisibility.Hidden -End Sub -Private Sub svc_PreviewDragDrop(ByVal sender As Object, ByVal e As RadDropEventArgs) - Dim draggedRowElement As GridDataRowElement = TryCast(e.DragInstance, GridDataRowElement) - Dim targetRowElement As GridDataRowElement = TryCast(e.HitTarget, GridDataRowElement) - If draggedRowElement Is Nothing Then - Return - End If - Dim sourceRowView As DataRowView = TryCast(draggedRowElement.RowInfo.DataBoundItem, DataRowView) - Dim targetRowView As DataRowView = TryCast(targetRowElement.RowInfo.DataBoundItem, DataRowView) - If Not (targetRowElement.RowInfo.Cells("ParentId").Equals(draggedRowElement.RowInfo.Cells("ParentId"))) Then - e.Handled = True - Dim targetIndex As Integer = dt.Rows.IndexOf(targetRowView.Row) - Dim newRow As DataRow = dt.NewRow() - newRow("ParentId") = targetRowView.Row("ParentId") - newRow("Name") = sourceRowView.Row("Name") - newRow("Id") = sourceRowView.Row("Id") - dt.Rows.Remove(sourceRowView.Row) - dt.Rows.InsertAt(newRow, targetIndex) - End If -End Sub - -```` - -{{endregion}} - + + # See Also * [RadGridViewDragDropService]({%slug winforms/gridview/radgridviewdragdropservice%}) diff --git a/controls/gridview/features/editing/editors/customizing-editor-behavior.md b/controls/gridview/features/editing/editors/customizing-editor-behavior.md index 816e06004..576e6099a 100644 --- a/controls/gridview/features/editing/editors/customizing-editor-behavior.md +++ b/controls/gridview/features/editing/editors/customizing-editor-behavior.md @@ -19,31 +19,8 @@ The look and behavior of grid editors can be changed programmatically. This can The following sample demonstrates how to change the default ForeColor of __GridSpinEditor__: -{{source=..\SamplesCS\GridView\Editors\CustomizingEditorBehavior.cs region=customizingEditors}} -{{source=..\SamplesVB\GridView\Editors\CustomizingEditorBehavior.vb region=customizingEditors}} - -````C# -void radGridView1_CellBeginEdit(object sender, Telerik.WinControls.UI.GridViewCellCancelEventArgs e) -{ - GridSpinEditor editor = this.radGridView1.ActiveEditor as GridSpinEditor; - if (editor != null) - { - ((RadSpinEditorElement)editor.EditorElement).ForeColor = Color.Red; - } -} - -```` -````VB.NET -Private Sub RadGridView1_CellBeginEdit(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewCellCancelEventArgs) Handles RadGridView1.CellBeginEdit - Dim editor As GridSpinEditor = TryCast(Me.RadGridView1.ActiveEditor, GridSpinEditor) - If editor IsNot Nothing Then - CType(editor.EditorElement, RadSpinEditorElement).ForeColor = Color.Red - End If -End Sub - -```` - -{{endregion}} + + >caption Figure 1: Accessing the editor element. diff --git a/controls/gridview/features/editing/editors/data-validation.md b/controls/gridview/features/editing/editors/data-validation.md index b39366b8d..da33734de 100644 --- a/controls/gridview/features/editing/editors/data-validation.md +++ b/controls/gridview/features/editing/editors/data-validation.md @@ -37,44 +37,8 @@ The code snippet below demonstrates simple data validation scenario. It is enabl #### Handling CellValidating Event -{{source=..\SamplesCS\GridView\Editors\DataValidation1.cs region=dataValidation}} -{{source=..\SamplesVB\GridView\Editors\DataValidation1.vb region=dataValidation}} - -````C# -void radGridView1_CellValidating(object sender, Telerik.WinControls.UI.CellValidatingEventArgs e) -{ - GridViewDataColumn column = e.Column as GridViewDataColumn; - if (e.Row is GridViewDataRowInfo && column != null && column.Name == "CategoryName") - { - if (string.IsNullOrEmpty((string)e.Value) || ((string)e.Value).Trim() == string.Empty) - { - e.Cancel = true; - ((GridViewDataRowInfo)e.Row).ErrorText = "Validation error!"; - } - else - { - ((GridViewDataRowInfo)e.Row).ErrorText = string.Empty; - } - } -} - -```` -````VB.NET -Private Sub RadGridView1_CellValidating(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.CellValidatingEventArgs) Handles RadGridView1.CellValidating - Dim column As GridViewDataColumn = TryCast(e.Column, GridViewDataColumn) - If TypeOf e.Row Is GridViewDataRowInfo AndAlso column IsNot Nothing AndAlso column.Name = "CategoryName" Then - If String.IsNullOrEmpty(DirectCast(e.Value, String)) OrElse DirectCast(e.Value, String).Trim() = String.Empty Then - e.Cancel = True - DirectCast(e.Row, GridViewDataRowInfo).ErrorText = "Validation error!" - Else - DirectCast(e.Row, GridViewDataRowInfo).ErrorText = String.Empty - End If - End If - End Sub - -```` - -{{endregion}} + + >note You can watch the [Validation with RadGridView for WinForms](http://tv.telerik.com/watch/winforms/radgridview/validation-with-radgridview-winforms) video regarding the usage of RadGridView built-in validation. > diff --git a/controls/gridview/features/editing/editors/default-editors.md b/controls/gridview/features/editing/editors/default-editors.md index d919965c3..5406bdefa 100644 --- a/controls/gridview/features/editing/editors/default-editors.md +++ b/controls/gridview/features/editing/editors/default-editors.md @@ -38,118 +38,8 @@ In some cases you will need to set the properties of the editor element. The fol #### Accessing Editors -{{source=..\SamplesCS\GridView\Editors\HandlingEditorsEvents.cs region=EditorsExamples}} -{{source=..\SamplesVB\GridView\Editors\HandlingEditorsEvents.vb region=EditorsExamples}} -````C# -private void RadGridView1_CellEditorInitialized(object sender, Telerik.WinControls.UI.GridViewCellEventArgs e) -{ - var textboxEditor = e.ActiveEditor as RadTextBoxEditor; - if (textboxEditor != null) - { - var element = textboxEditor.EditorElement as RadTextBoxEditorElement; - element.TextBoxItem.MaxLength = 10; - } - var spinEditor = e.ActiveEditor as GridSpinEditor; - if (spinEditor != null) - { - var element = spinEditor.EditorElement as RadSpinEditorElement; - element.MaxValue = 10; - element.MinValue = -10; - element.ShowUpDownButtons = true; - } - var mccbEditor = e.ActiveEditor as RadMultiColumnComboBoxElement; - if (mccbEditor != null) - { - mccbEditor.AutoSizeDropDownHeight = true; - mccbEditor.AutoSizeDropDownToBestFit = true; - } - var maskedEditBoxEditor = e.ActiveEditor as RadMaskedEditBoxEditor; - if (maskedEditBoxEditor != null) - { - var element = maskedEditBoxEditor.EditorElement as RadMaskedEditBoxEditorElement; - element.TextBoxItem.TextBoxControl.BackColor = Color.Black; - element.TextBoxItem.BackColor = Color.Black; - } - var dateTimeEditor = e.ActiveEditor as RadDateTimeEditor; - if (dateTimeEditor != null) - { - var element = dateTimeEditor.EditorElement as RadDateTimeEditorElement; - element.MinDate = DateTime.Now; - } - var timeEditor = e.ActiveEditor as GridTimePickerEditor; - if (timeEditor != null) - { - var element = timeEditor.EditorElement as RadTimePickerElement; - element.ClockPosition = ClockPosition.HideClock; - } - var ddlEditor = e.ActiveEditor as RadDropDownListEditor; - if (ddlEditor != null) - { - var element = ddlEditor.EditorElement as RadDropDownListEditorElement; - element.DropDownStyle = Telerik.WinControls.RadDropDownStyle.DropDown; - element.AutoCompleteMode = AutoCompleteMode.Suggest; - } - var browseEditor = e.ActiveEditor as GridBrowseEditor; - if (browseEditor != null) - { - var element = browseEditor.EditorElement as RadBrowseEditorElement; - element.ReadOnly = true; - } -} - -```` -````VB.NET -Private Sub RadGridView1_CellEditorInitialized1(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewCellEventArgs) - Dim textboxEditor = TryCast(e.ActiveEditor, RadTextBoxEditor) - If textboxEditor IsNot Nothing Then - Dim element = TryCast(textboxEditor.EditorElement, RadTextBoxEditorElement) - element.TextBoxItem.MaxLength = 10 - End If - Dim spinEditor = TryCast(e.ActiveEditor, GridSpinEditor) - If spinEditor IsNot Nothing Then - Dim element = TryCast(spinEditor.EditorElement, RadSpinEditorElement) - element.MaxValue = 10 - element.MinValue = -10 - element.ShowUpDownButtons = True - End If - Dim mccbEditor = TryCast(e.ActiveEditor, RadMultiColumnComboBoxElement) - If mccbEditor IsNot Nothing Then - mccbEditor.AutoSizeDropDownHeight = True - mccbEditor.AutoSizeDropDownToBestFit = True - End If - Dim maskedEditBoxEditor = TryCast(e.ActiveEditor, RadMaskedEditBoxEditor) - If maskedEditBoxEditor IsNot Nothing Then - Dim element = TryCast(maskedEditBoxEditor.EditorElement, RadMaskedEditBoxEditorElement) - element.TextBoxItem.TextBoxControl.BackColor = Color.Black - element.TextBoxItem.BackColor = Color.Black - End If - Dim dateTimeEditor = TryCast(e.ActiveEditor, RadDateTimeEditor) - If dateTimeEditor IsNot Nothing Then - Dim element = TryCast(dateTimeEditor.EditorElement, RadDateTimeEditorElement) - element.MinDate = Date.Now - End If - Dim timeEditor = TryCast(e.ActiveEditor, GridTimePickerEditor) - If timeEditor IsNot Nothing Then - Dim element = TryCast(timeEditor.EditorElement, RadTimePickerElement) - element.ClockPosition = ClockPosition.HideClock - End If - Dim ddlEditor = TryCast(e.ActiveEditor, RadDropDownListEditor) - If ddlEditor IsNot Nothing Then - Dim element = TryCast(ddlEditor.EditorElement, RadDropDownListEditorElement) - element.DropDownStyle = Telerik.WinControls.RadDropDownStyle.DropDown - element.AutoCompleteMode = AutoCompleteMode.Suggest - End If - Dim browseEditor = TryCast(e.ActiveEditor, GridBrowseEditor) - If browseEditor IsNot Nothing Then - Dim element = TryCast(browseEditor.EditorElement, RadBrowseEditorElement) - element.ReadOnly = True - End If -End Sub - -```` - - -{{endregion}} + + ## See Also diff --git a/controls/gridview/features/editing/editors/handling-editors'-events.md b/controls/gridview/features/editing/editors/handling-editors'-events.md index 184eed353..bc5298c6a 100644 --- a/controls/gridview/features/editing/editors/handling-editors'-events.md +++ b/controls/gridview/features/editing/editors/handling-editors'-events.md @@ -15,68 +15,8 @@ In some cases you may need to perform a specific operation depending on the user For example if you are in __GridViewTextBoxColumn__, the editor for the cells in this column is __RadTextBoxEditor__. You may need to set specific text in the text box editor when the user presses CTRL + L. In this case, you should subscribe to the __KeyDown__ event of the __RadTextBoxEditorElement__ in the __CellEditorInitialized__ event handler. The editors in RadGridView are reused, so we define a field which prevents us from subscribing to the __KeyDown__ more than once. -{{source=..\SamplesCS\GridView\Editors\HandlingEditorsEvents.cs region=HandlingEditorsEvents}} -{{source=..\SamplesVB\GridView\Editors\HandlingEditorsEvents.vb region=HandlingEditorsEvents}} - -````C# -public HandlingEditorsEvents() -{ - InitializeComponent(); - radGridView1.CellEditorInitialized += new Telerik.WinControls.UI.GridViewCellEventHandler(radGridView1_CellEditorInitialized); -} -bool tbSubscribed = false; -void radGridView1_CellEditorInitialized(object sender, Telerik.WinControls.UI.GridViewCellEventArgs e) -{ - RadTextBoxEditor tbEditor = this.radGridView1.ActiveEditor as RadTextBoxEditor; - if (tbEditor != null) - { - if (!tbSubscribed) - { - tbSubscribed = true; - RadTextBoxEditorElement tbElement = (RadTextBoxEditorElement)tbEditor.EditorElement; - tbElement.KeyDown += new KeyEventHandler(tbElement_KeyDown); - } - } -} -void tbElement_KeyDown(object sender, KeyEventArgs e) -{ - if (e.Control) - { - if (e.KeyCode == Keys.L) - { - ((RadTextBoxEditorElement)sender).Text = "Default text"; - } - } -} - -```` -````VB.NET -Public Sub New() - InitializeComponent() - AddHandler RadGridView1.CellEditorInitialized, AddressOf radGridView1_CellEditorInitialized -End Sub -Private tbSubscribed As Boolean = False -Private Sub radGridView1_CellEditorInitialized(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewCellEventArgs) - Dim tbEditor As RadTextBoxEditor = TryCast(Me.RadGridView1.ActiveEditor, RadTextBoxEditor) - If Not tbEditor Is Nothing Then - If (Not tbSubscribed) Then - tbSubscribed = True - Dim tbElement As RadTextBoxEditorElement = CType(tbEditor.EditorElement, RadTextBoxEditorElement) - AddHandler tbElement.KeyDown, AddressOf tbElement_KeyDown - End If - End If -End Sub -Private Sub tbElement_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) - If e.Control Then - If e.KeyCode = Keys.L Then - CType(sender, RadTextBoxEditorElement).Text = "Default text" - End If - End If -End Sub - -```` - -{{endregion}} + + ## See Also diff --git a/controls/gridview/features/editing/editors/how-to/allow-end-users-to-add-items-to-dropdownlisteditor.md b/controls/gridview/features/editing/editors/how-to/allow-end-users-to-add-items-to-dropdownlisteditor.md index 8ae74e88c..570f30fe1 100644 --- a/controls/gridview/features/editing/editors/how-to/allow-end-users-to-add-items-to-dropdownlisteditor.md +++ b/controls/gridview/features/editing/editors/how-to/allow-end-users-to-add-items-to-dropdownlisteditor.md @@ -34,203 +34,35 @@ Let's assume that: 1\. First, we need to create a __GridViewComboBoxColumn__ that will later display our custom editor. This column should be bound to the binding source of the __Categories__ table. For additional information about __GridViewComboBoxColumn__ and its specifics, you can read [this article]({%slug winforms/gridview/columns/column-types/gridviewcomboboxcolumn%}). The following snippet shows how you can add the column: -{{source=..\SamplesCS\GridView\Editors\How-To\AllowEnd-usersAddItemsComboBoxEditor.cs region=comboColumn}} -{{source=..\SamplesVB\GridView\Editors\How-To\AllowEnd-usersAddItemsComboBoxEditor.vb region=comboColumn}} - -````C# -GridViewComboBoxColumn categoriesColumn = new GridViewComboBoxColumn(); -categoriesColumn.DisplayMember = "CategoryName"; -categoriesColumn.ValueMember = "CategoryID"; -categoriesColumn.FieldName = "CategoryID"; -categoriesColumn.HeaderText = "Category"; -categoriesColumn.DataSource = this.categoriesBindingSource; -categoriesColumn.DropDownStyle = Telerik.WinControls.RadDropDownStyle.DropDown; -categoriesColumn.Width = 150; -this.radGridView1.Columns.Insert(4, categoriesColumn); - -```` -````VB.NET -Dim categoriesColumn As New GridViewComboBoxColumn() -categoriesColumn.DisplayMember = "CategoryName" -categoriesColumn.ValueMember = "CategoryID" -categoriesColumn.FieldName = "CategoryID" -categoriesColumn.HeaderText = "Category" -categoriesColumn.DataSource = Me.CategoriesBindingSource -categoriesColumn.DropDownStyle = Telerik.WinControls.RadDropDownStyle.DropDown -categoriesColumn.Width = 150 -Me.RadGridView1.Columns.Insert(4, categoriesColumn) - -```` - -{{endregion}} + + 2\. Since we will need to get the instances of the DataSet and the TableAdapters of the Category table outside the context of the main form, let's expose two properties in the body of the form: -{{source=..\SamplesCS\GridView\Editors\How-To\AllowEnd-usersAddItemsComboBoxEditor.cs region=properties}} -{{source=..\SamplesVB\GridView\Editors\How-To\AllowEnd-usersAddItemsComboBoxEditor.vb region=properties}} - -````C# -public NwindDataSet DataSet -{ - get - { - return this.nwindDataSet; - } -} -public CategoriesTableAdapter CategoriesTA -{ - get - { - return this.categoriesTableAdapter; - } -} - -```` -````VB.NET -Public ReadOnly Property DataSet() As NwindDataSet - Get - Return Me.NwindDataSet - End Get -End Property -Public ReadOnly Property CategoriesTA() As CategoriesTableAdapter - Get - Return Me.CategoriesTableAdapter - End Get -End Property - -```` - -{{endregion}} + + 3\. Now it is time to create our custom editor. For the purposes of our goal, we need to create a class that derives from __RadDropDownListEditor__ and override the __EndEdit__ method. 4\. In the __EndEdit__ method, we first need to check whether the value typed by the user exists or not in the datasource of the GridViewComboBoxColumn. If it exists, we should terminate the execution of the EndEdit method: -{{source=..\SamplesCS\GridView\Editors\How-To\CustomDropDownEditor.cs region=checkValue}} -{{source=..\SamplesVB\GridView\Editors\How-To\CustomDropDownEditor.vb region=checkValue}} - -````C# -GridComboBoxCellElement cellElement = this.OwnerElement as GridComboBoxCellElement; -RadGridView grid = cellElement.GridControl; -AllowEnd_usersAddItemsComboBoxEditor f = (AllowEnd_usersAddItemsComboBoxEditor)grid.FindForm(); -// Checking if the typed value exists in the datasource of the column. -NwindDataSet.CategoriesDataTable dt = f.DataSet.Categories; -for (int i = 0; i < dt.Rows.Count; i++) -{ - if (dt.Rows[i]["CategoryName"].ToString() == ((RadDropDownListEditorElement)this.EditorElement).Text) - { - return base.EndEdit(); - } -} - -```` -````VB.NET -Dim cellElement As GridComboBoxCellElement = TryCast(Me.OwnerElement, GridComboBoxCellElement) -Dim grid As RadGridView = cellElement.GridControl -Dim f As AllowEnd_usersAddItemsComboBoxEditor = CType(grid.FindForm(), AllowEnd_usersAddItemsComboBoxEditor) -' Checking if the typed value exists in the datasource of the column. -Dim dt As NwindDataSet.CategoriesDataTable = f.DataSet.Categories -For i As Integer = 0 To dt.Rows.Count - 1 - If dt.Rows(i)("CategoryName").ToString() = (CType(Me.EditorElement, RadDropDownListEditorElement)).Text Then - Return MyBase.EndEdit() - End If -Next i - -```` - -{{endregion}} + + 5\. If the typed value is not found in the datasource, we continue with the execution of our code in the EndEdit method. Since the typed value does not exist, we should add it to the data source. Here you can add it to the database as well: -{{source=..\SamplesCS\GridView\Editors\How-To\CustomDropDownEditor.cs region=addValue}} -{{source=..\SamplesVB\GridView\Editors\How-To\CustomDropDownEditor.vb region=addValue}} - -````C# -// An example of what we can do when we enter the custom text. -// In this case we are adding a new data row in the underlying datasource of -// the combobox column and then in the CellEndEdit we are setting -// the ID value of the newly created row to RadGridView. -NwindDataSet.CategoriesRow newCategoriesRow = dt.NewCategoriesRow(); -newCategoriesRow.CategoryName = ((RadDropDownListEditorElement)this.EditorElement).Text; -f.DataSet.Categories.Rows.Add(newCategoriesRow); -// Updating the database. You can do it here at another place -// you find suitable for this purpose, for example, on FormClosing. -f.CategoriesTA.Update(f.DataSet.Categories); -cellElement.Tag = newCategoriesRow.CategoryID; -return base.EndEdit(); - -```` -````VB.NET -' An example of what we can do when we enter the custom text. -' In this case we are adding a new data row in the underlying datasource of -' the combobox column and then in the CellEndEdit we are setting -' the ID value of the newly created row to RadGridView. -Dim newCategoriesRow As NwindDataSet.CategoriesRow = dt.NewCategoriesRow() -newCategoriesRow.CategoryName = (CType(Me.EditorElement, RadDropDownListEditorElement)).Text -f.DataSet.Categories.Rows.Add(newCategoriesRow) -' Updating the database. You can do it here at another place -' you find suitable for this purpose, for example, on FormClosing. -f.CategoriesTA.Update(f.DataSet.Categories) -cellElement.Tag = newCategoriesRow.CategoryID -Return MyBase.EndEdit() - -```` - -{{endregion}} + + 6\. The Tag value saved in the previous code snippet is used in the CellEndEdit event handler of RadGridView. It helps us to set the ID of the newly created record to the cell that the end-user has just edited. As a consequence, the correct string value is displayed in the cell of RadGridView. -{{source=..\SamplesCS\GridView\Editors\How-To\AllowEnd-usersAddItemsComboBoxEditor.cs region=cellEndEdit}} -{{source=..\SamplesVB\GridView\Editors\How-To\AllowEnd-usersAddItemsComboBoxEditor.vb region=cellEndEdit}} - -````C# -void radGridView1_CellEndEdit(object sender, GridViewCellEventArgs e) -{ - if (this.radGridView1.CurrentCell.Tag != null) - { - this.radGridView1.CurrentCell.Value = this.radGridView1.CurrentCell.Tag; - this.radGridView1.CurrentCell.Tag = null; - } -} - -```` -````VB.NET -Private Sub radGridView1_CellEndEdit(ByVal sender As Object, ByVal e As GridViewCellEventArgs) - If Me.RadGridView1.CurrentCell.Tag IsNot Nothing Then - Me.RadGridView1.CurrentCell.Value = Me.RadGridView1.CurrentCell.Tag - Me.RadGridView1.CurrentCell.Tag = Nothing - End If -End Sub - -```` - -{{endregion}} + + 7\. Finally, we need to attach the custom editor to RadGridView. This is done in the EditorRequired event handler. Let's assume that the class of our custom editor is called CustomDropDownEditor: -{{source=..\SamplesCS\GridView\Editors\How-To\AllowEnd-usersAddItemsComboBoxEditor.cs region=editorRequired}} -{{source=..\SamplesVB\GridView\Editors\How-To\AllowEnd-usersAddItemsComboBoxEditor.vb region=editorRequired}} - -````C# -void radGridView1_EditorRequired(object sender, EditorRequiredEventArgs e) -{ - if (e.EditorType == typeof(RadDropDownListEditor)) - { - e.Editor = new CustomDropDownEditor(); - } -} - -```` -````VB.NET -Private Sub radGridView1_EditorRequired(ByVal sender As Object, ByVal e As EditorRequiredEventArgs) - If e.EditorType Is GetType(RadDropDownListEditor) Then - e.Editor = New CustomDropDownEditor() - End If -End Sub - -```` - -{{endregion}} + + ## End-user experience diff --git a/controls/gridview/features/editing/editors/how-to/change-the-active-editor-depending-on-the-cell-value-type.md b/controls/gridview/features/editing/editors/how-to/change-the-active-editor-depending-on-the-cell-value-type.md index e84ee55bc..9d0750b3c 100644 --- a/controls/gridview/features/editing/editors/how-to/change-the-active-editor-depending-on-the-cell-value-type.md +++ b/controls/gridview/features/editing/editors/how-to/change-the-active-editor-depending-on-the-cell-value-type.md @@ -16,103 +16,13 @@ Common case is to have a single column (for example a GridViewTextBoxColumn) wit First we can set up the grid with some columns and rows, this will allow us to observe the editor behavior later. Just drop a RadGridView in a blank form and then use the following code to initialize the grid. At the end, subscribe to the __EditorRequired__ event, which is triggered when a cell needs an editor: -{{source=..\SamplesCS\GridView\Editors\How-To\ChangeTheActiveEditorDependingOnTheCellValueType.cs region=FormLoad}} -{{source=..\SamplesVB\GridView\Editors\How-To\ChangeTheActiveEditorDependingOnTheCellValueType.vb region=FormLoad}} - -````C# - -private void ChangeTheActiveEditorDependingOnTheCellValueType_Load(object sender, EventArgs e) -{ - GridViewTextBoxColumn gridViewTextBoxColumn1 = new GridViewTextBoxColumn(); - GridViewTextBoxColumn gridViewTextBoxColumn2 = new GridViewTextBoxColumn(); - gridViewTextBoxColumn1.HeaderText = "column1"; - gridViewTextBoxColumn1.Name = "column1"; - gridViewTextBoxColumn1.Width = 100; - gridViewTextBoxColumn2.HeaderText = "column2"; - gridViewTextBoxColumn2.Name = "column2"; - gridViewTextBoxColumn2.Width = 150; - this.radGridView1.MasterTemplate.Columns.AddRange(new GridViewDataColumn[] - { - gridViewTextBoxColumn1, - gridViewTextBoxColumn2 - }); - this.radGridView1.Rows.Add("row 1", DateTime.Now.ToString()); - this.radGridView1.Rows.Add("row 2", "6"); - this.radGridView1.Rows.Add("row 3", "test"); - this.radGridView1.EditorRequired += radGridView1_EditorRequired; -} - -```` -````VB.NET -Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load - Dim gridViewTextBoxColumn1 As New GridViewTextBoxColumn() - Dim gridViewTextBoxColumn2 As New GridViewTextBoxColumn() - gridViewTextBoxColumn1.HeaderText = "column1" - gridViewTextBoxColumn1.Name = "column1" - gridViewTextBoxColumn1.Width = 100 - gridViewTextBoxColumn2.HeaderText = "column2" - gridViewTextBoxColumn2.Name = "column2" - gridViewTextBoxColumn2.Width = 150 - Me.RadGridView1.MasterTemplate.Columns.AddRange(New GridViewDataColumn() {gridViewTextBoxColumn1, gridViewTextBoxColumn2}) - Me.RadGridView1.Rows.Add("row 1", DateTime.Now.ToString()) - Me.RadGridView1.Rows.Add("row 2", "7") - Me.RadGridView1.Rows.Add("row 3", "test") - AddHandler RadGridView1.EditorRequired, AddressOf radGridView1_EditorRequired -End Sub - -```` - -{{endregion}} + + Now we just need to match the value with the appropriate type and show the corresponding editor. We can do that with the following __EditorRequired__ event handler: -{{source=..\SamplesCS\GridView\Editors\How-To\ChangeTheActiveEditorDependingOnTheCellValueType.cs region=EditorRequired}} -{{source=..\SamplesVB\GridView\Editors\How-To\ChangeTheActiveEditorDependingOnTheCellValueType.vb region=EditorRequired}} - -````C# -void radGridView1_EditorRequired(object sender, EditorRequiredEventArgs e) -{ - DateTime date; - if (DateTime.TryParse(radGridView1.CurrentCell.Value.ToString(), out date)) - { - e.EditorType = typeof(RadDateTimeEditor); - return; - } - int i = 0; - if (int.TryParse(radGridView1.CurrentCell.Value.ToString(), out i)) - { - e.EditorType = typeof(GridSpinEditor); - return; - } - if (radGridView1.CurrentCell.Value is string) - { - e.EditorType = typeof(RadTextBoxEditor); - return; - } -} - -```` -````VB.NET -Private Sub radGridView1_EditorRequired(sender As Object, e As EditorRequiredEventArgs) - Dim [date] As DateTime - If DateTime.TryParse(RadGridView1.CurrentCell.Value.ToString(), [date]) Then - e.EditorType = GetType(RadDateTimeEditor) - Return - End If - Dim i As Integer = 0 - If Integer.TryParse(RadGridView1.CurrentCell.Value.ToString(), i) Then - e.EditorType = GetType(GridSpinEditor) - Return - End If - If TypeOf RadGridView1.CurrentCell.Value Is String Then - e.EditorType = GetType(RadTextBoxEditor) - Return - End If -End Sub - -```` - -{{endregion}} + + The result is that the end user can edit the cells with the appropriate for their values editor: diff --git a/controls/gridview/features/editing/editors/using-custom-editors.md b/controls/gridview/features/editing/editors/using-custom-editors.md index 78ea77c02..f2cac3bde 100644 --- a/controls/gridview/features/editing/editors/using-custom-editors.md +++ b/controls/gridview/features/editing/editors/using-custom-editors.md @@ -15,191 +15,18 @@ This following snippet demonstrates how to replace the standard spin editor with All grid editors inherit from __BaseGridEditor__. So, you have to inherit from this class and override several methods: -{{source=..\SamplesCS\GridView\Editors\UsingCustomEditors.cs region=trackBarEditor}} -{{source=..\SamplesVB\GridView\Editors\UsingCustomEditors.vb region=trackBarEditor}} - -````C# -public class TrackBarEditor : BaseGridEditor -{ - public override object Value - { - get - { - TrackBarEditorElement editor = (TrackBarEditorElement)this.EditorElement; - return editor.Value; - } - set - { - TrackBarEditorElement editor = (TrackBarEditorElement)this.EditorElement; - if (value != null && value != DBNull.Value) - { - editor.Value = Convert.ToInt32(value); - } - else - { - editor.Value = 0; - } - } - } - public override void BeginEdit() - { - base.BeginEdit(); - this.EditorElement.Focus(); - ((TrackBarEditorElement)this.EditorElement).TrackPositionChanged += new EventHandler(TrackBarEditor_TrackPositionChanged); - } - public override bool EndEdit() - { - ((TrackBarEditorElement)this.EditorElement).TrackPositionChanged -= new EventHandler(TrackBarEditor_TrackPositionChanged); - return base.EndEdit(); - } - void TrackBarEditor_TrackPositionChanged(object sender, EventArgs e) - { - OnValueChanged(); - } - protected override RadElement CreateEditorElement() - { - return new TrackBarEditorElement(); - } -} - -```` -````VB.NET -Public Class TrackBarEditor - Inherits BaseGridEditor - Public Overrides Property Value() As Object - Get - Dim editor As TrackBarEditorElement = CType(Me.EditorElement, TrackBarEditorElement) - Return editor.Value - End Get - Set(ByVal value As Object) - Dim editor As TrackBarEditorElement = CType(Me.EditorElement, TrackBarEditorElement) - If value IsNot Nothing AndAlso value IsNot DBNull.Value Then - editor.Value = Convert.ToInt32(value) - Else - editor.Value = 0 - End If - End Set - End Property - Public Overrides Sub BeginEdit() - MyBase.BeginEdit() - Me.EditorElement.Focus() - AddHandler (CType(EditorElement, TrackBarEditorElement)).TrackPositionChanged, AddressOf TrackBarEditor_TrackPositionChanged - End Sub - Public Overrides Function EndEdit() As Boolean - RemoveHandler (CType(EditorElement, TrackBarEditorElement)).TrackPositionChanged, AddressOf TrackBarEditor_TrackPositionChanged - Return MyBase.EndEdit() - End Function - Private Sub TrackBarEditor_TrackPositionChanged(ByVal sender As Object, ByVal e As EventArgs) - OnValueChanged() - End Sub - Protected Overrides Function CreateEditorElement() As RadElement - Return New TrackBarEditorElement() - End Function -End Class - -```` - -{{endregion}} + + We use the standard __RadTrackBar__ element in this example with some modification to enable keyboard navigation: -{{source=..\SamplesCS\GridView\Editors\UsingCustomEditors.cs region=trackBarEditorElement}} -{{source=..\SamplesVB\GridView\Editors\UsingCustomEditors.vb region=trackBarEditorElement}} - -````C# -public class TrackBarEditorElement : RadTrackBarElement -{ - public TrackBarEditorElement() - { - this.CanFocus = true; - } - public event EventHandler TrackPositionChanged; - protected override Type ThemeEffectiveType - { - get - { - return typeof(RadTrackBarElement); - } - } - protected override SizeF MeasureOverride(SizeF availableSize) - { - int desiredHeight = 30; - foreach (RadElement element in this.Children) - { - element.Measure(new SizeF(availableSize.Width, desiredHeight)); - } - return new SizeF(1, desiredHeight); - } - protected override void OnPropertyChanged(RadPropertyChangedEventArgs e) - { - base.OnPropertyChanged(e); - if (e.Property == RadTrackBarItem.ValueProperty - && this.Parent != null - && this.TrackPositionChanged != null) - { - this.TrackPositionChanged(this, EventArgs.Empty); - } - } -} - -```` -````VB.NET -Public Class TrackBarEditorElement - Inherits RadTrackBarElement - Public Sub New() - Me.CanFocus = True - End Sub - Public Event TrackPositionChanged As EventHandler - Protected Overrides ReadOnly Property ThemeEffectiveType() As Type - Get - Return GetType(RadTrackBarElement) - End Get - End Property - Protected Overrides Function MeasureOverride(ByVal availableSize As System.Drawing.SizeF) As System.Drawing.SizeF - Dim desiredHeight As Integer = 30 - For Each element As RadElement In Me.Children - element.Measure(New System.Drawing.SizeF(availableSize.Width, desiredHeight)) - Next element - Return New System.Drawing.SizeF(1, desiredHeight) - End Function - Protected Overrides Sub OnPropertyChanged(ByVal e As RadPropertyChangedEventArgs) - MyBase.OnPropertyChanged(e) - If e.Property Is RadTrackBarItem.ValueProperty AndAlso Me.Parent IsNot Nothing AndAlso Me.TrackPositionChangedEvent IsNot Nothing Then - RaiseEvent TrackPositionChanged(Me, EventArgs.Empty) - End If - End Sub -End Class - -```` - -{{endregion}} + + The __EditorRequired__ event is the correct place to replace the default editor: -{{source=..\SamplesCS\GridView\Editors\UsingCustomEditors.cs region=changingTheEditor}} -{{source=..\SamplesVB\GridView\Editors\UsingCustomEditors.vb region=changingTheEditor}} - -````C# -void radGridView1_EditorRequired(object sender, EditorRequiredEventArgs e) -{ - if (e.EditorType == typeof(GridSpinEditor)) - { - e.EditorType = typeof(TrackBarEditor); - } -} - -```` -````VB.NET -Private Sub RadGridView1_EditorRequired(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.EditorRequiredEventArgs) Handles RadGridView1.EditorRequired - If e.EditorType Is GetType(GridSpinEditor) Then - e.EditorType = GetType(TrackBarEditor) - End If -End Sub - -```` - -{{endregion}} - + + >note You can find a working version of this sample in our Demo application ( *GridView -> Custom Editors* ). To access the Live Demo simply click on the Windows Start button and type WinForms Demo. If you are not able to find the Live Demos using that approach you can also download it directly from [here](https://telerik-winforms-demos.s3.amazonaws.com/TelerikWinFormsExamplesLauncher.exe). > diff --git a/controls/gridview/features/editing/expression-editor/customizing-radexpressioneditor.md b/controls/gridview/features/editing/expression-editor/customizing-radexpressioneditor.md index dab2f4e0b..b59566fd1 100644 --- a/controls/gridview/features/editing/expression-editor/customizing-radexpressioneditor.md +++ b/controls/gridview/features/editing/expression-editor/customizing-radexpressioneditor.md @@ -15,69 +15,18 @@ previous_url: gridview-expressioneditor-cutomizing-radexpressioneditor Although Telerik provides a large number of predefined functions, some scenarios require additional functionality. You can create a custom expression method for use in `RadExpressionEditor` or as a value of the `Expression` property. To do that, create a class that inherits from the `ExpressionContext` class: -{{source=..\SamplesCS\GridView\ExpressionEditor\CustomFunctions.cs region=customFunction}} -{{source=..\SamplesVB\GridView\ExpressionEditor\CustomFunctions.vb region=customFunction}} - -````C# -public class CustomExpressionContext : Telerik.Data.Expressions.ExpressionContext - { -/// -/// My custom function, which returns Pi constant. -/// -/// -public double Pi() -{ - return Math.PI; -} - } - -```` -````VB.NET -Public Class CustomExpressionContext - Inherits Telerik.Data.Expressions.ExpressionContext - ''' - ''' My custom function, which returns Pi constant. - ''' - ''' - Public Function Pi() As Double - Return Math.PI - End Function -End Class - -```` - -{{endregion}} + + Once implemented, assign the new custom `ExpressionContext` class by using the static `Context` property: -{{source=..\SamplesCS\GridView\ExpressionEditor\CustomFunctions.cs region=settingCustom}} -{{source=..\SamplesVB\GridView\ExpressionEditor\CustomFunctions.vb region=settingCustom}} - -````C# -Telerik.Data.Expressions.ExpressionContext.Context = new CustomExpressionContext(); - -```` -````VB.NET -Telerik.Data.Expressions.ExpressionContext.Context = New CustomExpressionContext() - -```` - -{{endregion}} + + Then you can use the new expression method: -{{source=..\SamplesCS\GridView\ExpressionEditor\CustomFunctions.cs region=settingExpression}} -{{source=..\SamplesVB\GridView\ExpressionEditor\CustomFunctions.vb region=settingExpression}} -````C# -this.radGridView1.Columns["expression"].Expression = "PI()"; - -```` -````VB.NET -Me.RadGridView1.Columns("expression").Expression = "PI()" - -```` - -{{endregion}} + + ## Customizing the functions list @@ -103,62 +52,15 @@ __RadExpressionEditor__ supports loading functions, operators and constants from To load a prepared XML source file, use the `LoadFromXML` method as shown below: -{{source=..\SamplesCS\GridView\ExpressionEditor\CustomFunctions.cs region=loadingXML}} -{{source=..\SamplesVB\GridView\ExpressionEditor\CustomFunctions.vb region=loadingXML}} - -````C# -string path = "Telerik.Examples.WinControls.GridView.Expressions.ExpressionItemsListData.xml"; -Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(path); -RadExpressionEditorForm.ExpressionItemsList.LoadFromXML(stream); - -```` -````VB.NET -Dim path As String = "Telerik.Examples.WinControls.GridView.Expressions.ExpressionItemsListData.xml" -Dim stream_ As Stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(path) -RadExpressionEditorForm.ExpressionItemsList.LoadFromXML(stream_) - -```` - -{{endregion}} + + ## ExpressionEditorFormCreated event This event fires before the expression editor form is shown. The following example changes the `BackColor` and hides the icon in the title bar: -{{source=..\SamplesCS\GridView\ExpressionEditor\CustomFunctions.cs region=FormatingExpressionForm}} -{{source=..\SamplesVB\GridView\ExpressionEditor\CustomFunctions.vb region=FormatingExpressionForm}} -````C# -private void RadGridView1_ExpressionEditorFormCreated(object sender, ExpressionEditorFormCreatedEventArgs e) -{ - e.ExpressionEditorForm.FormElement.TitleBar.FillPrimitive.BackColor = Color.LightSkyBlue; - e.ExpressionEditorForm.ShowIcon = false; -} - -```` -````VB.NET -Private Sub RadGridView1_ExpressionEditorFormCreated(ByVal sender As Object, ByVal e As ExpressionEditorFormCreatedEventArgs) - e.ExpressionEditorForm.FormElement.TitleBar.FillPrimitive.BackColor = Color.LightSkyBlue - e.ExpressionEditorForm.ShowIcon = False -End Sub -'#endgion -Class -gion customFunction -ic Class CustomExpressionContext -Inherits Telerik.Data.Expressions.ExpressionContext -''' -''' My custom function, which returns Pi constant. -''' -''' -Public Function Pi() As Double - Return Math.PI -End Function -Class - -```` - - -{{endregion}} - + + ## See Also diff --git a/controls/gridview/features/editing/expression-editor/end-user-support.md b/controls/gridview/features/editing/expression-editor/end-user-support.md index 2d5f5a289..01f5cdd30 100644 --- a/controls/gridview/features/editing/expression-editor/end-user-support.md +++ b/controls/gridview/features/editing/expression-editor/end-user-support.md @@ -19,49 +19,15 @@ End-users can open the editor by navigating to a built-in menu item from the con ![WinForms RadGridView ExpressionEditor](images/gridview-expressioneditor-end-user-support001.png) -{{source=..\SamplesCS\GridView\ExpressionEditor\CustomFunctions.cs region=enableExpressionEditor}} -{{source=..\SamplesVB\GridView\ExpressionEditor\CustomFunctions.vb region=enableExpressionEditor}} - -````C# -GridViewTextBoxColumn col = new GridViewTextBoxColumn(); -col.Name = "expression"; -col.HeaderText = "My Expression"; -col.Width = 150; -col.EnableExpressionEditor = true; -this.radGridView1.Columns.Add(col); - -```` -````VB.NET -Dim col As GridViewTextBoxColumn = New GridViewTextBoxColumn() -col.Name = "expression" -col.HeaderText = "My Expression" -col.Width = 150 -col.EnableExpressionEditor = True -Me.RadGridView1.Columns.Add(col) - -```` - -{{endregion}} + + ## Showing RadExpressionEditor on a custom user action You can show `RadExpressionEditor` on a custom user action, for example a button click, without using the standard RadGridView UI. Call the static `Show` method: -{{source=..\SamplesCS\GridView\ExpressionEditor\CustomFunctions.cs region=expressionFormShow}} -{{source=..\SamplesVB\GridView\ExpressionEditor\CustomFunctions.vb region=expressionFormShow}} - -````C# -RadExpressionEditorForm.Show(this.radGridView1, this.radGridView1.Columns["expression"]); - -```` -````VB.NET -RadExpressionEditorForm.Show(Me.RadGridView1, Me.RadGridView1.Columns("expression")) - -```` - -{{endregion}} - - + + ## See Also diff --git a/controls/gridview/features/editing/expression-editor/expression-syntax.md b/controls/gridview/features/editing/expression-editor/expression-syntax.md index d50802248..33fe63670 100644 --- a/controls/gridview/features/editing/expression-editor/expression-syntax.md +++ b/controls/gridview/features/editing/expression-editor/expression-syntax.md @@ -28,18 +28,16 @@ Numeric values support decimal notation and scientific notation (for example, `1 Reference grid column values by enclosing the column name in square brackets. -```` -[ProductName] -[UnitPrice] -[OrderDate] -```` +* [ProductName] +* [UnitPrice] +* [OrderDate] + If a column name contains special characters (spaces, operators, brackets, or other reserved characters), the square bracket syntax handles escaping automatically. -```` -[Unit Price] -[Order#] -```` +* [Unit Price] +* [Order#] + ## Arithmetic Operators @@ -106,21 +104,10 @@ Operators are evaluated in the following order from highest to lowest precedence Combine functions, operators, and field references to create complex expressions. Use parentheses to group sub-expressions and control evaluation order. -```` -IIF([UnitPrice] * [Quantity] > 1000, 'High Value', 'Standard') -```` - -```` -IIF(ISNULL([ShippedDate], TODAY()) > [RequiredDate], 'Late', 'On Time') -```` - -```` -UPPER(SUBSTR([ProductName], 0, 3)) + '-' + CSTR([ProductID]) -```` - -```` -[UnitPrice] * [Quantity] * IIF([Discount] > 0, 1 - [Discount], 1) -```` +* IIF([UnitPrice] * [Quantity] > 1000, 'High Value', 'Standard') +* IIF(ISNULL([ShippedDate], TODAY()) > [RequiredDate], 'Late', 'On Time') +* UPPER(SUBSTR([ProductName], 0, 3)) + '-' + CSTR([ProductID]) +* [UnitPrice] * [Quantity] * IIF([Discount] > 0, 1 - [Discount], 1) ## See Also diff --git a/controls/gridview/features/editing/expression-editor/functions-reference.md b/controls/gridview/features/editing/expression-editor/functions-reference.md index 1bb48cf9b..734726748 100644 --- a/controls/gridview/features/editing/expression-editor/functions-reference.md +++ b/controls/gridview/features/editing/expression-editor/functions-reference.md @@ -37,15 +37,15 @@ Text functions perform string manipulation operations. **Examples:** -```` -LOWER([ProductName]) -SUBSTR([ProductName], 0, 3) -FORMAT('{0:N2}', [UnitPrice]) -REPLACE([Description], 'old', 'new') -TRIM([CustomerName]) -LEN([ProductName]) -INSERT([Code], 0, 'PRD-') -```` + +* LOWER([ProductName]) +* SUBSTR([ProductName], 0, 3) +* FORMAT('{0:N2}', [UnitPrice]) +* REPLACE([Description], 'old', 'new') +* TRIM([CustomerName]) +* LEN([ProductName]) +* INSERT([Code], 0, 'PRD-') + ## Aggregate Functions @@ -63,13 +63,11 @@ Aggregate functions compute a single value from a column across all rows. Pass a **Examples:** -```` -SUM([UnitPrice]) -AVG([Quantity]) -COUNT([OrderID]) -MAX([OrderDate]) -MIN([UnitPrice]) -```` +* SUM([UnitPrice]) +* AVG([Quantity]) +* COUNT([OrderID]) +* MAX([OrderDate]) +* MIN([UnitPrice]) ## Date-Time Functions @@ -128,13 +126,11 @@ These functions return the difference between two dates in the specified unit. **Examples:** -```` -ADDDAYS([OrderDate], 30) -DATEDIFFDAY([OrderDate], NOW()) -GETYEAR([OrderDate]) -GETMONTH([ShippedDate]) -ADDMONTHS(TODAY(), -6) -```` +* ADDDAYS([OrderDate], 30) +* DATEDIFFDAY([OrderDate], NOW()) +* GETYEAR([OrderDate]) +* GETMONTH([ShippedDate]) +* ADDMONTHS(TODAY(), -6) ## Logical Functions @@ -145,11 +141,10 @@ ADDMONTHS(TODAY(), -6) **Examples:** -```` -IIF([UnitPrice] > 100, 'Expensive', 'Affordable') -ISNULL([ShippedDate], #01/01/2000#) -IIF([Quantity] > 0 AND [UnitPrice] > 0, [Quantity] * [UnitPrice], 0) -```` + +* IIF([UnitPrice] > 100, 'Expensive', 'Affordable') +* ISNULL([ShippedDate], #01/01/2000#) +* IIF([Quantity] > 0 AND [UnitPrice] > 0, [Quantity] * [UnitPrice], 0) ## Math Functions @@ -179,13 +174,11 @@ IIF([Quantity] > 0 AND [UnitPrice] > 0, [Quantity] * [UnitPrice], 0) **Examples:** -```` -ABS([Quantity] - [Expected]) -ROUND([UnitPrice] * 1.1) -POWER([Value], 2) -SQRT([Area]) -CEILING([Total] / 10) -```` +* ABS([Quantity] - [Expected]) +* ROUND([UnitPrice] * 1.1) +* POWER([Value], 2) +* SQRT([Area]) +* CEILING([Total] / 10) ## Conversion Functions @@ -201,13 +194,12 @@ Conversion functions convert an expression to a specific .NET data type. **Examples:** -```` -CINT([Quantity]) -CDBL([UnitPrice]) * 1.5 -CDATE('2025-01-15') -CSTR([ProductID]) -IIF(CBOOL([IsActive]), 'Active', 'Inactive') -```` +* CINT([Quantity]) +* CDBL([UnitPrice]) * 1.5 +* CDATE('2025-01-15') +* CSTR([ProductID]) +* IIF(CBOOL([IsActive]), 'Active', 'Inactive') + ## See Also diff --git a/controls/gridview/features/editing/expression-editor/localization.md b/controls/gridview/features/editing/expression-editor/localization.md index 2fd259dd8..b399343b3 100644 --- a/controls/gridview/features/editing/expression-editor/localization.md +++ b/controls/gridview/features/editing/expression-editor/localization.md @@ -15,134 +15,8 @@ previous_url: gridview-expressioneditor-localization You can localize the UI elements of __RadExpressionEditor__ by using a custom __RadGridLocalizationProvider__. For more details, please refer to [this article.]({%slug winforms/gridview/localization/localization%}) -{{source=..\SamplesCS\GridView\ExpressionEditor\CustomLocalizationProvider.cs region=expressionEditorLocalization}} -{{source=..\SamplesVB\GridView\ExpressionEditor\CustomLocalizationProvider.vb region=expressionEditorLocalization}} - -````C# -public class CustomLocalizationProvider : RadGridLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case RadGridStringId.ExpressionMenuItem: return "Expression"; - case RadGridStringId.ExpressionFormTitle: return "Expression Builder"; - case RadGridStringId.ExpressionFormFunctions: return "Functions"; - case RadGridStringId.ExpressionFormFunctionsText: return "Text"; - case RadGridStringId.ExpressionFormFunctionsAggregate: return "Aggregate"; - case RadGridStringId.ExpressionFormFunctionsDateTime: return "Date-Time"; - case RadGridStringId.ExpressionFormFunctionsLogical: return "Logical"; - case RadGridStringId.ExpressionFormFunctionsMath: return "Math"; - case RadGridStringId.ExpressionFormFunctionsOther: return "Other"; - case RadGridStringId.ExpressionFormOperators: return "Operators"; - case RadGridStringId.ExpressionFormConstants: return "Constants"; - case RadGridStringId.ExpressionFormFields: return "Fields"; - case RadGridStringId.ExpressionFormDescription: return "Description"; - case RadGridStringId.ExpressionFormResultPreview: return "Result preview"; - case RadGridStringId.ExpressionFormTooltipPlus: return "Plus"; - case RadGridStringId.ExpressionFormTooltipMinus: return "Minus"; - case RadGridStringId.ExpressionFormTooltipMultiply: return "Multiply"; - case RadGridStringId.ExpressionFormTooltipDivide: return "Divide"; - case RadGridStringId.ExpressionFormTooltipModulo: return "Modulo"; - case RadGridStringId.ExpressionFormTooltipEqual: return "Equal"; - case RadGridStringId.ExpressionFormTooltipNotEqual: return "Not Equal"; - case RadGridStringId.ExpressionFormTooltipLess: return "Less"; - case RadGridStringId.ExpressionFormTooltipLessOrEqual: return "Less Or Equal"; - case RadGridStringId.ExpressionFormTooltipGreaterOrEqual: return "Greater Or Equal"; - case RadGridStringId.ExpressionFormTooltipGreater: return "Greater"; - case RadGridStringId.ExpressionFormTooltipAnd: return "Logical \"AND\""; - case RadGridStringId.ExpressionFormTooltipOr: return "Logical \"OR\""; - case RadGridStringId.ExpressionFormTooltipNot: return "Logical \"NOT\""; - case RadGridStringId.ExpressionFormAndButton: return "And"; - case RadGridStringId.ExpressionFormOrButton: return "Or"; - case RadGridStringId.ExpressionFormNotButton: return "Not"; - case RadGridStringId.ExpressionFormOKButton: return "OK"; - case RadGridStringId.ExpressionFormCancelButton: return "Cancel"; - } - return string.Empty; - } -} - -```` -````VB.NET -Public Class CustomLocalizationProvider - Inherits RadGridLocalizationProvider - Public Overrides Function GetLocalizedString(ByVal id As String) As String - Select Case id - Case RadGridStringId.ExpressionMenuItem - Return "Expression" - Case RadGridStringId.ExpressionFormTitle - Return "Expression Builder" - Case RadGridStringId.ExpressionFormFunctions - Return "Functions" - Case RadGridStringId.ExpressionFormFunctionsText - Return "Text" - Case RadGridStringId.ExpressionFormFunctionsAggregate - Return "Aggregate" - Case RadGridStringId.ExpressionFormFunctionsDateTime - Return "Date-Time" - Case RadGridStringId.ExpressionFormFunctionsLogical - Return "Logical" - Case RadGridStringId.ExpressionFormFunctionsMath - Return "Math" - Case RadGridStringId.ExpressionFormFunctionsOther - Return "Other" - Case RadGridStringId.ExpressionFormOperators - Return "Operators" - Case RadGridStringId.ExpressionFormConstants - Return "Constants" - Case RadGridStringId.ExpressionFormFields - Return "Fields" - Case RadGridStringId.ExpressionFormDescription - Return "Description" - Case RadGridStringId.ExpressionFormResultPreview - Return "Result preview" - Case RadGridStringId.ExpressionFormTooltipPlus - Return "Plus" - Case RadGridStringId.ExpressionFormTooltipMinus - Return "Minus" - Case RadGridStringId.ExpressionFormTooltipMultiply - Return "Multiply" - Case RadGridStringId.ExpressionFormTooltipDivide - Return "Divide" - Case RadGridStringId.ExpressionFormTooltipModulo - Return "Modulo" - Case RadGridStringId.ExpressionFormTooltipEqual - Return "Equal" - Case RadGridStringId.ExpressionFormTooltipNotEqual - Return "Not Equal" - Case RadGridStringId.ExpressionFormTooltipLess - Return "Less" - Case RadGridStringId.ExpressionFormTooltipLessOrEqual - Return "Less Or Equal" - Case RadGridStringId.ExpressionFormTooltipGreaterOrEqual - Return "Greater Or Equal" - Case RadGridStringId.ExpressionFormTooltipGreater - Return "Greater" - Case RadGridStringId.ExpressionFormTooltipAnd - Return "Logical ""AND""" - Case RadGridStringId.ExpressionFormTooltipOr - Return "Logical ""OR""" - Case RadGridStringId.ExpressionFormTooltipNot - Return "Logical ""NOT""" - Case RadGridStringId.ExpressionFormAndButton - Return "And" - Case RadGridStringId.ExpressionFormOrButton - Return "Or" - Case RadGridStringId.ExpressionFormNotButton - Return "Not" - Case RadGridStringId.ExpressionFormOKButton - Return "OK" - Case RadGridStringId.ExpressionFormCancelButton - Return "Cancel" - End Select - Return String.Empty - End Function -End Class - -```` - -{{endregion}} + + ## Localizing functions diff --git a/controls/gridview/features/editing/insert-update-delete-records/delete-using-controls-api.md b/controls/gridview/features/editing/insert-update-delete-records/delete-using-controls-api.md index 80aa7fdc7..80f39c85b 100644 --- a/controls/gridview/features/editing/insert-update-delete-records/delete-using-controls-api.md +++ b/controls/gridview/features/editing/insert-update-delete-records/delete-using-controls-api.md @@ -17,33 +17,8 @@ Two general approaches in adding new rows exist. The first one is to add rows di #### Adding rows to the rows collection -{{source=..\SamplesCS\GridView\InsertUpdateDeleteRecords\InsertUpdateDeleteRecords.cs region=addingToTheRowsCollection}} -{{source=..\SamplesVB\GridView\InsertUpdateDeleteRecords\InsertUpdateDeleteRecords.vb region=addingToTheRowsCollection}} - -````C# -object[] row1 = new object[3]; -row1[0] = 1; -row1[1] = "some text"; -row1[2] = true; -// add first row -radGridView1.Rows.Add(row1); -// add second row -radGridView1.Rows.Add(2, "another text", false); - -```` -````VB.NET -Dim row1 As Object() = New Object(3) {} -row1(0) = 1 -row1(1) = "some text" -row1(2) = True -' add first row -RadGridView1.Rows.Add(row1) -' add second row -RadGridView1.Rows.Add(2, "another text", False) - -```` - -{{endregion}} + + ## Update rows @@ -53,21 +28,8 @@ Before the value is set __Validating__ event is fired. This event could be __can #### Assigning value to a cell -{{source=..\SamplesCS\GridView\InsertUpdateDeleteRecords\InsertUpdateDeleteRecords.cs region=assigningACellValue}} -{{source=..\SamplesVB\GridView\InsertUpdateDeleteRecords\InsertUpdateDeleteRecords.vb region=assigningACellValue}} - -````C# -radGridView1.Rows[0].Cells[0].Value = 4.3; -radGridView1.Rows[1].Cells["Column1"].Value = 114f; - -```` -````VB.NET -RadGridView1.Rows(0).Cells(0).Value = 4.3 -RadGridView1.Rows(1).Cells("Column1").Value = 114.0F - -```` - -{{endregion}} + + ## Delete rows @@ -75,23 +37,8 @@ To delete row call __GridViewRowCollection.Remove__(GridViewRowInfo value) or _ #### Removing a row from the rows collection -{{source=..\SamplesCS\GridView\InsertUpdateDeleteRecords\InsertUpdateDeleteRecords.cs region=removingARowFromTheRowsCollection}} -{{source=..\SamplesVB\GridView\InsertUpdateDeleteRecords\InsertUpdateDeleteRecords.vb region=removingARowFromTheRowsCollection}} - -````C# -this.radGridView1.Rows.RemoveAt(1); -this.radGridView1.Rows.Remove(this.radGridView1.CurrentRow); - -```` -````VB.NET -Me.RadGridView1.Rows.RemoveAt(1) -Me.RadGridView1.Rows.Remove(Me.RadGridView1.CurrentRow) - -```` - -{{endregion}} - - + + # See Also * [Data Editing Event Sequence]({%slug winforms/gridview/insert/update/delete-records/data-editing-event-sequence%}) diff --git a/controls/gridview/features/editing/insert-update-delete-records/validation.md b/controls/gridview/features/editing/insert-update-delete-records/validation.md index 3c2f6eeae..3ccbbd081 100644 --- a/controls/gridview/features/editing/insert-update-delete-records/validation.md +++ b/controls/gridview/features/editing/insert-update-delete-records/validation.md @@ -21,40 +21,8 @@ strings longer than 10 characters: #### Handling the value changed event -{{source=..\SamplesCS\GridView\InsertUpdateDeleteRecords\InsertUpdateDeleteRecords.cs region=handlingValueChangingEvent}} -{{source=..\SamplesVB\GridView\InsertUpdateDeleteRecords\InsertUpdateDeleteRecords.vb region=handlingValueChangingEvent}} - -````C# -void radGridView1_ValueChanging(object sender, Telerik.WinControls.UI.ValueChangingEventArgs e) -{ - if (e.NewValue.GetType() == typeof(string)) - { - if (e.NewValue.ToString().Length > 10) - { - { - e.Cancel = true; - } - } - } -} - -```` -````VB.NET -Private Sub RadGridView1_ValueChanging(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.ValueChangingEventArgs) Handles RadGridView1.ValueChanging - If e.NewValue.GetType() Is GetType(String) Then - If e.NewValue.ToString().Length > 10 Then - If True Then - e.Cancel = True - End If - End If - End If - End Sub - -```` - -{{endregion}} - - + + # See Also * [Data Editing Event Sequence]({%slug winforms/gridview/insert/update/delete-records/data-editing-event-sequence%}) diff --git a/controls/gridview/features/exporting-data/export-data-in-a-group-to-excel.md b/controls/gridview/features/exporting-data/export-data-in-a-group-to-excel.md index f08e00998..e56a33a6a 100644 --- a/controls/gridview/features/exporting-data/export-data-in-a-group-to-excel.md +++ b/controls/gridview/features/exporting-data/export-data-in-a-group-to-excel.md @@ -15,186 +15,20 @@ Sometimes you may need to export just the data in a group in a grouped RadGridVi 1\. Create RadContextMenu and get the right-clicked group header row by using the __MouseDown__ event and the __GetGridGroupHeaderRowElement__ method. After determining the clicked group row, you can get its child rows. Then simply show the context menu: -{{source=..\SamplesCS\GridView\ExportingData\ExportDataInAGroupToExcel.cs region=createContextMenuAndGetTheGroupChildRows}} -{{source=..\SamplesVB\GridView\ExportingData\ExportDataInAGroupToExcel.vb region=createContextMenuAndGetTheGroupChildRows}} - -````C# -GridViewChildRowCollection childRowsForExport; -void radGridView1_MouseDown(object sender, MouseEventArgs e) -{ - if (e.Button == MouseButtons.Right) - { - GridGroupHeaderRowElement headerRowElement = this.GetGridGroupHeaderRowElement(e.Location); - RadContextMenu radContextMenu1 = new RadContextMenu(); - RadMenuItem contextMenuItem = new RadMenuItem(); - - contextMenuItem.Text = "Export to Excel"; - contextMenuItem.Click += new EventHandler(contextMenuItem_Click); - radContextMenu1.Items.Add(contextMenuItem); - if (headerRowElement != null) - { - this.childRowsForExport = headerRowElement.RowInfo.ChildRows; - radContextMenu1.DropDown.Location = this.PointToScreen(e.Location); - radContextMenu1.Show(); - } - } -} -private GridGroupHeaderRowElement GetGridGroupHeaderRowElement(Point location) -{ - RadElement elementUnderMouse = this.radGridView1.ElementTree.GetElementAtPoint(location); - while (elementUnderMouse != null) - { - GridGroupHeaderRowElement headerRow = elementUnderMouse as GridGroupHeaderRowElement; - if (headerRow != null) - { - return headerRow; - } - elementUnderMouse = elementUnderMouse.Parent; - } - return null; -} - -```` -````VB.NET -Private childRowsForExport As GridViewChildRowCollection -Private Sub radGridView1_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles RadGridView1.MouseDown - If e.Button = MouseButtons.Right Then - Dim headerRowElement As GridGroupHeaderRowElement = Me.GetGridGroupHeaderRowElement(e.Location) - Dim radContextMenu1 As New RadContextMenu() - Dim contextMenuItem As New RadMenuItem() - contextMenuItem.Text = "Export to Excel" - AddHandler contextMenuItem.Click, AddressOf contextMenuItem_Click - radContextMenu1.Items.Add(contextMenuItem) - If headerRowElement IsNot Nothing Then - Me.childRowsForExport = headerRowElement.RowInfo.ChildRows - radContextMenu1.DropDown.Location = Me.PointToScreen(e.Location) - radContextMenu1.Show() - End If - End If -End Sub -Private Function GetGridGroupHeaderRowElement(ByVal location As Point) As GridGroupHeaderRowElement - Dim elementUnderMouse As RadElement = Me.RadGridView1.ElementTree.GetElementAtPoint(location) - While elementUnderMouse IsNot Nothing - Dim headerRow As GridGroupHeaderRowElement = TryCast(elementUnderMouse, GridGroupHeaderRowElement) - If headerRow IsNot Nothing Then - Return headerRow - End If - elementUnderMouse = elementUnderMouse.Parent - End While - Return Nothing -End Function - -```` - -{{endregion}} + + 2\. Since the export to excel methods do not support exporting only specified records, you can work-around this if you temporarily hide the unnecessary rows and use [ExportToExcelML]({%slug winforms/gridview/exporting-data/export-to-excel-via-excelml-format%}) class with the __DonNotExport__ for __HiddenRowOption__ properties. 3\. In the click event of the context menu item, mark the rows in the RadGridView.Rows collection that match the rows of the child collection by setting their __IsVisible__ property to *true*, and all the rest to *false*. Then simply export RadGridView with __HiddenRowOption__ set to *HiddenOption.DoNotExport*: -{{source=..\SamplesCS\GridView\ExportingData\ExportDataInAGroupToExcel.cs region=markTheUnnesseceryRowsAndExportTheRestOfThem}} -{{source=..\SamplesVB\GridView\ExportingData\ExportDataInAGroupToExcel.vb region=markTheUnnesseceryRowsAndExportTheRestOfThem}} - -````C# -void contextMenuItem_Click(object sender, EventArgs e) -{ - if (this.childRowsForExport != null && this.childRowsForExport.Count > 0) - { - SaveFileDialog dialog = new SaveFileDialog(); - dialog.Filter = "Excel File (*.xls)|*.xls"; - if (dialog.ShowDialog() == DialogResult.OK) - { - //hide rows, which should not be exported - foreach (GridViewRowInfo row in this.radGridView1.Rows) - { - bool isVisible = false; - foreach (GridViewRowInfo childRow in this.childRowsForExport) - { - if (row == childRow) - { - isVisible = true; - } - } - row.IsVisible = isVisible; - } - ExportToExcelML exporter = new ExportToExcelML(this.radGridView1); - exporter.HiddenRowOption = HiddenOption.DoNotExport; - exporter.RunExport(dialog.FileName); - MessageBox.Show("Export Finished"); - } - //show all rows - foreach (GridViewRowInfo row in this.radGridView1.Rows) - { - row.IsVisible = true; - } - } - //release resources - RadMenuItem menuItem = (RadMenuItem)sender; - menuItem.Click -= contextMenuItem_Click; - this.childRowsForExport = null; -} - -```` -````VB.NET -Private Sub contextMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) - If Me.childRowsForExport IsNot Nothing AndAlso Me.childRowsForExport.Count > 0 Then - Dim dialog As New SaveFileDialog() - dialog.Filter = "Excel File (*.xls)|*.xls" - If dialog.ShowDialog() = DialogResult.OK Then - 'hide rows, which should not be exported - For Each row As GridViewRowInfo In Me.RadGridView1.Rows - Dim isVisible As Boolean = False - For Each childRow As GridViewRowInfo In Me.childRowsForExport - If row.Equals(childRow) Then - isVisible = True - End If - Next - row.IsVisible = isVisible - Next - Dim exporter As New ExportToExcelML(Me.RadGridView1) - exporter.HiddenRowOption = HiddenOption.DoNotExport - exporter.RunExport(dialog.FileName) - MessageBox.Show("Export Finished") - End If - 'show all rows - For Each row As GridViewRowInfo In Me.RadGridView1.Rows - row.IsVisible = True - Next - End If - 'release resources - Dim menuItem As RadMenuItem = DirectCast(sender, RadMenuItem) - RemoveHandler menuItem.Click, AddressOf contextMenuItem_Click - Me.childRowsForExport = Nothing -End Sub - -```` - -{{endregion}} + + 4\. If you need to get the text from the GroupRowHeader, use the following snippet: -{{source=..\SamplesCS\GridView\ExportingData\ExportDataInAGroupToExcel.cs region=getTheGroupLineText}} -{{source=..\SamplesVB\GridView\ExportingData\ExportDataInAGroupToExcel.vb region=getTheGroupLineText}} - -````C# -private string GetGroupLineHeaderText(GridGroupHeaderRowElement headerRowElement) -{ - string headerText = headerRowElement.RowInfo.Group.GroupRow.HeaderText; - return headerText; -} - -```` -````VB.NET -Private Function GetGroupLineHeaderText(ByVal headerRowElement As GridGroupHeaderRowElement) As String - Dim headerText As String = headerRowElement.RowInfo.Group.GroupRow.HeaderText - Return headerText -End Function - -```` - -{{endregion}} - - + + ## See Also * [Export to CSV]({%slug winforms/gridview/exporting-data/export-to-csv%}) diff --git a/controls/gridview/features/exporting-data/export-to-csv.md b/controls/gridview/features/exporting-data/export-to-csv.md index d6c26b2d2..d7970bb16 100644 --- a/controls/gridview/features/exporting-data/export-to-csv.md +++ b/controls/gridview/features/exporting-data/export-to-csv.md @@ -33,19 +33,8 @@ Before running export to CSV, you have to initialize the ExportToCSV class. The #### ExportToCSV initialization -{{source=..\SamplesCS\GridView\ExportingData\ExportToCSV1.cs region=exportToCsvInitialization}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToCSV1.vb region=exportToCsvInitialization}} - -````C# -ExportToCSV exporter = new ExportToCSV(this.radGridView1); - -```` -````VB.NET -Dim exporter As ExportToCSV = New ExportToCSV(Me.RadGridView1) - -```` - -{{endregion}} + + ### File Extension @@ -53,19 +42,8 @@ This property allows for changing the default (*.csv) file extension of the expo #### Setting the file extension -{{source=..\SamplesCS\GridView\ExportingData\ExportToCSV1.cs region=settingTheFileExtention}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToCSV1.vb region=settingTheFileExtention}} - -````C# -exporter.FileExtension = ""; - -```` -````VB.NET -exporter.FileExtension = "" - -```` - -{{endregion}} + + ### Hidden Columns and Rows Option @@ -91,19 +69,8 @@ You can use __SummariesExportOption__ property to specify how to export summary #### Setting summaries to export -{{source=..\SamplesCS\GridView\ExportingData\ExportToCSV1.cs region=settingSummariesToExport}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToCSV1.vb region=settingSummariesToExport}} - -````C# -exporter.SummariesExportOption = SummariesOption.DoNotExport; - -```` -````VB.NET -exporter.SummariesExportOption = SummariesOption.DoNotExport - -```` - -{{endregion}} + + ## RunExport method @@ -113,21 +80,8 @@ Exporting data to CSV file is done through the RunExport method of the `ExportTo #### Export to CVS format -{{source=..\SamplesCS\GridView\ExportingData\ExportToCSV1.cs region=exportToCsvFormat}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToCSV1.vb region=exportToCsvFormat}} - -````C# -string fileName = "C:\\ExportedData.csv"; -exporter.RunExport(fileName); - -```` -````VB.NET -Dim fileName As String = "C:\\ExportedData.csv" -exporter.RunExport(fileName) - -```` - -{{endregion}} + + ## Events @@ -137,29 +91,8 @@ It gives access to a single cell’s element that allows you to replace the actu #### Handling the CSVCellFormatting event -{{source=..\SamplesCS\GridView\ExportingData\ExportToCSV1.cs region=handlingTheCsvCellFormattingEvent}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToCSV1.vb region=handlingTheCsvCellFormattingEvent}} - -````C# -void exporter_CSVCellFormatting(object sender, Telerik.WinControls.UI.Export.CSV.CSVCellFormattingEventArgs e) -{ - if (e.GridColumnIndex == 1 && e.GridRowInfoType == typeof(GridViewDataRowInfo)) - { - e.CSVCellElement.Value = "test value"; - } -} - -```` -````VB.NET -Private Sub exporter_CSVCellFormatting(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.Export.CSV.CSVCellFormattingEventArgs) - If (e.GridColumnIndex = 1 AndAlso e.GridRowInfoType.Equals(GetType(GridViewDataRowInfo))) Then - e.CSVCellElement.Value = "test value" - End If -End Sub - -```` - -{{endregion}} + + __CSVTableCreated event__: @@ -167,28 +100,8 @@ It can be used together with the public method __AddCustomCSVRow__. It allows fo #### Handling the CSVTableCreated event -{{source=..\SamplesCS\GridView\ExportingData\ExportToCSV1.cs region=handlingTheCsvTableCreatedevent}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToCSV1.vb region=handlingTheCsvTableCreatedevent}} - -````C# -void exporter_CSVTableCreated(object sender, Telerik.WinControls.UI.Export.CSV.CSVTableCreatedEventArgs e) -{ - ((ExportToCSV)sender).AddCustomCSVRow(e.CSVTableElement, "MY TABLE CAPTION"); -} - -```` -````VB.NET -Private Sub exporter_CSVTableCreated(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.Export.CSV.CSVTableCreatedEventArgs) - DirectCast(sender, ExportToCSV).AddCustomCSVRow(e.CSVTableElement, "MY TABLE CAPTION") -End Sub - -```` - -{{endregion}} - - - - + + ## See Also * [Export Data in a Group to Excel]({%slug winforms/gridview/exporting-data/export-data-in-a-group-to-excel%}) diff --git a/controls/gridview/features/exporting-data/export-to-excel-via-excelml-format.md b/controls/gridview/features/exporting-data/export-to-excel-via-excelml-format.md index c3701f55d..d9bfc7821 100644 --- a/controls/gridview/features/exporting-data/export-to-excel-via-excelml-format.md +++ b/controls/gridview/features/exporting-data/export-to-excel-via-excelml-format.md @@ -26,19 +26,8 @@ Before running export to **ExcelML**, you have to initialize the `ExportToExcelM #### ExportToExcelIML initialization -{{source=..\SamplesCS\GridView\ExportingData\ExportToExcelViaExcelIMLFormat.cs region=ExportToExcelMLInitialization}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToExcelViaExcelIMLFormat.vb region=ExportToExcelMLInitialization}} - -````C# -ExportToExcelML exporter = new ExportToExcelML(this.radGridView1); - -```` -````VB.NET -Dim exporter As ExportToExcelML = New ExportToExcelML(Me.RadGridView1) - -```` - -{{endregion}} + + __Hidden columns and rows option__ @@ -54,19 +43,8 @@ MS Excel does not support other ways of hiding a column different from setting i #### Setting the hidden column option -{{source=..\SamplesCS\GridView\ExportingData\ExportToExcelViaExcelIMLFormat.cs region=settingTheHiddenColumnOption}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToExcelViaExcelIMLFormat.vb region=settingTheHiddenColumnOption}} - -````C# -exporter.HiddenColumnOption = Telerik.WinControls.UI.Export.HiddenOption.DoNotExport; - -```` -````VB.NET -exporter.HiddenColumnOption = Telerik.WinControls.UI.Export.HiddenOption.DoNotExport - -```` - -{{endregion}} + + __Exporting Visual Settings__ @@ -76,19 +54,8 @@ You can enable exporting visual settings through the **ExportVisualSettings** pr #### Setting ExportVisualSettings -{{source=..\SamplesCS\GridView\ExportingData\ExportToExcelViaExcelIMLFormat.cs region=exportVisualSettings}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToExcelViaExcelIMLFormat.vb region=exportVisualSettings}} - -````C# -exporter.ExportVisualSettings = true; - -```` -````VB.NET -exporter.ExportVisualSettings = True - -```` - -{{endregion}} + + __MS Excel Max Rows Settings__ @@ -100,19 +67,8 @@ __MS Excel Max Rows Settings__ #### Setting Maximum Number of Rows -{{source=..\SamplesCS\GridView\ExportingData\ExportToExcelViaExcelIMLFormat.cs region=settingMaximumNumberOfRows}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToExcelViaExcelIMLFormat.vb region=settingMaximumNumberOfRows}} - -````C# -exporter.SheetMaxRows = ExcelMaxRows._1048576; - -```` -````VB.NET -exporter.SheetMaxRows = ExcelMaxRows._1048576 - -```` - -{{endregion}} + + __MS Excel Sheet Name__ @@ -120,19 +76,8 @@ You can specify the sheet name through __SheetName__ property. If your data is l #### Setting the SheetName -{{source=..\SamplesCS\GridView\ExportingData\ExportToExcelViaExcelIMLFormat.cs region=settingTheSheetName}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToExcelViaExcelIMLFormat.vb region=settingTheSheetName}} - -````C# -exporter.SheetName = "Sheet"; - -```` -````VB.NET -exporter.SheetName = "Sheet" - -```` - -{{endregion}} + + __Summaries export option__ @@ -148,19 +93,8 @@ You can use the __SummariesExportOption__ property to specify how to export summ #### Setting SummariesExportOption -{{source=..\SamplesCS\GridView\ExportingData\ExportToExcelViaExcelIMLFormat.cs region=settingSumariesExportOption}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToExcelViaExcelIMLFormat.vb region=settingSumariesExportOption}} - -````C# -exporter.SummariesExportOption = SummariesOption.DoNotExport; - -```` -````VB.NET -exporter.SummariesExportOption = SummariesOption.DoNotExport - -```` - -{{endregion}} + + ## RunExport method @@ -172,21 +106,8 @@ Consider the code sample below: #### Export to Excel in ExcelML format -{{source=..\SamplesCS\GridView\ExportingData\ExportToExcelViaExcelIMLFormat.cs region=runExport}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToExcelViaExcelIMLFormat.vb region=runExport}} - -````C# -string fileName = "C:\\ExportedData123.xls"; -exporter.RunExport(fileName); - -```` -````VB.NET -Dim fileName As String = "C:\\ExportedData.xls" -exporter.RunExport(fileName) - -```` - -{{endregion}} + + ## Format Codes @@ -196,21 +117,8 @@ Here is an example for a date time formatting: #### Fomatting dates -{{source=..\SamplesCS\GridView\ExportingData\ExportToExcelViaExcelIMLFormat.cs region=formattingCodes}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToExcelViaExcelIMLFormat.vb region=formattingCodes}} - -````C# -this.radGridView1.Columns["Date"].ExcelExportType = DisplayFormatType.Custom; -this.radGridView1.Columns["Date"].ExcelExportFormatString = "yyyy.MMMM.dd hh:mm:ss AM/PM"; - -```` -````VB.NET -Me.RadGridView1.Columns("Date").ExcelExportType = DisplayFormatType.Custom -Me.RadGridView1.Columns("Date").ExcelExportFormatString = " yyyy.MMMM.dd hh:mm:ss AM/PM " - -```` - -{{endregion}} + + ## Events @@ -220,47 +128,8 @@ It gives you access to a single cell’s __SingleStyleElement__ that allows you #### Handling the ExcelCellFormatting event -{{source=..\SamplesCS\GridView\ExportingData\ExportToExcelViaExcelIMLFormat.cs region=ExcelCellFormatting}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToExcelViaExcelIMLFormat.vb region=ExcelCellFormatting}} - -````C# -void exporter_ExcelCellFormatting(object sender, Telerik.WinControls.UI.Export.ExcelML.ExcelCellFormattingEventArgs e) -{ - if (e.GridRowInfoType == typeof(GridViewTableHeaderRowInfo)) - { - BorderStyles border = new BorderStyles(); - border.Color = Color.Black; - border.Weight = 2; - border.LineStyle = Telerik.WinControls.UI.Export.ExcelML.LineStyle.Continuous; - border.PositionType = PositionType.Bottom; - e.ExcelStyleElement.Borders.Add(border); - } - else if (e.GridRowIndex == 2 && e.GridColumnIndex == 1) - { - e.ExcelStyleElement.InteriorStyle.Color = Color.Yellow; - e.ExcelStyleElement.AlignmentElement.WrapText = true; - } -} - -```` -````VB.NET -Private Sub exporter_ExcelCellFormatting(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.Export.ExcelML.ExcelCellFormattingEventArgs) - If e.GridRowInfoType Is GetType(GridViewTableHeaderRowInfo) Then - Dim border As BorderStyles = New BorderStyles() - border.Color = Color.Black - border.Weight = 2 - border.LineStyle = Telerik.WinControls.UI.Export.ExcelML.LineStyle.Continuous - border.PositionType = PositionType.Bottom - e.ExcelStyleElement.Borders.Add(border) - ElseIf e.GridRowIndex = 2 AndAlso e.GridColumnIndex = 1 Then - e.ExcelStyleElement.InteriorStyle.Color = Color.Yellow - e.ExcelStyleElement.AlignmentElement.WrapText = True - End If -End Sub - -```` - -{{endregion}} + + The __ExcelTableCreated event:__ @@ -268,40 +137,8 @@ It can be used together with the public method __AddCustomExcelRow__. It allows #### Handling the ExcelTableCreated event -{{source=..\SamplesCS\GridView\ExportingData\ExportToExcelViaExcelIMLFormat.cs region=ExcelTableCreated}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToExcelViaExcelIMLFormat.vb region=ExcelTableCreated}} - -````C# -void exporter_ExcelTableCreated(object sender, ExcelTableCreatedEventArgs e) -{ - string headerText = "Custom added header text."; - SingleStyleElement style = ((ExportToExcelML)sender).AddCustomExcelRow(e.ExcelTableElement, 50, headerText); - style.FontStyle.Bold = true; - style.FontStyle.Size = 18; - style.FontStyle.Color = Color.White; - style.InteriorStyle.Color = Color.Red; - style.InteriorStyle.Pattern = InteriorPatternType.Solid; - style.AlignmentElement.HorizontalAlignment = HorizontalAlignmentType.Center; - style.AlignmentElement.VerticalAlignment = VerticalAlignmentType.Center; -} - -```` -````VB.NET -Private Sub exporter_ExcelTableCreated(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.Export.ExcelML.ExcelTableCreatedEventArgs) - Dim headerText As String = "Custom added header text." - Dim style As SingleStyleElement = (CType(sender, ExportToExcelML)).AddCustomExcelRow(e.ExcelTableElement, 50, headerText) - style.FontStyle.Bold = True - style.FontStyle.Size = 18 - style.FontStyle.Color = Color.White - style.InteriorStyle.Color = Color.Red - style.InteriorStyle.Pattern = InteriorPatternType.Solid - style.AlignmentElement.HorizontalAlignment = HorizontalAlignmentType.Center - style.AlignmentElement.VerticalAlignment = VerticalAlignmentType.Center -End Sub - -```` - -{{endregion}} + + ## diff --git a/controls/gridview/features/exporting-data/export-to-pdf.md b/controls/gridview/features/exporting-data/export-to-pdf.md index 5854b434b..0b3224048 100644 --- a/controls/gridview/features/exporting-data/export-to-pdf.md +++ b/controls/gridview/features/exporting-data/export-to-pdf.md @@ -34,20 +34,8 @@ Before running export to PDF, you have to initialize the __GridViewPdfExport__ c #### GridViewPdfExport initialization -{{source=..\SamplesCS\GridView\ExportingData\GridViewPdfExport.cs region=InitializePdfExporter}} -{{source=..\SamplesVB\GridView\ExportingData\GridViewPdfExport.vb region=InitializePdfExporter}} - -````C# - -Telerik.WinControls.Export.GridViewPdfExport pdfExporter = new Telerik.WinControls.Export.GridViewPdfExport(this.radGridView1); - -```` -````VB.NET -Dim pdfExporter As New Telerik.WinControls.Export.GridViewPdfExport(Me.RadGridView1) - -```` - -{{endregion}} + + ### File Extension @@ -55,20 +43,8 @@ The __FileExtension__ property allows you to change the default (*.pdf) file ext #### Setting the file extension -{{source=..\SamplesCS\GridView\ExportingData\GridViewPdfExport.cs region=SetFileExtension}} -{{source=..\SamplesVB\GridView\ExportingData\GridViewPdfExport.vb region=SetFileExtension}} - -````C# - -pdfExporter.FileExtension = ".pdf"; - -```` -````VB.NET -pdfExporter.FileExtension = ".pdf" - -```` - -{{endregion}} + + ### Hidden columns and rows option @@ -83,20 +59,8 @@ __GridViewPdfExport__ uses the default enumeration of hidden column and row sett #### Setting the HiddenColumnOption -{{source=..\SamplesCS\GridView\ExportingData\GridViewPdfExport.cs region=SetHiddenPref}} -{{source=..\SamplesVB\GridView\ExportingData\GridViewPdfExport.vb region=SetHiddenPref}} - -````C# - -pdfExporter.HiddenColumnOption = Telerik.WinControls.UI.Export.HiddenOption.DoNotExport; - -```` -````VB.NET -pdfExporter.HiddenColumnOption = Telerik.WinControls.UI.Export.HiddenOption.DoNotExport - -```` - -{{endregion}} + + ### Header and Footer @@ -104,77 +68,20 @@ Before applying customizations to the headers and footers we need to enable them #### Enabling headers and footers -{{source=..\SamplesCS\GridView\ExportingData\GridViewPdfExport.cs region=ShowHeaderAndFooter}} -{{source=..\SamplesVB\GridView\ExportingData\GridViewPdfExport.vb region=ShowHeaderAndFooter}} - -````C# - -pdfExporter.ShowHeaderAndFooter = true; - -```` -````VB.NET -pdfExporter.ShowHeaderAndFooter = True - -```` - -{{endregion}} - + + #### Customizing headers and footers -{{source=..\SamplesCS\GridView\ExportingData\GridViewPdfExport.cs region=CustomizeHeaderAndFooter}} -{{source=..\SamplesVB\GridView\ExportingData\GridViewPdfExport.vb region=CustomizeHeaderAndFooter}} - -````C# - -pdfExporter.HeaderHeight = 30; -pdfExporter.HeaderFont = new Font("Arial", 22); -pdfExporter.Logo = System.Drawing.Image.FromFile(@"C:\MyLogo.png"); -pdfExporter.LeftHeader = "[Logo]"; -pdfExporter.LogoAlignment = ContentAlignment.MiddleLeft; -pdfExporter.LogoLayout = Telerik.WinControls.Export.LogoLayout.Fit; - -pdfExporter.MiddleHeader = "Middle header"; -pdfExporter.RightHeader = "Right header"; -pdfExporter.ReverseHeaderOnEvenPages = true; - -pdfExporter.FooterHeight = 30; -pdfExporter.FooterFont = new Font("Arial", 22); -pdfExporter.LeftFooter = "Left footer"; -pdfExporter.MiddleFooter = "Middle footer"; -pdfExporter.RightFooter = "Right footer"; -pdfExporter.ReverseFooterOnEvenPages = true; - -```` -````VB.NET -pdfExporter.HeaderHeight = 30 -pdfExporter.HeaderFont = New Font("Arial", 22) -pdfExporter.Logo = System.Drawing.Image.FromFile("C:\MyLogo.png") -pdfExporter.LeftHeader = "[Logo]" -pdfExporter.LogoAlignment = ContentAlignment.MiddleLeft -pdfExporter.LogoLayout = Telerik.WinControls.Export.LogoLayout.Fit -pdfExporter.MiddleHeader = "Middle header" -pdfExporter.RightHeader = "Right header" -pdfExporter.ReverseHeaderOnEvenPages = True -pdfExporter.FooterHeight = 30 -pdfExporter.FooterFont = New Font("Arial", 22) -pdfExporter.LeftFooter = "Left footer" -pdfExporter.MiddleFooter = "Middle footer" -pdfExporter.RightFooter = "Right footer" -pdfExporter.ReverseFooterOnEvenPages = True - -```` - -{{endregion}} + + The __HeaderExported__ event can be used to perform custom drawing in the header. The following example shows how you can draw a two line header. #### Using the HeaderExported event -{{source=..\SamplesCS\GridView\ExportingData\GridViewPdfExport.cs region=HeaderExportedEvent}} -{{source=..\SamplesVB\GridView\ExportingData\GridViewPdfExport.vb region=HeaderExportedEvent}} - -{{endregion}} + + ### Summaries export option @@ -190,20 +97,8 @@ The __SummariesExportOption__ property to specifies how to export summary items. #### Setting summary items -{{source=..\SamplesCS\GridView\ExportingData\GridViewPdfExport.cs region=SetSummaryItems}} -{{source=..\SamplesVB\GridView\ExportingData\GridViewPdfExport.vb region=SetSummaryItems}} - -````C# - -pdfExporter.SummariesExportOption = SummariesOption.ExportAll; - -```` -````VB.NET -pdfExporter.SummariesExportOption = SummariesOption.ExportAll - -```` - -{{endregion}} + + ### Fit to page @@ -211,20 +106,8 @@ Use this property to make the grid fits to the PDF page width. #### Setting FitToPageWidth -{{source=..\SamplesCS\GridView\ExportingData\GridViewPdfExport.cs region=SetFitToPage}} -{{source=..\SamplesVB\GridView\ExportingData\GridViewPdfExport.vb region=SetFitToPage}} - -````C# - -pdfExporter.FitToPageWidth = true; - -```` -````VB.NET -pdfExporter.FitToPageWidth = True - -```` - -{{endregion}} + + ### Scale @@ -232,20 +115,8 @@ You can use __Scale__ to change the grid size on the PDF. For example if __Scale #### Setting scale -{{source=..\SamplesCS\GridView\ExportingData\GridViewPdfExport.cs region=SetScale}} -{{source=..\SamplesVB\GridView\ExportingData\GridViewPdfExport.vb region=SetScale}} - -````C# - -pdfExporter.Scale = 1.2; - -```` -````VB.NET -pdfExporter.Scale = 1.2 - -```` - -{{endregion}} + + __PDF Export Settings__ @@ -259,20 +130,8 @@ The __PDFExportSettings__ property supports various settings on PDF file level. #### Using export settings -{{source=..\SamplesCS\GridView\ExportingData\GridViewPdfExport.cs region=ExportSettings}} -{{source=..\SamplesVB\GridView\ExportingData\GridViewPdfExport.vb region=ExportSettings}} - -````C# - -pdfExporter.ExportSettings.Description = "Document Description"; - -```` -````VB.NET -pdfExporter.ExportSettings.Description = "Document Description" - -```` - -{{endregion}} + + __ExportViewDefinition__ @@ -300,20 +159,8 @@ The __PDFExportSettings__ property supports various settings on PDF file level. #### Using export settings -{{source=..\SamplesCS\GridView\ExportingData\GridViewPdfExport.cs region=ExportSettings}} -{{source=..\SamplesVB\GridView\ExportingData\GridViewPdfExport.vb region=ExportSettings}} - -````C# - -pdfExporter.ExportSettings.Description = "Document Description"; - -```` -````VB.NET -pdfExporter.ExportSettings.Description = "Document Description" - -```` - -{{endregion}} + + ### Exporting to PDF @@ -323,135 +170,27 @@ Two methods are responsible for exporting data to PDF. Both receive as a paramet #### Running export -{{source=..\SamplesCS\GridView\ExportingData\GridViewPdfExport.cs region=RunExport}} -{{source=..\SamplesVB\GridView\ExportingData\GridViewPdfExport.vb region=RunExport}} - -````C# - -string fileName = "c:\\ExportedData.pdf"; -pdfExporter.RunExport(fileName, new Telerik.WinControls.Export.PdfExportRenderer()); - -```` -````VB.NET -Dim fileName As String = "c:\ExportedData.pdf" -pdfExporter.RunExport(fileName, New Telerik.WinControls.Export.PdfExportRenderer()) - -```` - -{{endregion}} - + + The __RunExport__ method has several overloads allowing the user to export using a stream as well: #### Running export synchronously using a stream -{{source=..\SamplesCS\GridView\ExportingData\GridViewPdfExport.cs region=StreamRunExport}} -{{source=..\SamplesVB\GridView\ExportingData\GridViewPdfExport.vb region=StreamRunExport}} - -````C# - -string exportFile = @"..\..\exportedData.pdf"; -using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) -{ - Telerik.WinControls.Export.GridViewPdfExport exporter = new Telerik.WinControls.Export.GridViewPdfExport(this.radGridView1); - Telerik.WinControls.Export.PdfExportRenderer renderer = new Telerik.WinControls.Export.PdfExportRenderer(); - exporter.RunExport(ms, renderer); - - using (System.IO.FileStream fileStream = new System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write)) - { - ms.WriteTo(fileStream); - } -} - -```` -````VB.NET -Dim exportFile As String = "..\..\exportedData.pdf" -Using ms As New System.IO.MemoryStream() - Dim exporter As New Telerik.WinControls.Export.GridViewPdfExport(Me.RadGridView1) - Dim renderer As New Telerik.WinControls.Export.PdfExportRenderer() - exporter.RunExport(ms, renderer) - Using fileStream As New System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write) - ms.WriteTo(fileStream) - End Using -End Using - -```` - -{{endregion}} - + + * RunExportAsync: Runs on a thread different than the UI thread. #### Running export asynchronously -{{source=..\SamplesCS\GridView\ExportingData\GridViewPdfExport.cs region=RunExportAsync}} -{{source=..\SamplesVB\GridView\ExportingData\GridViewPdfExport.vb region=RunExportAsync}} - -````C# - -string fileNameAsync = "c:\\ExportedDataAsync.pdf"; -pdfExporter.RunExportAsync(fileNameAsync, new Telerik.WinControls.Export.PdfExportRenderer()); - -```` -````VB.NET -Dim fileNameAsync As String = "c:\ExportedDataAsync.pdf" -pdfExporter.RunExportAsync(fileNameAsync, New Telerik.WinControls.Export.PdfExportRenderer()) - -```` - -{{endregion}} - + + The __RunExportAsync__ method has several overloads allowing the user to export using a stream as well: -{{source=..\SamplesCS\GridView\ExportingData\GridViewPdfExport.cs region=StreamRunExportAsync}} -{{source=..\SamplesVB\GridView\ExportingData\GridViewPdfExport.vb region=StreamRunExportAsync}} - -````C# - -private void radButton1_Click(object sender, EventArgs e) -{ - System.IO.MemoryStream ms = new System.IO.MemoryStream(); - Telerik.WinControls.Export.GridViewPdfExport pdfExporter = new Telerik.WinControls.Export.GridViewPdfExport(this.radGridView1); - Telerik.WinControls.Export.PdfExportRenderer renderer = new Telerik.WinControls.Export.PdfExportRenderer(); - pdfExporter.AsyncExportCompleted += pdfExporter_AsyncExportCompleted; - pdfExporter.RunExportAsync(ms, renderer); -} - -private void pdfExporter_AsyncExportCompleted(object sender, AsyncCompletedEventArgs e) -{ - RunWorkerCompletedEventArgs args = e as RunWorkerCompletedEventArgs; - string exportFile = @"..\..\exportedAsyncData.pdf"; - using (System.IO.FileStream fileStream = new System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write)) - { - MemoryStream ms = args.Result as MemoryStream; - ms.WriteTo(fileStream); - ms.Close(); - } -} - -```` -````VB.NET -Private Sub radButton1_Click(sender As Object, e As EventArgs) - Dim ms As New System.IO.MemoryStream() - Dim pdfExporter As New Telerik.WinControls.Export.GridViewPdfExport(Me.RadGridView1) - Dim renderer As New Telerik.WinControls.Export.PdfExportRenderer() - AddHandler pdfExporter.AsyncExportCompleted, AddressOf pdfExporter_AsyncExportCompleted - pdfExporter.RunExportAsync(ms, renderer) -End Sub -Private Sub pdfExporter_AsyncExportCompleted(sender As Object, e As AsyncCompletedEventArgs) - Dim args As RunWorkerCompletedEventArgs = TryCast(e, RunWorkerCompletedEventArgs) - Dim exportFile As String = "..\..\exportedAsyncData.pdf" - Using fileStream As New System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write) - Dim ms As MemoryStream = TryCast(args.Result, MemoryStream) - ms.WriteTo(fileStream) - ms.Close() - End Using -End Sub - -```` - -{{endregion}} + + ## Events @@ -467,19 +206,8 @@ Before running export to PDF, you have to initialize the __ExportToPDF__ class. #### ExportToPDF initialization -{{source=..\SamplesCS\GridView\ExportingData\ExportToPDF1.cs region=exportToPdfInitialization}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToPDF1.vb region=exportToPdfInitialization}} - -````C# -ExportToPDF exporter = new ExportToPDF(this.radGridView1); - -```` -````VB.NET -Dim exporter As New ExportToPDF(Me.RadGridView1) - -```` - -{{endregion}} + + ### File Extension @@ -487,19 +215,8 @@ The __FileExtension__ property allows you to change the default (*.pdf) file ext #### Setting the FileExtension -{{source=..\SamplesCS\GridView\ExportingData\ExportToPDF1.cs region=settingTheFileExtension}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToPDF1.vb region=settingTheFileExtension}} - -````C# -exporter.FileExtension = "pdf"; - -```` -````VB.NET -exporter.FileExtension = "pdf" - -```` - -{{endregion}} + + ### Hidden columns and rows option @@ -513,19 +230,8 @@ __ExportToPDF__ uses the default enumeration of hidden column and row settings. #### Setting the HiddenColumnOption -{{source=..\SamplesCS\GridView\ExportingData\ExportToPDF1.cs region=settingTheHiddenColumnOption}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToPDF1.vb region=settingTheHiddenColumnOption}} - -````C# -exporter.HiddenColumnOption = Telerik.WinControls.UI.Export.HiddenOption.DoNotExport; - -```` -````VB.NET -exporter.HiddenColumnOption = Telerik.WinControls.UI.Export.HiddenOption.DoNotExport - -```` - -{{endregion}} + + ### Exporting Visual Settings @@ -533,19 +239,8 @@ Using the __ExportToPDF__ class allows you to export the visual settings (themes #### Setting the ExportVisualSettings -{{source=..\SamplesCS\GridView\ExportingData\ExportToPDF1.cs region=settingExportVisualSettings}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToPDF1.vb region=settingExportVisualSettings}} - -````C# -exporter.ExportVisualSettings = true; - -```` -````VB.NET -exporter.ExportVisualSettings = True - -```` - -{{endregion}} + + ### Page Title @@ -553,19 +248,8 @@ You can add a page title which will be presented on every page of the PDF docume #### Setting the PageTitle -{{source=..\SamplesCS\GridView\ExportingData\ExportToPDF1.cs region=settingThePageTitleProperty}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToPDF1.vb region=settingThePageTitleProperty}} - -````C# -exporter.PageTitle = "Title"; - -```` -````VB.NET -exporter.PageTitle = "Title" - -```` - -{{endregion}} + + ### Summaries export option @@ -581,19 +265,8 @@ You can use __SummariesExportOption__ property to specify how to export summary #### Setting the SummariesExportOption -{{source=..\SamplesCS\GridView\ExportingData\ExportToPDF1.cs region=settingSummariesExportOption}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToPDF1.vb region=settingSummariesExportOption}} - -````C# -exporter.SummariesExportOption = SummariesOption.ExportAll; - -```` -````VB.NET -exporter.SummariesExportOption = SummariesOption.ExportAll - -```` - -{{endregion}} + + ### Fit to page @@ -601,19 +274,8 @@ Use this property to make the grid fits to the PDF page width. #### Setting the FitToPageWidth -{{source=..\SamplesCS\GridView\ExportingData\ExportToPDF1.cs region=settingFitToPageWidth}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToPDF1.vb region=settingFitToPageWidth}} - -````C# -exporter.FitToPageWidth = true; - -```` -````VB.NET -exporter.FitToPageWidth = True - -```` - -{{endregion}} + + ### Scale @@ -621,19 +283,8 @@ You can use __Scale__ to change the grid size on the PDF. For example if __Scale #### Setting the Scale -{{source=..\SamplesCS\GridView\ExportingData\ExportToPDF1.cs region=settingScale}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToPDF1.vb region=settingScale}} - -````C# -exporter.Scale = 1.2f; - -```` -````VB.NET -exporter.Scale = 1.2F - -```` - -{{endregion}} + + ### TableBorderThickness @@ -641,19 +292,8 @@ This property controls the thickness of the table border. The default value is 0 #### Setting the TableBorderTickness -{{source=..\SamplesCS\GridView\ExportingData\ExportToPDF1.cs region=settingTableBorderTickness}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToPDF1.vb region=settingTableBorderTickness}} - -````C# -exporter.TableBorderThickness = 1; - -```` -````VB.NET -exporter.TableBorderThickness = 1 - -```` - -{{endregion}} + + ### PDF Export Settings @@ -687,21 +327,8 @@ The __PDFExportSettings__ property supports various settings on PDF file level. #### Setting the PDFDocumentSettings -{{source=..\SamplesCS\GridView\ExportingData\ExportToPDF1.cs region=pdfDocumentSettings}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToPDF1.vb region=pdfDocumentSettings}} - -````C# -exporter.PdfExportSettings.PageHeight = 210; -exporter.PdfExportSettings.PageWidth = 297; - -```` -````VB.NET -exporter.PdfExportSettings.PageHeight = 210 - exporter.PdfExportSettings.PageWidth = 297 - -```` - -{{endregion}} + + ## RunExport method @@ -713,21 +340,8 @@ Consider the code sample below: #### Exporting to PDF format -{{source=..\SamplesCS\GridView\ExportingData\ExportToPDF1.cs region=exportingToPdfFormat}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToPDF1.vb region=exportingToPdfFormat}} - -````C# -string fileName = "c:\\ExportedData.pdf"; -exporter.RunExport(fileName); - -```` -````VB.NET -Dim fileName As String = "c:\ExportedData.pdf" - exporter.RunExport(fileName) - -```` - -{{endregion}} + + ## Events @@ -735,58 +349,16 @@ __HTMLCellFormating__ event: Since the the export process first renders RadGrid #### Handling the HTMLCellFormatting event -{{source=..\SamplesCS\GridView\ExportingData\ExportToPDF1.cs region=hanglingHtmlCellFormattingEvent}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToPDF1.vb region=hanglingHtmlCellFormattingEvent}} - -````C# -void exporter_HTMLCellFormatting(object sender, Telerik.WinControls.UI.Export.HTML.HTMLCellFormattingEventArgs e) -{ - if (e.GridColumnIndex == 1 && e.GridRowInfoType == typeof(GridViewDataRowInfo)) - { - e.HTMLCellElement.Value = "Test value"; - e.HTMLCellElement.Styles.Add("background-color", ColorTranslator.ToHtml(Color.Orange)); - } -} - -```` -````VB.NET -Private Sub exporter_HTMLCellFormatting(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.Export.HTML.HTMLCellFormattingEventArgs) - If e.GridColumnIndex = 1 AndAlso e.GridRowInfoType.Equals(GetType(GridViewDataRowInfo)) Then - e.HTMLCellElement.Value = "Test value" - e.HTMLCellElement.Styles.Add("background-color", ColorTranslator.ToHtml(Color.Orange)) - End If - End Sub - -```` - -{{endregion}} + + ## Fonts / Unicode support __ExportToPDF__ supports all left-to-right languages when the appropriate Unicode font is set. The most common international font is [Arial Unicode MS](http://support.microsoft.com/kb/287247), because it covers all Unicode characters. Of course, you can use other-specific fonts such as [Batang](http://www.ascenderfonts.com/font/batang-korean.aspx) for Korean, [SimSun](http://www.ascenderfonts.com/font/simsun-simplified-chinese.aspx) for Chinese, [MS Mincho](http://www.ascenderfonts.com/font/ms-mincho-japanese.aspx) for Japanese, etc. -{{source=..\SamplesCS\GridView\ExportingData\ExportToPDF1.cs region=htmlCellFormattingUnicode}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToPDF1.vb region=htmlCellFormattingUnicode}} - -````C# -void pdfExporter_HTMLCellFormatting(object sender, HTMLCellFormattingEventArgs e) -{ - //The following sets unicode font for every cell. - e.HTMLCellElement.Styles.Remove("font-family"); - e.HTMLCellElement.Styles.Add("font-family", "Arial Unicode MS"); -} - -```` -````VB.NET -Private Sub pdfExporter_HTMLCellFormatting(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.Export.HTML.HTMLCellFormattingEventArgs) - 'The following sets unicode font for every cell. - e.HTMLCellElement.Styles.Remove("font-family") - e.HTMLCellElement.Styles.Add("font-family", "Arial Unicode MS") -End Sub - -```` + + -{{endregion}} # See Also * [Export Data in a Group to Excel]({%slug winforms/gridview/exporting-data/export-data-in-a-group-to-excel%}) diff --git a/controls/gridview/features/exporting-data/how-to/add-header-and-footer-to-the-exported-document.md b/controls/gridview/features/exporting-data/how-to/add-header-and-footer-to-the-exported-document.md index 5a510ca52..4b0d0eed8 100644 --- a/controls/gridview/features/exporting-data/how-to/add-header-and-footer-to-the-exported-document.md +++ b/controls/gridview/features/exporting-data/how-to/add-header-and-footer-to-the-exported-document.md @@ -24,45 +24,15 @@ The [spread export]({%slug winforms/gridview/exporting-data/spread-export%}) fun #### Initialize the exporter -{{source=..\SamplesCS\GridView\ExportingData\HowTo\HeaderAndFooter.cs region=SetExporter}} -{{source=..\SamplesVB\GridView\ExportingData\HowTo\HeaderAndFooter.vb region=SetExporter}} - -````C# -GridViewSpreadExport spreadExporter = new GridViewSpreadExport(radGridView1); -SpreadExportRenderer exportRenderer = new SpreadExportRenderer(); -exportRenderer.WorkbookCreated += exportRenderer_WorkbookCreated; -spreadExporter.RunExport(@"C:\exportedFile.xlsx", exportRenderer); - -```` -````VB.NET -Dim spreadExporter As New GridViewSpreadExport(radGridView1) -Dim exportRenderer As New SpreadExportRenderer() - AddHandler exportRenderer.WorkbookCreated, AddressOf exportRenderer_WorkbookCreated -spreadExporter.RunExport("C:\exportedFile.xlsx", exportRenderer) - -```` - -{{endregion}} + + 2\. Before adding the header you should declare the two elements which will be used later for the cell value format and the background color. #### Define styles and formats -{{source=..\SamplesCS\GridView\ExportingData\HowTo\HeaderAndFooter.cs region=StlylesAndFormats}} -{{source=..\SamplesVB\GridView\ExportingData\HowTo\HeaderAndFooter.vb region=StlylesAndFormats}} - -````C# -PatternFill solidPatternFill = new PatternFill(PatternType.Solid, System.Windows.Media.Color.FromRgb(46, 204, 113), Colors.Transparent); -CellValueFormat textFormat = new CellValueFormat("@"); - -```` -````VB.NET -Dim solidPatternFill As New PatternFill(PatternType.Solid, System.Windows.Media.Color.FromRgb(46, 204, 113), Colors.Transparent) -Dim textFormat As New CellValueFormat("@") - -```` - -{{endregion}} + + >important You need to add a reference to the `PresentationCore` assembly and the `System.Windows.Media` namespace. @@ -70,94 +40,12 @@ Dim textFormat As New CellValueFormat("@") #### Add header -{{source=..\SamplesCS\GridView\ExportingData\HowTo\HeaderAndFooter.cs region=Header}} -{{source=..\SamplesVB\GridView\ExportingData\HowTo\HeaderAndFooter.vb region=Header}} - -````C# -Worksheet worksheet = e.Workbook.Sheets[0] as Worksheet; -CellRange range = new CellRange(0, 0, 1, radGridView1.Columns.Count - 4); -CellSelection header = worksheet.Cells[range]; -if (header.CanInsertOrRemove(range, ShiftType.Down)) -{ - header.Insert(InsertShiftType.Down); -} -header.Merge(); -header.SetFormat(textFormat); -header.SetHorizontalAlignment(RadHorizontalAlignment.Center); -header.SetVerticalAlignment(RadVerticalAlignment.Center); -header.SetFontFamily(new ThemableFontFamily("Rockwell")); -header.SetFontSize(24); -header.SetFill(solidPatternFill); -header.SetValue("Nortwind Products Details"); - -```` -````VB.NET -Dim worksheet As Worksheet = TryCast(e.Workbook.Sheets(0), Worksheet) -Dim range As New CellRange(0, 0, 1, radGridView1.Columns.Count - 4) -Dim header As CellSelection = worksheet.Cells(range) -If header.CanInsertOrRemove(range, ShiftType.Down) Then - header.Insert(InsertShiftType.Down) -End If -header.Merge() -header.SetFormat(textFormat) -header.SetHorizontalAlignment(RadHorizontalAlignment.Center) -header.SetVerticalAlignment(RadVerticalAlignment.Center) -header.SetFontFamily(New ThemableFontFamily("Rockwell")) -header.SetFontSize(24) -header.SetFill(solidPatternFill) -header.SetValue("Nortwind Products Details") - -```` - -{{endregion}} + + 4\. The final part is adding the footer. For example you can select the left most and right most cells below the actual grid data and set their styles and value. At the end you can set the fill for the entire row. #### Add footer -{{source=..\SamplesCS\GridView\ExportingData\HowTo\HeaderAndFooter.cs region=Footer}} -{{source=..\SamplesVB\GridView\ExportingData\HowTo\HeaderAndFooter.vb region=Footer}} - -````C# -CellSelection footerLeft = worksheet.Cells[radGridView1.RowCount + 4, 0]; -footerLeft.SetFormat(textFormat); -footerLeft.SetValue("Nortwind 2015"); -footerLeft.SetVerticalAlignment(RadVerticalAlignment.Center); -footerLeft.SetFontFamily(new ThemableFontFamily("Rockwell")); -footerLeft.SetFontSize(24); -CellSelection footerRight = worksheet.Cells[radGridView1.RowCount + 4, radGridView1.Columns.Count - 1]; -footerRight.SetFormat(textFormat); -footerRight.SetValue(DateTime.Now.ToShortDateString()); -footerRight.SetVerticalAlignment(RadVerticalAlignment.Center); -footerRight.SetFontFamily(new ThemableFontFamily("Rockwell")); -footerRight.SetFontSize(24); -range = new CellRange(radGridView1.RowCount + 4, 0, radGridView1.RowCount + 4, radGridView1.Columns.Count - 1); -CellSelection footer = worksheet.Cells[range]; -footer.SetFill(solidPatternFill); -worksheet.Columns[worksheet.UsedCellRange].SetWidth(new ColumnWidth(130, false)); - -```` -````VB.NET -Dim footerLeft As CellSelection = worksheet.Cells(radGridView1.RowCount + 4, 0) -footerLeft.SetFormat(textFormat) -footerLeft.SetValue("Nortwind 2015") -footerLeft.SetVerticalAlignment(RadVerticalAlignment.Center) -footerLeft.SetFontFamily(New ThemableFontFamily("Rockwell")) -footerLeft.SetFontSize(24) -Dim footerRight As CellSelection = worksheet.Cells(radGridView1.RowCount + 4, radGridView1.Columns.Count - 1) -footerRight.SetFormat(textFormat) -footerRight.SetValue(Date.Now.ToShortDateString()) -footerRight.SetVerticalAlignment(RadVerticalAlignment.Center) -footerRight.SetFontFamily(New ThemableFontFamily("Rockwell")) -footerRight.SetFontSize(24) -range = New CellRange(radGridView1.RowCount + 4, 0, radGridView1.RowCount + 4, radGridView1.Columns.Count - 1) -Dim footer As CellSelection = worksheet.Cells(range) -footer.SetFill(solidPatternFill) -worksheet.Columns(worksheet.UsedCellRange).SetWidth(New ColumnWidth(130, False)) - -```` - -{{endregion}} - - - + + diff --git a/controls/gridview/features/exporting-data/how-to/colum-width-and-row-height-with-excelml.md b/controls/gridview/features/exporting-data/how-to/colum-width-and-row-height-with-excelml.md index 982728666..2e7662100 100644 --- a/controls/gridview/features/exporting-data/how-to/colum-width-and-row-height-with-excelml.md +++ b/controls/gridview/features/exporting-data/how-to/colum-width-and-row-height-with-excelml.md @@ -14,67 +14,12 @@ position: 1 You can set the columns with by using the __ExcelTableCreated__ event. This event allows you to access the the column attributes and set the columns width. -{{source=..\SamplesCS\GridView\ExportingData\ExportToExcelViaExcelIMLFormat.cs region=ColumnWidth}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToExcelViaExcelIMLFormat.vb region=ColumnWidth}} -````C# -private void Exporter_ExcelTableCreated(object sender, Telerik.WinControls.UI.Export.ExcelML.ExcelTableCreatedEventArgs e) -{ - foreach (ColumnElement item in e.ExcelTableElement.Columns) - { - item.Attributes["ss:Width"] = "300"; - } -} - -```` -````VB.NET -Private Sub Exporter_ExcelTableCreated1(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.Export.ExcelML.ExcelTableCreatedEventArgs) - For Each item As ColumnElement In e.ExcelTableElement.Columns - item.Attributes("ss:Width") = "300" - Next item -End Sub - -```` - - -{{endregion}} - + + ### Rows Height You can set the rows height by using the __ExcelRowFormating__ event. This event allows you to access the the row attributes and set the height. -{{source=..\SamplesCS\GridView\ExportingData\ExportToExcelViaExcelIMLFormat.cs region=RowHeight}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToExcelViaExcelIMLFormat.vb region=RowHeight}} -````C# -private void Exporter_ExcelRowFormatting(object sender, ExcelRowFormattingEventArgs e) -{ - if (e.ExcelRowElement.Attributes.Contains("ss:Height")) - { - var att = e.ExcelRowElement.Attributes["ss:Height"]; - if (Convert.ToInt32(att) > 400) - { - e.ExcelRowElement.Attributes["ss:Height"] = "400"; - } - } -} - -```` -````VB.NET -Private Sub Exporter_ExcelRowFormatting(ByVal sender As Object, ByVal e As ExcelRowFormattingEventArgs) - If e.ExcelRowElement.Attributes.Contains("ss:Height") Then - Dim att = e.ExcelRowElement.Attributes("ss:Height") - If Convert.ToInt32(att) > 400 Then - e.ExcelRowElement.Attributes("ss:Height") = "400" - End If - End If -End Sub - -```` - - - -{{endregion}} - - - - + + diff --git a/controls/gridview/features/exporting-data/html-export.md b/controls/gridview/features/exporting-data/html-export.md index 44f603762..f6ce89caa 100644 --- a/controls/gridview/features/exporting-data/html-export.md +++ b/controls/gridview/features/exporting-data/html-export.md @@ -32,19 +32,8 @@ Before running export to HTML, you have to initialize the __ExportToHTML__ class #### ExportToHTML initialization -{{source=..\SamplesCS\GridView\ExportingData\ExportToHTML1.cs region=exportToHtmlInitialization}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToHTML1.vb region=exportToHtmlInitialization}} - -````C# -ExportToHTML exporter = new ExportToHTML(this.radGridView1); - -```` -````VB.NET -Dim exporter As ExportToHTML = New ExportToHTML(Me.RadGridView1) - -```` - -{{endregion}} + + ### File extension @@ -52,19 +41,8 @@ This property allows for changing the default (*.htm) file extension of the expo #### Setting the file extension -{{source=..\SamplesCS\GridView\ExportingData\ExportToHTML1.cs region=settingTheFileExtention}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToHTML1.vb region=settingTheFileExtention}} - -````C# -exporter.FileExtension = ""; - -```` -````VB.NET -exporter.FileExtension = "" - -```` - -{{endregion}} + + ### Hidden columns and rows option @@ -80,19 +58,8 @@ Please note that some browsers do not support hidden columns and if you open exp #### Setting the HiddenColumnOption -{{source=..\SamplesCS\GridView\ExportingData\ExportToHTML1.cs region=settingTheHiddenColumnOption}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToHTML1.vb region=settingTheHiddenColumnOption}} - -````C# -exporter.HiddenColumnOption = Telerik.WinControls.UI.Export.HiddenOption.DoNotExport; - -```` -````VB.NET -exporter.HiddenColumnOption = Telerik.WinControls.UI.Export.HiddenOption.DoNotExport - -```` - -{{endregion}} + + #### Columns Width options @@ -100,37 +67,15 @@ There are three options for the column widths. First option is to have columns w #### Setting FitWidthSize -{{source=..\SamplesCS\GridView\ExportingData\ExportToHTML1.cs region=settingFixedColumnsWidth}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToHTML1.vb region=settingFixedColumnsWidth}} - -````C# -exporter.FitWidthSize = 1000; - -```` -````VB.NET -exporter.FitWidthSize = 1000 - -```` - -{{endregion}} + + The third option is to set the column widths to be auto calculated depending on the content of the cells in the column. For this option you can use the __AutoSizeColumns__ property. #### Setting AutoSizeColumns -{{source=..\SamplesCS\GridView\ExportingData\ExportToHTML1.cs region=settingAutoSizeColumns}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToHTML1.vb region=settingAutoSizeColumns}} - -````C# -exporter.AutoSizeColumns = true; - -```` -````VB.NET -exporter.AutoSizeColumns = True - -```` - -{{endregion}} + + If you use this option you need to control how the cells are sized. To do that you can use the __CellWhiteSpace__ option of the `HTMLCellElement` which controls how white spaces are handled. The possible values are. @@ -150,19 +95,8 @@ Using the __ExportToHTML__ class allows you to export the visual settings (theme #### Setting ExportVisualSettings -{{source=..\SamplesCS\GridView\ExportingData\ExportToHTML1.cs region=settingExportVisualSettings}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToHTML1.vb region=settingExportVisualSettings}} - -````C# -exporter.ExportVisualSettings = true; - -```` -````VB.NET -exporter.ExportVisualSettings = True - -```` - -{{endregion}} + + ### HTML Table Caption @@ -170,19 +104,8 @@ You can specify the table caption through __TableCaption__ property. #### Setting the SheetName -{{source=..\SamplesCS\GridView\ExportingData\ExportToHTML1.cs region=settingTheSheetName}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToHTML1.vb region=settingTheSheetName}} - -````C# -exporter.TableCaption = "Table"; - -```` -````VB.NET -exporter.TableCaption = "Table" - -```` - -{{endregion}} + + ### Summaries export option @@ -198,19 +121,8 @@ You can use __SummariesExportOption__ property to specify how to export summary #### Setting the SummariesExportOption -{{source=..\SamplesCS\GridView\ExportingData\ExportToHTML1.cs region=settingSummariesExportOptions}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToHTML1.vb region=settingSummariesExportOptions}} - -````C# -exporter.SummariesExportOption = SummariesOption.DoNotExport; - -```` -````VB.NET -exporter.SummariesExportOption = SummariesOption.DoNotExport - -```` - -{{endregion}} + + ## RunExport method @@ -222,21 +134,8 @@ Consider the code sample below: #### Export to HTML format -{{source=..\SamplesCS\GridView\ExportingData\ExportToHTML1.cs region=exportToHtmlFormat}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToHTML1.vb region=exportToHtmlFormat}} - -````C# -string fileName = "c:\\ExportedData.htm"; -exporter.RunExport(fileName); - -```` -````VB.NET -Dim fileName As String = "c:\\ExportedData.htm" -exporter.RunExport(fileName) - -```` - -{{endregion}} + + ## Events @@ -244,66 +143,15 @@ exporter.RunExport(fileName) #### Handling the HTMLCellFormatting event -{{source=..\SamplesCS\GridView\ExportingData\ExportToHTML1.cs region=handlingHtmlCellFormattingEvent}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToHTML1.vb region=handlingHtmlCellFormattingEvent}} - -````C# -void exporter_HTMLCellFormatting(object sender, Telerik.WinControls.UI.Export.HTML.HTMLCellFormattingEventArgs e) -{ - if (e.GridColumnIndex == 1 && e.GridRowInfoType == typeof(GridViewDataRowInfo)) - { - e.HTMLCellElement.Value = "Test value"; - e.HTMLCellElement.Styles.Add("background-color", ColorTranslator.ToHtml(Color.Orange)); - } -} - -```` -````VB.NET -Private Sub exporter_HTMLCellFormatting(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.Export.HTML.HTMLCellFormattingEventArgs) - If e.GridColumnIndex = 1 AndAlso e.GridRowInfoType.Equals(GetType(GridViewDataRowInfo)) Then - e.HTMLCellElement.Value = "Test value" - e.HTMLCellElement.Styles.Add("background-color", ColorTranslator.ToHtml(Color.Orange)) - End If -End Sub - -```` - -{{endregion}} + + 2\. __HTMLTableCaptionFormatting:__ this event can be used to make an additional formatting on the HTML table caption element. You can access __TableCaptionElement__ through event’s arguments and apply a valid HTML format. #### Handling the HTMLTableCaptionFormatting event -{{source=..\SamplesCS\GridView\ExportingData\ExportToHTML1.cs region=handlingHtmlTableCaptionFormattingEvent}} -{{source=..\SamplesVB\GridView\ExportingData\ExportToHTML1.vb region=handlingHtmlTableCaptionFormattingEvent}} - -````C# -void exporter_HTMLTableCaptionFormatting(object sender, Telerik.WinControls.UI.Export.HTML.HTMLTableCaptionFormattingEventArgs e) -{ - e.TableCaptionElement.Styles.Add("background-color", ColorTranslator.ToHtml(Color.Red)); - e.TableCaptionElement.Styles.Add("font-size", "200%"); - e.TableCaptionElement.Styles.Add("color", ColorTranslator.ToHtml(Color.White)); - e.TableCaptionElement.Styles.Add("font-weight", "bold"); - e.CaptionText = "My Table Caption"; -} - -```` -````VB.NET -Private Sub exporter_HTMLTableCaptionFormatting(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.Export.HTML.HTMLTableCaptionFormattingEventArgs) - e.TableCaptionElement.Styles.Add("background-color", ColorTranslator.ToHtml(Color.Red)) - e.TableCaptionElement.Styles.Add("font-size", "200%") - e.TableCaptionElement.Styles.Add("color", ColorTranslator.ToHtml(Color.White)) - e.TableCaptionElement.Styles.Add("font-weight", "bold") - e.CaptionText = "My Table Caption" -End Sub - -```` - -{{endregion}} - - - - + + # See Also * [Export Data in a Group to Excel]({%slug winforms/gridview/exporting-data/export-data-in-a-group-to-excel%}) diff --git a/controls/gridview/features/exporting-data/spread-export.md b/controls/gridview/features/exporting-data/spread-export.md index 90b50c6c4..26513e5c3 100644 --- a/controls/gridview/features/exporting-data/spread-export.md +++ b/controls/gridview/features/exporting-data/spread-export.md @@ -53,63 +53,15 @@ To use the spread export functionality: 1. Use the __RunExport__ method to trigger the export process. __RunExport__ accepts a filename as a parameter for the exported file. -{{source=..\SamplesCS\GridView\ExportingData\SpreadExport1.cs region=Export}} -{{source=..\SamplesVB\GridView\ExportingData\SpreadExport1.vb region=Export}} - -````C# - -GridViewSpreadExport spreadExporter = new GridViewSpreadExport(this.radGridView1); -SpreadExportRenderer exportRenderer = new SpreadExportRenderer(); -spreadExporter.RunExport("D:\\exportedFile.xlsx", exportRenderer); - -```` -````VB.NET -Dim spreadExporter As GridViewSpreadExport = New GridViewSpreadExport(radGridView1) -Dim exportRenderer As New SpreadExportRenderer() -spreadExporter.RunExport("D:\exportedFile.xlsx", exportRenderer) - -```` - -{{endregion}} + + ### Running export synchronously using a stream The __RunExport__ method has several overloads that allow the user to export using a stream as well: -{{source=..\SamplesCS\GridView\ExportingData\SpreadExport1.cs region=StreamRunExport}} -{{source=..\SamplesVB\GridView\ExportingData\SpreadExport1.vb region=StreamRunExport}} - -````C# - -string exportFile = @"..\..\exportedData.xlsx"; -using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) -{ - Telerik.WinControls.Export.GridViewSpreadExport exporter = new Telerik.WinControls.Export.GridViewSpreadExport(this.radGridView1); - Telerik.WinControls.Export.SpreadExportRenderer renderer = new Telerik.WinControls.Export.SpreadExportRenderer(); - exporter.RunExport(ms, renderer); - - using (System.IO.FileStream fileStream = new System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write)) - { - ms.WriteTo(fileStream); - } -} - -```` -````VB.NET -Dim exportFile As String = "..\..\exportedData.xlsx" -Using ms As New System.IO.MemoryStream() - Dim exporter As New Telerik.WinControls.Export.GridViewSpreadExport(Me.radGridView1) - Dim renderer As New Telerik.WinControls.Export.SpreadExportRenderer() - exporter.RunExport(ms, renderer) - - Using fileStream As New System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write) - ms.WriteTo(fileStream) - End Using -End Using - -```` - -{{endregion}} + + ### Image exporting @@ -237,69 +189,8 @@ This event is used to format the cells to be exported. The event arguments provi Here is an example of formatting the exported grid: -{{source=..\SamplesCS\GridView\ExportingData\SpreadExport1.cs region=CellFormatting}} -{{source=..\SamplesVB\GridView\ExportingData\SpreadExport1.vb region=CellFormatting}} - -````C# - -void spreadExporter_CellFormatting(object sender, Telerik.WinControls.Export.CellFormattingEventArgs e) -{ - if (e.GridRowInfoType == typeof(GridViewTableHeaderRowInfo)) - { - e.CellStyleInfo.Underline = true; - - if (e.GridCellInfo.RowInfo.HierarchyLevel == 0) - { - e.CellStyleInfo.BackColor = Color.DeepSkyBlue; - } - else if (e.GridCellInfo.RowInfo.HierarchyLevel == 1) - { - e.CellStyleInfo.BackColor = Color.LightSkyBlue; - } - } - - if (e.GridRowInfoType == typeof(GridViewHierarchyRowInfo)) - { - if (e.GridCellInfo.RowInfo.HierarchyLevel == 0) - { - e.CellStyleInfo.IsItalic = true; - e.CellStyleInfo.FontSize = 12; - e.CellStyleInfo.BackColor = Color.GreenYellow; - } - else if (e.GridCellInfo.RowInfo.HierarchyLevel == 1) - { - e.CellStyleInfo.ForeColor = Color.DarkGreen; - e.CellStyleInfo.BackColor = Color.LightGreen; - } - } -} - -```` -````VB.NET -Private Sub spreadExporter_CellFormatting(ByVal sender As Object, ByVal e As Telerik.WinControls.Export.CellFormattingEventArgs) - If e.GridRowInfoType Is GetType(GridViewTableHeaderRowInfo) Then - e.CellStyleInfo.Underline = True - If e.GridCellInfo.RowInfo.HierarchyLevel = 0 Then - e.CellStyleInfo.BackColor = Color.DeepSkyBlue - ElseIf e.GridCellInfo.RowInfo.HierarchyLevel = 1 Then - e.CellStyleInfo.BackColor = Color.LightSkyBlue - End If - End If - If e.GridRowInfoType Is GetType(GridViewHierarchyRowInfo) Then - If e.GridCellInfo.RowInfo.HierarchyLevel = 0 Then - e.CellStyleInfo.IsItalic = True - e.CellStyleInfo.FontSize = 12 - e.CellStyleInfo.BackColor = Color.GreenYellow - ElseIf e.GridCellInfo.RowInfo.HierarchyLevel = 1 Then - e.CellStyleInfo.ForeColor = Color.DarkGreen - e.CellStyleInfo.BackColor = Color.LightGreen - End If - End If -End Sub - -```` - -{{endregion}} + + ![WinForms RadGridView gridview-exporting-data-spread-export 003](images/gridview-exporting-data-spread-export003.png) @@ -325,26 +216,8 @@ __RadGridView__ can export its grouped content by simply setting the __ExportChi #### Exporting Grouped Data -{{source=..\SamplesCS\GridView\ExportingData\SpreadExport1.cs region=ExportingGroupedData}} -{{source=..\SamplesVB\GridView\ExportingData\SpreadExport1.vb region=ExportingGroupedData}} - -````C# - -GridViewSpreadExport spreadExporter = new GridViewSpreadExport(this.radGridView1); -spreadExporter.ExportChildRowsGrouped = true; -SpreadExportRenderer exportRenderer = new SpreadExportRenderer(); -spreadExporter.RunExport(@"..\..\exportedFile.xlsx", exportRenderer); - -```` -````VB.NET -Dim spreadExporter As New GridViewSpreadExport(Me.radGridView1) -spreadExporter.ExportChildRowsGrouped = True -Dim exportRenderer As New SpreadExportRenderer() -spreadExporter.RunExport("..\..\exportedFile.xlsx", exportRenderer) - -```` - -{{endregion}} + + ## Async Spread Export @@ -379,171 +252,23 @@ This example demonstrates how to combine the async spread export feature with a 1\. Bind __RadGridView__ and define the initial settings. -{{source=..\SamplesCS\GridView\ExportingData\AsyncSpreadExport.cs region=BindAndDefineSettings}} -{{source=..\SamplesVB\GridView\ExportingData\AsyncSpreadExport.vb region=BindAndDefineSettings}} - -````C# -public AsyncSpreadExport() -{ - InitializeComponent(); - this.BindGrid(); - this.radProgressBar1.Minimum = 0; - this.radProgressBar1.Maximum = 100; - this.radProgressBar1.ShowProgressIndicators = true; - this.radGridView1.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill; - this.btnExportAsync.Click += btnExportAsync_Click; -} -private void BindGrid() -{ - DataTable dataTable = new DataTable(); - dataTable.Columns.Add("Id", typeof(int)); - dataTable.Columns.Add("Name", typeof(string)); - dataTable.Columns.Add("IsValid", typeof(bool)); - dataTable.Columns.Add("Date", typeof(DateTime)); - for (int i = 0; i < 50000; i++) - { - dataTable.Rows.Add(i, "Name " + i, i % 2 == 0, DateTime.Now.AddDays(i)); - } - this.radGridView1.DataSource = dataTable; -} - -```` -````VB.NET -Public Sub New() - InitializeComponent() - Me.BindGrid() - Me.RadProgressBar1.Minimum = 0 - Me.RadProgressBar1.Maximum = 100 - Me.RadProgressBar1.ShowProgressIndicators = True - Me.RadGridView1.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill - AddHandler Me.BtnExportAsync.Click, AddressOf BtnExportAsync_Click -End Sub -Private Sub BindGrid() - Dim dataTable As New DataTable() - dataTable.Columns.Add("Id", GetType(Integer)) - dataTable.Columns.Add("Name", GetType(String)) - dataTable.Columns.Add("IsValid", GetType(Boolean)) - dataTable.Columns.Add("Date", GetType(DateTime)) - For i As Integer = 0 To 49999 - dataTable.Rows.Add(i, "Name " & i, i Mod 2 = 0, DateTime.Now.AddDays(i)) - Next - Me.RadGridView1.DataSource = dataTable -End Sub - -```` - -{{endregion}} + + 2\. Start export and subscribe to the progress notification events. -{{source=..\SamplesCS\GridView\ExportingData\AsyncSpreadExport.cs region=ExportData}} -{{source=..\SamplesVB\GridView\ExportingData\AsyncSpreadExport.vb region=ExportData}} - -````C# -private void btnExportAsync_Click(object sender, EventArgs e) -{ - GridViewSpreadExport spreadExporter = new GridViewSpreadExport(this.radGridView1); - spreadExporter.AsyncExportProgressChanged += spreadExporter_AsyncExportProgressChanged; - spreadExporter.AsyncExportCompleted += spreadExporter_AsyncExportCompleted; - SpreadExportRenderer exportRenderer = new SpreadExportRenderer(); - spreadExporter.RunExportAsync(@"..\..\exportedFile.xlsx",exportRenderer); -} - -```` -````VB.NET -Private Sub BtnExportAsync_Click(sender As Object, e As EventArgs) - Dim spreadExporter As New GridViewSpreadExport(Me.RadGridView1) - AddHandler spreadExporter.AsyncExportProgressChanged, AddressOf spreadExporter_AsyncExportProgressChanged - AddHandler spreadExporter.AsyncExportCompleted, AddressOf spreadExporter_AsyncExportCompleted - Dim exportRenderer As New SpreadExportRenderer() - spreadExporter.RunExportAsync("..\..\exportedFile.xlsx", exportRenderer) -End Sub - -```` - -{{endregion}} + + 3\. Handle the notification events and report progress. -{{source=..\SamplesCS\GridView\ExportingData\AsyncSpreadExport.cs region=ReportProgress}} -{{source=..\SamplesVB\GridView\ExportingData\AsyncSpreadExport.vb region=ReportProgress}} - -````C# -private void spreadExporter_AsyncExportProgressChanged(object sender, ProgressChangedEventArgs e) -{ - this.radProgressBar1.Value1 = e.ProgressPercentage; -} -private void spreadExporter_AsyncExportCompleted(object sender, AsyncCompletedEventArgs e) -{ - RadMessageBox.Show("Async Spread Export Completed!"); - this.radProgressBar1.Value1 = 0; -} - -```` -````VB.NET -Private Sub spreadExporter_AsyncExportProgressChanged(sender As Object, e As ProgressChangedEventArgs) - Me.RadProgressBar1.Value1 = e.ProgressPercentage -End Sub -Private Sub spreadExporter_AsyncExportCompleted(sender As Object, e As AsyncCompletedEventArgs) - RadMessageBox.Show("Async Spread Export Completed!") - Me.RadProgressBar1.Value1 = 0 -End Sub - -```` - -{{endregion}} + + The __RunExportAsync__ method has several overloads allowing the user to export using a stream as well: -{{source=..\SamplesCS\GridView\ExportingData\SpreadExport1.cs region=StreamRunExportAsync}} -{{source=..\SamplesVB\GridView\ExportingData\SpreadExport1.vb region=StreamRunExportAsync}} - -````C# - -private void button1_Click(object sender, EventArgs e) -{ - System.IO.MemoryStream ms = new System.IO.MemoryStream(); - Telerik.WinControls.Export.GridViewSpreadExport exporter = new Telerik.WinControls.Export.GridViewSpreadExport(this.radGridView1); - Telerik.WinControls.Export.SpreadExportRenderer renderer = new Telerik.WinControls.Export.SpreadExportRenderer(); - exporter.AsyncExportCompleted += exporter_AsyncExportCompleted; - exporter.RunExportAsync(ms, renderer); -} - -private void exporter_AsyncExportCompleted(object sender, AsyncCompletedEventArgs e) -{ - RunWorkerCompletedEventArgs args = e as RunWorkerCompletedEventArgs; - string exportFile = @"..\..\exportedAsyncData.xlsx"; - using (System.IO.FileStream fileStream = new System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write)) - { - MemoryStream ms = args.Result as MemoryStream; - ms.WriteTo(fileStream); - ms.Close(); - } -} - -```` -````VB.NET -Private Sub button1_Click(sender As Object, e As EventArgs) - Dim ms As New System.IO.MemoryStream() - Dim exporter As New Telerik.WinControls.Export.GridViewSpreadExport(Me.radGridView1) - Dim renderer As New Telerik.WinControls.Export.SpreadExportRenderer() - AddHandler exporter.AsyncExportCompleted, AddressOf exporter_AsyncExportCompleted - exporter.RunExportAsync(ms, renderer) -End Sub -Private Sub exporter_AsyncExportCompleted(sender As Object, e As AsyncCompletedEventArgs) - Dim args As RunWorkerCompletedEventArgs = TryCast(e, RunWorkerCompletedEventArgs) - Dim exportFile As String = "..\..\exportedAsyncData.xlsx" - Using fileStream As New System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write) - Dim ms As MemoryStream = TryCast(args.Result, MemoryStream) - ms.WriteTo(fileStream) - ms.Close() - End Using -End Sub - -```` - -{{endregion}} - + + ## See Also * [Export Data in a Group to Excel]({%slug winforms/gridview/exporting-data/export-data-in-a-group-to-excel%}) diff --git a/controls/gridview/features/exporting-data/spreadstream-export.md b/controls/gridview/features/exporting-data/spreadstream-export.md index 1db569c25..4ae79147d 100644 --- a/controls/gridview/features/exporting-data/spreadstream-export.md +++ b/controls/gridview/features/exporting-data/spreadstream-export.md @@ -33,22 +33,8 @@ To use the spread export functionality create an instance of the __GridViewSprea #### Exporting the grid. -{{source=..\SamplesCS\GridView\ExportingData\SpreadStreamExportCode.cs region=SyncPort}} -{{source=..\SamplesVB\GridView\ExportingData\SpreadStreamExportCode.vb region=SyncPort}} -````C# -GridViewSpreadStreamExport spreadStreamExport = new GridViewSpreadStreamExport(this.radGridView1); -spreadStreamExport.ExportVisualSettings = true; -spreadStreamExport.RunExport(@"D:\StreamExport.xlsx", new SpreadStreamExportRenderer()); - -```` -````VB.NET -Dim spreadStreamExport As New GridViewSpreadStreamExport(Me.radGridView1) -spreadStreamExport.ExportVisualSettings = True -spreadStreamExport.RunExport("D:\StreamExport.xlsx", New SpreadStreamExportRenderer()) - -```` - -{{endregion}} + + ## Properties @@ -84,30 +70,8 @@ This event occurs for every cell that is being exported. It can be used for styl #### Using the CellFormatting event -{{source=..\SamplesCS\GridView\ExportingData\SpreadStreamExportCode.cs region=CellFormatting}} -{{source=..\SamplesVB\GridView\ExportingData\SpreadStreamExportCode.vb region=CellFormatting}} -````C# -private void SpreadStreamExport_CellFormatting(object sender, SpreadStreamCellFormattingEventArgs e) -{ - e.CellStyleInfo.BackColor = Color.Green; - e.CellStyleInfo.ForeColor = Color.Red; - e.CellStyleInfo.BottomBorder = new SpreadBorder(SpreadBorderStyle.Double, SpreadThemableColor.FromRgb(100, 100, 100)); - e.CellStyleInfo.TopBorder = Color.Black; -} - -```` -````VB.NET -Private Sub SpreadStreamExport_CellFormatting(ByVal sender As Object, ByVal e As SpreadStreamCellFormattingEventArgs) - e.CellStyleInfo.BackColor = Color.Green - e.CellStyleInfo.ForeColor = Color.Red - e.CellStyleInfo.BottomBorder = New SpreadBorder(SpreadBorderStyle.Double, SpreadThemableColor.FromRgb(100, 100, 100)) - e.CellStyleInfo.TopBorder = Color.Black -End Sub - -```` - - -{{endregion}} + + ### RowCreated @@ -115,84 +79,16 @@ Occurs when a new row is created in current worksheet. This is suitable place to #### Using RowCreated to set the rows height. -{{source=..\SamplesCS\GridView\ExportingData\SpreadStreamExportCode.cs region=RowCreated}} -{{source=..\SamplesVB\GridView\ExportingData\SpreadStreamExportCode.vb region=RowCreated}} -````C# -private void SpreadStreamExport_RowCreated(object sender, SpreadStreamRowEventArgs e) -{ - if (e.GridRowInfoType == typeof(GridViewTableHeaderRowInfo)) - { - var row = e.Row as Telerik.Documents.SpreadsheetStreaming.IRowExporter; - row.SetHeightInPixels(50); - } -} - -```` -````VB.NET -Private Sub SpreadStreamExport_RowCreated(ByVal sender As Object, ByVal e As SpreadStreamRowEventArgs) - If e.GridRowInfoType Is GetType(GridViewTableHeaderRowInfo) Then - Dim row = TryCast(e.Row, Telerik.Documents.SpreadsheetStreaming.IRowExporter) - row.SetHeightInPixels(50) - End If -End Sub - -```` - - -{{endregion}} - + + ### RowExporting Occurs before every spread row is exported. This is suitable place to add any additional cells at the end of the row. -{{source=..\SamplesCS\GridView\ExportingData\SpreadStreamExportCode.cs region=RowExporting}} -{{source=..\SamplesVB\GridView\ExportingData\SpreadStreamExportCode.vb region=RowExporting}} -````C# -private void SpreadStreamExport_RowExporting(object sender, SpreadStreamRowEventArgs e) -{ - if (e.GridRowIndex % 2 == 0) - { - var row = e.Row as IRowExporter; - using (ICellExporter cell = row.CreateCellExporter()) - { - SpreadCellFormat format = new SpreadCellFormat() - { - Fill = SpreadPatternFill.CreateSolidFill(new SpreadColor(100, 100, 100)) - }; - cell.SetValue("---"); - format.HorizontalAlignment = SpreadHorizontalAlignment.Center; - format.VerticalAlignment = SpreadVerticalAlignment.Center; - format.LeftBorder = new SpreadBorder(SpreadBorderStyle.Double, SpreadThemableColor.FromRgb(100, 100, 100)); - format.RightBorder = new SpreadBorder(SpreadBorderStyle.Double, SpreadThemableColor.FromRgb(100, 100, 100)); - cell.SetFormat(format); - } - } -} - -```` -````VB.NET -Private Sub SpreadStreamExport_RowExporting(ByVal sender As Object, ByVal e As SpreadStreamRowEventArgs) - If e.GridRowIndex Mod 2 = 0 Then - Dim row = TryCast(e.Row, IRowExporter) - Using cell As ICellExporter = row.CreateCellExporter() - Dim format As New SpreadCellFormat() With {.Fill = SpreadPatternFill.CreateSolidFill(New SpreadColor(100, 100, 100))} - cell.SetValue("---") - format.HorizontalAlignment = SpreadHorizontalAlignment.Center - format.VerticalAlignment = SpreadVerticalAlignment.Center - format.LeftBorder = New SpreadBorder(SpreadBorderStyle.Double, SpreadThemableColor.FromRgb(100, 100, 100)) - format.RightBorder = New SpreadBorder(SpreadBorderStyle.Double, SpreadThemableColor.FromRgb(100, 100, 100)) - cell.SetFormat(format) - End Using - End If -End Sub - -```` - - -{{endregion}} - + + ### ExportCompleted @@ -217,44 +113,8 @@ This feature can be utilized by calling the __RunExportAsync__ method on the __G #### Exporting asynchronously and reporting the progress. -{{source=..\SamplesCS\GridView\ExportingData\SpreadStreamExportCode.cs region=AsyncRun}} -{{source=..\SamplesVB\GridView\ExportingData\SpreadStreamExportCode.vb region=AsyncRun}} -````C# -private void RadButton1_Click(object sender, EventArgs e) -{ - GridViewSpreadStreamExport spreadStreamExport = new GridViewSpreadStreamExport(this.radGridView1); - spreadStreamExport.AsyncExportProgressChanged += SpreadStreamExport_AsyncExportProgressChanged; - spreadStreamExport.AsyncExportCompleted += SpreadStreamExport_AsyncExportCompleted; - spreadStreamExport.RunExportAsync(@"D:\StreamExport.xlsx", new SpreadStreamExportRenderer()); -} -private void SpreadStreamExport_AsyncExportCompleted(object sender, AsyncCompletedEventArgs e) -{ - RadMessageBox.Show("Export Completed"); -} -private void SpreadStreamExport_AsyncExportProgressChanged(object sender, ProgressChangedEventArgs e) -{ - radProgressBar1.Value1 = e.ProgressPercentage; -} - -```` -````VB.NET -Private Sub RadButton1_Click(ByVal sender As Object, ByVal e As EventArgs) - Dim spreadStreamExport As New GridViewSpreadStreamExport(Me.radGridView1) - AddHandler spreadStreamExport.AsyncExportProgressChanged, AddressOf SpreadStreamExport_AsyncExportProgressChanged - AddHandler spreadStreamExport.AsyncExportCompleted, AddressOf SpreadStreamExport_AsyncExportCompleted - spreadStreamExport.RunExportAsync("D:\StreamExport.xlsx", New SpreadStreamExportRenderer()) -End Sub -Private Sub SpreadStreamExport_AsyncExportCompleted(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs) - RadMessageBox.Show("Export Completed") -End Sub -Private Sub SpreadStreamExport_AsyncExportProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) - radProgressBar1.Value1 = e.ProgressPercentage -End Sub - -```` - - -{{endregion}} + + ## See Also diff --git a/controls/gridview/features/exporting-data/troubleshooting.md b/controls/gridview/features/exporting-data/troubleshooting.md index 7d217b52f..25ef22864 100644 --- a/controls/gridview/features/exporting-data/troubleshooting.md +++ b/controls/gridview/features/exporting-data/troubleshooting.md @@ -23,42 +23,15 @@ Images cannot be exported to MS Excel, because Excel does not support embedded i Since __ExportToExcelML iterates__ through the grid elements, it does not export anything if the grid has not created its child elements yet (i.e. if there is a grid instance but it is not shown on a form). The solution is to use the __LoadElementTree__ method before running the export:  -{{source=..\SamplesCS\GridView\ExportingData\Troubleshooting.cs region=inCaseOfBlankExcelDocument}} -{{source=..\SamplesVB\GridView\ExportingData\Troubleshooting.vb region=inCaseOfBlankExcelDocument}} - -````C# -this.radGridView1.LoadElementTree(); - -```` -````VB.NET -Me.RadGridView1.LoadElementTree() - -```` - -{{endregion}} - + + ## MS Excel does not open the file directly after exporting the data from RadGridView (it prompts to save the file instead) The ExportToExcelML class does not support opening the excel file directly. However, you can easily implement similar functionality through the __Process.Start__ method: -{{source=..\SamplesCS\GridView\ExportingData\Troubleshooting.cs region=openTheFileAfterExport}} -{{source=..\SamplesVB\GridView\ExportingData\Troubleshooting.vb region=openTheFileAfterExport}} - -````C# -ExportToExcelML exporter = new ExportToExcelML(this.radGridView1); -exporter.RunExport(@"C:\Test.xls"); -System.Diagnostics.Process.Start(@"C:\Test.xls"); - -```` -````VB.NET -Dim exporter As ExportToExcelML = New ExportToExcelML(Me.RadGridView1) -exporter.RunExport("C:\Test.xls") -System.Diagnostics.Process.Start("C:\Test.xls") - -```` - -{{endregion}} + + ## Wrong text alignment for rows with conditional formatting diff --git a/controls/gridview/features/filtering/How-To/filter-on-enter.md b/controls/gridview/features/filtering/How-To/filter-on-enter.md index 7c0cf97e2..6666abc97 100644 --- a/controls/gridview/features/filtering/How-To/filter-on-enter.md +++ b/controls/gridview/features/filtering/How-To/filter-on-enter.md @@ -16,63 +16,8 @@ By default the filtering operation is performed on every keystroke. However a co #### Cancel filtering until Enter is pressed. -{{source=..\SamplesCS\GridView\Filtering\FilterOnEnter.cs region=FilterCode}} -{{source=..\SamplesVB\GridView\Filtering\FilterOnEnter.vb region=FilterCode}} -````C# -private bool EnterPress = false; -private void radGridView1_FilterChanging(object sender, GridViewCollectionChangingEventArgs e) -{ - if (!EnterPress) - { - e.Cancel = true; - } - EnterPress = false; -} -private void radGridView1_CellBeginEdit(object sender, GridViewCellCancelEventArgs e) -{ - if (e.Row is GridViewFilteringRowInfo) - { - RadTextBoxEditor ed = e.ActiveEditor as RadTextBoxEditor; - RadTextBoxEditorElement el = ed.EditorElement as RadTextBoxEditorElement; - el.KeyDown -= el_KeyDown; - el.KeyDown += el_KeyDown; - } -} -private void el_KeyDown(object sender, KeyEventArgs e) -{ - if (e.KeyCode == Keys.Enter) - { - EnterPress = true; - } -} - -```` -````VB.NET -Private EnterPress As Boolean = False -Private Sub radGridView1_FilterChanging(ByVal sender As Object, ByVal e As GridViewCollectionChangingEventArgs) - If Not EnterPress Then - e.Cancel = True - End If - EnterPress = False -End Sub -Private Sub radGridView1_CellBeginEdit(ByVal sender As Object, ByVal e As GridViewCellCancelEventArgs) - If TypeOf e.Row Is GridViewFilteringRowInfo Then - Dim ed As RadTextBoxEditor = TryCast(e.ActiveEditor, RadTextBoxEditor) - Dim el As RadTextBoxEditorElement = TryCast(ed.EditorElement, RadTextBoxEditorElement) - RemoveHandler el.KeyDown, AddressOf el_KeyDown - AddHandler el.KeyDown, AddressOf el_KeyDown - End If -End Sub -Private Sub el_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) - If e.KeyCode = Keys.Enter Then - EnterPress = True - End If -End Sub - -```` - - -{{endregion}} + + ## See Also diff --git a/controls/gridview/features/filtering/basic-filtering.md b/controls/gridview/features/filtering/basic-filtering.md index 87fc6e522..13095ddae 100644 --- a/controls/gridview/features/filtering/basic-filtering.md +++ b/controls/gridview/features/filtering/basic-filtering.md @@ -19,21 +19,8 @@ User filtering in RadGridView is enabled by the __EnableFiltering__ property. By #### Enable filtering -{{source=..\SamplesCS\GridView\Filtering\Filtering.cs region=enableFiltering}} -{{source=..\SamplesVB\GridView\Filtering\Filtering.vb region=enableFiltering}} - -````C# -this.radGridView1.EnableFiltering = true; -this.radGridView1.MasterTemplate.EnableFiltering = true; - -```` -````VB.NET -Me.RadGridView1.EnableFiltering = True -Me.RadGridView1.MasterTemplate.EnableFiltering = True - -```` - -{{endregion}} + + __GridViewDataColumn__ @@ -49,62 +36,8 @@ See [End-User capabilities - Filtering]({%slug winforms/gridview/end-user-capabi #### Bypass default filtering -{{source=..\SamplesCS\GridView\Filtering\Filtering.cs region=BypassFiltering}} -{{source=..\SamplesVB\GridView\Filtering\Filtering.vb region=BypassFiltering}} - -````C# -DataTable dt = new DataTable(); -public void FillData() -{ - dt.Columns.Add("Id", typeof(int)); - dt.Columns.Add("Name", typeof(string)); - for (int i = 0; i < 30; i++) - { - dt.Rows.Add(i, "Item" + i); - } - this.radGridView1.DataSource = dt; - this.radGridView1.EnableFiltering = true; - this.radGridView1.MasterTemplate.DataView.BypassFilter = true; - this.radGridView1.FilterChanged += radGridView1_FilterChanged; -} -private void radGridView1_FilterChanged(object sender, GridViewCollectionChangedEventArgs e) -{ - if (e.Action == NotifyCollectionChangedAction.Add || e.Action == NotifyCollectionChangedAction.ItemChanged) - { - dt.DefaultView.RowFilter = this.radGridView1.FilterDescriptors.Expression; - } - if (e.Action == NotifyCollectionChangedAction.Remove) - { - dt.DefaultView.RowFilter = ""; - } -} - -```` -````VB.NET -Private dt As New DataTable() -Public Sub FillData() - dt.Columns.Add("Id", GetType(Integer)) - dt.Columns.Add("Name", GetType(String)) - For i As Integer = 0 To 29 - dt.Rows.Add(i, "Item" & i) - Next - Me.RadGridView1.DataSource = dt - Me.RadGridView1.EnableFiltering = True - Me.RadGridView1.MasterTemplate.DataView.BypassFilter = True - AddHandler Me.RadGridView1.FilterChanged, AddressOf radGridView1_FilterChanged -End Sub -Private Sub radGridView1_FilterChanged(sender As Object, e As GridViewCollectionChangedEventArgs) - If e.Action = NotifyCollectionChangedAction.Add OrElse e.Action = NotifyCollectionChangedAction.ItemChanged Then - dt.DefaultView.RowFilter = Me.RadGridView1.FilterDescriptors.Expression - End If - If e.Action = NotifyCollectionChangedAction.Remove Then - dt.DefaultView.RowFilter = "" - End If -End Sub - -```` - -{{endregion}} + + ## See Also * [Customizing composite filter dialog]({%slug winforms/gridview/filtering/composite-filter-dialog%}) diff --git a/controls/gridview/features/filtering/custom-filter-dialog.md b/controls/gridview/features/filtering/custom-filter-dialog.md index 2eb8bd606..81c2a6b7c 100644 --- a/controls/gridview/features/filtering/custom-filter-dialog.md +++ b/controls/gridview/features/filtering/custom-filter-dialog.md @@ -26,30 +26,8 @@ Since *R1 2017 SP*, a **CompositeDataFilterForm** is shown. This dialog uses a [ #### Specify default filter dialog -{{source=..\SamplesCS\GridView\Filtering\Filtering.cs region=DefaultFilterDialog}} -{{source=..\SamplesVB\GridView\Filtering\Filtering.vb region=DefaultFilterDialog}} - -````C# -Font f = new Font("Arial", 12, FontStyle.Italic); -private void radGridView1_CreateCompositeFilterDialog(object sender, GridViewCreateCompositeFilterDialogEventArgs e) -{ - CompositeFilterForm filterDialog = new CompositeFilterForm(); - filterDialog.Font = f; - e.Dialog = filterDialog; -} - -```` -````VB.NET -Private f As New Font("Arial", 12, FontStyle.Italic) -Private Sub radGridView1_CreateCompositeFilterDialog(sender As Object, e As GridViewCreateCompositeFilterDialogEventArgs) - Dim filterDialog As New CompositeFilterForm() - filterDialog.Font = f - e.Dialog = filterDialog -End Sub - -```` - -{{endregion}} + + >caption Figure 3: CompositeFilterForm diff --git a/controls/gridview/features/filtering/custom-filtering.md b/controls/gridview/features/filtering/custom-filtering.md index a530101c5..6a7b6ebdf 100644 --- a/controls/gridview/features/filtering/custom-filtering.md +++ b/controls/gridview/features/filtering/custom-filtering.md @@ -37,92 +37,19 @@ The arguments of the **CustomFiltering** event provide the following properties: The following example demonstrates how to hide all **RadGridView** rows that contain a value less than 30 for the `UnitPrice` column. The added __FilterDescriptor__ for the **UnitPrice** column in this example is not considered when defining which rows to hide. All **RadGridView** rows are processed from the custom logic in the __CustomFiltering__ event handler. -{{source=..\SamplesCS\GridView\Filtering\CustomFiltering.cs region=usingCustomFiltering}} -{{source=..\SamplesVB\GridView\Filtering\CustomFiltering.vb region=usingCustomFiltering}} - -````C# -this.radGridView1.EnableCustomFiltering = true; -this.radGridView1.CustomFiltering += new GridViewCustomFilteringEventHandler(radGridView1_CustomFiltering); -FilterDescriptor descriptor = new FilterDescriptor("UnitsPrice", FilterOperator.IsGreaterThan, 0); -this.radGridView1.FilterDescriptors.Add(descriptor); - -```` -````VB.NET -Me.RadGridView1.EnableCustomFiltering = True -Dim descriptor As New FilterDescriptor("UnitsPrice", FilterOperator.IsGreaterThan, 0) -Me.RadGridView1.FilterDescriptors.Add(descriptor) - -```` - -{{endregion}} - -{{source=..\SamplesCS\GridView\Filtering\CustomFiltering.cs region=usingCustomFiltering1}} -{{source=..\SamplesVB\GridView\Filtering\CustomFiltering.vb region=usingCustomFiltering1}} - -````C# -private void radGridView1_CustomFiltering(object sender, GridViewCustomFilteringEventArgs e) -{ - e.Visible = (decimal)e.Row.Cells["UnitPrice"].Value > 30; -} - -```` -````VB.NET -Private Sub RadGridView1_CustomFiltering(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewCustomFilteringEventArgs) Handles RadGridView1.CustomFiltering - e.Visible = CDec(e.Row.Cells("UnitPrice").Value) > 30 -End Sub - -```` - -{{endregion}} + + + + ![WinForms RadGridView CustomFiltering Event](images/gridview-filtering-custom-filtering001.png) The following example demonstrates how you can use the __Handled__ property of the __CustomFiltering__ event arguments. We will hide all rows that have their **UnitPrice** less than "30" and **ProductName** not starting with "Ch". In addition, there is a __FilterDescriptor__ that will hide rows containing values less than "1" in the `UnitsInStock` column. -{{source=..\SamplesCS\GridView\Filtering\CustomFiltering1.cs region=usingCustomFilteringPlusHandled}} -{{source=..\SamplesVB\GridView\Filtering\CustomFiltering1.vb region=usingCustomFilteringPlusHandled}} - -````C# -this.radGridView1.EnableCustomFiltering = true; -this.radGridView1.CustomFiltering += new GridViewCustomFilteringEventHandler(radGridView1_CustomFiltering); -FilterDescriptor descriptor = new FilterDescriptor("UnitsInStock", FilterOperator.IsGreaterThan, 0); -descriptor.IsFilterEditor = true; -this.radGridView1.FilterDescriptors.Add(descriptor); - -```` -````VB.NET -Me.RadGridView1.EnableCustomFiltering = True -Dim descriptor As New FilterDescriptor("UnitsInStock", FilterOperator.IsGreaterThan, 0) -descriptor.IsFilterEditor = True -Me.RadGridView1.FilterDescriptors.Add(descriptor) - -```` - -{{endregion}} - -{{source=..\SamplesCS\GridView\Filtering\CustomFiltering1.cs region=usingCustomFilteringPlusHandled1}} -{{source=..\SamplesVB\GridView\Filtering\CustomFiltering1.vb region=usingCustomFilteringPlusHandled1}} - -````C# -private void radGridView1_CustomFiltering(object sender, GridViewCustomFilteringEventArgs e) -{ - string productName = e.Row.Cells["ProductName"].Value.ToString(); - e.Handled = !productName.StartsWith("Ch"); - e.Visible = (decimal)e.Row.Cells["UnitPrice"].Value > 30; -} - -```` -````VB.NET -Private Sub RadGridView1_CustomFiltering(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewCustomFilteringEventArgs) Handles RadGridView1.CustomFiltering - Dim productName As String = e.Row.Cells("ProductName").Value.ToString() - e.Handled = Not productName.StartsWith("Ch") - e.Visible = CDec(e.Row.Cells("UnitPrice").Value) > 30 -End Sub - -```` - -{{endregion}} - + + + + ![WinForms RadGridView Custom Filtering Event](images/gridview-filtering-custom-filtering002.png) @@ -134,42 +61,10 @@ You can replace the filtering mechanism in RadGridView with a custom one, by set The following example demonstrates how to use a custom filtering mechanism in RadGridView to hide all RadGridView rows which that have UnitPrice less than 30: -{{source=..\SamplesCS\GridView\Filtering\CustomFiltering.cs region=usingFilterPredicate}} -{{source=..\SamplesVB\GridView\Filtering\CustomFiltering.vb region=usingFilterPredicate}} - -````C# -this.radGridView1.MasterTemplate.FilterPredicate = new Predicate(PerformFiltering); - -```` -````VB.NET -Me.RadGridView1.MasterTemplate.FilterPredicate = New Predicate(Of GridViewRowInfo)(AddressOf PerformFiltering) - -```` - -{{endregion}} - -{{source=..\SamplesCS\GridView\Filtering\CustomFiltering.cs region=usingFilterPredicate1}} -{{source=..\SamplesVB\GridView\Filtering\CustomFiltering.vb region=usingFilterPredicate1}} - -````C# -private bool PerformFiltering(GridViewRowInfo row) -{ - bool valid = (decimal)row.Cells["UnitPrice"].Value > 30; - return valid; -} - -```` -````VB.NET -Private Function PerformFiltering(ByVal row As GridViewRowInfo) As Boolean - Dim valid As Boolean = CDec(row.Cells("UnitPrice").Value) > 30 - Return valid -End Function - -```` - -{{endregion}} - - + + + + ## See Also * [Basic Filtering]({%slug winforms/gridview/filtering/basic-filtering%}) diff --git a/controls/gridview/features/filtering/events.md b/controls/gridview/features/filtering/events.md index 57fd46195..a1b578b8e 100644 --- a/controls/gridview/features/filtering/events.md +++ b/controls/gridview/features/filtering/events.md @@ -13,33 +13,8 @@ previous_url: gridview-filtering-events There are two events that are raised when the data in the RadGridView is filtered. The first one is the __FilterChanging__ event and it is raised before the data is filtered. The second one is the __FilterChanged__ event which is raised after the data is filtered. -{{source=..\SamplesCS\GridView\Filtering\FilteringEvents.cs region=events1}} -{{source=..\SamplesVB\GridView\Filtering\FilteringEvents.vb region=events1}} -````C# -void radGridView1_FilterChanged(object sender, Telerik.WinControls.UI.GridViewCollectionChangedEventArgs e) -{ - -} - -void radGridView1_FilterChanging(object sender, Telerik.WinControls.UI.GridViewCollectionChangingEventArgs e) -{ - -} - - -```` -````VB.NET -Private Sub RadGridView1_FilterChanged(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewCollectionChangedEventArgs) Handles RadGridView1.FilterChanged - -End Sub - -Private Sub RadGridView1_FilterChanging(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewCollectionChangingEventArgs) Handles RadGridView1.FilterChanging - -End Sub - -```` - -{{endregion}} + + From the event arguments of both events you can access the following data: @@ -49,57 +24,15 @@ From the event arguments of both events you can access the following data: You are also able to cancel the filtering operation by setting the __Cancel__ property to *True*. -{{source=..\SamplesCS\GridView\Filtering\FilteringEvents.cs region=cancelFilteringEvent}} -{{source=..\SamplesVB\GridView\Filtering\FilteringEvents.vb region=cancelFilteringEvent}} -````C# -void radGridView1_FilterChanging1(object sender, Telerik.WinControls.UI.GridViewCollectionChangingEventArgs e) -{ - e.Cancel = true; -} - -```` -````VB.NET -Private Sub RadGridView1_FilterChanging1(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewCollectionChangingEventArgs) Handles RadGridView1.FilterChanging - e.Cancel = True -End Sub - -```` - -{{endregion}} + + Since the __FilterDescriptors__ collection implements the __INotifyCollectionChanged__ interface, you can use its __CollectionChanged__ event: -{{source=..\SamplesCS\GridView\Filtering\FilteringEvents.cs region=collectionChanged}} -{{source=..\SamplesVB\GridView\Filtering\FilteringEvents.vb region=collectionChanged}} -````C# -this.radGridView1.FilterDescriptors.CollectionChanged += new Telerik.WinControls.Data.NotifyCollectionChangedEventHandler(FilterDescriptors_CollectionChanged); - -```` -````VB.NET -AddHandler Me.RadGridView1.FilterDescriptors.CollectionChanged, AddressOf FilterDescriptors_CollectionChanged - -```` - -{{endregion}} - -{{source=..\SamplesCS\GridView\Filtering\FilteringEvents.cs region=collectionChanged1}} -{{source=..\SamplesVB\GridView\Filtering\FilteringEvents.vb region=collectionChanged1}} - -````C# -void FilterDescriptors_CollectionChanged(object sender, Telerik.WinControls.Data.NotifyCollectionChangedEventArgs e) -{ - -} - -```` -````VB.NET -Private Sub FilterDescriptors_CollectionChanged(ByVal sender As Object, ByVal e As Telerik.WinControls.Data.NotifyCollectionChangedEventArgs) - Throw New NotImplementedException -End Sub - -```` - -{{endregion}} + + + + The arguments of this event provide the same data as the __FilterChanged__ event. diff --git a/controls/gridview/features/filtering/excel-like-filtering.md b/controls/gridview/features/filtering/excel-like-filtering.md index 981b74cf7..f392d9681 100644 --- a/controls/gridview/features/filtering/excel-like-filtering.md +++ b/controls/gridview/features/filtering/excel-like-filtering.md @@ -23,42 +23,10 @@ Enabling the excel-like filtering is quite easy. You have to set the grid's prop #### Enabling Excel-like filtering -{{source=..\SamplesCS\GridView\Filtering\Excel-like Filtering.cs region=excel-like filtering}} -{{source=..\SamplesVB\GridView\Filtering\Excel-like Filtering.vb region=excel-like filtering}} + + -````C# -this.radGridView1.EnableFiltering = true; -this.radGridView1.MasterTemplate.ShowHeaderCellButtons = true; -this.radGridView1.MasterTemplate.ShowFilteringRow = false; -```` -````VB.NET -Me.RadGridView1.EnableFiltering = True -Me.RadGridView1.MasterTemplate.ShowHeaderCellButtons = True -Me.RadGridView1.MasterTemplate.ShowFilteringRow = False - -```` - -{{endregion}} - -Note that __ShowHeaderCellButtons__ property can be specified on grid templates level, and scenarios with mixed filter functionality on the different hierarchy levels are possible. Also excel-like filtering will be synchronized with the previous filter row functionality if __ShowFilteringRow__ remains *true*. - - -After enabling the Excel-like filtering feature, you may decide that you do not want it for a specific column. In this case you should set the __AllowFiltering__ property of that column to *false*: - -{{source=..\SamplesCS\GridView\Filtering\Excel-like Filtering.cs region=allowFiltering}} -{{source=..\SamplesVB\GridView\Filtering\Excel-like Filtering.vb region=allowFiltering}} - -````C# -this.radGridView1.Columns["ContactName"].AllowFiltering = false; - -```` -````VB.NET -Me.RadGridView1.Columns("ContactName").AllowFiltering = False - -```` - -{{endregion}} ![WinForms RadGridView AllowFiltering](images/gridview-filtering-excel-like-filtering003.png) @@ -74,33 +42,10 @@ This popup allows convenient selection of specific date, or period. It will be s The following code demonstrates how to clear the default custom items, and how to add your own item to this popup: -{{source=..\SamplesCS\GridView\Filtering\Excel-like Filtering2.cs region=CalendarFilterPopup}} -{{source=..\SamplesVB\GridView\Filtering\Excel-like Filtering2.vb region=CalendarFilterPopup}} - -````C# -void radGridView1_FilterPopupRequired(object sender, Telerik.WinControls.UI.FilterPopupRequiredEventArgs e) -{ - if (e.FilterPopup is RadDateFilterPopup) - { - RadDateFilterPopup popup = (RadDateFilterPopup)e.FilterPopup; - popup.ClearCustomMenuItems(); - popup.AddCustomMenuItem("today", new DateFilterDescriptor(e.Column.Name, FilterOperator.IsEqualTo, DateTime.Today)); - } -} - -```` -````VB.NET -Private Sub radGridView1_FilterPopupRequired(sender As Object, e As Telerik.WinControls.UI.FilterPopupRequiredEventArgs) Handles RadGridView1.FilterPopupRequired - If TypeOf e.FilterPopup Is RadDateFilterPopup Then - Dim popup As RadDateFilterPopup = DirectCast(e.FilterPopup, RadDateFilterPopup) - popup.ClearCustomMenuItems() - popup.AddCustomMenuItem("today", New DateFilterDescriptor(e.Column.Name, FilterOperator.IsEqualTo, DateTime.Today)) - End If -End Sub - -```` - -{{endregion}} + + + + Here is how the customized popup looks like @@ -110,29 +55,10 @@ Here is how the customized popup looks like This popup allows easy and fast filtering based on simple list and one-click filter apply. It can be set up through __FilterPopupRequired__ event: -{{source=..\SamplesCS\GridView\Filtering\Excel-like Filtering2.cs region=SimpleListPopup}} -{{source=..\SamplesVB\GridView\Filtering\Excel-like Filtering2.vb region=SimpleListPopup}} - -````C# -void radGridView1_FilterPopupRequired1(object sender, Telerik.WinControls.UI.FilterPopupRequiredEventArgs e) -{ - if (e.Column.Name == "ShipCountry") - { - e.FilterPopup = new RadSimpleListFilterPopup(e.Column); - } -} + + -```` -````VB.NET -Private Sub radGridView1_FilterPopupRequired1(sender As Object, e As Telerik.WinControls.UI.FilterPopupRequiredEventArgs) Handles RadGridView1.FilterPopupRequired - If e.Column.Name = "ShipCountry" Then - e.FilterPopup = New RadSimpleListFilterPopup(e.Column) - End If -End Sub -```` - -{{endregion}} >note As of R1 2021 **RadSimpleListFilterPopup** can filter the time part more precisely. It is possible through GridViewDateTimeColumn.**FilteringTimePrecision** property that allows to specify how the time part of the DateTime value will be evaluated while filtering. The possible values are *Hour*, *Minute*, *Second*, and *All*. **FilteringTimePrecision** property works with **FilteringMode** property of the column set to GridViewTimeFilteringMode.**DateTime** or GridViewTimeFilteringMode.**Time**. > @@ -146,29 +72,10 @@ This pop allows representation of date values grouped by year and month in a lis >note Note that if there are a lot of values, there will be performance impact of selecting items on higher level (as month and year) because a lot of FilterDescriptors will be applied simultaneously. > -{{source=..\SamplesCS\GridView\Filtering\Excel-like Filtering2.cs region=GroupedDatesPopup}} -{{source=..\SamplesVB\GridView\Filtering\Excel-like Filtering2.vb region=GroupedDatesPopup}} - -````C# -void radGridView1_FilterPopupRequired2(object sender, Telerik.WinControls.UI.FilterPopupRequiredEventArgs e) -{ - if (e.Column.Name == "OrderDate") - { - e.FilterPopup = new RadListFilterPopup(e.Column, true); - } -} - -```` -````VB.NET -Private Sub radGridView1_FilterPopupRequired2(sender As Object, e As Telerik.WinControls.UI.FilterPopupRequiredEventArgs) Handles RadGridView1.FilterPopupRequired - If e.Column.Name = "OrderDate" Then - e.FilterPopup = New RadListFilterPopup(e.Column, True) - End If -End Sub - -```` - -{{endregion}} + + + + ![WinForms RadGridView Grouped Dates Popup](images/gridview-filtering-excel-like-filtering007.png) diff --git a/controls/gridview/features/filtering/filterexpressionchanged-event.md b/controls/gridview/features/filtering/filterexpressionchanged-event.md index b852ccbd8..cbb041450 100644 --- a/controls/gridview/features/filtering/filterexpressionchanged-event.md +++ b/controls/gridview/features/filtering/filterexpressionchanged-event.md @@ -15,24 +15,8 @@ The RadGridView.**FilterExpressionChanged** event is the only place where you ca #### Filter expression changed event -{{source=..\SamplesCS\GridView\Filtering\Filtering.cs region=filterExpressionChangedEvent}} -{{source=..\SamplesVB\GridView\Filtering\Filtering.vb region=filterExpressionChangedEvent}} - -````C# -void radGridView1_FilterExpressionChanged(object sender, Telerik.WinControls.UI.FilterExpressionChangedEventArgs e) -{ - e.FilterExpression = "(([ProductName] LIKE '%Qu%'))"; -} - -```` -````VB.NET -Private Sub RadGridView1_FilterExpressionChanged(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.FilterExpressionChangedEventArgs) - e.FilterExpression = "(((ProductName) LIKE '%Qu%'))" -End Sub - -```` - -{{endregion}} + + This event is also the final place where the filtering expression can be changed before it is evaluated.  diff --git a/controls/gridview/features/filtering/filtering-row.md b/controls/gridview/features/filtering/filtering-row.md index 60ae651f3..3f3224661 100644 --- a/controls/gridview/features/filtering/filtering-row.md +++ b/controls/gridview/features/filtering/filtering-row.md @@ -19,19 +19,8 @@ You can hide the operator text of the filter cells by setting the __ShowFilterCe ## Hide Operator Text -{{source=..\SamplesCS\GridView\Filtering\Filtering.cs region=filterOperatorText}} -{{source=..\SamplesVB\GridView\Filtering\Filtering.vb region=filterOperatorText}} - -````C# -this.radGridView1.MasterTemplate.ShowFilterCellOperatorText = false; - -```` -````VB.NET -Me.RadGridView1.MasterTemplate.ShowFilterCellOperatorText = False - -```` - -{{endregion}} + + ![WinForms RadGridView gridview-filtering-filtering-row 002](images/gridview-filtering-filtering-row002.png) @@ -39,19 +28,8 @@ You can also hide the entire __GridFilterRowElement__:  ## Hide filter row -{{source=..\SamplesCS\GridView\Filtering\Filtering.cs region=hidingTheFilterRow}} -{{source=..\SamplesVB\GridView\Filtering\Filtering.vb region=hidingTheFilterRow}} - -````C# -this.radGridView1.ShowFilteringRow = false; - -```` -````VB.NET -Me.RadGridView1.ShowFilteringRow = False - -```` - -{{endregion}} + + You can still add [FilterDescriptors]({%slug winforms/gridview/filtering/setting-filters-programmatically-(simple-descriptors)%}) programmatically when the __GridFilterRowElement__ is hidden. diff --git a/controls/gridview/features/filtering/put-a-filter-cell-into-edit-mode-programmatically.md b/controls/gridview/features/filtering/put-a-filter-cell-into-edit-mode-programmatically.md index fa7e736ab..e6ad1ab81 100644 --- a/controls/gridview/features/filtering/put-a-filter-cell-into-edit-mode-programmatically.md +++ b/controls/gridview/features/filtering/put-a-filter-cell-into-edit-mode-programmatically.md @@ -15,19 +15,8 @@ You can easily put a filter cell into edit mode by code. You should simply call #### Put a filter cell in edit mode programmatically -{{source=..\SamplesCS\GridView\Filtering\Filtering.cs region=putFilterCellIntoEditModeProgramatically}} -{{source=..\SamplesVB\GridView\Filtering\Filtering.vb region=putFilterCellIntoEditModeProgramatically}} - -````C# -this.radGridView1.MasterView.TableFilteringRow.Cells[1].BeginEdit(); - -```` -````VB.NET -Me.RadGridView1.MasterView.TableFilteringRow.Cells(0).BeginEdit() - -```` - -{{endregion}} + + ![WinForms RadGridView Filter Cell Non Edit Mode](images/gridview-filtering-put-a-filter-cell-into-edit-mode-programatically001.png) diff --git a/controls/gridview/features/filtering/setting-filters-programmatically-(composite-descriptors).md b/controls/gridview/features/filtering/setting-filters-programmatically-(composite-descriptors).md index 7a4f9b075..f130f4832 100644 --- a/controls/gridview/features/filtering/setting-filters-programmatically-(composite-descriptors).md +++ b/controls/gridview/features/filtering/setting-filters-programmatically-(composite-descriptors).md @@ -17,27 +17,8 @@ To filter a single data field by multiple values, you have to use the __Composit #### Setting composite filter descriptors -{{source=..\SamplesCS\GridView\Filtering\Filtering.cs region=settingCompositeFilterDescriptors}} -{{source=..\SamplesVB\GridView\Filtering\Filtering.vb region=settingCompositeFilterDescriptors}} - -````C# -CompositeFilterDescriptor compositeFilter = new CompositeFilterDescriptor(); -compositeFilter.FilterDescriptors.Add(new FilterDescriptor("UnitsInStock", FilterOperator.IsGreaterThan, 100)); -compositeFilter.FilterDescriptors.Add(new FilterDescriptor("ProductName", FilterOperator.StartsWith, "G")); -compositeFilter.LogicalOperator = FilterLogicalOperator.And; -this.radGridView1.FilterDescriptors.Add(compositeFilter); - -```` -````VB.NET -Dim compositeFilter As New CompositeFilterDescriptor() -compositeFilter.FilterDescriptors.Add(New FilterDescriptor("UnitsInStock", FilterOperator.IsGreaterThan, 100)) -compositeFilter.FilterDescriptors.Add(New FilterDescriptor("ProductName", FilterOperator.StartsWith, "G")) -compositeFilter.LogicalOperator = FilterLogicalOperator.[And] -Me.RadGridView1.FilterDescriptors.Add(compositeFilter) - -```` - -{{endregion}} + + The __CompositeFilterDescriptors__ supports *__And__* and *__Or__* logical operators. Result of the above example using *__And__* logical operator: @@ -53,37 +34,8 @@ The composite filters allow you to create more complex filtering expressions. Su #### Setting complex composite filter descriptors -{{source=..\SamplesCS\GridView\Filtering\Filtering.cs region=settingComplexCompositeFilterDescriptors}} -{{source=..\SamplesVB\GridView\Filtering\Filtering.vb region=settingComplexCompositeFilterDescriptors}} - -````C# -CompositeFilterDescriptor compositeFilter1 = new CompositeFilterDescriptor(); -compositeFilter1.FilterDescriptors.Add(new FilterDescriptor("UnitsInStock", FilterOperator.IsGreaterThan, 100)); -compositeFilter1.FilterDescriptors.Add(new FilterDescriptor("ProductName", FilterOperator.StartsWith, "G")); -compositeFilter1.LogicalOperator = FilterLogicalOperator.Or; -FilterDescriptor filter2 = new FilterDescriptor("UnitsOnOrder", FilterOperator.IsEqualTo, 0); -CompositeFilterDescriptor filterDescriptor2 = new CompositeFilterDescriptor(); -filterDescriptor2.FilterDescriptors.Add(compositeFilter1); -filterDescriptor2.FilterDescriptors.Add(filter2); -filterDescriptor2.LogicalOperator = FilterLogicalOperator.And; -this.radGridView1.FilterDescriptors.Add(filterDescriptor2); - -```` -````VB.NET -Dim compositeFilter1 As New CompositeFilterDescriptor() -compositeFilter1.FilterDescriptors.Add(New FilterDescriptor("UnitsInStock", FilterOperator.IsGreaterThan, 100)) -compositeFilter1.FilterDescriptors.Add(New FilterDescriptor("ProductName", FilterOperator.StartsWith, "G")) -compositeFilter1.LogicalOperator = FilterLogicalOperator.[Or] -Dim filter2 As New FilterDescriptor("UnitsOnOrder", FilterOperator.IsEqualTo, 0) -Dim filterDescriptor2 As New CompositeFilterDescriptor() -filterDescriptor2.FilterDescriptors.Add(compositeFilter1) -filterDescriptor2.FilterDescriptors.Add(filter2) -filterDescriptor2.LogicalOperator = FilterLogicalOperator.[And] -Me.RadGridView1.FilterDescriptors.Add(filterDescriptor2) - -```` - -{{endregion}} + + ## Setting Filters for Excel-like filtering @@ -91,38 +43,8 @@ The following example shows how you can add descriptors that will be reflected i #### Setting filters for Excel-like filtering -{{source=..\SamplesCS\GridView\Filtering\Filtering.cs region=Excel}} -{{source=..\SamplesVB\GridView\Filtering\Filtering.vb region=Excel}} -````C# -var filterDescriptor = new FilterDescriptor(); -filterDescriptor.PropertyName = "Title"; -filterDescriptor.Value = "Sales Representative"; -filterDescriptor.Operator = FilterOperator.IsNotEqualTo; -var cfd = new CompositeFilterDescriptor(); -cfd.LogicalOperator = FilterLogicalOperator.And; -cfd.FilterDescriptors.Add(filterDescriptor); -cfd.IsFilterEditor = true; -this.radGridView1.FilterDescriptors.Add(cfd); -this.radGridView1.MasterTemplate.ExcelFilteredColumns.Add(this.radGridView1.Columns["Title"]); - -```` -````VB.NET -Dim filterDescriptor As New FilterDescriptor() -filterDescriptor.PropertyName = "Title" -filterDescriptor.Value = "Sales Representative" -filterDescriptor.Operator = FilterOperator.IsNotEqualTo -Dim cfd As New CompositeFilterDescriptor() -cfd.LogicalOperator = FilterLogicalOperator.And -cfd.FilterDescriptors.Add(filterDescriptor) -cfd.IsFilterEditor = True -Me.RadGridView1.FilterDescriptors.Add(cfd) -Me.RadGridView1.MasterTemplate.ExcelFilteredColumns.Add(Me.RadGridView1.Columns("Title")) - -```` - - - -{{endregion}} + + ## See Also * [Basic Filtering]({%slug winforms/gridview/filtering/basic-filtering%}) diff --git a/controls/gridview/features/filtering/setting-filters-programmatically-(simple-descriptors).md b/controls/gridview/features/filtering/setting-filters-programmatically-(simple-descriptors).md index f3554fec7..6e0376fc2 100644 --- a/controls/gridview/features/filtering/setting-filters-programmatically-(simple-descriptors).md +++ b/controls/gridview/features/filtering/setting-filters-programmatically-(simple-descriptors).md @@ -27,29 +27,8 @@ The **RadGridView** control includes __FilterDescriptors__ property of the **Gri #### Using simple filter descriptor -{{source=..\SamplesCS\GridView\Filtering\Filtering.cs region=usingSimpleFilterDescriptor}} -{{source=..\SamplesVB\GridView\Filtering\Filtering.vb region=usingSimpleFilterDescriptor}} - -````C# -FilterDescriptor filter = new FilterDescriptor(); -filter.PropertyName = "ProductName"; -filter.Operator = FilterOperator.Contains; -filter.Value = "Qu"; -filter.IsFilterEditor = true; -this.radGridView1.FilterDescriptors.Add(filter); - -```` -````VB.NET -Dim filter As New FilterDescriptor() -filter.PropertyName = "ProductName" -filter.[Operator] = FilterOperator.Contains -filter.Value = "Qu" -filter.IsFilterEditor = True -Me.RadGridView1.FilterDescriptors.Add(filter) - -```` - -{{endregion}} + + ![WinForms RadGridView FilterDescriptor](images/gridview-filtering-setting-filters-programmatically-simple-descriptors001.png) @@ -69,27 +48,8 @@ Each data column (represented by [GridViewDataColumn](http://www.telerik.com/hel #### Assigning a filter descriptor object -{{source=..\SamplesCS\GridView\Filtering\Filtering.cs region=assingingAFilterDescriptorObject}} -{{source=..\SamplesVB\GridView\Filtering\Filtering.vb region=assingingAFilterDescriptorObject}} - -````C# -FilterDescriptor filter1 = new FilterDescriptor(); -filter1.Operator = FilterOperator.Contains; -filter1.Value = "Qu"; -filter1.IsFilterEditor = true; -this.radGridView1.Columns["ProductName"].FilterDescriptor = filter1; - -```` -````VB.NET -Dim filter1 As New FilterDescriptor() -filter1.[Operator] = FilterOperator.Contains -filter1.Value = "Qu" -filter1.IsFilterEditor = True -Me.RadGridView1.Columns("ProductName").FilterDescriptor = filter1 - -```` - -{{endregion}} + + ### Setting Multiple Filters @@ -97,41 +57,8 @@ You can add filters to multiple columns by adding a __FilterDescriptor__ for eac #### Setting multiple filters -{{source=..\SamplesCS\GridView\Filtering\Filtering.cs region=settingMultipleFilters}} -{{source=..\SamplesVB\GridView\Filtering\Filtering.vb region=settingMultipleFilters}} - -````C# -FilterDescriptor filterUnitsInStock = new FilterDescriptor(); -filterUnitsInStock.PropertyName = "UnitsInStock"; -filterUnitsInStock.Operator = FilterOperator.IsGreaterThan; -filterUnitsInStock.Value = 100; -filterUnitsInStock.IsFilterEditor = true; -this.radGridView1.FilterDescriptors.Add(filterUnitsInStock); -FilterDescriptor filterProductName = new FilterDescriptor(); -filterProductName.PropertyName = "ProductName"; -filterProductName.Operator = FilterOperator.StartsWith; -filterProductName.Value = "G"; -filterProductName.IsFilterEditor = true; -this.radGridView1.FilterDescriptors.Add(filterProductName); - -```` -````VB.NET -Dim filterUnitsInStock As New FilterDescriptor() -filterUnitsInStock.PropertyName = "UnitsInStock" -filterUnitsInStock.[Operator] = FilterOperator.IsGreaterThan -filterUnitsInStock.Value = 100 -filterUnitsInStock.IsFilterEditor = True -Me.RadGridView1.FilterDescriptors.Add(filterUnitsInStock) -Dim filterProductName As New FilterDescriptor() -filterProductName.PropertyName = "ProductName" -filterProductName.[Operator] = FilterOperator.StartsWith -filterProductName.Value = "G" -filterProductName.IsFilterEditor = True -Me.RadGridView1.FilterDescriptors.Add(filterProductName) - -```` - -{{endregion}} + + ![WinForms RadGridView Setting Multiple Filters](images/gridview-filtering-setting-filters-programmatically-simple-descriptors002.png) diff --git a/controls/gridview/features/grouping/basic-grouping.md b/controls/gridview/features/grouping/basic-grouping.md index 40b461056..bc639c77b 100644 --- a/controls/gridview/features/grouping/basic-grouping.md +++ b/controls/gridview/features/grouping/basic-grouping.md @@ -36,23 +36,8 @@ The example below allows GroupDescriptors to be added programmatically, but doe #### Setting grouping properties -{{source=..\SamplesCS\GridView\Grouping\Grouping.cs region=settingGroupingProperties}} -{{source=..\SamplesVB\GridView\Grouping\Grouping.vb region=settingGroupingProperties}} - -````C# -this.radGridView1.MasterTemplate.EnableGrouping = true; -this.radGridView1.MasterTemplate.AllowDragToGroup = false; -this.radGridView1.MasterTemplate.AutoExpandGroups = true; - -```` -````VB.NET -Me.RadGridView1.MasterTemplate.EnableGrouping = True -Me.RadGridView1.MasterTemplate.AllowDragToGroup = False -Me.RadGridView1.MasterTemplate.AutoExpandGroups = True - -```` - -{{endregion}} + + ## GroupPanel @@ -60,37 +45,16 @@ You can hide the __GroupPanel__ using the following code: #### Hide the group panel -{{source=..\SamplesCS\GridView\Grouping\Grouping.cs region=hideTheGroupPanel}} -{{source=..\SamplesVB\GridView\Grouping\Grouping.vb region=hideTheGroupPanel}} - -````C# -this.radGridView1.ShowGroupPanel = false; - -```` -````VB.NET -Me.RadGridView1.ShowGroupPanel = False - -```` - -{{endregion}} + + The __ShowGroupPanelScrollbars__ property indicates whether the group panel will show scroll-bars or it will expand to show all group headers. #### Show the group panel scroll-bar -{{source=..\SamplesCS\GridView\Grouping\Grouping.cs region=ShowGroupPanelScrollbars}} -{{source=..\SamplesVB\GridView\Grouping\Grouping.vb region=ShowGroupPanelScrollbars}} - -````C# -this.radGridView1.ShowGroupPanelScrollbars = true; - -```` -````VB.NET -Me.RadGridView1.ShowGroupPanelScrollbars = True - -```` + + -{{endregion}} |ShowGroupPanelScrollbars = *false* |ShowGroupPanelScrollbars = *true* | | ------ | ------ | |![WinForms RadGridView ShowGroupPanelScrollbars False](images/gridview-grouping-basic-grouping002.png)|![WinForms RadGridView ShowGroupPanelScrollbars True](images/gridview-grouping-basic-grouping003.png)| diff --git a/controls/gridview/features/grouping/custom-grouping.md b/controls/gridview/features/grouping/custom-grouping.md index ae78e2798..b2764b0bd 100644 --- a/controls/gridview/features/grouping/custom-grouping.md +++ b/controls/gridview/features/grouping/custom-grouping.md @@ -43,87 +43,10 @@ The following example demonstrates how to handle the __CustomGrouping__ event to ![WinForms RadGridView Custom Grouping](images/gridview-grouping-custom-grouping001.png) -{{source=..\SamplesCS\GridView\Grouping\CustomGrouping.cs region=usingCustomGrouping}} -{{source=..\SamplesVB\GridView\Grouping\CustomGrouping.vb region=usingCustomGrouping}} - -````C# -this.radGridView1.EnableCustomGrouping = true; -this.radGridView1.CustomGrouping += new GridViewCustomGroupingEventHandler(radGridView1_CustomGrouping); -GroupDescriptor descriptor = new GroupDescriptor("Country"); -this.radGridView1.GroupDescriptors.Add(descriptor); -this.radGridView1.GroupSummaryEvaluate += new GroupSummaryEvaluateEventHandler(radGridView1_GroupSummaryEvaluate); - -```` -````VB.NET -Me.RadGridView1.EnableCustomGrouping = True -Dim descriptor As New GroupDescriptor("Country") -Me.RadGridView1.GroupDescriptors.Add(descriptor) - -```` - -{{endregion}} - - - -{{source=..\SamplesCS\GridView\Grouping\CustomGrouping.cs region=usingCustomGrouping1}} -{{source=..\SamplesVB\GridView\Grouping\CustomGrouping.vb region=usingCustomGrouping1}} - -````C# -private void radGridView1_CustomGrouping(object sender, GridViewCustomGroupingEventArgs e) -{ - string country = e.Row.Cells["Country"].Value.ToString(); - switch (country) - { - case "USA": - e.GroupKey = "1. USA"; - break; - case "Japan": - e.GroupKey = "2. Japan"; - break; - case "Germany": - e.GroupKey = "3. Germany"; - break; - default: - e.GroupKey = "Other country"; - break; - } -} -private void radGridView1_GroupSummaryEvaluate(object sender, GroupSummaryEvaluationEventArgs e) -{ - if (e.Value == null) - { - e.FormatString = e.Group.Key.ToString(); - } -} - -```` -````VB.NET -Private Sub RadGridView1_CustomGrouping(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewCustomGroupingEventArgs) Handles RadGridView1.CustomGrouping - Dim country As String = e.Row.Cells("Country").Value.ToString() - Select Case country - Case "USA" - e.GroupKey = "1. USA" - Exit Select - Case "Japan" - e.GroupKey = "2. Japan" - Exit Select - Case "Germany" - e.GroupKey = "3. Germany" - Exit Select - Case Else - e.GroupKey = "Other country" - Exit Select - End Select -End Sub -Private Sub RadGridView1_GroupSummaryEvaluate(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GroupSummaryEvaluationEventArgs) Handles RadGridView1.GroupSummaryEvaluate - If e.Value Is Nothing Then - e.FormatString = e.Group.Key.ToString() - End If -End Sub - -```` - -{{endregion}} + + + + When __RadGridView__ is displaying date columns, it is a common requirement to perform grouping by certain part of the DateTime value. The example below will handle a scenario in which the date fields are grouped in year quarters. @@ -135,68 +58,8 @@ When __RadGridView__ is displaying date columns, it is a common requirement to p ![WinForms RadGridView DateTime Grouping Custom Behavior](images/gridview-grouping-custom-grouping004.png) -{{source=..\SamplesCS\GridView\Grouping\CustomGroupingDateFields.cs region=CustomGrouping}} -{{source=..\SamplesVB\GridView\Grouping\CustomGroupingDateFields.vb region=CustomGrouping}} - -````C# -private void radGridView1_CustomGrouping(object sender, GridViewCustomGroupingEventArgs e) -{ - DateTime date = (DateTime)e.Row.Cells["Date"].Value; - e.GroupKey = date.Year + " " + this.GetQuarter(date); -} -private string GetQuarter(DateTime date) -{ - if (date.Month >= 0 && date.Month <= 3) - { - return "Q1"; - } - else if (date.Month >= 4 && date.Month <= 6) - { - return "Q2"; - } - else if (date.Month >= 7 && date.Month <= 9) - { - return "Q3"; - } - else - { - return "Q4"; - } -} -private void radGridView1_GroupSummaryEvaluate(object sender, GroupSummaryEvaluationEventArgs e) -{ - if (e.Value == null) - { - e.FormatString = e.Group.Key.ToString(); - } -} - -```` -````VB.NET -Private Sub radGridView1_CustomGrouping(sender As Object, e As GridViewCustomGroupingEventArgs) - Dim [date] As DateTime = DirectCast(e.Row.Cells("Date").Value, DateTime) - e.GroupKey = Convert.ToString([date].Year) & " " & Me.GetQuarter([date]) -End Sub -Private Function GetQuarter([date] As DateTime) As String - If [date].Month >= 0 AndAlso [date].Month <= 3 Then - Return "Q1" - ElseIf [date].Month >= 4 AndAlso [date].Month <= 6 Then - Return "Q2" - ElseIf [date].Month >= 7 AndAlso [date].Month <= 9 Then - Return "Q3" - Else - Return "Q4" - End If -End Function -Private Sub radGridView1_GroupSummaryEvaluate(sender As Object, e As GroupSummaryEvaluationEventArgs) - If e.Value Is Nothing Then - e.FormatString = e.Group.Key.ToString() - End If -End Sub - -```` - -{{endregion}} + + ## Implementing grouping mechanism by using GroupPredicate diff --git a/controls/gridview/features/grouping/events.md b/controls/gridview/features/grouping/events.md index a1e6e63e1..43419717d 100644 --- a/controls/gridview/features/grouping/events.md +++ b/controls/gridview/features/grouping/events.md @@ -13,24 +13,8 @@ previous_url: gridview-grouping-events There are two events that are raised, when the data in the RadGridView is grouped. The first one is the __GroupByChanging__ event which is raised before the data is grouped and he second one is the __GroupByChanged__ event raised after the data is grouped. -{{source=..\SamplesCS\GridView\Grouping\GroupingEvents.cs region=eventHandlers}} -{{source=..\SamplesVB\GridView\Grouping\GroupingEvents.vb region=eventHandlers}} - -````C# -void radGridView1_GroupByChanging1(object sender, Telerik.WinControls.UI.GridViewCollectionChangingEventArgs e) -{ - e.Cancel = true; -} - -```` -````VB.NET -Private Sub RadGridView1_GroupByChanging1(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewCollectionChangingEventArgs) Handles RadGridView1.GroupByChanging - e.Cancel = True -End Sub - -```` - -{{endregion}} + + From the event arguments of both events you can access the following data: @@ -40,56 +24,15 @@ From the event arguments of both events you can access the following data: You are also able to cancel the grouping operation by setting the __Cancel__ property to *True* -{{source=..\SamplesCS\GridView\Grouping\GroupingEvents.cs region=cancelGrouping}} -{{source=..\SamplesVB\GridView\Grouping\GroupingEvents.vb region=cancelGrouping}} -````C# -void radGridView1_GroupByChanging1(object sender, Telerik.WinControls.UI.GridViewCollectionChangingEventArgs e) -{ - e.Cancel = true; -} - -```` -````VB.NET -Private Sub RadGridView1_GroupByChanging1(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewCollectionChangingEventArgs) Handles RadGridView1.GroupByChanging - e.Cancel = True -End Sub - -```` - -{{endregion}} + + Since the __GroupDescriptors__ collection implements the __INotifyPropertyChanged__ interface, you can use its __CollectionChanged__ event: -{{source=..\SamplesCS\GridView\Grouping\GroupingEvents.cs region=subscribeToCollectionChanged}} -{{source=..\SamplesVB\GridView\Grouping\GroupingEvents.vb region=subscribeToCollectionChanged}} -````C# -radGridView1.GroupDescriptors.CollectionChanged += new Telerik.WinControls.Data.NotifyCollectionChangedEventHandler(GroupDescriptors_CollectionChanged); - -```` -````VB.NET -AddHandler Me.RadGridView1.GroupDescriptors.CollectionChanged, AddressOf GroupDescriptors_CollectionChanged - -```` - -{{endregion}} - - -{{source=..\SamplesCS\GridView\Grouping\GroupingEvents.cs region=CollectionChangedHandler}} -{{source=..\SamplesVB\GridView\Grouping\GroupingEvents.vb region=CollectionChangedHandler}} - -````C# -void GroupDescriptors_CollectionChanged(object sender, Telerik.WinControls.Data.NotifyCollectionChangedEventArgs e) -{ -} - -```` -````VB.NET -Private Sub GroupDescriptors_CollectionChanged(ByVal sender As Object, ByVal e As Telerik.WinControls.Data.NotifyCollectionChangedEventArgs) -End Sub - -```` - -{{endregion}} + + + + The arguments of this event provide the same data as the __GroupByChanged__ event. diff --git a/controls/gridview/features/grouping/formatting-group-header-row.md b/controls/gridview/features/grouping/formatting-group-header-row.md index 93f46e0b1..aa939a6a6 100644 --- a/controls/gridview/features/grouping/formatting-group-header-row.md +++ b/controls/gridview/features/grouping/formatting-group-header-row.md @@ -17,30 +17,8 @@ The example below demonstrates how you can change the group header text of each #### Change group header text -{{source=..\SamplesCS\GridView\Grouping\FormattingGroupHeaderRow.cs region=groupHeaderText}} -{{source=..\SamplesVB\GridView\Grouping\FormattingGroupHeaderRow.vb region=groupHeaderText}} - -````C# -void radGridView1_GroupSummaryEvaluate(object sender, Telerik.WinControls.UI.GroupSummaryEvaluationEventArgs e) -{ - if (e.SummaryItem.Name == "Country") - { - e.FormatString = String.Format("Group by country: {0}", e.Value); - } -} - -```` -````VB.NET -Private Sub RadGridView1_GroupSummaryEvaluate(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GroupSummaryEvaluationEventArgs) Handles RadGridView1.GroupSummaryEvaluate - If e.SummaryItem.Name = "Country" Then - e.FormatString = [String].Format("Group by country: {0}", e.Value) - End If -End Sub - -```` - -{{endregion}} - + + ![WinForms RadGridView Change group header text](images/gridview-grouping-formatting-group-header-row001.png) @@ -48,45 +26,8 @@ The following example demonstrates formatting of group header which uses data fr #### Formatting group header by using data from data rows -{{source=..\SamplesCS\GridView\Grouping\FormattingGroupHeaderRow.cs region=formatGroupHeaderWhichUsersDataFromGroupRows}} -{{source=..\SamplesVB\GridView\Grouping\FormattingGroupHeaderRow.vb region=formatGroupHeaderWhichUsersDataFromGroupRows}} - -````C# -void radGridView1_GroupSummaryEvaluate1(object sender, Telerik.WinControls.UI.GroupSummaryEvaluationEventArgs e) -{ - if (e.SummaryItem.Name == "ContactTitle") - { - int count = e.Group.ItemCount; - int contactsInCanada = 0; - foreach (GridViewRowInfo row in e.Group) - { - if (row.Cells["Country"].Value.ToString() == "Canada") - { - contactsInCanada++; - } - } - e.FormatString = String.Format("There are {0} {1} and {2} of them is(are) from Canada.", count, e.Value, contactsInCanada); - } -} - -```` -````VB.NET -Private Sub RadGridView1_GroupSummaryEvaluate1(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GroupSummaryEvaluationEventArgs) Handles RadGridView1.GroupSummaryEvaluate - If e.SummaryItem.Name = "ContactTitle" Then - Dim contactsCount As Integer = e.Group.ItemCount - Dim contactsInCanada As Integer = 0 - For Each row As GridViewRowInfo In e.Group - If row.Cells("Country").Value.ToString() = "Canada" Then - contactsInCanada += 1 - End If - Next - e.FormatString = [String].Format("There are {0} {1} and {2} of them is(are) from France.", contactsCount, e.Value, contactsInCanada) - End If -End Sub - -```` - -{{endregion}} + + ![WinForms RadGridView Formatting group header](images/gridview-grouping-formatting-group-header-row002.png) # See Also diff --git a/controls/gridview/features/grouping/group-aggregates.md b/controls/gridview/features/grouping/group-aggregates.md index 8f666a908..1d2917871 100644 --- a/controls/gridview/features/grouping/group-aggregates.md +++ b/controls/gridview/features/grouping/group-aggregates.md @@ -23,59 +23,16 @@ You can define the format of the group header row by using the __GroupDescriptor #### Example 1: Adding the Count Aggregate -{{source=..\SamplesCS\GridView\Grouping\GroupAggregates.cs region=GroupAggregates}} -{{source=..\SamplesVB\GridView\Grouping\GroupAggregates.vb region=GroupAggregates}} - -````C# -GroupDescriptor descriptor = new GroupDescriptor(); -descriptor.GroupNames.Add("Country", ListSortDirection.Ascending); -descriptor.Aggregates.Add("Count(Country)"); -descriptor.Format = "{0}: {1} has {2} records in its group."; -this.radGridView1.GroupDescriptors.Add(descriptor); - -```` -````VB.NET -Dim descriptor As New GroupDescriptor() -descriptor.GroupNames.Add("Country", ListSortDirection.Ascending) -descriptor.Aggregates.Add("Count(Country)") -descriptor.Format = "{0}: {1} has {2} records in its group." -Me.RadGridView1.GroupDescriptors.Add(descriptor) - -```` - -{{endregion}} + + ![WinForms RadGridView Adding the Count Aggregate](images/gridview-group-aggregates001.png) #### Example 2: Adding and Formatting Several Aggregates -{{source=..\SamplesCS\GridView\Grouping\GroupAggregates1.cs region=GroupAggregates1}} -{{source=..\SamplesVB\GridView\Grouping\GroupAggregates1.vb region=GroupAggregates1}} - -````C# -GroupDescriptor descriptor = new GroupDescriptor(); -descriptor.GroupNames.Add("ShipName", ListSortDirection.Ascending); -descriptor.Aggregates.Add("Count(ShipName)"); -descriptor.Aggregates.Add("Max(Freight)"); -descriptor.Aggregates.Add("Avg(Freight)"); -descriptor.Format = "The ship {1} has {2} item(s) with maximum freight {3} and average freight of {4:c2} per ship."; -this.radGridView1.GroupDescriptors.Add(descriptor); - -```` -````VB.NET -Dim descriptor As New GroupDescriptor() -descriptor.GroupNames.Add("ShipName", ListSortDirection.Ascending) -descriptor.Aggregates.Add("Count(ShipName)") -descriptor.Aggregates.Add("Max(Freight)") -descriptor.Aggregates.Add("Avg(Freight)") -descriptor.Format = "The ship {1} has {2} item(s) with maximum freight {3} and average freight of {4:c2} per ship." -Me.RadGridView1.GroupDescriptors.Add(descriptor) - -```` - -{{endregion}} - + + ![WinForms RadGridView Adding and Formatting Several Aggregates](images/gridview-group-aggregates002.png) # See Also diff --git a/controls/gridview/features/grouping/groups-collection.md b/controls/gridview/features/grouping/groups-collection.md index 9daaf8a31..27ff12fc2 100644 --- a/controls/gridview/features/grouping/groups-collection.md +++ b/controls/gridview/features/grouping/groups-collection.md @@ -15,72 +15,27 @@ When a group is created it is added to the *Groups* collection of the correspond #### Accessing groups -{{source=..\SamplesCS\GridView\Grouping\Grouping.cs region=accessGroups}} -{{source=..\SamplesVB\GridView\Grouping\Grouping.vb region=accessGroups}} - -````C# -DataGroupCollection templateGroupCollection = this.radGridView1.MasterTemplate.Groups; - -```` -````VB.NET -Dim templateGroupCollection = Me.RadGridView1.MasterTemplate.Groups - -```` - -{{endregion}} + + You can expand and collapse groups programmatically. The code blocks below demonstrates how you can expand and collapse the first group in the *Groups* collection. #### Expanding groups -{{source=..\SamplesCS\GridView\Grouping\Grouping.cs region=expandGroups}} -{{source=..\SamplesVB\GridView\Grouping\Grouping.vb region=expandGroups}} - -````C# -this.radGridView1.Groups[0].Expand(); - -```` -````VB.NET -Me.RadGridView1.Groups(0).Expand() - -```` - -{{endregion}} - + + #### Collapse groups -{{source=..\SamplesCS\GridView\Grouping\Grouping.cs region=collapseGroups}} -{{source=..\SamplesVB\GridView\Grouping\Grouping.vb region=collapseGroups}} - -````C# -this.radGridView1.Groups[0].Collapse(); - -```` -````VB.NET -Me.RadGridView1.Groups(0).Collapse() - -```` - -{{endregion}} + + You can use __AllowGroup__ property of each column to indicate whether the user will be able to group by this column or not. The default value is *true*. #### Allow groups -{{source=..\SamplesCS\GridView\Grouping\Grouping.cs region=allowGroup}} -{{source=..\SamplesVB\GridView\Grouping\Grouping.vb region=allowGroup}} - -````C# -this.radGridView1.Columns["Country"].AllowGroup = false; - -```` -````VB.NET -Me.RadGridView1.Columns("Country").AllowGroup = False - -```` - -{{endregion}} + + ## DataGroup class @@ -88,43 +43,15 @@ DataGroup collections have hierarchical structure. One or more group levels coul #### Accessing parent/child groups -{{source=..\SamplesCS\GridView\Grouping\Grouping.cs region=accessingParentChildGroups}} -{{source=..\SamplesVB\GridView\Grouping\Grouping.vb region=accessingParentChildGroups}} - -````C# -int groupLevel= this.radGridView1.Groups[0].Level; -Group parentGroup = this.radGridView1.Groups[0].Parent; -DataGroupCollection groups = this.radGridView1.Groups[0].Groups; - -```` -````VB.NET -Dim groupLevel As Integer = Me.RadGridView1.Groups(0).Level -Dim parentGroup As Group(Of GridViewRowInfo) = Me.RadGridView1.Groups(0).Parent -Dim groups As DataGroupCollection = Me.RadGridView1.Groups(0).Groups - -```` - -{{endregion}} + + The header row of a group (*GridViewGroupRowInfo*) can be accessed using the __GroupRow__ property for a particular data group, for example: #### Accessing group header row -{{source=..\SamplesCS\GridView\Grouping\Grouping.cs region=groupHeaderRow}} -{{source=..\SamplesVB\GridView\Grouping\Grouping.vb region=groupHeaderRow}} - -````C# -GridViewRowInfo groupHeaderRow = radGridView1.Groups[0].GroupRow; - -```` -````VB.NET -Dim groupHeaderRow = Me.RadGridView1.Groups(0).GroupRow - -```` - -{{endregion}} - - + + # See Also * [Basic Grouping]({%slug winforms/gridview/grouping/basic-grouping%}) diff --git a/controls/gridview/features/grouping/setting-groups-programmatically.md b/controls/gridview/features/grouping/setting-groups-programmatically.md index bdbc0bb8f..d3b2bea12 100644 --- a/controls/gridview/features/grouping/setting-groups-programmatically.md +++ b/controls/gridview/features/grouping/setting-groups-programmatically.md @@ -21,23 +21,8 @@ As this is a collection, you are able not only to add, but to remove or clear it #### Using simple group descriptor -{{source=..\SamplesCS\GridView\Grouping\Grouping.cs region=usingSimpleGroupDescriptor}} -{{source=..\SamplesVB\GridView\Grouping\Grouping.vb region=usingSimpleGroupDescriptor}} - -````C# -GroupDescriptor descriptor = new GroupDescriptor(); -descriptor.GroupNames.Add("Country", ListSortDirection.Ascending); -this.radGridView1.GroupDescriptors.Add(descriptor); - -```` -````VB.NET -Dim descriptor As New GroupDescriptor() -descriptor.GroupNames.Add("Country", ListSortDirection.Ascending) -Me.RadGridView1.GroupDescriptors.Add(descriptor) - -```` - -{{endregion}} + + ![WinForms RadGridView GroupDescriptors](images/gridview-grouping-setting-groups-programmatically001.png) @@ -47,26 +32,8 @@ The __GroupNames__ property defines the property, by which the data will be grou #### Grouping by more than one column name -{{source=..\SamplesCS\GridView\Grouping\Grouping.cs region=groupingByMoreThanOneColumnName}} -{{source=..\SamplesVB\GridView\Grouping\Grouping.vb region=groupingByMoreThanOneColumnName}} - -````C# -GroupDescriptor descriptor1 = new GroupDescriptor(); -descriptor1.GroupNames.Add("Country", ListSortDirection.Ascending); -descriptor1.GroupNames.Add("ContactTitle", ListSortDirection.Descending); -this.radGridView1.GroupDescriptors.Add(descriptor1); - -```` -````VB.NET -Dim descriptor1 As New GroupDescriptor() -descriptor1.GroupNames.Add("Country", ListSortDirection.Ascending) -descriptor1.GroupNames.Add("ContactTitle", ListSortDirection.Descending) -Me.RadGridView1.GroupDescriptors.Add(descriptor1) - -```` - -{{endregion}} - + + ![WinForms RadGridView Grouping more than one column](images/gridview-grouping-setting-groups-programmatically002.png) @@ -74,29 +41,8 @@ Me.RadGridView1.GroupDescriptors.Add(descriptor1) #### Grouping on one or more levels -{{source=..\SamplesCS\GridView\Grouping\Grouping.cs region=groupingOnOneOrMoreLevels}} -{{source=..\SamplesVB\GridView\Grouping\Grouping.vb region=groupingOnOneOrMoreLevels}} - -````C# -GroupDescriptor descriptor2 = new GroupDescriptor(); -descriptor2.GroupNames.Add("Country", ListSortDirection.Ascending); -GroupDescriptor descriptor3 = new GroupDescriptor(); -descriptor3.GroupNames.Add("ContactTitle", ListSortDirection.Ascending); -this.radGridView1.GroupDescriptors.Add(descriptor2); -this.radGridView1.GroupDescriptors.Add(descriptor3); - -```` -````VB.NET -Dim descriptor2 As New GroupDescriptor() -descriptor2.GroupNames.Add("Country", ListSortDirection.Ascending) -Dim descriptor3 As New GroupDescriptor() -descriptor3.GroupNames.Add("ContactTitle", ListSortDirection.Ascending) -Me.RadGridView1.GroupDescriptors.Add(descriptor2) -Me.RadGridView1.GroupDescriptors.Add(descriptor3) - -```` - -{{endregion}} + + ![WinForms RadGridView Grouping on one or more levels](images/gridview-grouping-setting-groups-programmatically003.png) # See Also diff --git a/controls/gridview/features/grouping/sorting-group-rows.md b/controls/gridview/features/grouping/sorting-group-rows.md index 427f51fea..a3c957041 100644 --- a/controls/gridview/features/grouping/sorting-group-rows.md +++ b/controls/gridview/features/grouping/sorting-group-rows.md @@ -23,74 +23,15 @@ However, you can change this sort order by using a group comparer. It is necessa #### Custom group comparer -{{source=..\SamplesCS\GridView\Grouping\SortingGroupRows.cs region=GroupComparer}} -{{source=..\SamplesVB\GridView\Grouping\SortingGroupRows.vb region=GroupComparer}} - -````C# - -public class GroupComparer : IComparer> -{ - public int Compare(Group x, Group y) - { - int parsedX; - int parsedY; - if (int.TryParse(((object[])x.Key).First().ToString(), out parsedX) && - int.TryParse(((object[])y.Key).First().ToString(), out parsedY)) - { - int result = parsedX.CompareTo(parsedY); - DataGroup xGroup = x as DataGroup; - if (xGroup != null && ((DataGroup)x).GroupDescriptor.GroupNames.First().Direction == ListSortDirection.Descending) - { - result *= -1; - } - return result; - } - return ((object[])x.Key)[0].ToString().CompareTo(((object[])y.Key)[0].ToString()); - } -} - -```` -````VB.NET -Public Class GroupComparer - Implements IComparer(Of Group(Of GridViewRowInfo)) - Public Function [Compare](x As Group(Of GridViewRowInfo), y As Group(Of GridViewRowInfo)) As Integer _ - Implements IComparer(Of Group(Of GridViewRowInfo)).[Compare] - Dim parsedX As Integer - Dim parsedY As Integer - If Integer.TryParse(DirectCast(x.Key, Object()).First().ToString(), parsedX) AndAlso Integer.TryParse(DirectCast(y.Key, Object()).First().ToString(), parsedY) Then - Dim result As Integer = parsedX.CompareTo(parsedY) - Dim xGroup As DataGroup = TryCast(x, DataGroup) - If xGroup IsNot Nothing AndAlso DirectCast(x, DataGroup).GroupDescriptor.GroupNames.First().Direction = ListSortDirection.Descending Then - result *= -1 - End If - Return result - End If - Return DirectCast(x.Key, Object())(0).ToString().CompareTo(DirectCast(y.Key, Object())(0).ToString()) - End Function -End Class - -```` - -{{endregion}} + + The last thing you need to do is to replace the default MasterTemplate.__GroupComparer__ with your custom one: #### Custom group comparer -{{source=..\SamplesCS\GridView\Grouping\SortingGroupRows.cs region=Replace}} -{{source=..\SamplesVB\GridView\Grouping\SortingGroupRows.vb region=Replace}} - -````C# - -this.radGridView1.MasterTemplate.GroupComparer = new GroupComparer(); - -```` -````VB.NET -Me.RadGridView1.MasterTemplate.GroupComparer = New GroupComparer() - -```` - -{{endregion}} + + >caption Figure 2: Custom Sort Order of Group Rows diff --git a/controls/gridview/features/grouping/using-grouping-expressions.md b/controls/gridview/features/grouping/using-grouping-expressions.md index 197f50678..d863484b4 100644 --- a/controls/gridview/features/grouping/using-grouping-expressions.md +++ b/controls/gridview/features/grouping/using-grouping-expressions.md @@ -20,71 +20,23 @@ The __GroupDescriptorCollection__ contains __Expression__ property which is used #### Creating simple grouping expression -{{source=..\SamplesCS\GridView\Grouping\Grouping.cs region=creatingSimpleExpression}} -{{source=..\SamplesVB\GridView\Grouping\Grouping.vb region=creatingSimpleExpression}} - -````C# -this.radGridView1.GroupDescriptors.Expression = "Country ASC"; - -```` -````VB.NET -Me.RadGridView1.GroupDescriptors.Expression = "Country ASC" - -```` - -{{endregion}} - - + + #### Grouping by two columns, by using an expression -{{source=..\SamplesCS\GridView\Grouping\Grouping.cs region=groupingByToColumnsUsingExpression}} -{{source=..\SamplesVB\GridView\Grouping\Grouping.vb region=groupingByToColumnsUsingExpression}} - -````C# -this.radGridView1.GroupDescriptors.Expression = "Country, ContactTitle DESC"; - -```` -````VB.NET -Me.RadGridView1.GroupDescriptors.Expression = "Country, ContactTitle DESC" - -```` - -{{endregion}} + + #### Creating group on two levels, by using an expression -{{source=..\SamplesCS\GridView\Grouping\Grouping.cs region=creatingGroupsOnTwoLevelsUsingExpression}} -{{source=..\SamplesVB\GridView\Grouping\Grouping.vb region=creatingGroupsOnTwoLevelsUsingExpression}} - -````C# -this.radGridView1.GroupDescriptors.Expression = "Country ASC; ContactTitle DESC"; - -```` -````VB.NET -Me.RadGridView1.GroupDescriptors.Expression = "Country ASC; ContactTitle DESC" - -```` - -{{endregion}} + + #### Complex grouping -{{source=..\SamplesCS\GridView\Grouping\Grouping.cs region=complexGrouping}} -{{source=..\SamplesVB\GridView\Grouping\Grouping.vb region=complexGrouping}} - -````C# -this.radGridView1.GroupDescriptors.Expression = "Country, ContactTitle ASC; City DESC"; - -```` -````VB.NET -Me.RadGridView1.GroupDescriptors.Expression = "Country, ContactTitle ASC; City DESC" - -```` - -{{endregion}} - - + + # See Also * [Basic Grouping]({%slug winforms/gridview/grouping/basic-grouping%}) diff --git a/controls/gridview/features/merged-cells.md b/controls/gridview/features/merged-cells.md index b217b9ae7..2e3b465db 100644 --- a/controls/gridview/features/merged-cells.md +++ b/controls/gridview/features/merged-cells.md @@ -22,21 +22,8 @@ When the RadGridView is setup, you can configure it to display the merged cells * Vertical * Horizontal -{{source=..\SamplesCS\GridView\Cells\MergeCells.cs region=mergeCellsMode}} -{{source=..\SamplesVB\GridView\Cells\MergeCells.vb region=mergeCellsMode}} - -````C# - -this.radGridView1.MergeCellsMode = Telerik.WinControls.UI.MergeCellsMode.None; - -```` -````VB.NET - -Me.RadGridView1.MergeCellsMode = Telerik.WinControls.UI.MergeCellsMode.None - -```` - -{{endregion}} + + >caption Figure 1: Merge Cells Direction @@ -56,79 +43,15 @@ When the merge cells functionality is enabled for the RadGridView, the control e In the following example, we will merge the cells in one column depending on the value in the other column: -{{source=..\SamplesCS\GridView\Cells\MergeCells.cs region=cellMergingEvent}} -{{source=..\SamplesVB\GridView\Cells\MergeCells.vb region=cellMergingEvent}} - -````C# - -private void RadGridView1_CellMerging(object sender, Telerik.WinControls.UI.GridViewCellMergingEventArgs e) -{ - if (e.Cell1.ColumnInfo.FieldName == "FirstName") // first column - { - e.Handled = true; - // Get next cell and compare them by family name - var familyNameValue1 = e.Cell1.RowInfo.Cells["LastName"].Value; // second column - var familyNameValue2 = e.Cell2.RowInfo.Cells["LastName"].Value; // second column - e.Result = object.Equals(familyNameValue1, familyNameValue2); - } -} - -```` -````VB.NET - -Private Sub RadGridView1_CellMerging(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewCellMergingEventArgs) - If e.Cell1.ColumnInfo.FieldName = "FirstName" Then - e.Handled = True - ' Get next cell and compare them by family name - Dim familyNameValue1 = e.Cell1.RowInfo.Cells("LastName").Value - Dim familyNameValue2 = e.Cell2.RowInfo.Cells("LastName").Value - e.Result = Object.Equals(familyNameValue1, familyNameValue2) - End If -End Sub - - -```` - -{{endregion}} + + ## Merge Cell Formatting __RadGridView__ offers customization options for merged cells, similar to its regular cells. Customizing the merge cells is possible by handling the __ViewCellFormatting__ event of the control. The following example demonstrates how to change the color of a merged cell spanning more than five underlying cells. -{{source=..\SamplesCS\GridView\Cells\MergeCells.cs region=mergeCellFormatting}} -{{source=..\SamplesVB\GridView\Cells\MergeCells.vb region=mergeCellFormatting}} - -````C# - -private void RadGridView1_ViewCellFormatting(object sender, CellFormattingEventArgs e) -{ - if (e.CellElement is GridMergeCellElement) - { - var mergeCell = e.CellElement as GridMergeCellElement; - if (mergeCell.Cells.Count > 5) - { - mergeCell.BackColor = Color.Red; - } - } -} - -```` -````VB.NET - -Private Sub RadGridView1_ViewCellFormatting(ByVal sender As Object, ByVal e As CellFormattingEventArgs) - If TypeOf e.CellElement Is GridMergeCellElement Then - Dim mergeCell = TryCast(e.CellElement, GridMergeCellElement) - - If mergeCell.Cells.Count > 5 Then - mergeCell.BackColor = Color.Red - End If - End If -End Sub - - -```` - -{{endregion}} + + ![WinForms RadGridView Merge Cells Formatting](images/gridview-merged-cells003.png) @@ -139,47 +62,13 @@ __RadGridView__ provides flexibility in merging cells by enabling you to define * __Column__: You can exclude a column from the merge cell algorithm by setting the __AllowCellMerging__ property to false. -{{source=..\SamplesCS\GridView\Cells\MergeCells.cs region=allowCellMerging}} -{{source=..\SamplesVB\GridView\Cells\MergeCells.vb region=allowCellMerging}} - -````C# - -this.radGridView1.Columns[0].AllowCellMerging = false; - -```` -````VB.NET - -Me.RadGridView1.Columns(0).AllowCellMerging = False - - -```` - -{{endregion}} + + * __Template__: When working with hierarchical data and multiple templates in RadGridView, the cell merging behavior can be disabled or enabled independently for each template. -{{source=..\SamplesCS\GridView\Cells\MergeCells.cs region=mergeCellTemplate}} -{{source=..\SamplesVB\GridView\Cells\MergeCells.vb region=mergeCellTemplate}} - -````C# - -GridViewTemplate template = new GridViewTemplate(); -template.MergeCellsMode = MergeCellsMode.None; -// template settings -radGridView1.MasterTemplate.Templates.Add(template); - -```` -````VB.NET - -Dim template As GridViewTemplate = New GridViewTemplate() -template.MergeCellsMode = MergeCellsMode.None -' template settings -radGridView1.MasterTemplate.Templates.Add(template) - -```` - -{{endregion}} - + + ## Known Limitations diff --git a/controls/gridview/features/printing-support/events-and-customization.md b/controls/gridview/features/printing-support/events-and-customization.md index 6622e0d13..824a8a6e7 100644 --- a/controls/gridview/features/printing-support/events-and-customization.md +++ b/controls/gridview/features/printing-support/events-and-customization.md @@ -17,44 +17,8 @@ The print events in RadGridView allow the developer to customize the print outpu Just like the other formatting events of RadGridView, this event allows you to format the appearance of the cells in the printed document. Here is a very simple example, which demonstrates how to customize the appearance of the header and the summary rows: -{{source=..\SamplesCS\GridView\Printing support\EventsAndCustomization.cs region=PrintCellFormatting}} -{{source=..\SamplesVB\GridView\Printing support\EventsAndCustomization.vb region=PrintCellFormatting}} - -````C# -private void radGridView1_PrintCellFormatting(object sender, PrintCellFormattingEventArgs e) -{ - if (e.Row is GridViewTableHeaderRowInfo) - { - e.PrintCell.DrawFill = true; - e.PrintCell.BackColor = Color.LightBlue; - e.PrintCell.BorderColor = Color.Blue; - } - else if (e.Row is GridViewSummaryRowInfo) - { - e.PrintCell.DrawFill = true; - e.PrintCell.BackColor = Color.LightSalmon; - e.PrintCell.BorderColor = Color.Tomato; - } -} - -```` -````VB.NET -Private Sub radGridView1_PrintCellFormatting(sender As Object, e As PrintCellFormattingEventArgs) - If TypeOf e.Row Is GridViewTableHeaderRowInfo Then - e.PrintCell.DrawFill = True - e.PrintCell.BackColor = Color.LightBlue - e.PrintCell.BorderColor = Color.Blue - ElseIf TypeOf e.Row Is GridViewSummaryRowInfo Then - e.PrintCell.DrawFill = True - e.PrintCell.BackColor = Color.LightSalmon - e.PrintCell.BorderColor = Color.Tomato - End If -End Sub - -```` - -{{endregion}} - + + ![WinForms RadGridView PrintCellFormatting](images/gridview-printing-support-events001.png) @@ -62,52 +26,8 @@ End Sub This event allow you to access the cell and to paint in it whatever you need. Here is a sample, where we will paint a green dot when the product quantity is more than 20 and a red dot if it is less: -{{source=..\SamplesCS\GridView\Printing support\EventsAndCustomization.cs region=PrintCellPaint}} -{{source=..\SamplesVB\GridView\Printing support\EventsAndCustomization.vb region=PrintCellPaint}} - -````C# -private void radGridView1_PrintCellPaint(object sender, PrintCellPaintEventArgs e) -{ - if (e.Row is GridViewDataRowInfo & e.Column.Name == "UnitsInStock") - { - int side = e.CellRect.Height - 8; - int x = e.CellRect.X + 4; - int y = e.CellRect.Y + 4; - Rectangle rect = new Rectangle(x, y, side, side); - Brush brush = default(Brush); - if (Convert.ToInt32(e.Row.Cells[e.Column.Name].Value) < 20) - { - brush = Brushes.Red; - } - else - { - brush = Brushes.Green; - } - e.Graphics.FillEllipse(brush, rect); - } -} - -```` -````VB.NET -Private Sub radGridView1_PrintCellPaint(sender As Object, e As PrintCellPaintEventArgs) - If TypeOf e.Row Is GridViewDataRowInfo And e.Column.Name = "UnitsInStock" Then - Dim side As Integer = e.CellRect.Height - 8 - Dim x As Integer = e.CellRect.X + 4 - Dim y As Integer = e.CellRect.Y + 4 - Dim rect As New Rectangle(x, y, side, side) - Dim brush As Brush - If CInt(e.Row.Cells(e.Column.Name).Value) < 20 Then - brush = Brushes.Red - Else - brush = Brushes.Green - End If - e.Graphics.FillEllipse(brush, rect) - End If -End Sub - -```` - -{{endregion}} + + ![WinForms RadGridView PrintCellPaint](images/gridview-printing-support-events002.png) # See Also diff --git a/controls/gridview/features/printing-support/gridprintstyle.md b/controls/gridview/features/printing-support/gridprintstyle.md index 52ea0ae4d..feead1566 100644 --- a/controls/gridview/features/printing-support/gridprintstyle.md +++ b/controls/gridview/features/printing-support/gridprintstyle.md @@ -79,33 +79,8 @@ You can customize the settings of the grid print job by setting the __PrintStyle ## Customizing GridPrintStyle -{{source=..\SamplesCS\GridView\Printing support\GridPrintStyle1.cs region=PrintStyle}} -{{source=..\SamplesVB\GridView\Printing support\GridPrintStyle1.vb region=PrintStyle}} - -````C# -GridPrintStyle style = new GridPrintStyle(); -style.FitWidthMode = PrintFitWidthMode.FitPageWidth; -style.PrintGrouping = true; -style.PrintSummaries = false; -style.PrintHeaderOnEachPage = true; -style.PrintHiddenColumns = false; -this.radGridView1.PrintStyle = style; -this.radGridView1.Print(); - -```` -````VB.NET -Dim style As New GridPrintStyle() -style.FitWidthMode = PrintFitWidthMode.FitPageWidth -style.PrintGrouping = True -style.PrintSummaries = False -style.PrintHeaderOnEachPage = True -style.PrintHiddenColumns = False -Me.RadGridView1.PrintStyle = style -Me.RadGridView1.Print() - -```` - -{{endregion}} + + ![WinForms RadGridView GridPrintStyle](images/gridview-printing-support-gridprintstyle.png) @@ -113,34 +88,8 @@ Me.RadGridView1.Print() Multi-page printing is supported for grids with ViewDefinition set to TableViewDefinition. To enable the functionality you should define the collection of columns each page will contain. For this purpose you can use the PrintPages collection of the TableViewDefinitionPrintRenderer. The PrintPages collection contains collections of columns, each representing a separate page. Here is an example which assumes the grid has 10 columns: -{{source=..\SamplesCS\GridView\Printing support\GridPrintStyle1.cs region=MultiPagePrintingPrintStyle}} -{{source=..\SamplesVB\GridView\Printing support\GridPrintStyle1.vb region=MultiPagePrintingPrintStyle}} - -````C# -GridPrintStyle printStyle = new GridPrintStyle(this.radGridView1); -TableViewDefinitionPrintRenderer renderer = new TableViewDefinitionPrintRenderer(this.radGridView1); -renderer.PrintPages.Add(this.radGridView1.Columns[0], this.radGridView1.Columns[2], this.radGridView1.Columns[5]); -renderer.PrintPages.Add(this.radGridView1.Columns[0], this.radGridView1.Columns[1], this.radGridView1.Columns[9]); -renderer.PrintPages.Add(this.radGridView1.Columns[8], this.radGridView1.Columns[7]); -renderer.PrintPages.Add(this.radGridView1.Columns[3], this.radGridView1.Columns[4], this.radGridView1.Columns[6]); -printStyle.PrintRenderer = renderer; -this.radGridView1.PrintStyle = printStyle; - -```` -````VB.NET -Dim printStyle As GridPrintStyle = New GridPrintStyle(RadGridView1) -Dim renderer As TableViewDefinitionPrintRenderer = New TableViewDefinitionPrintRenderer(RadGridView1) -renderer.PrintPages.Add(RadGridView1.Columns(0), RadGridView1.Columns(2), RadGridView1.Columns(5)) -renderer.PrintPages.Add(RadGridView1.Columns(0), RadGridView1.Columns(1), RadGridView1.Columns(9)) -renderer.PrintPages.Add(RadGridView1.Columns(8), RadGridView1.Columns(7)) -renderer.PrintPages.Add(RadGridView1.Columns(3), RadGridView1.Columns(4), RadGridView1.Columns(6)) -printStyle.PrintRenderer = renderer -RadGridView1.PrintStyle = printStyle -RadGridView1.PrintPreview() - -```` - -{{endregion}} + + This code defines four pages where the content of the pages is as follows: diff --git a/controls/gridview/features/printing-support/printing-hierarchical-grid.md b/controls/gridview/features/printing-support/printing-hierarchical-grid.md index f3c52aedd..6e95c2c69 100644 --- a/controls/gridview/features/printing-support/printing-hierarchical-grid.md +++ b/controls/gridview/features/printing-support/printing-hierarchical-grid.md @@ -19,27 +19,8 @@ When bound to hierarchical data __RadGridView__ can print its contents preservin #### Printing Settings -{{source=..\SamplesCS\GridView\Printing support\PrintingHierarchicalGrid.cs region=PrintingSettings}} -{{source=..\SamplesVB\GridView\Printing support\PrintingHierarchicalGrid.vb region=PrintingSettings}} - -````C# -GridPrintStyle style = new GridPrintStyle(); -style.PrintHierarchy = true; -style.HierarchyIndent = 20; -style.ChildViewPrintMode = ChildViewPrintMode.SelectViewToPrint; -this.radGridView1.PrintStyle = style; - -```` -````VB.NET -Dim style As New GridPrintStyle() -style.PrintHierarchy = True -style.HierarchyIndent = 20 -style.ChildViewPrintMode = ChildViewPrintMode.SelectViewToPrint -Me.RadGridView1.PrintStyle = style - -```` - -{{endregion}} + + ## GridPrintSyle Properties diff --git a/controls/gridview/features/printing-support/printing-support.md b/controls/gridview/features/printing-support/printing-support.md index dd844e112..1a005bfa2 100644 --- a/controls/gridview/features/printing-support/printing-support.md +++ b/controls/gridview/features/printing-support/printing-support.md @@ -29,39 +29,15 @@ RadGridView provides printing support, which allows you to print the grid conten RadGridView has two public methods available for printing - __Print()__ and __PrintPreview()__. The first method will directly send a print job to the default printer with the settings currently saved in the [PrintStyle]({%slug winforms/gridview/printing-support/gridprintstyle%}) property. This method has one overload available which can show a system __PrintDialog__ with the available printers and their options. -{{source=..\SamplesCS\GridView\Printing support\PrintingSupport.cs region=print}} -{{source=..\SamplesVB\GridView\Printing support\PrintingSupport.vb region=print}} - -````C# -this.radGridView1.Print(); -this.radGridView1.Print(true); - -```` -````VB.NET -Me.RadGridView1.Print() -Me.RadGridView1.Print(True) - -```` - -{{endregion}} + + ![WinForms RadGridView Print Option](images/gridview-printing-support001.png) The other available method is __PrintPreview()__, which opens [RadPrintPreviewDialog.]({%slug winforms/telerik-presentation-framework/printing-support/end-user-functionality/print-preview-dialog%}) -{{source=..\SamplesCS\GridView\Printing support\PrintingSupport.cs region=PrintPreview}} -{{source=..\SamplesVB\GridView\Printing support\PrintingSupport.vb region=PrintPreview}} - -````C# -this.radGridView1.PrintPreview(); - -```` -````VB.NET -Me.RadGridView1.PrintPreview() - -```` - -{{endregion}} + + ![WinForms RadGridView PrintPreview](images/gridview-printing-support002.png) diff --git a/controls/gridview/features/save-and-load-layout/advanced.md b/controls/gridview/features/save-and-load-layout/advanced.md index 8eec48737..423cde322 100644 --- a/controls/gridview/features/save-and-load-layout/advanced.md +++ b/controls/gridview/features/save-and-load-layout/advanced.md @@ -25,118 +25,32 @@ Here are several properties to have in mind: Here is a snippet clearing the default settings: -{{source=..\SamplesCS\GridView\SaveLoadLayout\Advanced.cs region=preparation}} -{{source=..\SamplesVB\GridView\SaveLoadLayout\Advanced.vb region=preparation}} - -````C# -this.radGridView1.XmlSerializationInfo.DisregardOriginalSerializationVisibility = true; -this.radGridView1.XmlSerializationInfo.SerializationMetadata.Clear(); - -```` -````VB.NET -Me.RadGridView1.XmlSerializationInfo.DisregardOriginalSerializationVisibility = True -Me.RadGridView1.XmlSerializationInfo.SerializationMetadata.Clear() - -```` - -{{endregion}} + + >note Clearing the default settings would require all the serialization meta data to be loaded manually. > The first property to add for serialization is the MasterGridViewTemplate, which contains RadGridView’s data and its structure. Please note that the MasterGridViewTemplate property is of type GridViewTemplate and that the __DesignerSerializationVisibilityAttribute__ works exactly as the standard Microsoft .NET Framework attribute. -{{source=..\SamplesCS\GridView\SaveLoadLayout\Advanced.cs region=SerializationMetadataRadGridView}} -{{source=..\SamplesVB\GridView\SaveLoadLayout\Advanced.vb region=SerializationMetadataRadGridView}} - -````C# -this.radGridView1.XmlSerializationInfo.SerializationMetadata.Add(typeof(RadGridView),"MasterTemplate",DesignerSerializationVisibilityAttribute.Content); - -```` -````VB.NET -Me.RadGridView1.XmlSerializationInfo.SerializationMetadata.Add(GetType(RadGridView), "MasterTemplate", DesignerSerializationVisibilityAttribute.Content) - -```` - -{{endregion}} + + You can use the same approach to add the child templates. Additionally, you may want to add the __Caption__ property of the template. -{{source=..\SamplesCS\GridView\SaveLoadLayout\Advanced.cs region=SerializationMetadataChildTemplates}} -{{source=..\SamplesVB\GridView\SaveLoadLayout\Advanced.vb region=SerializationMetadataChildTemplates}} - -````C# -this.radGridView1.XmlSerializationInfo.SerializationMetadata.Add(typeof(GridViewTemplate), "Templates", DesignerSerializationVisibilityAttribute.Content); -this.radGridView1.XmlSerializationInfo.SerializationMetadata.Add(typeof(GridViewTemplate), "Caption", DesignerSerializationVisibilityAttribute.Visible); - -```` -````VB.NET -Me.RadGridView1.XmlSerializationInfo.SerializationMetadata.Add(GetType(GridViewTemplate), "Templates", DesignerSerializationVisibilityAttribute.Content) -Me.RadGridView1.XmlSerializationInfo.SerializationMetadata.Add(GetType(GridViewTemplate), "Caption", DesignerSerializationVisibilityAttribute.Visible) - -```` - -{{endregion}} + + Since the __Columns__ property points to a complex object, you should set the __DesignerSerializationVisibilityAttribute__ attribute to __Content__. In this way, the serialization engine will automatically detect that Columns points to a collection and will enumerate its items. Further, for each column you should define the properties to be stored in the XML output. In the following snippet the serialized properties are __UniqueName__ and __Width__. By specifying the __GridViewDataColumn__ type you tell the serializer that this instruction should be considered each time an object of this type is found. Please note that the __DesignerSerializationVisibilityAttribute__ attribute is set to __Visibility__, because the value of the property should be serialized. -{{source=..\SamplesCS\GridView\SaveLoadLayout\Advanced.cs region=SerializationMetadataGridViewDataColumn}} -{{source=..\SamplesVB\GridView\SaveLoadLayout\Advanced.vb region=SerializationMetadataGridViewDataColumn}} - -````C# -this.radGridView1.XmlSerializationInfo.SerializationMetadata.Add(typeof(GridViewTemplate), "Columns", DesignerSerializationVisibilityAttribute.Content); -this.radGridView1.XmlSerializationInfo.SerializationMetadata.Add(typeof(GridViewDataColumn), "Name", DesignerSerializationVisibilityAttribute.Visible); -this.radGridView1.XmlSerializationInfo.SerializationMetadata.Add(typeof(GridViewDataColumn), "Width", DesignerSerializationVisibilityAttribute.Visible); - -```` -````VB.NET -Me.RadGridView1.XmlSerializationInfo.SerializationMetadata.Add(GetType(GridViewTemplate), "Columns", DesignerSerializationVisibilityAttribute.Content) -Me.RadGridView1.XmlSerializationInfo.SerializationMetadata.Add(GetType(GridViewDataColumn), "Name", DesignerSerializationVisibilityAttribute.Visible) -Me.RadGridView1.XmlSerializationInfo.SerializationMetadata.Add(GetType(GridViewDataColumn), "Width", DesignerSerializationVisibilityAttribute.Visible) - -```` - -{{endregion}} - + + Further, you may want to save information concerning grouping, sorting, filtering. Here is a sample snippet: -{{source=..\SamplesCS\GridView\SaveLoadLayout\Advanced.cs region=SerializationMetadataOperations}} -{{source=..\SamplesVB\GridView\SaveLoadLayout\Advanced.vb region=SerializationMetadataOperations}} - -````C# -//Groups Descriptors -this.radGridView1.XmlSerializationInfo.SerializationMetadata.Add(typeof(GridViewTemplate), "GroupDescriptors", DesignerSerializationVisibilityAttribute.Content); -this.radGridView1.XmlSerializationInfo.SerializationMetadata.Add(typeof(GroupDescriptor), "GroupNames", DesignerSerializationVisibilityAttribute.Content); -this.radGridView1.XmlSerializationInfo.SerializationMetadata.Add(typeof(SortDescriptor), "PropertyName", DesignerSerializationVisibilityAttribute.Visible); -//Sort Descriptors -this.radGridView1.XmlSerializationInfo.SerializationMetadata.Add(typeof(GridViewTemplate), "SortDescriptors", DesignerSerializationVisibilityAttribute.Content); -this.radGridView1.XmlSerializationInfo.SerializationMetadata.Add(typeof(SortDescriptor), "Direction", DesignerSerializationVisibilityAttribute.Visible); -//Filter Descriptors -this.radGridView1.XmlSerializationInfo.SerializationMetadata.Add(typeof(GridViewTemplate), "FilterDescriptors", DesignerSerializationVisibilityAttribute.Content); -this.radGridView1.XmlSerializationInfo.SerializationMetadata.Add(typeof(FilterDescriptor), "PropertyName", DesignerSerializationVisibilityAttribute.Visible); -this.radGridView1.XmlSerializationInfo.SerializationMetadata.Add(typeof(FilterDescriptor), "Operator", DesignerSerializationVisibilityAttribute.Visible); -this.radGridView1.XmlSerializationInfo.SerializationMetadata.Add(typeof(FilterDescriptor), "Value", DesignerSerializationVisibilityAttribute.Visible); -this.radGridView1.XmlSerializationInfo.SerializationMetadata.Add(typeof(FilterDescriptor), "IsFilterEditor", DesignerSerializationVisibilityAttribute.Visible); - -```` -````VB.NET -'Groups Descriptors -Me.RadGridView1.XmlSerializationInfo.SerializationMetadata.Add(GetType(GridViewTemplate), "GroupDescriptors", DesignerSerializationVisibilityAttribute.Content) -Me.RadGridView1.XmlSerializationInfo.SerializationMetadata.Add(GetType(GroupDescriptor), "GroupNames", DesignerSerializationVisibilityAttribute.Content) -Me.RadGridView1.XmlSerializationInfo.SerializationMetadata.Add(GetType(SortDescriptor), "PropertyName", DesignerSerializationVisibilityAttribute.Visible) -'Sort Descriptors -Me.RadGridView1.XmlSerializationInfo.SerializationMetadata.Add(GetType(GridViewTemplate), "SortDescriptors", DesignerSerializationVisibilityAttribute.Content) -Me.RadGridView1.XmlSerializationInfo.SerializationMetadata.Add(GetType(SortDescriptor), "Direction", DesignerSerializationVisibilityAttribute.Visible) -'Filter Descriptors -Me.RadGridView1.XmlSerializationInfo.SerializationMetadata.Add(GetType(GridViewTemplate), "FilterDescriptors", DesignerSerializationVisibilityAttribute.Content) -Me.RadGridView1.XmlSerializationInfo.SerializationMetadata.Add(GetType(FilterDescriptor), "PropertyName", DesignerSerializationVisibilityAttribute.Content) -Me.RadGridView1.XmlSerializationInfo.SerializationMetadata.Add(GetType(FilterDescriptor), "Operator", DesignerSerializationVisibilityAttribute.Content) -Me.RadGridView1.XmlSerializationInfo.SerializationMetadata.Add(GetType(FilterDescriptor), "Value", DesignerSerializationVisibilityAttribute.Visible) - -```` - -{{endregion}} + + + # See Also * [Save/Load layout buttons in the Property Grid]({%slug winforms/gridview/save-and-load-layout/load-layout-buttons-in-the-property-grid%}) diff --git a/controls/gridview/features/save-and-load-layout/save-and-load-layout.md b/controls/gridview/features/save-and-load-layout/save-and-load-layout.md index 0448c460d..545ea5597 100644 --- a/controls/gridview/features/save-and-load-layout/save-and-load-layout.md +++ b/controls/gridview/features/save-and-load-layout/save-and-load-layout.md @@ -17,77 +17,15 @@ Here is a sample demonstrating how you can implement a *Save Layout* button even #### Save layout -{{source=..\SamplesCS\GridView\SaveLoadLayout\SaveLoadLayoutOverview.cs region=saveLayout}} -{{source=..\SamplesVB\GridView\SaveLoadLayout\SaveLoadLayoutOverview.vb region=saveLayout}} - -````C# -private void SaveButton_Click(object sender, EventArgs e) -{ - string s = "default.xml"; - SaveFileDialog dialog = new SaveFileDialog(); - dialog.Filter ="xml files (*.xml)|*.xml|All files (*.*)|*.*"; - dialog.Title = "Select a xml file"; - if (dialog.ShowDialog() == DialogResult.OK) - { - s = dialog.FileName; - } - this.radGridView1.SaveLayout(s); -} - -```` -````VB.NET -Private Sub SaveButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadButton1.Click - Dim s As String = "default.xml" - Dim dialog As New SaveFileDialog() - dialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*" - dialog.Title = "Select a xml file" - If dialog.ShowDialog() = DialogResult.OK Then - s = dialog.FileName - End If - Me.RadGridView1.SaveLayout(s) -End Sub - -```` - -{{endregion}} + + The code snippets below demonstrates how you can implement a *Load Layout* button event handler:  #### Load layout -{{source=..\SamplesCS\GridView\SaveLoadLayout\SaveLoadLayoutOverview.cs region=loadLayout}} -{{source=..\SamplesVB\GridView\SaveLoadLayout\SaveLoadLayoutOverview.vb region=loadLayout}} - -````C# -private void LoadButton_Click(object sender, EventArgs e) -{ - string s = "default.xml"; - OpenFileDialog dialog = new OpenFileDialog(); - dialog.Filter ="xml files (*.xml)|*.xml|All files (*.*)|*.*"; - dialog.Title = "Select a xml file"; - if (dialog.ShowDialog() == DialogResult.OK) - { - s = dialog.FileName; - } - this.radGridView1.LoadLayout(s); -} - -```` -````VB.NET -Private Sub LoadButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadButton2.Click - Dim s As String = "default.xml" - Dim dialog As New OpenFileDialog() - dialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*" - dialog.Title = "Select a xml file" - If dialog.ShowDialog() = DialogResult.OK Then - s = dialog.FileName - End If - Me.RadGridView1.LoadLayout(s) -End Sub - -```` - -{{endregion}} + + >note Once the layout is being loaded the __LayoutLoaded__ event is being thrown in order to notify that the load process is being finished. > diff --git a/controls/gridview/features/scrolling/events.md b/controls/gridview/features/scrolling/events.md index 0182e4529..967dd6b77 100644 --- a/controls/gridview/features/scrolling/events.md +++ b/controls/gridview/features/scrolling/events.md @@ -19,41 +19,13 @@ They can be accessed via the TableElement.**VScrollBar** and TableElement.**HScr For instance, to subscribe to **ValueChanged** event of the vertical scroll bar use the following code: -{{source=..\SamplesCS\GridView\Scrolling\Scrolling.cs region=Subscribe}} -{{source=..\SamplesVB\GridView\Scrolling\Scrolling.vb region=Subscribe}} - -````C# -radGridView1.TableElement.VScrollBar.ValueChanged += new EventHandler(VScrollBar_ValueChanged); - -```` -````VB.NET -AddHandler Me.RadGridView1.TableElement.VScrollBar.ValueChanged, AddressOf VScrollBar_ValueChanged - -```` - -{{endregion}} - + + #### ScrollBar value changed event -{{source=..\SamplesCS\GridView\Scrolling\Scrolling.cs region=scrollBarValueChanged}} -{{source=..\SamplesVB\GridView\Scrolling\Scrolling.vb region=scrollBarValueChanged}} - -````C# -void VScrollBar_ValueChanged(object sender, EventArgs e) -{ - Console.WriteLine(this.radGridView1.TableElement.VScrollBar.Value); -} - -```` -````VB.NET -Sub VScrollBar_ValueChanged(ByVal sender As Object, ByVal e As EventArgs) - Console.WriteLine(Me.RadGridView1.TableElement.VScrollBar.Value) -End Sub - -```` - -{{endregion}} + + >caution Please note that **RadGridView** **Scroll** event is NOT used. > diff --git a/controls/gridview/features/scrolling/scroll-modes.md b/controls/gridview/features/scrolling/scroll-modes.md index a8bfd0169..ce9db3ff5 100644 --- a/controls/gridview/features/scrolling/scroll-modes.md +++ b/controls/gridview/features/scrolling/scroll-modes.md @@ -18,22 +18,8 @@ This is the default value of the __ScrollMode__ property. Items in this mode are ![WinForms RadGridView ScrollMode](images/gridview-scrolling-scroll-modes001.GIF) -{{source=..\SamplesCS\GridView\Scrolling\Scrolling.cs region=ScrollMode_Smooth}} -{{source=..\SamplesVB\GridView\Scrolling\Scrolling.vb region=ScrollMode_Smooth}} - -````C# - -this.radGridView1.TableElement.RowScroller.ScrollMode = ItemScrollerScrollModes.Smooth; - -```` -````VB.NET - -Me.RadGridView1.TableElement.RowScroller.ScrollMode = ItemScrollerScrollModes.Smooth - -```` - -{{endregion}} - + + ## Discrete @@ -41,22 +27,8 @@ When the __Discrete__ mode is set, the items are scrolled one at a time. The scr ![WinForms RadGridView ScrollMode](images/gridview-scrolling-scroll-modes002.GIF) -{{source=..\SamplesCS\GridView\Scrolling\Scrolling.cs region=ScrollMode_Discrete}} -{{source=..\SamplesVB\GridView\Scrolling\Scrolling.vb region=ScrollMode_Discrete}} - -````C# - -this.radGridView1.TableElement.RowScroller.ScrollMode = ItemScrollerScrollModes.Discrete; - -```` -````VB.NET - -Me.RadGridView1.TableElement.RowScroller.ScrollMode = ItemScrollerScrollModes.Discrete - -```` - -{{endregion}} - + + ## Deferred @@ -64,69 +36,19 @@ In this mode, the content in the view is static until scrolling is completed. ![WinForms RadGridView ScrollMode](images/gridview-scrolling-scroll-modes003.GIF) -{{source=..\SamplesCS\GridView\Scrolling\Scrolling.cs region=ScrollMode_Deferred}} -{{source=..\SamplesVB\GridView\Scrolling\Scrolling.vb region=ScrollMode_Deferred}} - -````C# - -this.radGridView1.TableElement.RowScroller.ScrollMode = ItemScrollerScrollModes.Deferred; - -```` -````VB.NET - -Me.RadGridView1.TableElement.RowScroller.ScrollMode = ItemScrollerScrollModes.Deferred - -```` - -{{endregion}} + + When RadGridView's ScrollMode is set to Deferred, a small ToolTip appears when scrolling which previews the current scroll position. You could modify the text inside the ToolTip by subscribing to the __ToolTipTextNeeded__ event of the RowScroller. -{{source=..\SamplesCS\GridView\Scrolling\Scrolling.cs region=Scroll_ToolTip}} -{{source=..\SamplesVB\GridView\Scrolling\Scrolling.vb region=Scroll_ToolTip}} - - -````C# - -this.radGridView1.TableElement.RowScroller.ToolTipTextNeeded += RowScroller_ToolTipTextNeeded; - - -```` -````VB.NET - -AddHandler this.radGridView1.TableElement.RowScroller.ToolTipTextNeeded, AddressOff RowScroller_ToolTipTextNeeded; - -```` - -{{endregion}} + + In the event handler, you can get the text from the event arguments ToolTipText property and modify it per your needs. -{{source=..\SamplesCS\GridView\Scrolling\Scrolling.cs region=Scroll_ToolTip_CustomText}} -{{source=..\SamplesVB\GridView\Scrolling\Scrolling.vb region=Scroll_ToolTip_CustomText}} - -````C# - -private void RowScroller_ToolTipTextNeeded(object sender, Telerik.WinControls.ToolTipTextNeededEventArgs e) -{ - string[] toolTipTextArray = e.ToolTipText.Split(); - e.ToolTipText = "Current Scroll Position: " + toolTipTextArray[1]; -} - - -```` -````VB.NET + + -Private Sub RowScroller_ToolTipTextNeeded(ByVal sender As Object, ByVal e As Telerik.WinControls.ToolTipTextNeededEventArgs) - Dim toolTipTextArray As String() = e.ToolTipText.Split() - e.ToolTipText = "Current Scroll Position: " & toolTipTextArray(1) -End Sub - - -```` - -{{endregion}} - ![WinForms RadGridView ScrollMode](images/gridview-scrolling-scroll-modes004.GIF) diff --git a/controls/gridview/features/scrolling/scrolling-programmatically.md b/controls/gridview/features/scrolling/scrolling-programmatically.md index bf523df0b..f3a7618aa 100644 --- a/controls/gridview/features/scrolling/scrolling-programmatically.md +++ b/controls/gridview/features/scrolling/scrolling-programmatically.md @@ -15,53 +15,18 @@ You can scroll programmatically using the following functions: #### ScrollTo -{{source=..\SamplesCS\GridView\Scrolling\Scrolling.cs region=ScrollTo}} -{{source=..\SamplesVB\GridView\Scrolling\Scrolling.vb region=ScrollTo}} - -````C# -this.radGridView1.TableElement.ScrollTo(5, 4); - -```` -````VB.NET -Me.RadGridView1.TableElement.ScrollTo(5, 4) - -```` - -{{endregion}} - + + #### ScrollToColumn -{{source=..\SamplesCS\GridView\Scrolling\Scrolling.cs region=Column}} -{{source=..\SamplesVB\GridView\Scrolling\Scrolling.vb region=Column}} - -````C# -radGridView1.TableElement.ScrollToColumn(3); - -```` -````VB.NET -RadGridView1.TableElement.ScrollToColumn(3) - -```` - -{{endregion}} - + + #### ScrollToRow -{{source=..\SamplesCS\GridView\Scrolling\Scrolling.cs region=Row}} -{{source=..\SamplesVB\GridView\Scrolling\Scrolling.vb region=Row}} - -````C# -radGridView1.TableElement.ScrollToRow(100); - -```` -````VB.NET -RadGridView1.TableElement.ScrollToRow(100) - -```` - -{{endregion}} + + ## Properties diff --git a/controls/gridview/features/selection/basic-selection.md b/controls/gridview/features/selection/basic-selection.md index aaa120964..f6e4bbe14 100644 --- a/controls/gridview/features/selection/basic-selection.md +++ b/controls/gridview/features/selection/basic-selection.md @@ -20,21 +20,8 @@ RadGridView provides you with a selection functionality, which allows the user t By default RadGridView allows the user to select only one row. In this case the default property settings are: -{{source=..\SamplesCS\GridView\Selection\Selection1.cs region=basicRowSelection}} -{{source=..\SamplesVB\GridView\Selection\Selection1.vb region=basicRowSelection}} - -````C# -radGridView1.MultiSelect = false; -radGridView1.SelectionMode = GridViewSelectionMode.FullRowSelect; - -```` -````VB.NET -RadGridView1.MultiSelect = False -RadGridView1.SelectionMode = GridViewSelectionMode.FullRowSelect - -```` - -{{endregion}} + + To select an item in RadGridView click in the rectangle area of the desired row. @@ -44,21 +31,8 @@ To select an item in RadGridView click in the rectangle area of the desired row. You can modify RadGridView to select single cells instead of rows by setting its __SelectionMode__ property to *CellSelect* from the `GridViewSelectionMode` enumeration: -{{source=..\SamplesCS\GridView\Selection\Selection1.cs region=basicCellSelection}} -{{source=..\SamplesVB\GridView\Selection\Selection1.vb region=basicCellSelection}} - -````C# -radGridView1.MultiSelect = false; -radGridView1.SelectionMode = GridViewSelectionMode.CellSelect; - -```` -````VB.NET -RadGridView1.MultiSelect = False -RadGridView1.SelectionMode = GridViewSelectionMode.CellSelect - -```` - -{{endregion}} + + After setting these properties, to select a cell in RadGridView, click the desired cell. @@ -68,21 +42,8 @@ After setting these properties, to select a cell in RadGridView, click the desir Once an item is selected (row or cell), you can find this item in the __SelectedRows__ and __SelectedCells__ collections respectively. The following code describes how to access those collections: -{{source=..\SamplesCS\GridView\Selection\Selection1.cs region=collections}} -{{source=..\SamplesVB\GridView\Selection\Selection1.vb region=collections}} - -````C# -GridViewSelectedRowsCollection selectedRows = radGridView1.SelectedRows; -GridViewSelectedCellsCollection selectedCells = radGridView1.SelectedCells; - -```` -````VB.NET -Dim selectedRows As GridViewSelectedRowsCollection = RadGridView1.SelectedRows -Dim selectedCells As GridViewSelectedCellsCollection = RadGridView1.SelectedCells - -```` - -{{endregion}} + + ## Events @@ -93,29 +54,8 @@ There are two events relevant to the selection: __SelectionChanged__, __CurrentC Once an item is selected, it automatically becomes current (when basic selection is used). This means that if you select the first row (cell) of RadGridView, its __IsCurrent__ property will be automatically set to *true* and __CurrentRow__ (__CurrentCell__) property of RadGridView will hold an instance of this row (respectively cell). The following example demonstrates how to access the __CurrentRow__ and __CurrentCell__ properties and additionally the __IsCurrent__ property of a row or a cell: -{{source=..\SamplesCS\GridView\Selection\Selection1.cs region=currentRowCell}} -{{source=..\SamplesVB\GridView\Selection\Selection1.vb region=currentRowCell}} - -````C# -//gets an instance of the current row -GridViewRowInfo row = radGridView1.CurrentRow; -//gets an instance of the current cell -GridDataCellElement cell = radGridView1.CurrentCell; -//gets or sets if the first row of radGridView1 is current or not -radGridView1.Rows[0].IsCurrent = true; - -```` -````VB.NET -'gets an instance of the current row -Dim row As GridViewRowInfo = RadGridView1.CurrentRow -'gets an instance of the current cell -Dim cell As GridDataCellElement = RadGridView1.CurrentCell -'gets or sets if the first row of radGridView1 is current or not -RadGridView1.Rows(0).IsCurrent = True - -```` - -{{endregion}} + + When basic selection is used, the opposite is also valid – if you set the __CurrentRow__ or __CurrentCell__ (or the __IsCurrent__ property to true for a cell or row) in RadGridView and only if basic selection is used (MultiSelect = false ), the selected row(cell) will be the same as the current row(cell). diff --git a/controls/gridview/features/selection/multiple-selection.md b/controls/gridview/features/selection/multiple-selection.md index 7b627d462..58b2d0257 100644 --- a/controls/gridview/features/selection/multiple-selection.md +++ b/controls/gridview/features/selection/multiple-selection.md @@ -17,21 +17,8 @@ RadGridView allows the user to select more than one item at a time from the disp In order to enable multiple row selection, after setting the MultiSelect property to true, you have to set the SelectionMode to GridViewSelectionMode.FullRowSelect: -{{source=..\SamplesCS\GridView\Selection\Selection1.cs region=multipleRowSelection}} -{{source=..\SamplesVB\GridView\Selection\Selection1.vb region=multipleRowSelection}} - -````C# -radGridView1.MultiSelect = true; -radGridView1.SelectionMode = GridViewSelectionMode.FullRowSelect; - -```` -````VB.NET -RadGridView1.MultiSelect = True -RadGridView1.SelectionMode = GridViewSelectionMode.FullRowSelect - -```` - -{{endregion}} + + When these settings are applied, you have several options to make a multiple selection: @@ -47,21 +34,8 @@ When these settings are applied, you have several options to make a multiple sel In order to enable multiple cell selection, after setting the MultiSelect property to true, you have to set the SelectionMode to GridViewSelectionMode.CellSelect: -{{source=..\SamplesCS\GridView\Selection\Selection1.cs region=multipleCellSelection}} -{{source=..\SamplesVB\GridView\Selection\Selection1.vb region=multipleCellSelection}} - -````C# -radGridView1.MultiSelect = true; -radGridView1.SelectionMode = GridViewSelectionMode.CellSelect; - -```` -````VB.NET -RadGridView1.MultiSelect = True -RadGridView1.SelectionMode = GridViewSelectionMode.CellSelect - -```` - -{{endregion}} + + Once you have applied these setting, the options for selection are: diff --git a/controls/gridview/features/selection/selecting-rows-and-cells-programmatically.md b/controls/gridview/features/selection/selecting-rows-and-cells-programmatically.md index 2f1b9a608..7fb068e5a 100644 --- a/controls/gridview/features/selection/selecting-rows-and-cells-programmatically.md +++ b/controls/gridview/features/selection/selecting-rows-and-cells-programmatically.md @@ -19,35 +19,13 @@ To select a single row programmatically: * You can set its __IsSelected__ property to `true`: -{{source=..\SamplesCS\GridView\Selection\Selection1.cs region=isRowSelected}} -{{source=..\SamplesVB\GridView\Selection\Selection1.vb region=isRowSelected}} - -````C# -radGridView1.Rows[2].IsSelected = true; - -```` -````VB.NET -RadGridView1.Rows(2).IsSelected = True - -```` - -{{endregion}} + + * You can make the row current: -{{source=..\SamplesCS\GridView\Selection\Selection1.cs region=isRowCurrent}} -{{source=..\SamplesVB\GridView\Selection\Selection1.vb region=isRowCurrent}} - -````C# -radGridView1.Rows[2].IsCurrent = true; - -```` -````VB.NET -RadGridView1.Rows(2).IsCurrent = True - -```` - -{{endregion}} + + Both ways to select a single row result in adding this row into the RadGridView.__SelectedRows__ collection. @@ -57,50 +35,15 @@ Both ways to select a single row result in adding this row into the RadGridView. To select multiple rows programmatically, set their __IsSelected__ property to `true`: -{{source=..\SamplesCS\GridView\Selection\Selection1.cs region=selectMultipleRows}} -{{source=..\SamplesVB\GridView\Selection\Selection1.vb region=selectMultipleRows}} - -````C# -radGridView1.ClearSelection(); -radGridView1.MultiSelect = true; -radGridView1.SelectionMode = Telerik.WinControls.UI.GridViewSelectionMode.FullRowSelect; -radGridView1.Rows[0].IsSelected = true; -radGridView1.Rows[4].IsSelected = true; -radGridView1.Rows[6].IsSelected = true; -radGridView1.Rows[9].IsSelected = true; - -```` -````VB.NET -RadGridView1.ClearSelection() -RadGridView1.MultiSelect = True -RadGridView1.SelectionMode = Telerik.WinControls.UI.GridViewSelectionMode.FullRowSelect -RadGridView1.Rows(0).IsSelected = True -RadGridView1.Rows(4).IsSelected = True -RadGridView1.Rows(6).IsSelected = True -RadGridView1.Rows(9).IsSelected = True - -```` - -{{endregion}} - + + ![WinForms RadGridView Selecting Multiple Rows Programmatically](images/gridview-selection-selecting-rows-and-cells-programmatically002.png) In this scenario all, four rows are added to the __SelectedRows__ collection of **RadGridView**. You can access the instances of the selected rows in the __SelectedRows__ collection by their index: -{{source=..\SamplesCS\GridView\Selection\Selection1.cs region=gettingSelectedRow}} -{{source=..\SamplesVB\GridView\Selection\Selection1.vb region=gettingSelectedRow}} - -````C# -GridViewRowInfo selectedRow = radGridView1.SelectedRows[0]; - -```` -````VB.NET -Dim selectedRow As GridViewRowInfo = RadGridView1.SelectedRows(0) - -```` - -{{endregion}} + + >note The rows are added to the __SelectedRows__ collection in the same order as the order in which you have set the selected rows. @@ -108,27 +51,8 @@ Dim selectedRow As GridViewRowInfo = RadGridView1.SelectedRows(0) You can select cells the same way you select rows – by setting their __IsSelected__ property to `true`: -{{source=..\SamplesCS\GridView\Selection\Selection1.cs region=selectingCell}} -{{source=..\SamplesVB\GridView\Selection\Selection1.vb region=selectingCell}} - -````C# -radGridView1.ClearSelection(); -radGridView1.SelectionMode = Telerik.WinControls.UI.GridViewSelectionMode.CellSelect; -//here instead of a cell index you can specify the Name of the column as a string -//i.e. radGridView1.Rows[1].Cells[“Column 1”].IsSelected = true; -radGridView1.Rows[1].Cells[3].IsSelected = true; - -```` -````VB.NET -RadGridView1.ClearSelection() -RadGridView1.SelectionMode = Telerik.WinControls.UI.GridViewSelectionMode.CellSelect -'here instead of a cell index you can specify the Name of the column as a string -'i.e. radGridView1.Rows(1).Cells(“Column 1”).IsSelected = true -RadGridView1.Rows(1).Cells(3).IsSelected = True - -```` - -{{endregion}} + + Selecting a single cell will result in adding this cell into the RadGridView.**SelectedCells** collection. @@ -138,47 +62,15 @@ Selecting a single cell will result in adding this cell into the RadGridView.**S To select multiple cells programmatically, set the __IsSelected__ property of the desired cells to `true`. -{{source=..\SamplesCS\GridView\Selection\Selection1.cs region=selectMultipleCells}} -{{source=..\SamplesVB\GridView\Selection\Selection1.vb region=selectMultipleCells}} - -````C# -radGridView1.MultiSelect = true; -radGridView1.SelectionMode = Telerik.WinControls.UI.GridViewSelectionMode.CellSelect; -radGridView1.Rows[0].Cells[0].IsSelected = true; -radGridView1.Rows[3].Cells[1].IsSelected = true; -radGridView1.Rows[5].Cells[2].IsSelected = true; -radGridView1.Rows[6].Cells[3].IsSelected = true; - -```` -````VB.NET -RadGridView1.MultiSelect = True -RadGridView1.SelectionMode = Telerik.WinControls.UI.GridViewSelectionMode.CellSelect -RadGridView1.Rows(0).Cells(0).IsSelected = True -RadGridView1.Rows(3).Cells(1).IsSelected = True -RadGridView1.Rows(5).Cells(2).IsSelected = True -RadGridView1.Rows(6).Cells(3).IsSelected = True - -```` - -{{endregion}} + + ![WinForms RadGridView Selecting Multiple Cells Programmatically](images/gridview-selection-selecting-rows-and-cells-programmatically004.png) In this scenario, all four cells are added to the __SelectedCells__ collection of **RadGridView**. You can access the instances of the selected cells in the __SelectedCells__ collection by their index: -{{source=..\SamplesCS\GridView\Selection\Selection1.cs region=gettingSelectedCell}} -{{source=..\SamplesVB\GridView\Selection\Selection1.vb region=gettingSelectedCell}} - -````C# -GridViewCellInfo selectedCell = radGridView1.SelectedCells[0]; - -```` -````VB.NET -Dim selectedCell As GridViewCellInfo = RadGridView1.SelectedCells(0) - -```` - -{{endregion}} + + Note that the cells are added to the collection in the same order as the order in which you have set the selected cells. diff --git a/controls/gridview/features/sorting/basic-sorting.md b/controls/gridview/features/sorting/basic-sorting.md index 11c0fb0cb..726bdc11d 100644 --- a/controls/gridview/features/sorting/basic-sorting.md +++ b/controls/gridview/features/sorting/basic-sorting.md @@ -15,19 +15,8 @@ previous_url: gridview-sorting-basic-sorting #### Enabling the user sorting -{{source=..\SamplesCS\GridView\Sorting\Sorting.cs region=enableSorting}} -{{source=..\SamplesVB\GridView\Sorting\Sorting.vb region=enableSorting}} - -````C# -this.radGridView1.MasterTemplate.EnableSorting = true; - -```` -````VB.NET -Me.RadGridView1.MasterTemplate.EnableSorting = True - -```` - -{{endregion}} + + When sorting is enabled, the user can click on the column headers to control the sorting order. **RadGridView** supports three orders: __Ascending__, __Descending__, and __None__ (no sort). Since R1 2017 columns have a property called **AllowNaturalSort** that defines whether the user will cycle through *no sort* when clicking on the header cell or whether once sorted the column cannot be "unsorted". @@ -50,83 +39,8 @@ TryCast(radGridView.MasterTemplate.ListSource.CollectionView, GridDataView).UseH #### Bypass default sorting -{{source=..\SamplesCS\GridView\Sorting\Sorting.cs region=BypassSorting}} -{{source=..\SamplesVB\GridView\Sorting\Sorting.vb region=BypassSorting}} - -````C# - -DataTable dt = new DataTable(); - -public void FillData() -{ - dt.Columns.Add("Id", typeof(int)); - dt.Columns.Add("Name", typeof(string)); - - for (int i = 0; i < 30; i++) - { - dt.Rows.Add(i, "Item" + i); - } - this.radGridView1.DataSource = dt; - - this.radGridView1.MasterTemplate.DataView.BypassSort = true; - this.radGridView1.SortChanged += radGridView1_SortChanged; -} - -private void radGridView1_SortChanged(object sender, Telerik.WinControls.UI.GridViewCollectionChangedEventArgs e) -{ - if (e.Action == NotifyCollectionChangedAction.Add || e.Action == NotifyCollectionChangedAction.ItemChanged) - { - SortDescriptor s = e.NewItems[0] as SortDescriptor; - string sortOperator = ""; - if (s.Direction == ListSortDirection.Ascending) - { - sortOperator = "ASC"; - } - else - { - sortOperator = "DESC"; - } - dt.DefaultView.Sort = s.PropertyName + " " + sortOperator; - } - if (e.Action == NotifyCollectionChangedAction.Remove) - { - dt.DefaultView.Sort = ""; - } -} - -```` -````VB.NET -Private dt As New DataTable() -Public Sub FillData() - dt.Columns.Add("Id", GetType(Integer)) - dt.Columns.Add("Name", GetType(String)) - For i As Integer = 0 To 29 - dt.Rows.Add(i, "Item" & i) - Next - Me.RadGridView1.DataSource = dt - Me.RadGridView1.MasterTemplate.DataView.BypassSort = True - AddHandler Me.RadGridView1.SortChanged, AddressOf radGridView1_SortChanged -End Sub -Private Sub radGridView1_SortChanged(sender As Object, e As Telerik.WinControls.UI.GridViewCollectionChangedEventArgs) - If e.Action = NotifyCollectionChangedAction.Add OrElse e.Action = NotifyCollectionChangedAction.ItemChanged Then - Dim s As SortDescriptor = TryCast(e.NewItems(0), SortDescriptor) - Dim sortOperator As String = "" - If s.Direction = ListSortDirection.Ascending Then - sortOperator = "ASC" - Else - sortOperator = "DESC" - End If - dt.DefaultView.Sort = Convert.ToString(s.PropertyName + " ") & sortOperator - End If - If e.Action = NotifyCollectionChangedAction.Remove Then - dt.DefaultView.Sort = "" - End If -End Sub - -```` - -{{endregion}} - + + See [End-user Capabilities Sorting]({%slug winforms/gridview/end-user-capabilities/sorting%}) topic about more information on the sorting behavior of RadGridView from the users' perspective. # See Also diff --git a/controls/gridview/features/sorting/custom-sorting.md b/controls/gridview/features/sorting/custom-sorting.md index 81a5ee85d..64d0530f3 100644 --- a/controls/gridview/features/sorting/custom-sorting.md +++ b/controls/gridview/features/sorting/custom-sorting.md @@ -37,132 +37,19 @@ The __CustomSorting__ event is fired if custom sorting is enabled. It requires t The following example demonstrates how to handle the __CustomSorting__ event sorting the RadGridView rows ascending by the values of the `Freight` column. The defined __SortOrder__ for the `Freight` column in this example assumes that row sorting is not applied. All RadGridView rows are processed by the custom logic. -{{source=..\SamplesCS\GridView\Sorting\CustomSorting.cs region=usingCustomSorting}} -{{source=..\SamplesVB\GridView\Sorting\CustomSorting.vb region=usingCustomSorting}} -````C# -this.radGridView1.EnableCustomSorting = true; -this.radGridView1.CustomSorting += new GridViewCustomSortingEventHandler(radGridView1_CustomSorting); -this.radGridView1.Columns["Freight"].SortOrder = RadSortOrder.Ascending; - -```` -````VB.NET -Me.RadGridView1.EnableCustomSorting = True -Me.RadGridView1.Columns("Freight").SortOrder = RadSortOrder.Ascending - -```` - -{{endregion}} - -{{source=..\SamplesCS\GridView\Sorting\CustomSorting.cs region=usingCustomSorting1}} -{{source=..\SamplesVB\GridView\Sorting\CustomSorting.vb region=usingCustomSorting1}} - -````C# -private void radGridView1_CustomSorting(object sender, GridViewCustomSortingEventArgs e) -{ - decimal row1Freight = (decimal)e.Row1.Cells["Freight"].Value; - decimal row2Freight = (decimal)e.Row2.Cells["Freight"].Value; - if (row1Freight > row2Freight) - { - e.SortResult = 1; - } - else if (row1Freight < row2Freight) - { - e.SortResult = -1; - } - else - { - e.SortResult = 0; - } -} - -```` -````VB.NET -Private Sub RadGridView1_CustomSorting(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewCustomSortingEventArgs) Handles RadGridView1.CustomSorting - Dim row1Freight As Decimal = CDec(e.Row1.Cells("Freight").Value) - Dim row2Freight As Decimal = CDec(e.Row2.Cells("Freight").Value) - If row1Freight > row2Freight Then - e.SortResult = 1 - ElseIf row1Freight < row2Freight Then - e.SortResult = -1 - Else - e.SortResult = 0 - End If -End Sub - -```` - -{{endregion}} - + + + + ![WinForms RadGridView Default Sorting](images/gridview-sorting-custom-sorting001.png) The following example demonstrates the usage of the __Handled__ property of the __CustomSorting__ event arguments. It uses custom sorting to sort the rows ascending by the values of the `Freight` column. This sorting is applied to the rows that have a value in the `Freight` column greater than "0.33". The rest are handled by the defined __SortDescriptor__ and sorted descending by the values of the `Freight` column. -{{source=..\SamplesCS\GridView\Sorting\CustomSorting1.cs region=usingCustomSortingPlusHandled}} -{{source=..\SamplesVB\GridView\Sorting\CustomSorting1.vb region=usingCustomSortingPlusHandled}} - -````C# -this.radGridView1.Columns["ShipCity"].SortOrder = RadSortOrder.Ascending; -this.radGridView1.MasterTemplate.SortComparer = new CustomComparer(); - -```` -````VB.NET -Me.RadGridView1.Columns("ShipCity").SortOrder = RadSortOrder.Ascending -Me.RadGridView1.MasterTemplate.SortComparer = New CustomComparer() - -```` - -{{endregion}} - -{{source=..\SamplesCS\GridView\Sorting\CustomSorting1.cs region=usingCustomSortingPlusHandled1}} -{{source=..\SamplesVB\GridView\Sorting\CustomSorting1.vb region=usingCustomSortingPlusHandled1}} - -````C# -private void radGridView1_CustomSorting(object sender, GridViewCustomSortingEventArgs e) -{ - decimal row1Freight = (decimal)e.Row1.Cells["Freight"].Value; - decimal row2Freight = (decimal)e.Row2.Cells["Freight"].Value; - if (row1Freight < 0.33m || row2Freight < 0.33m) - { - e.Handled = false; - return; - } - if (row1Freight > row2Freight) - { - e.SortResult = 1; - } - else if (row1Freight < row2Freight) - { - e.SortResult = -1; - } - else - { - e.SortResult = 0; - } -} - -```` -````VB.NET -Private Sub RadGridView1_CustomSorting(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewCustomSortingEventArgs) Handles RadGridView1.CustomSorting - Dim row1Freight As Decimal = CDec(e.Row1.Cells("Freight").Value) - Dim row2Freight As Decimal = CDec(e.Row2.Cells("Freight").Value) - If row1Freight < 0.33D OrElse row2Freight < 0.33D Then - e.Handled = False - Return - End If - If row1Freight > row2Freight Then - e.SortResult = 1 - ElseIf row1Freight < row2Freight Then - e.SortResult = -1 - Else - e.SortResult = 0 - End If -End Sub - -```` - -{{endregion}} - + + + + ![WinForms RadGridView Custom Sorting Event](images/gridview-sorting-custom-sorting002.png) @@ -172,22 +59,8 @@ You can replace the sorting mechanism in RadGridView with a custom one by settin The following example demonstrates how to use a custom sorting mechanism in RadGridView to sort the RadGridView rows ascending by the length of the `ShipCity` column: -{{source=..\SamplesCS\GridView\Sorting\CustomSorting.cs region=usingSortComparer}} -{{source=..\SamplesVB\GridView\Sorting\CustomSorting.vb region=usingSortComparer}} - -````C# -this.radGridView1.Columns["ShipCity"].SortOrder = RadSortOrder.Ascending; -this.radGridView1.MasterTemplate.SortComparer = new CustomComparer(); - -```` -````VB.NET -Me.RadGridView1.Columns("ShipCity").SortOrder = RadSortOrder.Ascending -Me.RadGridView1.MasterTemplate.SortComparer = New CustomComparer() - -```` - -{{endregion}} - + + ![WinForms RadGridView Using Custom SortComparer](images/gridview-sorting-custom-sorting003.png) @@ -195,70 +68,8 @@ Me.RadGridView1.MasterTemplate.SortComparer = New CustomComparer() You can use the custom sorting functionality to change the default sorting behavior for a particular column. This will leave the sorting functionality for the other columns intact and the user will be able to sort them in the usual way. However, when the user presses the column header cell for the column that we have changed the sort criteria, it will be sorted by the custom criteria. To achieve this we can use the __SortDescriptors__ collection of __RadGridView__. For example, you can order the rows by the text length in the *Customer* column with the following code: -{{source=..\SamplesCS\GridView\Sorting\CustomSorting2.cs region=SortByCustomCriteria}} -{{source=..\SamplesVB\GridView\Sorting\CustomSorting2.vb region=SortByCustomCriteria}} - -````C# -void radGridView1_CustomSorting(object sender, Telerik.WinControls.UI.GridViewCustomSortingEventArgs e) -{ - int descriptorIndex = -1; - for (int i = 0; i < this.radGridView1.SortDescriptors.Count; i++) - { - if (radGridView1.SortDescriptors[i].PropertyName == "Customer") - { - descriptorIndex = i; - break; - } - } - if (descriptorIndex != -1) - { - string cellValue1 = e.Row1.Cells["Customer"].Value.ToString(); - string cellValue2 = e.Row2.Cells["Customer"].Value.ToString(); - int result = cellValue1.Length - cellValue2.Length; - if (result != 0) - { - if (this.radGridView1.SortDescriptors[descriptorIndex].Direction == ListSortDirection.Descending) - { - result = -result; - } - } - e.SortResult = result; - } - else - { - e.Handled = false; - } -} - -```` -````VB.NET - Private Sub radGridView1_CustomSorting(sender As Object, e As Telerik.WinControls.UI.GridViewCustomSortingEventArgs) - Dim descriptorIndex As Integer = -1 - For i As Integer = 0 To Me.radGridView1.SortDescriptors.Count - 1 - If radGridView1.SortDescriptors(i).PropertyName = "Customer" Then - descriptorIndex = i - Exit For - End If - Next - If descriptorIndex <> -1 Then - Dim cellValue1 As String = e.Row1.Cells("Customer").Value.ToString() - Dim cellValue2 As String = e.Row2.Cells("Customer").Value.ToString() - Dim result As Integer = cellValue1.Length - cellValue2.Length - If result <> 0 Then - If Me.radGridView1.SortDescriptors(descriptorIndex).Direction = ListSortDirection.Descending Then - result = -result - End If - End If - e.SortResult = result - Else - e.Handled = False - End If - End Sub - -```` - -{{endregion}} - + + ![WinForms RadGridView Column Custom Sort Order Criteria](images/gridview-sorting-custom-sorting005.png) diff --git a/controls/gridview/features/sorting/events.md b/controls/gridview/features/sorting/events.md index c033fe2b6..93eebd263 100644 --- a/controls/gridview/features/sorting/events.md +++ b/controls/gridview/features/sorting/events.md @@ -13,27 +13,8 @@ previous_url: gridview-sorting-events There are two events that are raised when the data in the RadGridView is sorted. The first one is the __SortChanging__ event which is raised before the data is sorted. The second one is the __SortChanged__ event and it is raised after the data is sorted. -{{source=..\SamplesCS\GridView\Sorting\SortingEvents.cs region=SortingEvents1}} -{{source=..\SamplesVB\GridView\Sorting\SortingEvents.vb region=SortingEvents}} - -````C# -void radGridView1_SortChanging(object sender, Telerik.WinControls.UI.GridViewCollectionChangingEventArgs e) -{ -} -void radGridView1_SortChanged(object sender, Telerik.WinControls.UI.GridViewCollectionChangedEventArgs e) -{ -} - -```` -````VB.NET -Private Sub RadGridView1_SortChanging(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewCollectionChangingEventArgs) Handles RadGridView1.SortChanging -End Sub -Private Sub RadGridView1_SortChanged(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewCollectionChangedEventArgs) Handles RadGridView1.SortChanged -End Sub - -```` - -{{endregion}} + + From the event arguments of both events you can access the following data: @@ -43,56 +24,15 @@ From the event arguments of both events you can access the following data: You are also able to cancel the sorting operation by setting the __Cancel__ property to *True*. -{{source=..\SamplesCS\GridView\Sorting\SortingEvents.cs region=CancelSorting}} -{{source=..\SamplesVB\GridView\Sorting\SortingEvents.vb region=CancelSorting}} -````C# -private void radGridView1_SortChanging1(object sender, GridViewCollectionChangingEventArgs e) -{ - e.Cancel = true; -} - -```` -````VB.NET -Private Sub RadGridView1_SortChanging1(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewCollectionChangingEventArgs) Handles RadGridView1.SortChanging - e.Cancel = True -End Sub - -```` - -{{endregion}} + + Since the __SortDescriptors__ collection implements the __INotifyPropertyChanged__ interface, you can use its __CollectionChanged__ event (The arguments of this event provide the same data as the __SortChanged__ event). -{{source=..\SamplesCS\GridView\Sorting\SortingEvents.cs region=CollectionChanged}} -{{source=..\SamplesVB\GridView\Sorting\SortingEvents.vb region=CollectionChanged}} -````C# -this.radGridView1.SortDescriptors.CollectionChanged += new Telerik.WinControls.Data.NotifyCollectionChangedEventHandler(SortDescriptors_CollectionChanged); - -```` -````VB.NET -AddHandler Me.RadGridView1.SortDescriptors.CollectionChanged, AddressOf SortDescriptors_CollectionChanged - -```` - -{{endregion}} - -{{source=..\SamplesCS\GridView\Sorting\SortingEvents.cs region=CollectionChanged1}} -{{source=..\SamplesVB\GridView\Sorting\SortingEvents.vb region=CollectionChanged1}} - -````C# -void SortDescriptors_CollectionChanged(object sender, Telerik.WinControls.Data.NotifyCollectionChangedEventArgs e) -{ - -} - -```` -````VB.NET -Private Sub SortDescriptors_CollectionChanged(ByVal sender As Object, ByVal e As Telerik.WinControls.Data.NotifyCollectionChangedEventArgs) -End Sub - -```` - -{{endregion}} + + + + >note As of **R1 2021** RadGridView offers two new events: > diff --git a/controls/gridview/features/sorting/setting-sorting-programmatically.md b/controls/gridview/features/sorting/setting-sorting-programmatically.md index 044524feb..0f2f17415 100644 --- a/controls/gridview/features/sorting/setting-sorting-programmatically.md +++ b/controls/gridview/features/sorting/setting-sorting-programmatically.md @@ -23,44 +23,15 @@ To enable sorting you need to set the __EnableSorting__ property of the desired #### Enable Sorting -{{source=..\SamplesCS\GridView\Sorting\Sorting.cs region=enableSorting}} -{{source=..\SamplesVB\GridView\Sorting\Sorting.vb region=enableSorting}} - -````C# -this.radGridView1.MasterTemplate.EnableSorting = true; - -```` -````VB.NET -Me.RadGridView1.MasterTemplate.EnableSorting = True - -```` - -{{endregion}} + + Here is how to create and add new __SortDescriptor__. #### Using SortDescriptor -{{source=..\SamplesCS\GridView\Sorting\Sorting.cs region=usingSortDescriptor}} -{{source=..\SamplesVB\GridView\Sorting\Sorting.vb region=usingSortDescriptor}} - -````C# - -SortDescriptor descriptor = new SortDescriptor(); -descriptor.PropertyName = "ShipCountry"; -descriptor.Direction = ListSortDirection.Ascending; -this.radGridView1.MasterTemplate.SortDescriptors.Add(descriptor); - -```` -````VB.NET -Dim descriptor As New SortDescriptor() -descriptor.PropertyName = "ShipCountry" -descriptor.Direction = ListSortDirection.Ascending -Me.RadGridView1.MasterTemplate.SortDescriptors.Add(descriptor) - -```` - -{{endregion}} + + The __PropertyName__ property defines the property, by which the data will be sorted, and the __SortDirection__ property allows you to define the sort direction. @@ -70,34 +41,8 @@ The __PropertyName__ property defines the property, by which the data will be so #### Sorting by Two Columns -{{source=..\SamplesCS\GridView\Sorting\Sorting.cs region=sortingByTwoOrMoreColumns}} -{{source=..\SamplesVB\GridView\Sorting\Sorting.vb region=sortingByTwoOrMoreColumns}} - -````C# - -SortDescriptor descriptorShipName = new SortDescriptor(); -descriptorShipName.PropertyName = "ShipName"; -descriptorShipName.Direction = ListSortDirection.Ascending; -SortDescriptor descriptorFreight = new SortDescriptor(); -descriptorFreight.PropertyName = "Freight"; -descriptorFreight.Direction = ListSortDirection.Descending; -this.radGridView1.SortDescriptors.Add(descriptorShipName); -this.radGridView1.SortDescriptors.Add(descriptorFreight); - -```` -````VB.NET -Dim descriptorShipName As New SortDescriptor() -descriptorShipName.PropertyName = "ShipName" -descriptorShipName.Direction = ListSortDirection.Ascending -Dim descriptorFreight As New SortDescriptor() -descriptorFreight.PropertyName = "Freight" -descriptorFreight.Direction = ListSortDirection.Descending -Me.RadGridView1.SortDescriptors.Add(descriptorShipName) -Me.RadGridView1.SortDescriptors.Add(descriptorFreight) - -```` - -{{endregion}} + + >caption Figure 1: Sorting by Two Columns diff --git a/controls/gridview/features/sorting/sorting-expressions.md b/controls/gridview/features/sorting/sorting-expressions.md index f7dd7446f..29d769d3f 100644 --- a/controls/gridview/features/sorting/sorting-expressions.md +++ b/controls/gridview/features/sorting/sorting-expressions.md @@ -21,39 +21,16 @@ Creating a simple expression: #### Creating simple sorting expression -{{source=..\SamplesCS\GridView\Sorting\Sorting.cs region=creatingSimpleSortingExpression}} -{{source=..\SamplesVB\GridView\Sorting\Sorting.vb region=creatingSimpleSortingExpression}} - -````C# - -this.radGridView1.SortDescriptors.Expression = "ShipName ASC"; - -```` -````VB.NET -Me.RadGridView1.SortDescriptors.Expression = "ShipName ASC" - -```` - -{{endregion}} + + Sorting by two columns using expressions: #### Sorting by two columns, using sorting expression -{{source=..\SamplesCS\GridView\Sorting\Sorting.cs region=sortingByTwoColumnsUsingExpression}} -{{source=..\SamplesVB\GridView\Sorting\Sorting.vb region=sortingByTwoColumnsUsingExpression}} - -````C# - -this.radGridView1.SortDescriptors.Expression = "ShipName ASC, Freight DESC"; - -```` -````VB.NET -Me.RadGridView1.SortDescriptors.Expression = "ShipName ASC, Freight DESC" - -```` + + -{{endregion}} # See Also * [Basic Sorting]({%slug winforms/gridview/sorting/basic-sorting%}) diff --git a/controls/gridview/features/virtual-mode.md b/controls/gridview/features/virtual-mode.md index d01676c06..95e498832 100644 --- a/controls/gridview/features/virtual-mode.md +++ b/controls/gridview/features/virtual-mode.md @@ -45,65 +45,8 @@ with __MockIntegerDataSource__ (the implementation of this data source can be fo #### Implementing the Virtual Mode -{{source=..\SamplesCS\GridView\VirtualMode\VirtualMode1.cs region=virtualMode}} -{{source=..\SamplesVB\GridView\VirtualMode\VirtualMode1.vb region=virtualMode}} - -````C# -public VirtualMode1() -{ - InitializeComponent(); - this.radGridView1.EnableSorting = false; - this.radGridView1.EnableFiltering = false; - this.radGridView1.EnableGrouping = false; - this.Load += new EventHandler(Form1_Load); -} -int COUNT = 100; -MockIntegerDataSource dataSource; -void Form1_Load(object sender, EventArgs e) -{ - dataSource = new MockIntegerDataSource(COUNT, COUNT); - this.radGridView1.CellValueNeeded += new GridViewCellValueEventHandler(radGridView1_CellValueNeeded); - this.radGridView1.CellValuePushed += new GridViewCellValueEventHandler(radGridView1_CellValuePushed); - radGridView1.VirtualMode = true; - radGridView1.ColumnCount = dataSource.Columns; - this.radGridView1.RowCount = dataSource.Rows; -} -void radGridView1_CellValuePushed(object sender, GridViewCellValueEventArgs e) -{ -} -void radGridView1_CellValueNeeded(object sender, GridViewCellValueEventArgs e) -{ - e.Value = this.dataSource.Source[e.RowIndex].Data[e.ColumnIndex]; -} - -```` -````VB.NET -Public Sub New() - InitializeComponent() - Me.RadGridView1.EnableSorting = False - Me.RadGridView1.EnableFiltering = False - Me.RadGridView1.EnableGrouping = False -End Sub -Dim COUNT As Integer = 100 -Dim dataSource As MockIntegerDataSource -Protected Overloads Overrides Sub OnLoad(ByVal e As EventArgs) - MyBase.OnLoad(e) - Me.dataSource = New MockIntegerDataSource(COUNT, COUNT) - AddHandler Me.RadGridView1.CellValueNeeded, AddressOf radGridView1_CellValueNeeded - AddHandler Me.RadGridView1.CellValuePushed, AddressOf radGridView1_CellValuePushed - RadGridView1.VirtualMode = True - RadGridView1.ColumnCount = Me.dataSource.Columns - Me.RadGridView1.RowCount = Me.dataSource.Rows -End Sub -Sub radGridView1_CellValuePushed(ByVal sender As Object, ByVal e As GridViewCellValueEventArgs) -End Sub -Sub radGridView1_CellValueNeeded(ByVal sender As Object, ByVal e As GridViewCellValueEventArgs) - e.Value = Me.dataSource.Source(e.RowIndex).Data(e.ColumnIndex) -End Sub - -```` - -{{endregion}} + + ## Virtual-Mode Events diff --git a/controls/gridview/fundamentals/creating-hierarchical-grids.md b/controls/gridview/fundamentals/creating-hierarchical-grids.md index c36103023..7c38c8af7 100644 --- a/controls/gridview/fundamentals/creating-hierarchical-grids.md +++ b/controls/gridview/fundamentals/creating-hierarchical-grids.md @@ -15,26 +15,9 @@ __RadGridView__ has the ability to represent hierarchical master-detail data. It #### Create hierarchical grid -{{source=..\SamplesCS\GridView\Fundamentials\CreatingHierarchicalGrid.cs region=AutoGenerateHierarchy}} -{{source=..\SamplesVB\GridView\Fundamentials\CreatingHierarchicalGrid.vb region=AutoGenerateHierarchy}} - -````C# -this.ordersTableAdapter.Fill(this.nwindDataSet.Orders); -this.order_DetailsTableAdapter.Fill(this.nwindDataSet.Order_Details); -this.customersTableAdapter.Fill(this.nwindDataSet.Customers); -radGridView1.AutoGenerateHierarchy = true; - -```` -````VB.NET -Me.OrdersTableAdapter.Fill(Me.NwindDataSet.Orders) -Me.Order_DetailsTableAdapter.Fill(Me.NwindDataSet.Order_Details) -Me.CustomersTableAdapter.Fill(Me.NwindDataSet.Customers) -RadGridView1.AutoGenerateHierarchy = True - -```` - -{{endregion}} - + + + The general steps to setting up hierarchical data manually are: 1. Configure the data source components for each table to be displayed. diff --git a/controls/gridview/fundamentals/logical-vs.-visual-grid-structure.md b/controls/gridview/fundamentals/logical-vs.-visual-grid-structure.md index 03320c508..fc3abd613 100644 --- a/controls/gridview/fundamentals/logical-vs.-visual-grid-structure.md +++ b/controls/gridview/fundamentals/logical-vs.-visual-grid-structure.md @@ -50,63 +50,16 @@ This logical tree structure allows you to traverse down through the cell level u #### Iterate the MasterGridViewTemplate cells -{{source=..\SamplesCS\GridView\Fundamentials\LogicalVsVisualStructure.cs region=iterateMasterGridViewTemplate}} -{{source=..\SamplesVB\GridView\Fundamentials\LogicalVsVisualStructure.vb region=iterateMasterGridViewTemplate}} - -````C# -foreach (GridViewRowInfo rowInfo in radGridView1.MasterTemplate.Rows) -{ - foreach (GridViewCellInfo cellInfo in rowInfo.Cells) - { - if (cellInfo.ColumnInfo.HeaderText == "Name") - { - cellInfo.Value = "TestName"; - } - } -} - -```` -````VB.NET -For Each rowInfo As GridViewRowInfo In RadGridView1.MasterTemplate.Rows - For Each cellInfo As GridViewCellInfo In rowInfo.Cells - If cellInfo.ColumnInfo.Name = "Name" Then - cellInfo.Value = "TestName" - End If - Next -Next - -```` - -{{endregion}} - + + + ...or to iterate all the columns of each child template within the master template: #### Iterate the child templates cells -{{source=..\SamplesCS\GridView\Fundamentials\LogicalVsVisualStructure.cs region=iterateChildTemplates}} -{{source=..\SamplesVB\GridView\Fundamentials\LogicalVsVisualStructure.vb region=iterateChildTemplates}} - -````C# -foreach (GridViewTemplate childTemplate in radGridView1.MasterTemplate.Templates) -{ - foreach (GridViewColumn column in childTemplate.Columns) - { - column.HeaderTextAlignment = ContentAlignment.TopCenter; - } -} - -```` -````VB.NET -For Each childtemplate As GridViewTemplate In RadGridView1.MasterTemplate.Templates - For Each column As GridViewColumn In childtemplate.Columns - column.HeaderTextAlignment = ContentAlignment.TopCenter - Next -Next - -```` - -{{endregion}} - + + + ## Visual Grid __RadGridView__ uses virtualization for its visual elements. This means that only the rows that are currently visible have a visual element. When the grid is scrolled up and down the visual elements are reused. For example, because of the virtualization, the __CellElement__ can only be accessed inside the __CellFormatting__ event and only for the current cell. The __CellFormatting__ event is fired every time when the cell's visual state needs to be updated. diff --git a/controls/gridview/fundamentals/ui-virtualization.md b/controls/gridview/fundamentals/ui-virtualization.md index 35a1b6c31..501137f86 100644 --- a/controls/gridview/fundamentals/ui-virtualization.md +++ b/controls/gridview/fundamentals/ui-virtualization.md @@ -20,65 +20,8 @@ Because of the virtualization you cannot access UI elements at design time or di Here is a quick sample: -{{source=..\SamplesCS\GridView\Fundamentials\UIVirtualization.cs region=cellFormatting}} -{{source=..\SamplesVB\GridView\Fundamentials\UIVirtualization.vb region=cellFormatting}} -````C# -void radGridView1_CellFormatting(object sender, CellFormattingEventArgs e) -{ - if (e.CellElement.ColumnInfo.Name == "UnitsOnOrder" && e.CellElement.Value != null) - { - if ((short)e.CellElement.Value <= 0) - { - e.CellElement.DrawFill = true; - e.CellElement.GradientStyle = GradientStyles.Solid; - e.CellElement.BackColor = Color.Red; - e.CellElement.BorderBoxStyle = BorderBoxStyle.SingleBorder; - } - else - { - e.CellElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(VisualElement.BackColorProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.BorderBoxStyleProperty, ValueResetFlags.Local); - } - } - else - { - e.CellElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(VisualElement.BackColorProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.BorderBoxStyleProperty, ValueResetFlags.Local); - } -} - -```` -````VB.NET -Private Sub radGridView1_CellFormatting(ByVal sender As Object, ByVal e As CellFormattingEventArgs) - If e.CellElement.ColumnInfo.Name = "UnitsOnOrder" AndAlso e.CellElement.Value IsNot Nothing Then - If CShort(Fix(e.CellElement.Value)) <= 0 Then - e.CellElement.DrawFill = True - e.CellElement.GradientStyle = GradientStyles.Solid - e.CellElement.BackColor = Color.Red - e.CellElement.BorderBoxStyle = BorderBoxStyle.SingleBorder - Else - e.CellElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(VisualElement.BackColorProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.BorderBoxStyleProperty, ValueResetFlags.Local) - End If - Else - e.CellElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(VisualElement.BackColorProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.BorderBoxStyleProperty, ValueResetFlags.Local) - End If -End Sub - -```` - - -{{endregion}} - + + ![WinForms RadGridView Formatting events](images/gridview-fundamentals-ui-virtualization001.png) diff --git a/controls/gridview/hierarchical-grid/binding-to-hierarchical-data-automatically.md b/controls/gridview/hierarchical-grid/binding-to-hierarchical-data-automatically.md index 6fb096276..f3e78ce89 100644 --- a/controls/gridview/hierarchical-grid/binding-to-hierarchical-data-automatically.md +++ b/controls/gridview/hierarchical-grid/binding-to-hierarchical-data-automatically.md @@ -23,36 +23,8 @@ At runtime, if the data source for the grid is a __System.Data.DataSet__ type an The run-time code fills the categories and products data tables, sets the __AutoGenerateHierarchy__ to *true*, assigns the data set containing both tables to the grid __DataSource__ and the __DataMember__ is the name of the parent table. The last three lines of code below can be configured at design time. -{{source=..\SamplesCS\GridView\HierarchicalGrid\BindingToHierarchicalGridAutomatically.cs region=BindingToHierarchicalGridAutomatically}} -{{source=..\SamplesVB\GridView\HierarchicalGrid\BindingToHierarchicalGridAutomatically.vb region=BindingToHierarchicalGridAutomatically}} - -````C# - -private void BindingToHierarchicalGridAutomatically_Load(object sender, EventArgs e) -{ - this.productsTableAdapter.Fill(this.nwindDataSet.Products); - this.categoriesTableAdapter.Fill(this.nwindDataSet.Categories); - radGridView1.AutoGenerateHierarchy = true; - radGridView1.DataSource = this.nwindDataSet; - radGridView1.DataMember = "Categories"; -} - -```` -````VB.NET -Private Sub BindingToHierarchicalGridAutomatically_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load - 'TODO: This line of code loads data into the 'NwindDataSet.Order_Details' table. You can move, or remove it, as needed. - Me.Order_DetailsTableAdapter.Fill(Me.NwindDataSet.Order_Details) - 'TODO: This line of code loads data into the 'NwindDataSet.Order_Details' table. You can move, or remove it, as needed. - Me.ProductsTableAdapter.Fill(Me.NwindDataSet.Products) - Me.CategoriesTableAdapter.Fill(Me.NwindDataSet.Categories) - RadGridView1.AutoGenerateHierarchy = True - RadGridView1.DataSource = Me.NwindDataSet - RadGridView1.DataMember = "Categories" -End Sub - -```` - -{{endregion}} + + ## Generating Multi-Level Hierarchy @@ -60,34 +32,8 @@ It is possible to auto generate Multi-level hierarchy as well. You should again ![WinForms RadGridView Multi-Level Hierarchy](images/gridview-hierarchical-grid-binding-to-hierarchical-data-automatically002.png) -{{source=..\SamplesCS\GridView\HierarchicalGrid\BindingToHierarchicalGridAutomatically.cs region=BindingToMultiLevelHierarchicalGridAutomatically}} -{{source=..\SamplesVB\GridView\HierarchicalGrid\BindingToHierarchicalGridAutomatically.vb region=BindingToMultiLevelHierarchicalGridAutomatically}} - -````C# - -public void Dummy() -{ - this.productsTableAdapter.Fill(this.nwindDataSet.Products); - this.categoriesTableAdapter.Fill(this.nwindDataSet.Categories); - this.order_DetailsTableAdapter.Fill(this.nwindDataSet.Order_Details); - radGridView1.DataSource = nwindDataSet; - radGridView1.DataMember = "Categories"; - radGridView1.AutoGenerateHierarchy = true; -} - -```` -````VB.NET -Public Sub Dummy() - Me.ProductsTableAdapter.Fill(Me.NwindDataSet.Products) - Me.CategoriesTableAdapter.Fill(Me.NwindDataSet.Categories) - RadGridView1.DataSource = NwindDataSet - RadGridView1.DataMember = "Categories" - RadGridView1.AutoGenerateHierarchy = True -End Sub - -```` - -{{endregion}} + + ![WinForms RadGridView AutoGenerateHierarchy](images/gridview-hierarchical-grid-binding-to-hierarchical-data-automatically003.png) diff --git a/controls/gridview/hierarchical-grid/binding-to-hierarchical-data-programmatically.md b/controls/gridview/hierarchical-grid/binding-to-hierarchical-data-programmatically.md index 317d1afc6..1ba07330c 100644 --- a/controls/gridview/hierarchical-grid/binding-to-hierarchical-data-programmatically.md +++ b/controls/gridview/hierarchical-grid/binding-to-hierarchical-data-programmatically.md @@ -24,52 +24,8 @@ There are many cases when you wouldn't want to include the whole dataset and hie For setting the hierarchy, you will need the special __GridViewRelation__ class, which defines the related field in parent and child tables. Consider the sample below: -{{source=..\SamplesCS\GridView\HierarchicalGrid\BindingToHierarchicalGridProgramatically.cs region=BindingToHierarchicalGridProgramatically}} -{{source=..\SamplesVB\GridView\HierarchicalGrid\BindingToHierarchicalGridProgramatically.vb region=BindingToHierarchicalGridProgramatically}} - -````C# - -private void BindingToHierarchicalGridProgramatically_Load(object sender, EventArgs e) -{ - this.productsTableAdapter.Fill(this.nwindDataSet.Products); - this.suppliersTableAdapter.Fill(this.nwindDataSet.Suppliers); - - radGridView1.DataSource = nwindDataSet.Suppliers; - - GridViewTemplate template = new GridViewTemplate(); - template.DataSource = nwindDataSet.Products; - radGridView1.MasterTemplate.Templates.Add(template); - - GridViewRelation relation = new GridViewRelation(radGridView1.MasterTemplate); - relation.ChildTemplate = template; - relation.RelationName = "SuppliersProducts"; - relation.ParentColumnNames.Add("SupplierID"); - relation.ChildColumnNames.Add("SupplierID"); - radGridView1.Relations.Add(relation); -} - -```` -````VB.NET -Private Sub BindingToHierarchicalGridProgramatically_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load - Me.SuppliersTableAdapter.Fill(Me.NwindDataSet.Suppliers) - Me.ProductsTableAdapter.Fill(Me.NwindDataSet.Products) - RadGridView1.DataSource = NwindDataSet.Suppliers - - Dim template As New GridViewTemplate() - template.DataSource = NwindDataSet.Products - RadGridView1.MasterTemplate.Templates.Add(template) - - Dim relation As New GridViewRelation(RadGridView1.MasterTemplate) - relation.ChildTemplate = template - relation.RelationName = "SuppliersProducts" - relation.ParentColumnNames.Add("SupplierID") - relation.ChildColumnNames.Add("SupplierID") - RadGridView1.Relations.Add(relation) - End Sub - -```` - -{{endregion}} + + >important The column names specified in the relation must be present in the parent and child templates. If you don't want these columns to be shown, just manage their visibility but make sure that they are present in the respective templates. @@ -88,71 +44,8 @@ It is possible to manually set up the child templates and the relations between ![WinForms RadGridView Multi-Level Hierarchy in Bound Mode](images/gridview-hierarchical-grid-binding-to-hierarchical-data-programmatically002.png) -{{source=..\SamplesCS\GridView\HierarchicalGrid\BindingToHierarchicalGridProgramatically.cs region=creatingMultiLevelHierarchicalGridInUnboundMode}} -{{source=..\SamplesVB\GridView\HierarchicalGrid\BindingToHierarchicalGridProgramatically.vb region=creatingMultiLevelHierarchicalGridInUnboundMode}} - -````C# - -private void BindingToMultiLevelHierarchicalGridInBoundMode_Load(object sender, EventArgs e) -{ - this.order_DetailsTableAdapter.Fill(this.nwindDataSet.Order_Details); - this.productsTableAdapter.Fill(this.nwindDataSet.Products); - this.categoriesTableAdapter.Fill(this.nwindDataSet.Categories); - radGridView1.DataSource = nwindDataSet.Categories; - - GridViewTemplate firstChildtemplate = new GridViewTemplate(); - firstChildtemplate.DataSource = nwindDataSet.Products; - radGridView1.MasterTemplate.Templates.Add(firstChildtemplate); - - GridViewRelation relation = new GridViewRelation(radGridView1.MasterTemplate); - relation.ChildTemplate = firstChildtemplate; - relation.RelationName = "CategoriesProducts"; - relation.ParentColumnNames.Add("CategoryID"); - relation.ChildColumnNames.Add("CategoryID"); - radGridView1.Relations.Add(relation); - - GridViewTemplate secondChildtemplate = new GridViewTemplate(); - secondChildtemplate.DataSource = nwindDataSet.Order_Details; - firstChildtemplate.Templates.Add(secondChildtemplate); - - GridViewRelation relation2 = new GridViewRelation(firstChildtemplate); - relation2.ChildTemplate = secondChildtemplate; - relation2.RelationName = "ProductsOrderDetails"; - relation2.ParentColumnNames.Add("ProductID"); - relation2.ChildColumnNames.Add("ProductID"); - radGridView1.Relations.Add(relation2); -} - -```` -````VB.NET -Private Sub BindingToMultiLevelHierarchicalGridInBoundMode_Load(sender As Object, e As EventArgs) - Me.Order_DetailsTableAdapter.Fill(Me.NwindDataSet.Order_Details) - Me.CategoriesTableAdapter.Fill(Me.NwindDataSet.Categories) - Me.ProductsTableAdapter.Fill(Me.NwindDataSet.Products) - radGridView1.DataSource = nwindDataSet.Categories - Dim firstChildtemplate As New GridViewTemplate() - firstChildtemplate.DataSource = nwindDataSet.Products - radGridView1.MasterTemplate.Templates.Add(firstChildtemplate) - Dim relation As New GridViewRelation(radGridView1.MasterTemplate) - relation.ChildTemplate = firstChildtemplate - relation.RelationName = "CategoriesProducts" - relation.ParentColumnNames.Add("CategoryID") - relation.ChildColumnNames.Add("CategoryID") - radGridView1.Relations.Add(relation) - Dim secondChildtemplate As New GridViewTemplate() - secondChildtemplate.DataSource = nwindDataSet.Order_Details - firstChildtemplate.Templates.Add(secondChildtemplate) - Dim relation2 As New GridViewRelation(firstChildtemplate) - relation2.ChildTemplate = secondChildtemplate - relation2.RelationName = "ProductsOrderDetails" - relation2.ParentColumnNames.Add("ProductID") - relation2.ChildColumnNames.Add("ProductID") - radGridView1.Relations.Add(relation2) -End Sub - -```` - -{{endregion}} + + ![WinForms RadGridView Multi-Level Hierarchy](images/gridview-hierarchical-grid-binding-to-hierarchical-data-programmatically003.png) @@ -163,318 +56,15 @@ Setting the hierarchical grid in unbound mode is quite similar to that for the b >note Note that the GridViewRelation is created by using the GridViewDataColumn.Name, not the FieldName. As in the example below it is best if you create the column and pass the FieldName in the column's constructor. This will automatically set its Name to the same value. > -{{source=..\SamplesCS\GridView\PopulatingWithData\UnboundMode.cs region=creatingHierarchicalGridInUnboundMode}} -{{source=..\SamplesVB\GridView\PopulatingWithData\UnboundMode.vb region=creatingHierarchicalGridInUnboundMode}} - -````C# - -public void creatingHierarchicalGridInUnboundMode() -{ - //setup the master template - GridViewImageColumn column = new GridViewImageColumn("Photo"); - column.ImageLayout = ImageLayout.Stretch; - radGridView1.MasterTemplate.Columns.Add(column); - GridViewTextBoxColumn textColumn = new GridViewTextBoxColumn("Name"); - textColumn.Width = 150; - radGridView1.MasterTemplate.Columns.Add(textColumn); - radGridView1.MasterTemplate.Columns.Add(new GridViewDecimalColumn("Salary")); - GridViewDateTimeColumn dateTimeColumn = new GridViewDateTimeColumn("Hire Date"); - dateTimeColumn.Width = 100; - dateTimeColumn.TextAlignment = ContentAlignment.MiddleCenter; - radGridView1.MasterTemplate.Columns.Add(dateTimeColumn); - textColumn = new GridViewTextBoxColumn("Title"); - textColumn.Width = 150; - radGridView1.MasterTemplate.Columns.Add(textColumn); - radGridView1.MasterTemplate.Columns.Add(new GridViewCheckBoxColumn("Active")); - radGridView1.MasterTemplate.Columns.Add(new GridViewCommandColumn("Action")); - - //setup the child template - GridViewTemplate template = new GridViewTemplate(); - template.AllowAddNewRow = true; - template.Columns.Add(new GridViewTextBoxColumn("Name")); - template.Columns.Add(new GridViewTextBoxColumn("Product Number")); - template.Columns.Add(new GridViewDecimalColumn("Quantity")); - template.Columns.Add(new GridViewDecimalColumn("Discount")); - template.Columns.Add(new GridViewDecimalColumn("Total")); - radGridView1.MasterTemplate.Templates.Add(template); - - //create the relation - GridViewRelation relation = new GridViewRelation(radGridView1.MasterTemplate); - relation.ChildTemplate = template; - relation.RelationName = "EmployeesOrders"; - relation.ParentColumnNames.Add("Name"); - relation.ChildColumnNames.Add("Name"); - radGridView1.Relations.Add(relation); - - //load data - LoadUnboundData(); -} - -private void LoadUnboundData() -{ - using (radGridView1.DeferRefresh()) - { - for (int i = 0; i < nwindDataSet.Employees.Count; i++) - { - Random random = new Random((int)DateTime.Now.Ticks); - NwindDataSet.EmployeesRow row = nwindDataSet.Employees[i]; - string name = row.FirstName + " " + row.LastName; - radGridView1.MasterTemplate.Rows.Add(GetImageFromData(row.Photo), name, random.Next(45000), row.HireDate, row.Title, (random.Next(100) > 50), "View"); - GridViewTemplate template = radGridView1.MasterTemplate.Templates[0]; - int rowCount = random.Next(20); - for (int j = 0; j < rowCount; j++) - { - template.Rows.Add(name, random.Next(1000), random.Next(50), random.Next(100), random.Next(10000)); - } - } - } -} - -private Image GetImageFromData(byte[] imageData) -{ - const int OleHeaderLength = 78; - - MemoryStream memoryStream = new MemoryStream(); - - if (HasOleContainerHeader(imageData)) - { - memoryStream.Write(imageData, OleHeaderLength, imageData.Length - OleHeaderLength); - } - else - { - memoryStream.Write(imageData, 0, imageData.Length); - } - - Bitmap bitmap = new Bitmap(memoryStream); - - return bitmap.GetThumbnailImage(55, 65, null, new IntPtr()); -} - -private bool HasOleContainerHeader(byte[] imageByteArray) -{ - const byte OleByte0 = 21; - - const byte OleByte1 = 28; - - return (imageByteArray[0] == OleByte0) && (imageByteArray[1] == OleByte1); -} - -```` -````VB.NET -Public Sub creatingHierarchicalGridInUnboundMode() - 'setup the master template - Dim column As New GridViewImageColumn("Photo") - column.ImageLayout = ImageLayout.Stretch - RadGridView1.MasterTemplate.Columns.Add(column) - Dim textColumn As New GridViewTextBoxColumn("Name") - textColumn.Width = 150 - RadGridView1.MasterTemplate.Columns.Add(textColumn) - RadGridView1.MasterTemplate.Columns.Add(New GridViewDecimalColumn("Salary")) - Dim dateTimeColumn As New GridViewDateTimeColumn("Hire Date") - dateTimeColumn.Width = 100 - dateTimeColumn.TextAlignment = ContentAlignment.MiddleCenter - RadGridView1.MasterTemplate.Columns.Add(dateTimeColumn) - textColumn = New GridViewTextBoxColumn("Title") - textColumn.Width = 150 - RadGridView1.MasterTemplate.Columns.Add(textColumn) - RadGridView1.MasterTemplate.Columns.Add(New GridViewCheckBoxColumn("Active")) - RadGridView1.MasterTemplate.Columns.Add(New GridViewCommandColumn("Action")) - 'setup the child template - Dim template As New GridViewTemplate() - template.AllowAddNewRow = True - template.Columns.Add(New GridViewTextBoxColumn("Name")) - template.Columns.Add(New GridViewTextBoxColumn("Product Number")) - template.Columns.Add(New GridViewDecimalColumn("Quantity")) - template.Columns.Add(New GridViewDecimalColumn("Discount")) - template.Columns.Add(New GridViewDecimalColumn("Total")) - RadGridView1.MasterTemplate.Templates.Add(template) - 'create the relation - Dim relation As New GridViewRelation(RadGridView1.MasterTemplate) - relation.ChildTemplate = template - relation.RelationName = "EmployeesOrders" - relation.ParentColumnNames.Add("Name") - relation.ChildColumnNames.Add("Name") - RadGridView1.Relations.Add(relation) - 'load data - LoadUnboundData() -End Sub -Private Sub LoadUnboundData() - Using RadGridView1.DeferRefresh() - For i As Integer = 0 To NwindDataSet.Employees.Count - 1 - Dim now As Long = Date.Now.Ticks - Dim seed As Integer = CType(now And Integer.MaxValue, Integer) - Dim random As New Random(seed) - Dim row As NwindDataSet.EmployeesRow = NwindDataSet.Employees(i) - Dim name As String = row.FirstName & " " & row.LastName - RadGridView1.MasterTemplate.Rows.Add(GetImageFromData(row.Photo), name, random.Next(45000), row.HireDate, row.Title, (random.Next(100) > 50), "View") - Dim template As GridViewTemplate = RadGridView1.MasterTemplate.Templates(0) - Dim rowCount As Integer = random.Next(20) - For j As Integer = 0 To rowCount - 1 - template.Rows.Add(name, random.Next(1000), random.Next(50), random.Next(100), random.Next(10000)) - Next j - Next i - End Using -End Sub -Private Function GetImageFromData(ByVal imageData() As Byte) As Image - Const OleHeaderLength As Integer = 78 - Dim memoryStream As New MemoryStream() - If HasOleContainerHeader(imageData) Then - memoryStream.Write(imageData, OleHeaderLength, imageData.Length - OleHeaderLength) - Else - memoryStream.Write(imageData, 0, imageData.Length) - End If - Dim bitmap As New Bitmap(memoryStream) - Return bitmap.GetThumbnailImage(55, 65, Nothing, New IntPtr()) -End Function -Private Function HasOleContainerHeader(ByVal imageByteArray() As Byte) As Boolean - Const OleByte0 As Byte = 21 - Const OleByte1 As Byte = 28 - Return (imageByteArray(0) = OleByte0) AndAlso (imageByteArray(1) = OleByte1) -End Function - -```` - -{{endregion}} + + ## Multi-Level Hierarchical Grid in Unbound mode Following the introduced approach in the previous section, the three-level hierarchy can be loaded in unbound mode as follows: -{{source=..\SamplesCS\GridView\PopulatingWithData\UnboundMode.cs region=creatingMultiLevelHierarchicalGridInUnboundMode}} -{{source=..\SamplesVB\GridView\PopulatingWithData\UnboundMode.vb region=creatingMultiLevelHierarchicalGridInUnboundMode}} - -````C# - -public void CreatingMultiLevelHierarchicalGridInUnboundMode() -{ - this.order_DetailsTableAdapter.Fill(this.nwindDataSet.Order_Details); - this.categoriesTableAdapter.Fill(this.nwindDataSet.Categories); - this.productsTableAdapter.Fill(this.nwindDataSet.Products); - radGridView1.MasterTemplate.Columns.Add(new GridViewDecimalColumn("CategoryID")); - radGridView1.MasterTemplate.Columns.Add("CategoryName"); - radGridView1.MasterTemplate.Columns.Add("Description"); - - GridViewTemplate firstChildtemplate = new GridViewTemplate(); - - firstChildtemplate.Columns.Add(new GridViewDecimalColumn("ProductID")); - firstChildtemplate.Columns.Add(new GridViewTextBoxColumn("ProductName")); - firstChildtemplate.Columns.Add(new GridViewDecimalColumn("CategoryID")); - firstChildtemplate.Columns.Add(new GridViewDecimalColumn("SupplierID")); - radGridView1.MasterTemplate.Templates.Add(firstChildtemplate); - - GridViewRelation relation = new GridViewRelation(radGridView1.MasterTemplate); - relation.ChildTemplate = firstChildtemplate; - relation.RelationName = "CategoriesProducts"; - relation.ParentColumnNames.Add("CategoryID"); - relation.ChildColumnNames.Add("CategoryID"); - radGridView1.Relations.Add(relation); - - GridViewTemplate secondChildtemplate = new GridViewTemplate(); - - secondChildtemplate.Columns.Add(new GridViewDecimalColumn("OrderID")); - secondChildtemplate.Columns.Add(new GridViewDecimalColumn("ProductID")); - secondChildtemplate.Columns.Add(new GridViewDecimalColumn("UnitPrice")); - secondChildtemplate.Columns.Add(new GridViewDecimalColumn("Quantity")); - secondChildtemplate.Columns.Add(new GridViewDecimalColumn("Discount")); - firstChildtemplate.Templates.Add(secondChildtemplate); - - GridViewRelation relation2 = new GridViewRelation(firstChildtemplate); - relation2.ChildTemplate = secondChildtemplate; - relation2.RelationName = "ProductsOrderDetails"; - relation2.ParentColumnNames.Add("ProductID"); - relation2.ChildColumnNames.Add("ProductID"); - radGridView1.Relations.Add(relation2); - - LoadDataInUnboundMode(); -} - -private void LoadDataInUnboundMode() -{ - using (radGridView1.DeferRefresh()) - { - GridViewTemplate firstLevelTemplate = radGridView1.MasterTemplate.Templates[0]; - GridViewTemplate secondLevelTemplate = radGridView1.MasterTemplate.Templates[0].Templates[0]; - - for (int i = 0; i < nwindDataSet.Categories.Count; i++) - { - NwindDataSet.CategoriesRow categoryRow = nwindDataSet.Categories[i]; - radGridView1.MasterTemplate.Rows.Add(categoryRow.CategoryID, - categoryRow.CategoryName, categoryRow.Description); - } - - for (int j = 0; j < nwindDataSet.Products.Count; j++) - { - NwindDataSet.ProductsRow productRow = nwindDataSet.Products[j]; - firstLevelTemplate.Rows.Add(productRow.ProductID, productRow.ProductName, - productRow.CategoryID, productRow.SupplierID); - } - for (int k = 0; k < nwindDataSet.Order_Details.Count; k++) - { - NwindDataSet.Order_DetailsRow orderDetailsRow = nwindDataSet.Order_Details[k]; - secondLevelTemplate.Rows.Add(orderDetailsRow.OrderID, orderDetailsRow.ProductID, - orderDetailsRow.UnitPrice, orderDetailsRow.Quantity, orderDetailsRow.Discount); - } - } -} - -```` -````VB.NET -Public Sub CreatingMultiLevelHierarchicalGridInUnboundMode() - Me.Order_DetailsTableAdapter.Fill(Me.NwindDataSet.Order_Details) - Me.CategoriesTableAdapter.Fill(Me.NwindDataSet.Categories) - Me.ProductsTableAdapter.Fill(Me.NwindDataSet.Products) - radGridView1.MasterTemplate.Columns.Add(New GridViewDecimalColumn("CategoryID")) - radGridView1.MasterTemplate.Columns.Add("CategoryName") - radGridView1.MasterTemplate.Columns.Add("Description") - Dim firstChildtemplate As New GridViewTemplate() - firstChildtemplate.Columns.Add(New GridViewDecimalColumn("ProductID")) - firstChildtemplate.Columns.Add(New GridViewTextBoxColumn("ProductName")) - firstChildtemplate.Columns.Add(New GridViewDecimalColumn("CategoryID")) - firstChildtemplate.Columns.Add(New GridViewDecimalColumn("SupplierID")) - radGridView1.MasterTemplate.Templates.Add(firstChildtemplate) - Dim relation As New GridViewRelation(radGridView1.MasterTemplate) - relation.ChildTemplate = firstChildtemplate - relation.RelationName = "CategoriesProducts" - relation.ParentColumnNames.Add("CategoryID") - relation.ChildColumnNames.Add("CategoryID") - radGridView1.Relations.Add(relation) - Dim secondChildtemplate As New GridViewTemplate() - secondChildtemplate.Columns.Add(New GridViewDecimalColumn("OrderID")) - secondChildtemplate.Columns.Add(New GridViewDecimalColumn("ProductID")) - secondChildtemplate.Columns.Add(New GridViewDecimalColumn("UnitPrice")) - secondChildtemplate.Columns.Add(New GridViewDecimalColumn("Quantity")) - secondChildtemplate.Columns.Add(New GridViewDecimalColumn("Discount")) - firstChildtemplate.Templates.Add(secondChildtemplate) - Dim relation2 As New GridViewRelation(firstChildtemplate) - relation2.ChildTemplate = secondChildtemplate - relation2.RelationName = "ProductsOrderDetails" - relation2.ParentColumnNames.Add("ProductID") - relation2.ChildColumnNames.Add("ProductID") - radGridView1.Relations.Add(relation2) - LoadDataInUnboundMode() -End Sub -Private Sub LoadDataInUnboundMode() - Using radGridView1.DeferRefresh() - Dim firstLevelTemplate As GridViewTemplate = radGridView1.MasterTemplate.Templates(0) - Dim secondLevelTemplate As GridViewTemplate = radGridView1.MasterTemplate.Templates(0).Templates(0) - For i As Integer = 0 To nwindDataSet.Categories.Count - 1 - Dim categoryRow As NwindDataSet.CategoriesRow = nwindDataSet.Categories(i) - radGridView1.MasterTemplate.Rows.Add(categoryRow.CategoryID, categoryRow.CategoryName, categoryRow.Description) - Next - For j As Integer = 0 To nwindDataSet.Products.Count - 1 - Dim productRow As NwindDataSet.ProductsRow = nwindDataSet.Products(j) - firstLevelTemplate.Rows.Add(productRow.ProductID, productRow.ProductName, productRow.CategoryID, productRow.SupplierID) - Next - For k As Integer = 0 To nwindDataSet.Order_Details.Count - 1 - Dim orderDetailsRow As NwindDataSet.Order_DetailsRow = nwindDataSet.Order_Details(k) - secondLevelTemplate.Rows.Add(orderDetailsRow.OrderID, orderDetailsRow.ProductID, orderDetailsRow.UnitPrice, orderDetailsRow.Quantity, orderDetailsRow.Discount) - Next - End Using -End Sub - -```` - -{{endregion}} + + ![WinForms RadGridView Multi-Level Hierarchical Grid in Unbound mode](images/gridview-hierarchical-grid-binding-to-hierarchical-data-programmatically004.png) diff --git a/controls/gridview/hierarchical-grid/creating-hierarchy-using-an-xml-data-source.md b/controls/gridview/hierarchical-grid/creating-hierarchy-using-an-xml-data-source.md index f05309270..e0c94069d 100644 --- a/controls/gridview/hierarchical-grid/creating-hierarchy-using-an-xml-data-source.md +++ b/controls/gridview/hierarchical-grid/creating-hierarchy-using-an-xml-data-source.md @@ -114,50 +114,8 @@ This xml file is used in the examples below: The `DataSet` created by __ReadXml__ method for the *given xml above* contains 3 tables which you can avoid easily by skipping the second table and using the first and the third ones only. Note also that *Invoice_Id* and *Parts_Id* columns were added automatically to the tables by the __ReadXml__ method: -{{source=..\SamplesCS\GridView\HierarchicalGrid\CreatingHierarchyUsingXmlDataSource.cs region=CreatingHierarchyUsingXmlDataSource}} -{{source=..\SamplesVB\GridView\HierarchicalGrid\CreatingHierarchyUsingXmlDataSource.vb region=CreatingHierarchyUsingXmlDataSource}} -````C# -void CreatingHierarchyUsingXmlDataSource_Load(object sender, EventArgs e) -{ - DataSet xmlDataSet = new DataSet(); - xmlDataSet.ReadXml("..\\..\\GridView\\HierarchicalGrid\\hierarchicalGridXml.xml"); - GridViewTemplate partsTemplate = new GridViewTemplate(); - this.radGridView1.MasterTemplate.Templates.Add(partsTemplate); - GridViewRelation relation = new GridViewRelation(this.radGridView1.MasterTemplate); - relation.ChildTemplate = partsTemplate; - relation.RelationName = "Invoices_Parts"; - relation.ParentColumnNames.Add("Invoice_Id"); - relation.ChildColumnNames.Add("Parts_Id"); - radGridView1.Relations.Add(relation); - this.radGridView1.DataSource = xmlDataSet.Tables[0]; - partsTemplate.DataSource = xmlDataSet.Tables[2]; - this.radGridView1.MasterTemplate.BestFitColumns(); - this.radGridView1.MasterTemplate.Templates[0].BestFitColumns(); -} - -```` -````VB.NET -Private Sub CreatingHierarchyUsingXmlDataSource_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load - Dim xmlDataSet As New DataSet() - xmlDataSet.ReadXml("..\..\GridView\HierarchicalGrid\hierarchicalGridXml.xml") - Dim partsTemplate As New GridViewTemplate() - Me.RadGridView1.MasterTemplate.Templates.Add(partsTemplate) - Dim relation As New GridViewRelation(Me.RadGridView1.MasterTemplate) - relation.ChildTemplate = partsTemplate - relation.RelationName = "Invoices_Parts" - relation.ParentColumnNames.Add("Invoice_Id") - relation.ChildColumnNames.Add("Parts_Id") - RadGridView1.Relations.Add(relation) - Me.RadGridView1.DataSource = xmlDataSet.Tables(0) - partsTemplate.DataSource = xmlDataSet.Tables(2) - Me.RadGridView1.MasterTemplate.BestFitColumns() - Me.RadGridView1.MasterTemplate.Templates(0).BestFitColumns() - End Sub - -```` - - -{{endregion}} + + ## See Also * [Binding to Hierarchical Data Automatically]({%slug winforms/gridview/hierarchical-grid/binding-to-hierarchical-data-automatically%}) diff --git a/controls/gridview/hierarchical-grid/hierarchy-of-one-to-many-relations.md b/controls/gridview/hierarchical-grid/hierarchy-of-one-to-many-relations.md index 54f5078ef..60ae6a90d 100644 --- a/controls/gridview/hierarchical-grid/hierarchy-of-one-to-many-relations.md +++ b/controls/gridview/hierarchical-grid/hierarchy-of-one-to-many-relations.md @@ -25,76 +25,8 @@ Follow these steps to setup the hierarchy: 4. Run the project. -{{source=..\SamplesCS\GridView\HierarchicalGrid\HierarchyOfOneToManyRelation.cs region=HierarchyOfOneToManyRelation}} -{{source=..\SamplesVB\GridView\HierarchicalGrid\HierarchyOfOneToManyRelation.vb region=HierarchyOfOneToManyRelation}} - -````C# -private void HierarchyOfOneToManyRelation_Load(object sender, EventArgs e) -{ - this.songsTableAdapter.Fill(this.musicCollectionDataSet.Songs); - this.artistsTableAdapter.Fill(this.musicCollectionDataSet.Artists); - this.albumsTableAdapter.Fill(this.musicCollectionDataSet.Albums); - - this.radGridView1.DataSource = albumsBindingSource; - radGridView1.Columns["Image"].ImageLayout = ImageLayout.Zoom; - GridViewTemplate childTemplate1 = new GridViewTemplate(); - childTemplate1.DataSource = artistsBindingSource; - childTemplate1.Columns["Image"].ImageLayout = ImageLayout.Zoom; - childTemplate1.Caption = "Artist"; - - this.radGridView1.MasterTemplate.Templates.Add(childTemplate1); - GridViewRelation relation1 = new GridViewRelation(this.radGridView1.MasterTemplate); - relation1.RelationName = "productmodel_productModelDescription"; - relation1.ParentColumnNames.Add("ArtistID"); - relation1.ChildColumnNames.Add("ArtistID"); - relation1.ChildTemplate = childTemplate1; - this.radGridView1.Relations.Add(relation1); - GridViewTemplate childTemplate2 = new GridViewTemplate(); - childTemplate2.DataSource = songsBindingSource; - childTemplate2.Caption = "Songs"; - this.radGridView1.MasterTemplate.Templates.Add(childTemplate2); - GridViewRelation relation2 = new GridViewRelation(this.radGridView1.MasterTemplate); - relation2.RelationName = "productdescription_productModelDescription"; - relation2.ParentColumnNames.Add("AlbumID"); - relation2.ChildColumnNames.Add("AlbumID"); - relation2.ChildTemplate = childTemplate2; - this.radGridView1.Relations.Add(relation2); -} - -```` -````VB.NET -Private Sub HierarchyOfOneToManyRelation_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load - Me.SongsTableAdapter.Fill(Me.MusicCollectionDataSet.Songs) - Me.ArtistsTableAdapter.Fill(Me.MusicCollectionDataSet.Artists) - Me.AlbumsTableAdapter.Fill(Me.MusicCollectionDataSet.Albums) - Me.RadGridView1.DataSource = AlbumsBindingSource - RadGridView1.Columns("Image").ImageLayout = ImageLayout.Zoom - Dim childTemplate1 As New GridViewTemplate() - childTemplate1.DataSource = ArtistsBindingSource - childTemplate1.Columns("Image").ImageLayout = ImageLayout.Zoom - childTemplate1.Caption = "Artist" - Me.RadGridView1.MasterTemplate.Templates.Add(childTemplate1) - Dim relation1 As New GridViewRelation(Me.RadGridView1.MasterTemplate) - relation1.RelationName = "productmodel_productModelDescription" - relation1.ParentColumnNames.Add("ArtistID") - relation1.ChildColumnNames.Add("ArtistID") - relation1.ChildTemplate = childTemplate1 - Me.RadGridView1.Relations.Add(relation1) - Dim childTemplate2 As New GridViewTemplate() - childTemplate2.DataSource = SongsBindingSource - childTemplate2.Caption = "Songs" - Me.RadGridView1.MasterTemplate.Templates.Add(childTemplate2) - Dim relation2 As New GridViewRelation(Me.RadGridView1.MasterTemplate) - relation2.RelationName = "productdescription_productModelDescription" - relation2.ParentColumnNames.Add("AlbumID") - relation2.ChildColumnNames.Add("AlbumID") - relation2.ChildTemplate = childTemplate2 - Me.RadGridView1.Relations.Add(relation2) -End Sub - -```` - -{{endregion}} + + >note There is an example demonstrating how to build hierarchy containing one-to-many relations in the demo application. > @@ -104,42 +36,8 @@ End Sub In some cases you may want to set custom text to the tabs of the child views different than the text of the template's caption. In this case, the solution is to use the [Formatting events]({%slug winforms/gridview/cells/formatting-cells%}) that RadGridView exposes, and more specifically, the __ViewCellFormatting__ event. This event will give you access to the detail cell that contains the whole `RadPageViewElement` and from this element you will be able to set the text of each tab separately. For example, if we need to display the count of the rows in each view, we can use the following code snippet in order to apply our custom text: -{{source=..\SamplesCS\GridView\HierarchicalGrid\HierarchyOfOneToManyRelation.cs region=formattingTabs}} -{{source=..\SamplesVB\GridView\HierarchicalGrid\HierarchyOfOneToManyRelation.vb region=formattingTabs}} - -````C# -void radGridView1_ViewCellFormatting(object sender, CellFormattingEventArgs e) -{ - GridDetailViewCellElement detailCell = e.CellElement as GridDetailViewCellElement; - if (detailCell != null) - { - for (int i = 0; i < detailCell.PageViewElement.Items.Count; i++) - { - // We take the view that contains the child rows from the corresponding RadPageViewStripItem - GridViewInfo info = (GridViewInfo)detailCell.PageViewElement.Items[i].Tag; - // We set our custom text to the tab, taking the count of rows that the child view has - detailCell.PageViewElement.Items[i].Text = string.Format("{0}, Rows={1}", info.ViewTemplate.Caption, info.Rows.Count.ToString()); - } - } -} - -```` -````VB.NET -Private Sub RadGridView1_ViewCellFormatting(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.CellFormattingEventArgs) Handles RadGridView1.ViewCellFormatting - Dim detailCell As GridDetailViewCellElement = TryCast(e.CellElement, GridDetailViewCellElement) - If detailCell IsNot Nothing Then - For i As Integer = 0 To detailCell.PageViewElement.Items.Count - 1 - ' We take the view that contains the child rows from the corresponding RadPageViewStripItem - Dim info As GridViewInfo = CType(detailCell.PageViewElement.Items(i).Tag, GridViewInfo) - ' We set our custom text to the tab, taking the count of rows that the child view has - detailCell.PageViewElement.Items(i).Text = String.Format("{0}, Rows={1}", info.ViewTemplate.Caption, info.Rows.Count.ToString()) - Next i - End If -End Sub - -```` - -{{endregion}} + + The result is shown on the image below: diff --git a/controls/gridview/hierarchical-grid/how-to/accessing-child-templates.md b/controls/gridview/hierarchical-grid/how-to/accessing-child-templates.md index fd565ac9e..e6eda4203 100644 --- a/controls/gridview/hierarchical-grid/how-to/accessing-child-templates.md +++ b/controls/gridview/hierarchical-grid/how-to/accessing-child-templates.md @@ -12,21 +12,8 @@ previous_url: gridview-hirarchical-grid-how-to-accessing-child-templates # Accessing Child Templates You can programmatically access your child templates using __MasterTemplate.Templates__ collection. For example, use the following code to set the __AutoSizeColumnsMode__ to *Fill* in the first child template : -{{source=..\SamplesCS\GridView\HierarchicalGrid\HowTo\HowTo.cs region=AccessingChildTemplates}} -{{source=..\SamplesVB\GridView\HierarchicalGrid\HowTo\HowTo1.vb region=AccessingChildTemplates}} - -````C# -this.radGridView1.MasterTemplate.Templates[0].AutoSizeColumnsMode = Telerik.WinControls.UI.GridViewAutoSizeColumnsMode.Fill; - -```` -````VB.NET -Me.RadGridView1.MasterTemplate.Templates(0).AutoSizeColumnsMode = Telerik.WinControls.UI.GridViewAutoSizeColumnsMode.Fill - -```` - -{{endregion}} - - + + # See Also * [Applying formatting only to cells in a child template]({%slug winforms/gridview/hierarchical-grid/how-to/applying-formatting-only-to-cells-in-a-child-template%}) diff --git a/controls/gridview/hierarchical-grid/how-to/applying-formatting-only-to-cells-in-a-child-template.md b/controls/gridview/hierarchical-grid/how-to/applying-formatting-only-to-cells-in-a-child-template.md index 32a693a00..388d74ad3 100644 --- a/controls/gridview/hierarchical-grid/how-to/applying-formatting-only-to-cells-in-a-child-template.md +++ b/controls/gridview/hierarchical-grid/how-to/applying-formatting-only-to-cells-in-a-child-template.md @@ -19,33 +19,8 @@ This idea is used in the code snippet below so that the BackColor of the cells l #### Changing the cells BackColor for cells located in a child template -{{source=..\SamplesCS\GridView\HierarchicalGrid\HowTo\HowTo.cs region=example1}} -{{source=..\SamplesVB\GridView\HierarchicalGrid\HowTo\HowTo1.vb region=example1}} - -````C# -void radGridView1_ViewCellFormatting(object sender, CellFormattingEventArgs e) -{ - if (e.CellElement.ViewTemplate.Parent != null) - { - e.CellElement.BackColor = Color.Yellow; - e.CellElement.NumberOfColors = 1; - e.CellElement.DrawFill = true; - } -} - -```` -````VB.NET -Private Sub RadGridView1_ViewCellFormatting(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.CellFormattingEventArgs) Handles RadGridView1.ViewCellFormatting - If e.CellElement.ViewTemplate.Parent IsNot Nothing Then - e.CellElement.BackColor = Color.Yellow - e.CellElement.NumberOfColors = 1 - e.CellElement.DrawFill = True - End If -End Sub - -```` - -{{endregion}} + + ###  Example 2 @@ -53,31 +28,8 @@ You can use the following code snippet to change the header height of the first #### Changing the child template header row height -{{source=..\SamplesCS\GridView\HierarchicalGrid\HowTo\HowTo.cs region=example2}} -{{source=..\SamplesVB\GridView\HierarchicalGrid\HowTo\HowTo1.vb region=example2}} - -````C# -void radGridView1_ViewCellFormatting1(object sender, CellFormattingEventArgs e) -{ - if (e.CellElement.ViewTemplate.Parent != null) - { - e.CellElement.TableElement.TableHeaderHeight = 100; - } -} - -```` -````VB.NET -Private Sub RadGridView1_ViewCellFormatting1(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.CellFormattingEventArgs) Handles RadGridView1.ViewCellFormatting - If e.CellElement.ViewTemplate.Parent IsNot Nothing Then - e.CellElement.TableElement.TableHeaderHeight = 100 - End If -End Sub - -```` - -{{endregion}} - - + + # See Also * [Accessing Child Templates]({%slug winforms/gridview/hierarchical-grid/how-to/accessing-child-templates%}) diff --git a/controls/gridview/hierarchical-grid/how-to/expanding-all-rows.md b/controls/gridview/hierarchical-grid/how-to/expanding-all-rows.md index 4852e0ffc..0908e0394 100644 --- a/controls/gridview/hierarchical-grid/how-to/expanding-all-rows.md +++ b/controls/gridview/hierarchical-grid/how-to/expanding-all-rows.md @@ -13,43 +13,8 @@ previous_url: gridview-hirarchical-grid-how-to-expading-all-rows In order to expand all rows in __RadGridView__ you have to iterate through them and set the __IsExpanded__ property to __true__. The following code snippet demonstrates how to achieve it. You can call the method when the grid is loaded or when you click a button : -{{source=..\SamplesCS\GridView\HierarchicalGrid\HowTo\HowTo.cs region=expandAllRows}} -{{source=..\SamplesVB\GridView\HierarchicalGrid\HowTo\HowTo1.vb region=expandAllRows}} - -````C# -void ExpandAllRows(GridViewTemplate template, bool expanded) -{ - foreach (GridViewRowInfo row in template.Rows) - { - row.IsExpanded = expanded; - } - if (template.Templates.Count > 0) - { - foreach (GridViewTemplate childTemplate in template.Templates) - { - ExpandAllRows(childTemplate, true); - } - } -} - -```` -````VB.NET -Private Sub ExpandAllRows(ByVal template As GridViewTemplate, ByVal expanded As Boolean) - For Each row As GridViewRowInfo In template.Rows - row.IsExpanded = expanded - Next - If template.Templates.Count > 0 Then - For Each childTemplate As GridViewTemplate In template.Templates - ExpandAllRows(childTemplate, True) - Next - End If -End Sub - -```` - -{{endregion}} - - + + # See Also * [Accessing Child Templates]({%slug winforms/gridview/hierarchical-grid/how-to/accessing-child-templates%}) diff --git a/controls/gridview/hierarchical-grid/how-to/iterating-the-child-rows-collection-of-a-chosen-parent-row-in-hierarchy-radgridview.md b/controls/gridview/hierarchical-grid/how-to/iterating-the-child-rows-collection-of-a-chosen-parent-row-in-hierarchy-radgridview.md index cc324ce74..a667e22a3 100644 --- a/controls/gridview/hierarchical-grid/how-to/iterating-the-child-rows-collection-of-a-chosen-parent-row-in-hierarchy-radgridview.md +++ b/controls/gridview/hierarchical-grid/how-to/iterating-the-child-rows-collection-of-a-chosen-parent-row-in-hierarchy-radgridview.md @@ -13,65 +13,8 @@ previous_url: gridview-hirarchical-grid-how-to-iterating-the-child-rows-collecti In order to iterate all child rows in RadGridView, you need to change the ActiveView of each hierarchy row to each of the available Views. This is needed as the grid will create the child rows for the sibling views (tabs in the detail cell) only after they are requested - when the tab is clicked. -{{source=..\SamplesCS\GridView\HierarchicalGrid\HowTo\HowTo.cs region=iterateChildRows}} -{{source=..\SamplesVB\GridView\HierarchicalGrid\HowTo\HowTo1.vb region=iterateChildRows}} - -````C# -void IterateRows() -{ - foreach (GridViewRowInfo row in radGridView1.Rows) - { - Console.WriteLine(row.Cells[1].Value); - GridViewHierarchyRowInfo hierarchyRow = row as GridViewHierarchyRowInfo; - if (hierarchyRow != null) - { - IterateChildRows(hierarchyRow); - } - } -} -private void IterateChildRows(GridViewHierarchyRowInfo rowInfo) -{ - GridViewInfo currentView = rowInfo.ActiveView; - foreach (GridViewInfo view in rowInfo.Views) - { - rowInfo.ActiveView = view; - foreach (GridViewRowInfo row in rowInfo.ChildRows) - { - Console.WriteLine(row.Cells[2].Value); - } - } - rowInfo.ActiveView = currentView; -} - -```` -````VB.NET -Private Sub IterateRows() - For Each row As GridViewRowInfo In radGridView1.Rows - Console.WriteLine(row.Cells(1).Value) - Dim hierarchyRow As GridViewHierarchyRowInfo = TryCast(row, GridViewHierarchyRowInfo) - If hierarchyRow IsNot Nothing Then - IterateChildRows(hierarchyRow) - End If - Next -End Sub -Private Sub IterateChildRows(rowInfo As GridViewHierarchyRowInfo) - Dim currentView As GridViewInfo = rowInfo.ActiveView - For Each view As GridViewInfo In rowInfo.Views - rowInfo.ActiveView = view - For Each row As GridViewRowInfo In rowInfo.ChildRows - Console.WriteLine(row.Cells(2).Value) - Next - Next - rowInfo.ActiveView = currentView -End Sub - -```` - -{{endregion}} - - - - + + # See Also * [Accessing Child Templates]({%slug winforms/gridview/hierarchical-grid/how-to/accessing-child-templates%}) diff --git a/controls/gridview/hierarchical-grid/how-to/resizing-child-gridviewinfo.md b/controls/gridview/hierarchical-grid/how-to/resizing-child-gridviewinfo.md index f9800ded5..1f8cd6d31 100644 --- a/controls/gridview/hierarchical-grid/how-to/resizing-child-gridviewinfo.md +++ b/controls/gridview/hierarchical-grid/how-to/resizing-child-gridviewinfo.md @@ -19,26 +19,8 @@ RadGridView supports resizing child GridViewInfos at runtime by a mouse drag ope Another option for you is to set a custom size for a child GridViewInfo programmatically. In order to do so, subscribe to the ChildViewExpanded event and set the custom size by setting the __Height__ property of the __ChildRow__ to a specific value. Please note that the following code will work only when the __UseScrollbarsInHierarchy__ property is set to *true*. -{{source=..\SamplesCS\GridView\HierarchicalGrid\CreatingHierarchyUsingXmlDataSource.cs region=setChildRowHeight}} -{{source=..\SamplesVB\GridView\HierarchicalGrid\CreatingHierarchyUsingXmlDataSource.vb region=setChildRowHeight}} - -````C# -void radGridView1_ChildViewExpanded(object sender, ChildViewExpandedEventArgs e) -{ - e.ChildRow.Height = 300; -} - -```` -````VB.NET -Private Sub RadGridView1_ChildViewExpanded(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.ChildViewExpandedEventArgs) Handles RadGridView1.ChildViewExpanded - e.ChildRow.Height = 300 -End Sub - -```` - -{{endregion}} - - + + ## See Also * [Accessing Child Templates]({%slug winforms/gridview/hierarchical-grid/how-to/accessing-child-templates%}) diff --git a/controls/gridview/hierarchical-grid/load-on-demand-hierarchy.md b/controls/gridview/hierarchical-grid/load-on-demand-hierarchy.md index d02b7e1c8..952af5011 100644 --- a/controls/gridview/hierarchical-grid/load-on-demand-hierarchy.md +++ b/controls/gridview/hierarchical-grid/load-on-demand-hierarchy.md @@ -41,148 +41,25 @@ Steps to create a Load-On-Demand hierarchy mode: 1\. First, create a columns schema for the first (parent) level of the hierarchy. If RadGridView is in a data-bound mode and we do not need to set a custom schema, we can just set the __DataSource__ property which will set the schema and will populate the parent level with data. You can also set the __AutoSizeColumnsMode__ to *Fill* to get a better view of the data: -{{source=..\SamplesCS\GridView\HierarchicalGrid\LoadOnDemandHierarchy.cs region=bindingRadGridView}} -{{source=..\SamplesVB\GridView\HierarchicalGrid\LoadOnDemandHierarchy.vb region=bindingRadGridView}} - -````C# -this.radGridView1.DataSource = productModelBindingSource; -this.radGridView1.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill; - -```` -````VB.NET -Me.RadGridView1.DataSource = ProductModelBindingSource -Me.RadGridView1.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill - -```` - -{{endregion}} + + 2\. Then, create a Child template and a columns schema for the "Product" data: -{{source=..\SamplesCS\GridView\HierarchicalGrid\LoadOnDemandHierarchy.cs region=childTemplate}} -{{source=..\SamplesVB\GridView\HierarchicalGrid\LoadOnDemandHierarchy.vb region=childTemplate}} - -````C# -private GridViewTemplate CreateChildTemplate() -{ - GridViewTemplate template = new GridViewTemplate(); - template.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill; - GridViewTextBoxColumn namecolumn = new GridViewTextBoxColumn("Name"); - GridViewTextBoxColumn productNumberColumn = new GridViewTextBoxColumn("ProductNumber"); - GridViewTextBoxColumn colorColumn = new GridViewTextBoxColumn("Color"); - GridViewDecimalColumn listPriceColumn = new GridViewDecimalColumn("ListPrice"); - GridViewTextBoxColumn sizeColumn = new GridViewTextBoxColumn("Size"); - GridViewDecimalColumn weightColumn = new GridViewDecimalColumn("Weight"); - GridViewDateTimeColumn discontinuedColumn = new GridViewDateTimeColumn("DiscontinuedDate"); - template.Columns.AddRange(namecolumn, - productNumberColumn, - colorColumn, - listPriceColumn, - sizeColumn, - weightColumn, - discontinuedColumn); - return template; -} - -```` -````VB.NET -Private Function CreateChildTemplate() As GridViewTemplate - Dim template As New GridViewTemplate() - template.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill - Dim namecolumn As New GridViewTextBoxColumn("Name") - Dim productNumberColumn As New GridViewTextBoxColumn("ProductNumber") - Dim colorColumn As New GridViewTextBoxColumn("Color") - Dim listPriceColumn As New GridViewDecimalColumn("ListPrice") - Dim sizeColumn As New GridViewTextBoxColumn("Size") - Dim weightColumn As New GridViewDecimalColumn("Weight") - Dim discontinuedColumn As New GridViewDateTimeColumn("DiscontinuedDate") - template.Columns.AddRange(namecolumn, productNumberColumn, colorColumn, listPriceColumn, sizeColumn, weightColumn, discontinuedColumn) - Return template -End Function - -```` - -{{endregion}} + + 3\. Setup the load-on-demand mode by using GridViewEventDataProvider and RowSourceNeeded event: -{{source=..\SamplesCS\GridView\HierarchicalGrid\LoadOnDemandHierarchy.cs region=loadOnDemandMode}} -{{source=..\SamplesVB\GridView\HierarchicalGrid\LoadOnDemandHierarchy.vb region=loadOnDemandMode}} - -````C# -void Form1_Load(object sender, EventArgs e) -{ - this.productModelTableAdapter.Fill(this.adventureLT2008DataSet.ProductModel); - this.productTableAdapter.Fill(this.adventureLT2008DataSet.Product); - GridViewTemplate childTemplate = CreateChildTemplate(); - this.radGridView1.Templates.Add(childTemplate); - childTemplate.HierarchyDataProvider = new GridViewEventDataProvider(childTemplate); - this.radGridView1.RowSourceNeeded += new GridViewRowSourceNeededEventHandler(radGridView1_RowSourceNeeded); -} - -```` -````VB.NET -Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load - Me.ProductModelTableAdapter.Fill(Me.AdventureLT2008DataSet.ProductModel) - Me.ProductTableAdapter.Fill(Me.AdventureLT2008DataSet.Product) - Dim childTemplate As GridViewTemplate = CreateChildTemplate() - Me.RadGridView1.Templates.Add(childTemplate) - childTemplate.HierarchyDataProvider = New GridViewEventDataProvider(childTemplate) - AddHandler RadGridView1.RowSourceNeeded, AddressOf radGridView1_RowSourceNeeded -End Sub - -```` - -{{endregion}} - + + 4\. Load the data on demand for an expanded parent row by using the __RowSourceNeeded__ event: >important You should make sure that there is a relation between the tables in the dataset. In the bellow example the relation name is "ProductModel_Product" and the relation is between the ProductModelID field in both tables. -{{source=..\SamplesCS\GridView\HierarchicalGrid\LoadOnDemandHierarchy.cs region=handlingRowSourceNeeded}} -{{source=..\SamplesVB\GridView\HierarchicalGrid\LoadOnDemandHierarchy.vb region=handlingRowSourceNeeded}} - -````C# -void radGridView1_RowSourceNeeded(object sender, GridViewRowSourceNeededEventArgs e) -{ - DataRowView rowView = e.ParentRow.DataBoundItem as DataRowView; - DataRow[] rows = rowView.Row.GetChildRows("ProductModel_Product"); - foreach (DataRow dataRow in rows) - { - GridViewRowInfo row = e.Template.Rows.NewRow(); - row.Cells["Name"].Value = dataRow["Name"]; - row.Cells["ProductNumber"].Value = dataRow["ProductNumber"]; - row.Cells["Color"].Value = dataRow["Color"]; - row.Cells["ListPrice"].Value = dataRow["ListPrice"]; - row.Cells["Size"].Value = dataRow["Size"]; - row.Cells["Weight"].Value = dataRow["Weight"]; - row.Cells["DiscontinuedDate"].Value = dataRow["DiscontinuedDate"]; - e.SourceCollection.Add(row); - } -} - -```` -````VB.NET -Private Sub radGridView1_RowSourceNeeded(ByVal sender As Object, ByVal e As GridViewRowSourceNeededEventArgs) - Dim rowView As DataRowView = TryCast(e.ParentRow.DataBoundItem, DataRowView) - Dim rows() As DataRow = rowView.Row.GetChildRows("ProductModel_Product") - For Each dataRow As DataRow In rows - Dim row As GridViewRowInfo = e.Template.Rows.NewRow() - row.Cells("Name").Value = dataRow("Name") - row.Cells("ProductNumber").Value = dataRow("ProductNumber") - row.Cells("Color").Value = dataRow("Color") - row.Cells("ListPrice").Value = dataRow("ListPrice") - row.Cells("Size").Value = dataRow("Size") - row.Cells("Weight").Value = dataRow("Weight") - row.Cells("DiscontinuedDate").Value = dataRow("DiscontinuedDate") - e.SourceCollection.Add(row) - Next dataRow -End Sub - -```` - -{{endregion}} + + This new event based hierarchy mode can be used in different lazy loading scenarios including ORM frameworks, WCF services or complex business objects. diff --git a/controls/gridview/hierarchical-grid/load-on-demand-self-referencing-hierarchy.md b/controls/gridview/hierarchical-grid/load-on-demand-self-referencing-hierarchy.md index 23ffadbe4..22d0c5c7f 100644 --- a/controls/gridview/hierarchical-grid/load-on-demand-self-referencing-hierarchy.md +++ b/controls/gridview/hierarchical-grid/load-on-demand-self-referencing-hierarchy.md @@ -41,276 +41,18 @@ You need to follow these steps to get the load on demand in self-referencing hie 2\. Add relation that represents the hierarchy structure. -{{source=..\SamplesCS\GridView\HierarchicalGrid\LoadOnDemandInSelfRefGrid.cs region=SetupSelfReferenceLoadOnDemandGrid}} -{{source=..\SamplesVB\GridView\HierarchicalGrid\LoadOnDemandInSelfRefGrid.vb region=SetupSelfReferenceLoadOnDemandGrid}} - -````C# -private void SetupSelfReferenceLoadOnDemandGrid() -{ - this.radGridView1.RowSourceNeeded += new GridViewRowSourceNeededEventHandler(RadGridView1_RowSourceNeeded); - this.radGridView1.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill; - this.radGridView1.AllowAddNewRow = false; - - GridViewDataColumn col = new GridViewDecimalColumn(typeof(int), "ID", "ID") { IsVisible = false }; - this.radGridView1.Columns.Add(col); - col = new GridViewDecimalColumn(typeof(int), "ParentID", "ParentID") { IsVisible = false }; - this.radGridView1.Columns.Add(col); - col = new GridViewTextBoxColumn("Name", "Name"); - this.radGridView1.Columns.Add(col); - col = new GridViewDateTimeColumn("Date", "Date"); - this.radGridView1.Columns.Add(col); - col = new GridViewTextBoxColumn("Type", "Type"); - this.radGridView1.Columns.Add(col); - col = new GridViewDecimalColumn(typeof(int), "Size", "Size"); - this.radGridView1.Columns.Add(col); - - // Load on demand - this.radGridView1.Relations.AddSelfReferenceLoadOnDemand(this.radGridView1.MasterTemplate, "ID", "ParentID"); -} - -```` -````VB.NET -Private Sub SetupSelfReferenceLoadOnDemandGrid() - AddHandler Me.RadGridView1.RowSourceNeeded, AddressOf RadGridView1_RowSourceNeeded - Me.radGridView1.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill - Me.radGridView1.AllowAddNewRow = False - Dim col As GridViewDataColumn = New GridViewDecimalColumn(GetType(Integer), "ID", "ID") With {.IsVisible = False} - Me.radGridView1.Columns.Add(col) - col = New GridViewDecimalColumn(GetType(Integer), "ParentID", "ParentID") With {.IsVisible = False} - Me.radGridView1.Columns.Add(col) - col = New GridViewTextBoxColumn("Name", "Name") - Me.radGridView1.Columns.Add(col) - col = New GridViewDateTimeColumn("Date", "Date") - Me.radGridView1.Columns.Add(col) - col = New GridViewTextBoxColumn("Type", "Type") - Me.radGridView1.Columns.Add(col) - col = New GridViewDecimalColumn(GetType(Integer), "Size", "Size") - Me.radGridView1.Columns.Add(col) - Me.radGridView1.Relations.AddSelfReferenceLoadOnDemand(Me.radGridView1.MasterTemplate, "ID", "ParentID") -End Sub - -```` - -{{endregion}} - + + 3\. Handle the **RowsourceNeeded** event to populate the data for each row. -{{source=..\SamplesCS\GridView\HierarchicalGrid\LoadOnDemandInSelfRefGrid.cs region=RowsourceNeeded}} -{{source=..\SamplesVB\GridView\HierarchicalGrid\LoadOnDemandInSelfRefGrid.vb region=RowsourceNeeded}} - -````C# -private void RadGridView1_RowSourceNeeded(object sender, GridViewRowSourceNeededEventArgs e) -{ - if (e.ParentRow == null) - { - // First level of hierarchy - var data = GetData(-1); - foreach (var item in data) - { - GridViewHierarchyRowInfo row = new GridViewHierarchyRowInfo(e.Template.MasterViewInfo); - row.Tag = item; - row.Cells["ID"].Value = item.Id; - row.Cells["ParentID"].Value = item.ParentId; - row.Cells["Name"].Value = item.Name; - row.Cells["Date"].Value = item.Date; - row.Cells["Type"].Value = item.Type; - row.Cells["Size"].Value = item.Size; - - // Setting this property will create Fully lazy mode for load on demand. - row.IsExpandable = item.IsExpandable; - e.SourceCollection.Add(row); - } - } - else - { - FileSystemItem parentItem = e.ParentRow.Tag as FileSystemItem; - if (parentItem.Type == "Folder") - { - var data = GetData(parentItem.Id); - foreach (var item in data) - { - GridViewHierarchyRowInfo row = new GridViewHierarchyRowInfo(e.Template.MasterViewInfo); - row.Tag = item; - row.Cells["ID"].Value = item.Id; - row.Cells["ParentID"].Value = item.ParentId; - row.Cells["Name"].Value = item.Name; - row.Cells["Date"].Value = item.Date; - row.Cells["Type"].Value = item.Type; - row.Cells["Size"].Value = item.Size; - - 'Setting this property will create Fully lazy mode for load on demand. - row.IsExpandable = item.IsExpandable; - e.SourceCollection.Add(row); - } - } - } -} - -```` -````VB.NET - -Private Sub RadGridView1_RowSourceNeeded(sender As Object, e As GridViewRowSourceNeededEventArgs) - If e.ParentRow Is Nothing Then - Dim data = GetData(-1) - - For Each item In data - Dim row As GridViewHierarchyRowInfo = New GridViewHierarchyRowInfo(e.Template.MasterViewInfo) - row.Tag = item - row.Cells("ID").Value = item.Id - row.Cells("ParentID").Value = item.ParentId - row.Cells("Name").Value = item.Name - row.Cells("Date").Value = item.Date - row.Cells("Type").Value = item.Type - row.Cells("Size").Value = item.Size - row.IsExpandable = item.IsExpandable - e.SourceCollection.Add(row) - Next - Else - Dim parentItem As FileSystemItem = TryCast(e.ParentRow.Tag, FileSystemItem) - - If parentItem.type = "Folder" Then - Dim data = GetData(parentItem.Id) - - For Each item In data - Dim row As GridViewHierarchyRowInfo = New GridViewHierarchyRowInfo(e.Template.MasterViewInfo) - row.Tag = item - row.Cells("ID").Value = item.Id - row.Cells("ParentID").Value = item.ParentId - row.Cells("Name").Value = item.Name - row.Cells("Date").Value = item.Date - row.Cells("Type").Value = item.Type - row.Cells("Size").Value = item.Size - row.IsExpandable = item.IsExpandable - e.SourceCollection.Add(row) - Next - End If - End If -End Sub - - -```` - -{{endregion}} + + 4\. Load data that is passed in the RowSourceNeeded event. -{{source=..\SamplesCS\GridView\HierarchicalGrid\LoadOnDemandInSelfRefGrid.cs region=GetData}} -{{source=..\SamplesVB\GridView\HierarchicalGrid\LoadOnDemandInSelfRefGrid.vb region=GetData}} - -````C# - -private static List GetData(int parentId) -{ - var collection = new List(); - if (parentId < 0) - { - collection.Add(new FileSystemItem(1, null, "MyDocuments", DateTime.Now, "Folder", 1024, true)); - collection.Add(new FileSystemItem(4, null, "Windows", DateTime.Now, "Folder", 10240, false)); - collection.Add(new FileSystemItem(5, null, "Users", DateTime.Now, "Folder", 5120, true)); - collection.Add(new FileSystemItem(9, null, "Library", DateTime.Now, "Folder", 3260, true)); - collection.Add(new FileSystemItem(11, null, "Music", DateTime.Now, "Folder", 3680, true)); - } - else if (parentId == 1) - { - collection.Add(new FileSystemItem(2, 1, "Salaries.xlsx", DateTime.Now, "File", 1, false)); - collection.Add(new FileSystemItem(3, 1, "RecesionAnalysis.xlsx", DateTime.Now, "File", 1, false)); - } - else if (parentId == 5) - { - collection.Add(new FileSystemItem(6, 5, "Administrator", DateTime.Now, "Folder", 1512, false)); - collection.Add(new FileSystemItem(7, 5, "Guest", DateTime.Now, "Folder", 2515, false)); - collection.Add(new FileSystemItem(8, 5, "User", DateTime.Now, "Folder", 3512, false)); - } - else if (parentId == 9) - { - collection.Add(new FileSystemItem(10, 9, "Program", DateTime.Now, "Folder", 512, false)); - } - else if (parentId == 11) - { - collection.Add(new FileSystemItem(12, 11, "Podcasts", DateTime.Now, "Folder", 320, false)); - collection.Add(new FileSystemItem(13, 11, "Alternative", DateTime.Now, "Folder", 690, false)); - collection.Add(new FileSystemItem(14, 11, "Rock", DateTime.Now, "Folder", 715, false)); - collection.Add(new FileSystemItem(15, 11, "Classic", DateTime.Now, "Folder", 1060, false)); - } - - return collection; -} - -public class FileSystemItem -{ - public FileSystemItem(int id, int? parentId, string name, DateTime date, string type, int size, bool isExpandable) - { - this.Id = id; - this.ParentId = parentId; - this.Name = name; - this.Date = date; - this.Type = type; - this.Size = size; - this.IsExpandable = isExpandable; - } - public int Id { get; set; } - public int? ParentId { get; set; } - public string Name { get; set; } - public DateTime Date { get; set; } - public string Type { get; set; } - public int Size { get; set; } - public bool IsExpandable { get; set; } -} - -```` -````VB.NET - -Private Shared Function GetData(ByVal parentId As Integer) As List(Of FileSystemItem) - Dim collection = New List(Of FileSystemItem)() - If parentId < 0 Then - collection.Add(New FileSystemItem(1, Nothing, "MyDocuments", DateTime.Now, "Folder", 1024, True)) - collection.Add(New FileSystemItem(4, Nothing, "Windows", DateTime.Now, "Folder", 10240, False)) - collection.Add(New FileSystemItem(5, Nothing, "Users", DateTime.Now, "Folder", 5120, True)) - collection.Add(New FileSystemItem(9, Nothing, "Library", DateTime.Now, "Folder", 3260, True)) - collection.Add(New FileSystemItem(11, Nothing, "Music", DateTime.Now, "Folder", 3680, True)) - ElseIf parentId = 1 Then - collection.Add(New FileSystemItem(2, 1, "Salaries.xlsx", DateTime.Now, "File", 1, False)) - collection.Add(New FileSystemItem(3, 1, "RecesionAnalysis.xlsx", DateTime.Now, "File", 1, False)) - ElseIf parentId = 5 Then - collection.Add(New FileSystemItem(6, 5, "Administrator", DateTime.Now, "Folder", 1512, False)) - collection.Add(New FileSystemItem(7, 5, "Guest", DateTime.Now, "Folder", 2515, False)) - collection.Add(New FileSystemItem(8, 5, "User", DateTime.Now, "Folder", 3512, False)) - ElseIf parentId = 9 Then - collection.Add(New FileSystemItem(10, 9, "Program", DateTime.Now, "Folder", 512, False)) - ElseIf parentId = 11 Then - collection.Add(New FileSystemItem(12, 11, "Podcasts", DateTime.Now, "Folder", 320, False)) - collection.Add(New FileSystemItem(13, 11, "Alternative", DateTime.Now, "Folder", 690, False)) - collection.Add(New FileSystemItem(14, 11, "Rock", DateTime.Now, "Folder", 715, False)) - collection.Add(New FileSystemItem(15, 11, "Classic", DateTime.Now, "Folder", 1060, False)) - End If - Return collection -End Function - -Public Class FileSystemItem - Public Sub New(ByVal id As Integer, ByVal parentId As Integer?, ByVal name As String, ByVal [date] As DateTime, ByVal type As String, ByVal size As Integer, ByVal isExpandable As Boolean) - Me.Id = id - Me.ParentId = parentId - Me.Name = name - Me.Date = [date] - Me.Type = type - Me.Size = size - Me.IsExpandable = isExpandable - End Sub - - Public Property Id As Integer - Public Property ParentId As Integer? - Public Property Name As String - Public Property [Date] As DateTime - Public Property Type As String - Public Property Size As Integer - Public Property IsExpandable As Boolean -End Class - - -```` - -{{endregion}} + + >note Full example in C# and VB is available in our ***Demo >> RadGridView >> Hierarchy*** examples. diff --git a/controls/gridview/hierarchical-grid/object-relational-hierarchy-mode.md b/controls/gridview/hierarchical-grid/object-relational-hierarchy-mode.md index 9d1b368ae..19790889e 100644 --- a/controls/gridview/hierarchical-grid/object-relational-hierarchy-mode.md +++ b/controls/gridview/hierarchical-grid/object-relational-hierarchy-mode.md @@ -25,31 +25,8 @@ Here is an example with an entity model using the Northwind database: ![WinForms RadGridView Generating Hierarchy Mode](images/gridview-hierarchical-grid-object-relational-hierarchy-mode001.png) -{{source=..\SamplesCS\GridView\HierarchicalGrid\AutoGenerateObjectRelationHierarchyMode.cs region=AutoGenerateObjectRelationHierarchyMode}} -{{source=..\SamplesVB\GridView\HierarchicalGrid\AutoGenerateObjectRelationHierarchyMode.vb region=AutoGenerateObjectRelationHierarchyMode}} - -````C# -private void AutoGenerateObjectRelationHierarchyMode_Load(object sender, EventArgs e) -{ - NorthwindEntities entities = new NorthwindEntities(); - var query = from suppliers in entities.Suppliers select suppliers; - this.radGridView1.DataSource = query.ToList(); - this.radGridView1.AutoGenerateHierarchy = true; -} - -```` -````VB.NET -Private Sub AutoGenerateObjectRelationHierarchyMode_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load - Dim entities As New NorthwindEntities() - Dim query = From suppliers In entities.Suppliers Select suppliers - Me.RadGridView1.DataSource = query.ToList() - Me.RadGridView1.AutoGenerateHierarchy = True -End Sub - -```` - -{{endregion}} - + + ![WinForms RadGridView Auto Generating Hierarchy Mode](images/gridview-hierarchical-grid-object-relational-hierarchy-mode002.png) @@ -65,74 +42,8 @@ The following example demonstrates how you can manually build an object-relation ![WinForms RadGridView Manually Generating Hierarchy Mode](images/gridview-hierarchical-grid-object-relational-hierarchy-mode006.png) -{{source=..\SamplesCS\GridView\HierarchicalGrid\ManualGenerateObjectRelationalMode.cs region=ManualGenerateObjectRelationalMode}} -{{source=..\SamplesVB\GridView\HierarchicalGrid\ManualGenerateObjectRelationalMode.vb region=ManualGenerateObjectRelationalMode}} - -````C# -void ManualGenerateObjectRelationalMode_Load(object sender, EventArgs e) -{ - NorthwindEntities entities = new NorthwindEntities(); - var query = from customers in entities.Customers select customers; - GridViewTemplate childTemplate = CreateChildTemplate(); - GridViewRelation relation = new GridViewRelation(this.radGridView1.MasterTemplate, childTemplate); - relation.ChildColumnNames.Add("Orders"); - this.radGridView1.Relations.Add(relation); - this.radGridView1.DataSource = query.ToList(); -} -private GridViewTemplate CreateChildTemplate() -{ - GridViewTemplate childTemplate = new GridViewTemplate(); - this.radGridView1.Templates.Add(childTemplate); - GridViewTextBoxColumn column = new GridViewTextBoxColumn("OrderDate"); - childTemplate.Columns.Add(column); - column = new GridViewTextBoxColumn("Freight"); - childTemplate.Columns.Add(column); - column = new GridViewTextBoxColumn("ShipName"); - childTemplate.Columns.Add(column); - column = new GridViewTextBoxColumn("ShipCountry"); - childTemplate.Columns.Add(column); - column = new GridViewTextBoxColumn("ShipCity"); - childTemplate.Columns.Add(column); - column = new GridViewTextBoxColumn("ShipAddress"); - childTemplate.Columns.Add(column); - childTemplate.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill; - return childTemplate; -} - -```` -````VB.NET -Private Sub ManualGenerateObjectRelationalMode_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load - Dim entities As New NorthwindEntities() - Dim query = From customers In entities.Customers Select customers - Dim childTemplate As GridViewTemplate = CreateChildTemplate() - Dim relation As New GridViewRelation(Me.RadGridView1.MasterTemplate, childTemplate) - relation.ChildColumnNames.Add("Orders") - Me.RadGridView1.Relations.Add(relation) - Me.RadGridView1.DataSource = query.ToList() -End Sub -Private Function CreateChildTemplate() As GridViewTemplate - Dim childTemplate As New GridViewTemplate() - Me.radGridView1.Templates.Add(childTemplate) - Dim column As New GridViewTextBoxColumn("OrderDate") - childTemplate.Columns.Add(column) - column = New GridViewTextBoxColumn("Freight") - childTemplate.Columns.Add(column) - column = New GridViewTextBoxColumn("ShipName") - childTemplate.Columns.Add(column) - column = New GridViewTextBoxColumn("ShipCountry") - childTemplate.Columns.Add(column) - column = New GridViewTextBoxColumn("ShipCity") - childTemplate.Columns.Add(column) - column = New GridViewTextBoxColumn("ShipAddress") - childTemplate.Columns.Add(column) - childTemplate.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill - Return childTemplate -End Function - -```` - -{{endregion}} - + + ![WinForms RadGridView Generating Hierarchy Mode](images/gridview-hierarchical-grid-object-relational-hierarchy-mode004.png) diff --git a/controls/gridview/hierarchical-grid/self-referencing-hierarchy.md b/controls/gridview/hierarchical-grid/self-referencing-hierarchy.md index 5d5cccf83..edaf5abd0 100644 --- a/controls/gridview/hierarchical-grid/self-referencing-hierarchy.md +++ b/controls/gridview/hierarchical-grid/self-referencing-hierarchy.md @@ -29,337 +29,35 @@ In order to achieve the look of the RadGridView from the above image, you need t >important All parent identifiers must be positive numbers. -{{source=..\SamplesCS\GridView\HierarchicalGrid\FileSystemItem.cs region=fileSystemItem}} -{{source=..\SamplesVB\GridView\HierarchicalGrid\FileSystemItem.vb region=fileSystemItem}} - -````C# -public class FileSystemItem -{ - int id; - string name; - DateTime creationTime; - int parentFolderId; - private string type; - public int Id - { - get - { - return id; - } - set - { - id = value; - } - } - public string FileSystemInfoType - { - get - { - return type; - } - set - { - type = value; - } - } - public string Name - { - get - { - return name; - } - set - { - name = value; - } - } - public DateTime CreationTime - { - get - { - return creationTime; - } - set - { - creationTime = value; - } - } - public int ParentFolderId - { - get - { - return parentFolderId; - } - set - { - parentFolderId = value; - } - } - public FileSystemItem(int id, string type, string name, DateTime creationTime, int parentFolderId) - { - this.id = id; - this.type = type; - this.name = name; - this.creationTime = creationTime; - this.parentFolderId = parentFolderId; - } -} - -```` -````VB.NET -Public Class FileSystemItem - Private id_Renamed As Integer - Private name_Renamed As String - Private creationTime_Renamed As Date - Private parentFolderId_Renamed As Integer - Private type As String - Public Property Id() As Integer - Get - Return id_Renamed - End Get - Set(ByVal value As Integer) - id_Renamed = value - End Set - End Property - Public Property FileSystemInfoType() As String - Get - Return type - End Get - Set(ByVal value As String) - type = value - End Set - End Property - Public Property Name() As String - Get - Return name_Renamed - End Get - Set(ByVal value As String) - name_Renamed = value - End Set - End Property - Public Property CreationTime() As Date - Get - Return creationTime_Renamed - End Get - Set(ByVal value As Date) - creationTime_Renamed = value - End Set - End Property - Public Property ParentFolderId() As Integer - Get - Return parentFolderId_Renamed - End Get - Set(ByVal value As Integer) - parentFolderId_Renamed = value - End Set - End Property - Public Sub New(ByVal id As Integer, ByVal type As String, ByVal name As String, ByVal creationTime As Date, ByVal parentFolderId As Integer) - Me.id_Renamed = id - Me.type = type - Me.name_Renamed = name - Me.creationTime_Renamed = creationTime - Me.parentFolderId_Renamed = parentFolderId - End Sub -End Class - -```` - -{{endregion}} + + 2\. Fill a BindingList with objects of type FileSystemItem. The content of the list will depend on the content of the "C:\Program Files (x86)\Telerik" folder: -{{source=..\SamplesCS\GridView\HierarchicalGrid\SelfReferencingHierarchy.cs region=fillingList}} -{{source=..\SamplesVB\GridView\HierarchicalGrid\SelfReferencingHierarchy.vb region=fillingList}} - -````C# -BindingList list = new BindingList(); -int fileFolderIndex = 0; -public void GetFilesAndFolders(string dir, int parentId) -{ - DirectoryInfo di = new DirectoryInfo(dir); - FileInfo[] rgFiles = di.GetFiles(); - foreach (FileInfo fi in rgFiles) - { - fileFolderIndex++; - list.Add(new FileSystemItem(fileFolderIndex, "File", fi.Name, fi.CreationTime, parentId)); - } - DirectoryInfo[] dirs = di.GetDirectories(); - foreach (DirectoryInfo d in dirs) - { - fileFolderIndex++; - list.Add(new FileSystemItem(fileFolderIndex, "Folder", d.Name, d.CreationTime, parentId)); - GetFilesAndFolders(d.FullName, fileFolderIndex); - } -} - -```` -````VB.NET -Private list As New BindingList(Of FileSystemItem)() -Private fileFolderIndex As Integer = 0 -Public Sub GetFilesAndFolders(ByVal dir As String, ByVal parentId As Integer) - Dim di As New DirectoryInfo(dir) - Dim rgFiles() As FileInfo = di.GetFiles() - For Each fi As FileInfo In rgFiles - fileFolderIndex += 1 - list.Add(New FileSystemItem(fileFolderIndex, "File", fi.Name, fi.CreationTime, parentId)) - Next fi - Dim dirs() As DirectoryInfo = di.GetDirectories() - For Each d As DirectoryInfo In dirs - fileFolderIndex += 1 - list.Add(New FileSystemItem(fileFolderIndex, "Folder", d.Name, d.CreationTime, parentId)) - GetFilesAndFolders(d.FullName, fileFolderIndex) - Next d -End Sub - -```` - -{{endregion}} + + 3\. The most important step of this example - setting up the self-referencing mode of RadGridView. To do this, you should call the __AddSelfReference__ method of the __Relations__ collection passing the template that should reflect the structure of the business object and the properties that should determine the parent-child relation: -{{source=..\SamplesCS\GridView\HierarchicalGrid\SelfReferencingHierarchy.cs region=addSelfReference}} -{{source=..\SamplesVB\GridView\HierarchicalGrid\SelfReferencingHierarchy.vb region=addSelfReference}} - -````C# -this.radGridView1.Relations.AddSelfReference(this.radGridView1.MasterTemplate, "Id", "ParentFolderId"); -this.radGridView1.DataSource = list; - -```` -````VB.NET -Me.RadGridView1.Relations.AddSelfReference(Me.RadGridView1.MasterTemplate, "Id", "ParentFolderId") -Me.RadGridView1.DataSource = list - -```` - -{{endregion}} + + 4\. Hide the columns that are not useful to your clients. These columns in our case are `Id`, `ParentFolderId` and `FileSystemInfoType`: -{{source=..\SamplesCS\GridView\HierarchicalGrid\SelfReferencingHierarchy.cs region=hideColumns}} -{{source=..\SamplesVB\GridView\HierarchicalGrid\SelfReferencingHierarchy.vb region=hideColumns}} - -````C# -this.radGridView1.Columns["Id"].IsVisible = false; -this.radGridView1.Columns["ParentFolderId"].IsVisible = false; -this.radGridView1.Columns["FileSystemInfoType"].IsVisible = false; - -```` -````VB.NET -Me.RadGridView1.Columns("Id").IsVisible = False -Me.RadGridView1.Columns("ParentFolderId").IsVisible = False -Me.RadGridView1.Columns("FileSystemInfoType").IsVisible = False - -```` - -{{endregion}} + + 5\. Last, but not least, you may want to show different images depending on the actual file system types. To do this, you should handle the __CellFormatting__ event, check if the `FileSystemInfoType` is *File* or *Folder* and set the appropriate image accordingly: -{{source=..\SamplesCS\GridView\HierarchicalGrid\SelfReferencingHierarchy.cs region=settingImagesToCells}} -{{source=..\SamplesVB\GridView\HierarchicalGrid\SelfReferencingHierarchy.vb region=settingImagesToCells}} - -````C# -// Getting the images from the resources of the project -Image documentImage = SamplesCS.Properties.Resources.Document; -Image folderImage = SamplesCS.Properties.Resources.Folder; -void radGridView1_CellFormatting(object sender, Telerik.WinControls.UI.CellFormattingEventArgs e) -{ - GridDataCellElement dataCell = e.CellElement as GridDataCellElement; - if (dataCell.ColumnInfo.Name == "Name") - { - GridViewDataRowInfo dataRow = dataCell.RowInfo as GridViewDataRowInfo; - if (dataRow != null) - { - dataCell.ImageAlignment = ContentAlignment.MiddleLeft; - string valueType = Convert.ToString(dataRow.Cells["FileSystemInfoType"].Value).ToUpperInvariant(); - if (valueType.Contains("FILE")) - { - dataCell.Image = documentImage; - } - else - { - dataCell.Image = folderImage; - } - dataCell.TextImageRelation = TextImageRelation.ImageBeforeText; - } - } - else - { - dataCell.ResetValue(LightVisualElement.ImageProperty, Telerik.WinControls.ValueResetFlags.Local); - dataCell.ResetValue(LightVisualElement.ImageAlignmentProperty, Telerik.WinControls.ValueResetFlags.Local); - dataCell.ResetValue(LightVisualElement.TextImageRelationProperty, Telerik.WinControls.ValueResetFlags.Local); - dataCell.ResetValue(LightVisualElement.ImageLayoutProperty, Telerik.WinControls.ValueResetFlags.Local); - } -} - -```` -````VB.NET -' Getting the images from the resources of the project -Private documentImage As Image = SamplesVB.My.Resources.Document -Private folderImage As Image = SamplesVB.My.Resources.Folder -Private Sub radGridView1_CellFormatting(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.CellFormattingEventArgs) - Dim dataCell As GridDataCellElement = TryCast(e.CellElement, GridDataCellElement) - If dataCell.ColumnInfo.Name = "Name" Then - Dim dataRow As GridViewDataRowInfo = TryCast(dataCell.RowInfo, GridViewDataRowInfo) - If dataRow IsNot Nothing Then - dataCell.ImageAlignment = ContentAlignment.MiddleLeft - Dim valueType As String = Convert.ToString(dataRow.Cells("FileSystemInfoType").Value).ToUpperInvariant() - If valueType.Contains("FILE") Then - dataCell.Image = documentImage - Else - dataCell.Image = folderImage - End If - dataCell.TextImageRelation = TextImageRelation.ImageBeforeText - End If - Else - dataCell.ResetValue(LightVisualElement.ImageProperty, Telerik.WinControls.ValueResetFlags.Local) - dataCell.ResetValue(LightVisualElement.ImageAlignmentProperty, Telerik.WinControls.ValueResetFlags.Local) - dataCell.ResetValue(LightVisualElement.TextImageRelationProperty, Telerik.WinControls.ValueResetFlags.Local) - dataCell.ResetValue(LightVisualElement.ImageLayoutProperty, Telerik.WinControls.ValueResetFlags.Local) - End If -End Sub - -```` - -{{endregion}} - + + It is possible to put the self-reference expander in any column by setting the __SelfReferenceExpanderColumn__ property of the __MasterTemplate__: ![WinForms RadGridView SelfReferenceExpanderColumn](images/gridview-hierarchical-grid-self-referencing-hierarchy003.png) -{{source=..\SamplesCS\GridView\HierarchicalGrid\SelfReferencingHierarchy.cs region=SelfReferenceExpanderColumn}} -{{source=..\SamplesVB\GridView\HierarchicalGrid\SelfReferencingHierarchy.vb region=SelfReferenceExpanderColumn}} - -````C# -this.radGridView1.MasterTemplate.SelfReferenceExpanderColumn = this.radGridView1.Columns["ParentFolderId"]; - -```` -````VB.NET -Me.RadGridView1.MasterTemplate.SelfReferenceExpanderColumn = Me.RadGridView1.Columns("ParentFolderId") -'#End Region -End Sub -'#region fillingList -Private list As New BindingList(Of FileSystemItem)() -Private fileFolderIndex As Integer = 0 -Public Sub GetFilesAndFolders(ByVal dir As String, ByVal parentId As Integer) -Dim di As New DirectoryInfo(dir) -Dim rgFiles() As FileInfo = di.GetFiles() -For Each fi As FileInfo In rgFiles - fileFolderIndex += 1 - list.Add(New FileSystemItem(fileFolderIndex, "File", fi.Name, fi.CreationTime, parentId)) -Next fi -Dim dirs() As DirectoryInfo = di.GetDirectories() -For Each d As DirectoryInfo In dirs - fileFolderIndex += 1 - list.Add(New FileSystemItem(fileFolderIndex, "Folder", d.Name, d.CreationTime, parentId)) - GetFilesAndFolders(d.FullName, fileFolderIndex) -Next d -End Sub - -```` - -{{endregion}} + + >note You can use the __TableElement.ShowSelfReferenceLines__ property to show lines that are connecting the parent/child rows. > diff --git a/controls/gridview/localization/localization.md b/controls/gridview/localization/localization.md index 90b927735..aa93de469 100644 --- a/controls/gridview/localization/localization.md +++ b/controls/gridview/localization/localization.md @@ -25,669 +25,15 @@ Below is a sample implementation of an English localization provider: #### Localizing RadGridView Strings -{{source=..\SamplesCS\GridView\Localization\MyEnglishRadGridLocalizationProvider.cs region=myEnglishLocalizationProvider}} -{{source=..\SamplesVB\GridView\Localization\MyEnglishRadGridLocalizationProvider.vb region=myEnglishLocalizationProvider}} - -````C# -public class MyEnglishRadGridLocalizationProvider : RadGridLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case RadGridStringId.ConditionalFormattingPleaseSelectValidCellValue: return "Please select valid cell value"; - case RadGridStringId.ConditionalFormattingPleaseSetValidCellValue: return "Please set a valid cell value"; - case RadGridStringId.ConditionalFormattingPleaseSetValidCellValues: return "Please set a valid cell values"; - case RadGridStringId.ConditionalFormattingPleaseSetValidExpression: return "Please set a valid expression"; - case RadGridStringId.ConditionalFormattingItem: return "Item"; - case RadGridStringId.ConditionalFormattingInvalidParameters: return "Invalid parameters"; - case RadGridStringId.FilterFunctionBetween: return "Between"; - case RadGridStringId.FilterFunctionContains: return "Contains"; - case RadGridStringId.FilterFunctionDoesNotContain: return "Does not contain"; - case RadGridStringId.FilterFunctionEndsWith: return "Ends with"; - case RadGridStringId.FilterFunctionEqualTo: return "Equals"; - case RadGridStringId.FilterFunctionGreaterThan: return "Greater than"; - case RadGridStringId.FilterFunctionGreaterThanOrEqualTo: return "Greater than or equal to"; - case RadGridStringId.FilterFunctionIsEmpty: return "Is empty"; - case RadGridStringId.FilterFunctionIsNull: return "Is null"; - case RadGridStringId.FilterFunctionLessThan: return "Less than"; - case RadGridStringId.FilterFunctionLessThanOrEqualTo: return "Less than or equal to"; - case RadGridStringId.FilterFunctionNoFilter: return "No filter"; - case RadGridStringId.FilterFunctionNotBetween: return "Not between"; - case RadGridStringId.FilterFunctionNotEqualTo: return "Not equal to"; - case RadGridStringId.FilterFunctionNotIsEmpty: return "Is not empty"; - case RadGridStringId.FilterFunctionNotIsNull: return "Is not null"; - case RadGridStringId.FilterFunctionStartsWith: return "Starts with"; - case RadGridStringId.FilterFunctionCustom: return "Custom"; - case RadGridStringId.FilterOperatorBetween: return "Between"; - case RadGridStringId.FilterOperatorContains: return "Contains"; - case RadGridStringId.FilterOperatorDoesNotContain: return "NotContains"; - case RadGridStringId.FilterOperatorEndsWith: return "EndsWith"; - case RadGridStringId.FilterOperatorEqualTo: return "Equals"; - case RadGridStringId.FilterOperatorGreaterThan: return "GreaterThan"; - case RadGridStringId.FilterOperatorGreaterThanOrEqualTo: return "GreaterThanOrEquals"; - case RadGridStringId.FilterOperatorIsEmpty: return "IsEmpty"; - case RadGridStringId.FilterOperatorIsNull: return "IsNull"; - case RadGridStringId.FilterOperatorLessThan: return "LessThan"; - case RadGridStringId.FilterOperatorLessThanOrEqualTo: return "LessThanOrEquals"; - case RadGridStringId.FilterOperatorNoFilter: return "No filter"; - case RadGridStringId.FilterOperatorNotBetween: return "NotBetween"; - case RadGridStringId.FilterOperatorNotEqualTo: return "NotEquals"; - case RadGridStringId.FilterOperatorNotIsEmpty: return "NotEmpty"; - case RadGridStringId.FilterOperatorNotIsNull: return "NotNull"; - case RadGridStringId.FilterOperatorStartsWith: return "StartsWith"; - case RadGridStringId.FilterOperatorIsLike: return "Like"; - case RadGridStringId.FilterOperatorNotIsLike: return "NotLike"; - case RadGridStringId.FilterOperatorIsContainedIn: return "ContainedIn"; - case RadGridStringId.FilterOperatorNotIsContainedIn: return "NotContainedIn"; - case RadGridStringId.FilterOperatorCustom: return "Custom"; - case RadGridStringId.CustomFilterMenuItem: return "Custom"; - case RadGridStringId.CustomFilterDialogCaption: return "Filter Dialog [{0}]"; - case RadGridStringId.CustomFilterDialogLabel: return "Show rows where:"; - case RadGridStringId.CustomFilterDialogRbAnd: return "And"; - case RadGridStringId.CustomFilterDialogRbOr: return "Or"; - case RadGridStringId.CustomFilterDialogBtnOk: return "OK"; - case RadGridStringId.CustomFilterDialogBtnCancel: return "Cancel"; - case RadGridStringId.CustomFilterDialogCheckBoxNot: return "Not"; - case RadGridStringId.CustomFilterDialogTrue: return "True"; - case RadGridStringId.CustomFilterDialogFalse: return "False"; - case RadGridStringId.FilterMenuBlanks: return "(Blanks)"; - case RadGridStringId.FilterMenuAvailableFilters: return "Available Filters"; - case RadGridStringId.FilterMenuSearchBoxText: return "Search..."; - case RadGridStringId.FilterMenuClearFilters: return "Clear Filter"; - case RadGridStringId.FilterMenuButtonOK: return "OK"; - case RadGridStringId.FilterMenuButtonCancel: return "Cancel"; - case RadGridStringId.FilterMenuSelectionAll: return "All"; - case RadGridStringId.FilterMenuSelectionAllSearched: return "All Search Result"; - case RadGridStringId.FilterMenuSelectionNull: return "Null"; - case RadGridStringId.FilterMenuSelectionNotNull: return "Not Null"; - case RadGridStringId.FilterFunctionSelectedDates: return "Filter by specific dates:"; - case RadGridStringId.FilterFunctionToday: return "Today"; - case RadGridStringId.FilterFunctionYesterday: return "Yesterday"; - case RadGridStringId.FilterFunctionDuringLast7days: return "During last 7 days"; - case RadGridStringId.FilterLogicalOperatorAnd: return "AND"; - case RadGridStringId.FilterLogicalOperatorOr: return "OR"; - case RadGridStringId.FilterCompositeNotOperator: return "NOT"; - case RadGridStringId.DeleteRowMenuItem: return "Delete Row"; - case RadGridStringId.SortAscendingMenuItem: return "Sort Ascending"; - case RadGridStringId.SortDescendingMenuItem: return "Sort Descending"; - case RadGridStringId.ClearSortingMenuItem: return "Clear Sorting"; - case RadGridStringId.ConditionalFormattingMenuItem: return "Conditional Formatting"; - case RadGridStringId.GroupByThisColumnMenuItem: return "Group by this column"; - case RadGridStringId.UngroupThisColumn: return "Ungroup this column"; - case RadGridStringId.ColumnChooserMenuItem: return "Column Chooser"; - case RadGridStringId.ShowMenuItem: return "Show Column"; - case RadGridStringId.HideMenuItem: return "Hide Column"; - case RadGridStringId.HideGroupMenuItem: return "Hide Group"; - case RadGridStringId.UnpinMenuItem: return "Unpin Column"; - case RadGridStringId.UnpinRowMenuItem: return "Unpin Row"; - case RadGridStringId.PinMenuItem: return "Pinned state"; - case RadGridStringId.PinAtLeftMenuItem: return "Pin at left"; - case RadGridStringId.PinAtRightMenuItem: return "Pin at right"; - case RadGridStringId.PinAtBottomMenuItem: return "Pin at bottom"; - case RadGridStringId.PinAtTopMenuItem: return "Pin at top"; - case RadGridStringId.BestFitMenuItem: return "Best Fit"; - case RadGridStringId.PasteMenuItem: return "Paste"; - case RadGridStringId.EditMenuItem: return "Edit"; - case RadGridStringId.ClearValueMenuItem: return "Clear Value"; - case RadGridStringId.CopyMenuItem: return "Copy"; - case RadGridStringId.CutMenuItem: return "Cut"; - case RadGridStringId.AddNewRowString: return "Click here to add a new row"; - case RadGridStringId.ConditionalFormattingSortAlphabetically: return "Sort columns alphabetically"; - case RadGridStringId.ConditionalFormattingCaption: return "Conditional Formatting Rules Manager"; - case RadGridStringId.ConditionalFormattingLblColumn: return "Format only cells with"; - case RadGridStringId.ConditionalFormattingLblName: return "Rule name"; - case RadGridStringId.ConditionalFormattingLblType: return "Cell value"; - case RadGridStringId.ConditionalFormattingLblValue1: return "Value 1"; - case RadGridStringId.ConditionalFormattingLblValue2: return "Value 2"; - case RadGridStringId.ConditionalFormattingGrpConditions: return "Rules"; - case RadGridStringId.ConditionalFormattingGrpProperties: return "Rule Properties"; - case RadGridStringId.ConditionalFormattingChkApplyToRow: return "Apply this formatting to entire row"; - case RadGridStringId.ConditionalFormattingChkApplyOnSelectedRows: return "Apply this formatting if the row is selected"; - case RadGridStringId.ConditionalFormattingBtnAdd: return "Add new rule"; - case RadGridStringId.ConditionalFormattingBtnRemove: return "Remove"; - case RadGridStringId.ConditionalFormattingBtnOK: return "OK"; - case RadGridStringId.ConditionalFormattingBtnCancel: return "Cancel"; - case RadGridStringId.ConditionalFormattingBtnApply: return "Apply"; - case RadGridStringId.ConditionalFormattingRuleAppliesOn: return "Rule applies to"; - case RadGridStringId.ConditionalFormattingCondition: return "Condition"; - case RadGridStringId.ConditionalFormattingExpression: return "Expression"; - case RadGridStringId.ConditionalFormattingChooseOne: return "[Choose one]"; - case RadGridStringId.ConditionalFormattingEqualsTo: return "equals to [Value1]"; - case RadGridStringId.ConditionalFormattingIsNotEqualTo: return "is not equal to [Value1]"; - case RadGridStringId.ConditionalFormattingStartsWith: return "starts with [Value1]"; - case RadGridStringId.ConditionalFormattingEndsWith: return "ends with [Value1]"; - case RadGridStringId.ConditionalFormattingContains: return "contains [Value1]"; - case RadGridStringId.ConditionalFormattingDoesNotContain: return "does not contain [Value1]"; - case RadGridStringId.ConditionalFormattingIsGreaterThan: return "is greater than [Value1]"; - case RadGridStringId.ConditionalFormattingIsGreaterThanOrEqual: return "is greater than or equal [Value1]"; - case RadGridStringId.ConditionalFormattingIsLessThan: return "is less than [Value1]"; - case RadGridStringId.ConditionalFormattingIsLessThanOrEqual: return "is less than or equal to [Value1]"; - case RadGridStringId.ConditionalFormattingIsBetween: return "is between [Value1] and [Value2]"; - case RadGridStringId.ConditionalFormattingIsNotBetween: return "is not between [Value1] and [Value1]"; - case RadGridStringId.ConditionalFormattingLblFormat: return "Format"; - case RadGridStringId.ConditionalFormattingBtnExpression: return "Expression editor"; - case RadGridStringId.ConditionalFormattingTextBoxExpression: return "Expression"; - case RadGridStringId.ConditionalFormattingPropertyGridCaseSensitive: return "CaseSensitive"; - case RadGridStringId.ConditionalFormattingPropertyGridCellBackColor: return "CellBackColor"; - case RadGridStringId.ConditionalFormattingPropertyGridCellForeColor: return "CellForeColor"; - case RadGridStringId.ConditionalFormattingPropertyGridEnabled: return "Enabled"; - case RadGridStringId.ConditionalFormattingPropertyGridRowBackColor: return "RowBackColor"; - case RadGridStringId.ConditionalFormattingPropertyGridRowForeColor: return "RowForeColor"; - case RadGridStringId.ConditionalFormattingPropertyGridRowFont: return "RowFont"; - case RadGridStringId.ConditionalFormattingPropertyGridRowTextAlignment: return "RowTextAlignment"; - case RadGridStringId.ConditionalFormattingPropertyGridTextAlignment: return "TextAlignment"; - case RadGridStringId.ConditionalFormattingPropertyGridCellFont: return "CellFont"; - case RadGridStringId.ConditionalFormattingPropertyGridCellFontDescription: return "Enter the font to be used for the cell."; - case RadGridStringId.ConditionalFormattingPropertyGridCaseSensitiveDescription: return "Determines whether case-sensitive comparisons will be made when evaluating string values."; - case RadGridStringId.ConditionalFormattingPropertyGridCellBackColorDescription: return "Enter the background color to be used for the cell."; - case RadGridStringId.ConditionalFormattingPropertyGridCellForeColorDescription: return "Enter the foreground color to be used for the cell."; - case RadGridStringId.ConditionalFormattingPropertyGridEnabledDescription: return "Determines whether the condition is enabled (can be evaluated and applied)."; - case RadGridStringId.ConditionalFormattingPropertyGridRowBackColorDescription: return "Enter the background color to be used for the entire row."; - case RadGridStringId.ConditionalFormattingPropertyGridRowForeColorDescription: return "Enter the foreground color to be used for the entire row."; - case RadGridStringId.ConditionalFormattingPropertyGridRowFontDescription: return "Enter the font to be used for the entire row."; - case RadGridStringId.ConditionalFormattingPropertyGridRowTextAlignmentDescription: return "Enter the alignment to be used for the cell values, when ApplyToRow is true."; - case RadGridStringId.ConditionalFormattingPropertyGridTextAlignmentDescription: return "Enter the alignment to be used for the cell values."; - case RadGridStringId.ColumnChooserFormCaption: return "Column Chooser"; - case RadGridStringId.ColumnChooserFormMessage: return "Drag a column header from the grid here to remove it from the current view."; - case RadGridStringId.ColumnChooserFilterTextBoxNullText: return "Filter"; - case RadGridStringId.GroupingPanelDefaultMessage: return "Drag a column here to group by this column."; - case RadGridStringId.GroupingPanelHeader: return "Group by:"; - case RadGridStringId.PagingPanelPagesLabel: return "Page"; - case RadGridStringId.PagingPanelOfPagesLabel: return "of"; - case RadGridStringId.NoDataText: return "No data to display"; - case RadGridStringId.CompositeFilterFormErrorCaption: return "Filter Error"; - case RadGridStringId.CompositeFilterFormInvalidFilter: return "The composite filter descriptor is not valid."; - case RadGridStringId.ExpressionMenuItem: return "Expression"; - case RadGridStringId.ExpressionFormTitle: return "Expression Builder"; - case RadGridStringId.ExpressionFormFunctions: return "Functions"; - case RadGridStringId.ExpressionFormFunctionsText: return "Text"; - case RadGridStringId.ExpressionFormFunctionsAggregate: return "Aggregate"; - case RadGridStringId.ExpressionFormFunctionsDateTime: return "Date-Time"; - case RadGridStringId.ExpressionFormFunctionsLogical: return "Logical"; - case RadGridStringId.ExpressionFormFunctionsMath: return "Math"; - case RadGridStringId.ExpressionFormFunctionsOther: return "Other"; - case RadGridStringId.ExpressionFormOperators: return "Operators"; - case RadGridStringId.ExpressionFormConstants: return "Constants"; - case RadGridStringId.ExpressionFormFields: return "Fields"; - case RadGridStringId.ExpressionFormDescription: return "Description"; - case RadGridStringId.ExpressionFormResultPreview: return "Result preview"; - case RadGridStringId.ExpressionFormTooltipPlus: return "Plus"; - case RadGridStringId.ExpressionFormTooltipMinus: return "Minus"; - case RadGridStringId.ExpressionFormTooltipMultiply: return "Multiply"; - case RadGridStringId.ExpressionFormTooltipDivide: return "Divide"; - case RadGridStringId.ExpressionFormTooltipModulo: return "Modulo"; - case RadGridStringId.ExpressionFormTooltipEqual: return "Equal"; - case RadGridStringId.ExpressionFormTooltipNotEqual: return "Not Equal"; - case RadGridStringId.ExpressionFormTooltipLess: return "Less"; - case RadGridStringId.ExpressionFormTooltipLessOrEqual: return "Less Or Equal"; - case RadGridStringId.ExpressionFormTooltipGreaterOrEqual: return "Greater Or Equal"; - case RadGridStringId.ExpressionFormTooltipGreater: return "Greater"; - case RadGridStringId.ExpressionFormTooltipAnd: return "Logical \"AND\""; - case RadGridStringId.ExpressionFormTooltipOr: return "Logical \"OR\""; - case RadGridStringId.ExpressionFormTooltipNot: return "Logical \"NOT\""; - case RadGridStringId.ExpressionFormAndButton: return string.Empty; //if empty, default button image is used - case RadGridStringId.ExpressionFormOrButton: return string.Empty; //if empty, default button image is used - case RadGridStringId.ExpressionFormNotButton: return string.Empty; //if empty, default button image is used - case RadGridStringId.ExpressionFormOKButton: return "OK"; - case RadGridStringId.ExpressionFormCancelButton: return "Cancel"; - case RadGridStringId.SearchRowChooseColumns: return "Search in columns"; - case RadGridStringId.SearchRowSearchFromCurrentPosition: return "Search from current position"; - case RadGridStringId.SearchRowMenuItemMasterTemplate: return "Master template"; - case RadGridStringId.SearchRowMenuItemChildTemplates: return "Child templates"; - case RadGridStringId.SearchRowMenuItemAllColumns: return "All"; - case RadGridStringId.SearchRowTextBoxNullText: return "Enter text to search"; - case RadGridStringId.SearchRowResultsOfLabel: return "of"; - case RadGridStringId.SearchRowMatchCase: return "Match case"; - } - return string.Empty; - } -} - -```` -````VB.NET -Public Class MyEnglishRadGridLocalizationProvider - Inherits RadGridLocalizationProvider - - Public Overrides Function GetLocalizedString(id As String) As String - Select Case id - Case RadGridStringId.ConditionalFormattingPleaseSelectValidCellValue - Return "Please select valid cell value" - Case RadGridStringId.ConditionalFormattingPleaseSetValidCellValue - Return "Please set a valid cell value" - Case RadGridStringId.ConditionalFormattingPleaseSetValidCellValues - Return "Please set a valid cell values" - Case RadGridStringId.ConditionalFormattingPleaseSetValidExpression - Return "Please set a valid expression" - Case RadGridStringId.ConditionalFormattingItem - Return "Item" - Case RadGridStringId.ConditionalFormattingInvalidParameters - Return "Invalid parameters" - Case RadGridStringId.FilterFunctionBetween - Return "Between" - Case RadGridStringId.FilterFunctionContains - Return "Contains" - Case RadGridStringId.FilterFunctionDoesNotContain - Return "Does not contain" - Case RadGridStringId.FilterFunctionEndsWith - Return "Ends with" - Case RadGridStringId.FilterFunctionEqualTo - Return "Equals" - Case RadGridStringId.FilterFunctionGreaterThan - Return "Greater than" - Case RadGridStringId.FilterFunctionGreaterThanOrEqualTo - Return "Greater than or equal to" - Case RadGridStringId.FilterFunctionIsEmpty - Return "Is empty" - Case RadGridStringId.FilterFunctionIsNull - Return "Is null" - Case RadGridStringId.FilterFunctionLessThan - Return "Less than" - Case RadGridStringId.FilterFunctionLessThanOrEqualTo - Return "Less than or equal to" - Case RadGridStringId.FilterFunctionNoFilter - Return "No filter" - Case RadGridStringId.FilterFunctionNotBetween - Return "Not between" - Case RadGridStringId.FilterFunctionNotEqualTo - Return "Not equal to" - Case RadGridStringId.FilterFunctionNotIsEmpty - Return "Is not empty" - Case RadGridStringId.FilterFunctionNotIsNull - Return "Is not null" - Case RadGridStringId.FilterFunctionStartsWith - Return "Starts with" - Case RadGridStringId.FilterFunctionCustom - Return "Custom" - Case RadGridStringId.FilterOperatorBetween - Return "Between" - Case RadGridStringId.FilterOperatorContains - Return "Contains" - Case RadGridStringId.FilterOperatorDoesNotContain - Return "NotContains" - Case RadGridStringId.FilterOperatorEndsWith - Return "EndsWith" - Case RadGridStringId.FilterOperatorEqualTo - Return "Equals" - Case RadGridStringId.FilterOperatorGreaterThan - Return "GreaterThan" - Case RadGridStringId.FilterOperatorGreaterThanOrEqualTo - Return "GreaterThanOrEquals" - Case RadGridStringId.FilterOperatorIsEmpty - Return "IsEmpty" - Case RadGridStringId.FilterOperatorIsNull - Return "IsNull" - Case RadGridStringId.FilterOperatorLessThan - Return "LessThan" - Case RadGridStringId.FilterOperatorLessThanOrEqualTo - Return "LessThanOrEquals" - Case RadGridStringId.FilterOperatorNoFilter - Return "No filter" - Case RadGridStringId.FilterOperatorNotBetween - Return "NotBetween" - Case RadGridStringId.FilterOperatorNotEqualTo - Return "NotEquals" - Case RadGridStringId.FilterOperatorNotIsEmpty - Return "NotEmpty" - Case RadGridStringId.FilterOperatorNotIsNull - Return "NotNull" - Case RadGridStringId.FilterOperatorStartsWith - Return "StartsWith" - Case RadGridStringId.FilterOperatorIsLike - Return "Like" - Case RadGridStringId.FilterOperatorNotIsLike - Return "NotLike" - Case RadGridStringId.FilterOperatorIsContainedIn - Return "ContainedIn" - Case RadGridStringId.FilterOperatorNotIsContainedIn - Return "NotContainedIn" - Case RadGridStringId.FilterOperatorCustom - Return "Custom" - Case RadGridStringId.CustomFilterMenuItem - Return "Custom" - Case RadGridStringId.CustomFilterDialogCaption - Return "Filter Dialog [{0}]" - Case RadGridStringId.CustomFilterDialogLabel - Return "Show rows where:" - Case RadGridStringId.CustomFilterDialogRbAnd - Return "And" - Case RadGridStringId.CustomFilterDialogRbOr - Return "Or" - Case RadGridStringId.CustomFilterDialogBtnOk - Return "OK" - Case RadGridStringId.CustomFilterDialogBtnCancel - Return "Cancel" - Case RadGridStringId.CustomFilterDialogCheckBoxNot - Return "Not" - Case RadGridStringId.CustomFilterDialogTrue - Return "True" - Case RadGridStringId.CustomFilterDialogFalse - Return "False" - Case RadGridStringId.FilterMenuBlanks - Return "(Blanks)" - Case RadGridStringId.FilterMenuAvailableFilters - Return "Available Filters" - Case RadGridStringId.FilterMenuSearchBoxText - Return "Search..." - Case RadGridStringId.FilterMenuClearFilters - Return "Clear Filter" - Case RadGridStringId.FilterMenuButtonOK - Return "OK" - Case RadGridStringId.FilterMenuButtonCancel - Return "Cancel" - Case RadGridStringId.FilterMenuSelectionAll - Return "All" - Case RadGridStringId.FilterMenuSelectionAllSearched - Return "All Search Result" - Case RadGridStringId.FilterMenuSelectionNull - Return "Null" - Case RadGridStringId.FilterMenuSelectionNotNull - Return "Not Null" - Case RadGridStringId.FilterFunctionSelectedDates - Return "Filter by specific dates:" - Case RadGridStringId.FilterFunctionToday - Return "Today" - Case RadGridStringId.FilterFunctionYesterday - Return "Yesterday" - Case RadGridStringId.FilterFunctionDuringLast7days - Return "During last 7 days" - Case RadGridStringId.FilterLogicalOperatorAnd - Return "AND" - Case RadGridStringId.FilterLogicalOperatorOr - Return "OR" - Case RadGridStringId.FilterCompositeNotOperator - Return "NOT" - Case RadGridStringId.DeleteRowMenuItem - Return "Delete Row" - Case RadGridStringId.SortAscendingMenuItem - Return "Sort Ascending" - Case RadGridStringId.SortDescendingMenuItem - Return "Sort Descending" - Case RadGridStringId.ClearSortingMenuItem - Return "Clear Sorting" - Case RadGridStringId.ConditionalFormattingMenuItem - Return "Conditional Formatting" - Case RadGridStringId.GroupByThisColumnMenuItem - Return "Group by this column" - Case RadGridStringId.UngroupThisColumn - Return "Ungroup this column" - Case RadGridStringId.ColumnChooserMenuItem - Return "Column Chooser" - Case RadGridStringId.ShowMenuItem - Return "Show Column" - Case RadGridStringId.HideMenuItem - Return "Hide Column" - Case RadGridStringId.HideGroupMenuItem - Return "Hide Group" - Case RadGridStringId.UnpinMenuItem - Return "Unpin Column" - Case RadGridStringId.UnpinRowMenuItem - Return "Unpin Row" - Case RadGridStringId.PinMenuItem - Return "Pinned state" - Case RadGridStringId.PinAtLeftMenuItem - Return "Pin at left" - Case RadGridStringId.PinAtRightMenuItem - Return "Pin at right" - Case RadGridStringId.PinAtBottomMenuItem - Return "Pin at bottom" - Case RadGridStringId.PinAtTopMenuItem - Return "Pin at top" - Case RadGridStringId.BestFitMenuItem - Return "Best Fit" - Case RadGridStringId.PasteMenuItem - Return "Paste" - Case RadGridStringId.EditMenuItem - Return "Edit" - Case RadGridStringId.ClearValueMenuItem - Return "Clear Value" - Case RadGridStringId.CopyMenuItem - Return "Copy" - Case RadGridStringId.CutMenuItem - Return "Cut" - Case RadGridStringId.AddNewRowString - Return "Click here to add a new row" - Case RadGridStringId.ConditionalFormattingSortAlphabetically - Return "Sort columns alphabetically" - Case RadGridStringId.ConditionalFormattingCaption - Return "Conditional Formatting Rules Manager" - Case RadGridStringId.ConditionalFormattingLblColumn - Return "Format only cells with" - Case RadGridStringId.ConditionalFormattingLblName - Return "Rule name" - Case RadGridStringId.ConditionalFormattingLblType - Return "Cell value" - Case RadGridStringId.ConditionalFormattingLblValue1 - Return "Value 1" - Case RadGridStringId.ConditionalFormattingLblValue2 - Return "Value 2" - Case RadGridStringId.ConditionalFormattingGrpConditions - Return "Rules" - Case RadGridStringId.ConditionalFormattingGrpProperties - Return "Rule Properties" - Case RadGridStringId.ConditionalFormattingChkApplyToRow - Return "Apply this formatting to entire row" - Case RadGridStringId.ConditionalFormattingChkApplyOnSelectedRows - Return "Apply this formatting if the row is selected" - Case RadGridStringId.ConditionalFormattingBtnAdd - Return "Add new rule" - Case RadGridStringId.ConditionalFormattingBtnRemove - Return "Remove" - Case RadGridStringId.ConditionalFormattingBtnOK - Return "OK" - Case RadGridStringId.ConditionalFormattingBtnCancel - Return "Cancel" - Case RadGridStringId.ConditionalFormattingBtnApply - Return "Apply" - Case RadGridStringId.ConditionalFormattingRuleAppliesOn - Return "Rule applies to" - Case RadGridStringId.ConditionalFormattingCondition - Return "Condition" - Case RadGridStringId.ConditionalFormattingExpression - Return "Expression" - Case RadGridStringId.ConditionalFormattingChooseOne - Return "[Choose one]" - Case RadGridStringId.ConditionalFormattingEqualsTo - Return "equals to [Value1]" - Case RadGridStringId.ConditionalFormattingIsNotEqualTo - Return "is not equal to [Value1]" - Case RadGridStringId.ConditionalFormattingStartsWith - Return "starts with [Value1]" - Case RadGridStringId.ConditionalFormattingEndsWith - Return "ends with [Value1]" - Case RadGridStringId.ConditionalFormattingContains - Return "contains [Value1]" - Case RadGridStringId.ConditionalFormattingDoesNotContain - Return "does not contain [Value1]" - Case RadGridStringId.ConditionalFormattingIsGreaterThan - Return "is greater than [Value1]" - Case RadGridStringId.ConditionalFormattingIsGreaterThanOrEqual - Return "is greater than or equal [Value1]" - Case RadGridStringId.ConditionalFormattingIsLessThan - Return "is less than [Value1]" - Case RadGridStringId.ConditionalFormattingIsLessThanOrEqual - Return "is less than or equal to [Value1]" - Case RadGridStringId.ConditionalFormattingIsBetween - Return "is between [Value1] and [Value2]" - Case RadGridStringId.ConditionalFormattingIsNotBetween - Return "is not between [Value1] and [Value1]" - Case RadGridStringId.ConditionalFormattingLblFormat - Return "Format" - Case RadGridStringId.ConditionalFormattingBtnExpression - Return "Expression editor" - Case RadGridStringId.ConditionalFormattingTextBoxExpression - Return "Expression" - Case RadGridStringId.ConditionalFormattingPropertyGridCaseSensitive - Return "CaseSensitive" - Case RadGridStringId.ConditionalFormattingPropertyGridCellBackColor - Return "CellBackColor" - Case RadGridStringId.ConditionalFormattingPropertyGridCellForeColor - Return "CellForeColor" - Case RadGridStringId.ConditionalFormattingPropertyGridEnabled - Return "Enabled" - Case RadGridStringId.ConditionalFormattingPropertyGridRowBackColor - Return "RowBackColor" - Case RadGridStringId.ConditionalFormattingPropertyGridRowForeColor - Return "RowForeColor" - Case RadGridStringId.ConditionalFormattingPropertyGridRowFont - Return "RowFont" - Case RadGridStringId.ConditionalFormattingPropertyGridRowTextAlignment - Return "RowTextAlignment" - Case RadGridStringId.ConditionalFormattingPropertyGridTextAlignment - Return "TextAlignment" - Case RadGridStringId.ConditionalFormattingPropertyGridCellFont - Return "CellFont" - Case RadGridStringId.ConditionalFormattingPropertyGridCellFontDescription - Return "Enter the font to be used for the cell." - Case RadGridStringId.ConditionalFormattingPropertyGridCaseSensitiveDescription - Return "Determines whether case-sensitive comparisons will be made when evaluating string values." - Case RadGridStringId.ConditionalFormattingPropertyGridCellBackColorDescription - Return "Enter the background color to be used for the cell." - Case RadGridStringId.ConditionalFormattingPropertyGridCellForeColorDescription - Return "Enter the foreground color to be used for the cell." - Case RadGridStringId.ConditionalFormattingPropertyGridEnabledDescription - Return "Determines whether the condition is enabled (can be evaluated and applied)." - Case RadGridStringId.ConditionalFormattingPropertyGridRowBackColorDescription - Return "Enter the background color to be used for the entire row." - Case RadGridStringId.ConditionalFormattingPropertyGridRowForeColorDescription - Return "Enter the foreground color to be used for the entire row." - Case RadGridStringId.ConditionalFormattingPropertyGridRowFontDescription - Return "Enter the font to be used for the entire row." - Case RadGridStringId.ConditionalFormattingPropertyGridRowTextAlignmentDescription - Return "Enter the alignment to be used for the cell values, when ApplyToRow is true." - Case RadGridStringId.ConditionalFormattingPropertyGridTextAlignmentDescription - Return "Enter the alignment to be used for the cell values." - Case RadGridStringId.ColumnChooserFormCaption - Return "Column Chooser" - Case RadGridStringId.ColumnChooserFormMessage - Return "Drag a column header from the grid here to remove it from the current view." - Case RadGridStringId.ColumnChooserFilterTextBoxNullText - Return "Filter" - Case RadGridStringId.GroupingPanelDefaultMessage - Return "Drag a column here to group by this column." - Case RadGridStringId.GroupingPanelHeader - Return "Group by:" - Case RadGridStringId.PagingPanelPagesLabel - Return "Page" - Case RadGridStringId.PagingPanelOfPagesLabel - Return "of" - Case RadGridStringId.NoDataText - Return "No data to display" - Case RadGridStringId.CompositeFilterFormErrorCaption - Return "Filter Error" - Case RadGridStringId.CompositeFilterFormInvalidFilter - Return "The composite filter descriptor is not valid." - Case RadGridStringId.ExpressionMenuItem - Return "Expression" - Case RadGridStringId.ExpressionFormTitle - Return "Expression Builder" - Case RadGridStringId.ExpressionFormFunctions - Return "Functions" - Case RadGridStringId.ExpressionFormFunctionsText - Return "Text" - Case RadGridStringId.ExpressionFormFunctionsAggregate - Return "Aggregate" - Case RadGridStringId.ExpressionFormFunctionsDateTime - Return "Date-Time" - Case RadGridStringId.ExpressionFormFunctionsLogical - Return "Logical" - Case RadGridStringId.ExpressionFormFunctionsMath - Return "Math" - Case RadGridStringId.ExpressionFormFunctionsOther - Return "Other" - Case RadGridStringId.ExpressionFormOperators - Return "Operators" - Case RadGridStringId.ExpressionFormConstants - Return "Constants" - Case RadGridStringId.ExpressionFormFields - Return "Fields" - Case RadGridStringId.ExpressionFormDescription - Return "Description" - Case RadGridStringId.ExpressionFormResultPreview - Return "Result preview" - Case RadGridStringId.ExpressionFormTooltipPlus - Return "Plus" - Case RadGridStringId.ExpressionFormTooltipMinus - Return "Minus" - Case RadGridStringId.ExpressionFormTooltipMultiply - Return "Multiply" - Case RadGridStringId.ExpressionFormTooltipDivide - Return "Divide" - Case RadGridStringId.ExpressionFormTooltipModulo - Return "Modulo" - Case RadGridStringId.ExpressionFormTooltipEqual - Return "Equal" - Case RadGridStringId.ExpressionFormTooltipNotEqual - Return "Not Equal" - Case RadGridStringId.ExpressionFormTooltipLess - Return "Less" - Case RadGridStringId.ExpressionFormTooltipLessOrEqual - Return "Less Or Equal" - Case RadGridStringId.ExpressionFormTooltipGreaterOrEqual - Return "Greater Or Equal" - Case RadGridStringId.ExpressionFormTooltipGreater - Return "Greater" - Case RadGridStringId.ExpressionFormTooltipAnd - Return "Logical ""AND""" - Case RadGridStringId.ExpressionFormTooltipOr - Return "Logical ""OR""" - Case RadGridStringId.ExpressionFormTooltipNot - Return "Logical ""NOT""" - Case RadGridStringId.ExpressionFormAndButton - Return String.Empty - 'if empty, default button image is used - Case RadGridStringId.ExpressionFormOrButton - Return String.Empty - 'if empty, default button image is used - Case RadGridStringId.ExpressionFormNotButton - Return String.Empty - 'if empty, default button image is used - Case RadGridStringId.ExpressionFormOKButton - Return "OK" - Case RadGridStringId.ExpressionFormCancelButton - Return "Cancel" - Case RadGridStringId.SearchRowChooseColumns - Return "Search in columns" - Case RadGridStringId.SearchRowSearchFromCurrentPosition - Return "Search from current position" - Case RadGridStringId.SearchRowMenuItemMasterTemplate - Return "Master template" - Case RadGridStringId.SearchRowMenuItemChildTemplates - Return "Child templates" - Case RadGridStringId.SearchRowMenuItemAllColumns - Return "All" - Case RadGridStringId.SearchRowTextBoxNullText - Return "Enter text to search" - Case RadGridStringId.SearchRowResultsOfLabel - Return "of" - Case RadGridStringId.SearchRowMatchCase - Return "Match case" - End Select - Return String.Empty - End Function -End Class - -```` - -{{endregion}} + + To apply the custom localization provider, instantiate and assign it to the current localization provider: #### Assigning the Current Localization Provider -{{source=..\SamplesCS\GridView\Localization\Localization1.cs region=localizeGrid}} -{{source=..\SamplesVB\GridView\Localization\Localization1.vb region=localizeGrid}} - -````C# -RadGridLocalizationProvider.CurrentProvider = new MyEnglishRadGridLocalizationProvider(); - -```` -````VB.NET -RadGridLocalizationProvider.CurrentProvider = New MyEnglishRadGridLocalizationProvider() - -```` - -{{endregion}} + + The code provided above illustrates the approach to be used to localize the __RadGridView__ and is not intended as a full translation. diff --git a/controls/gridview/localization/right-to-left-support.md b/controls/gridview/localization/right-to-left-support.md index 20cc81610..4b7c82411 100644 --- a/controls/gridview/localization/right-to-left-support.md +++ b/controls/gridview/localization/right-to-left-support.md @@ -13,19 +13,8 @@ previous_url: gridview-localization-rtl You can present the content of your grid instance in a right-to-left direction by setting the __RightToLeft__ property to *Yes*: -{{source=..\SamplesCS\GridView\Localization\Localization1.cs region=rtl}} -{{source=..\SamplesVB\GridView\Localization\Localization1.vb region=rtl}} - -````C# -this.radGridView1.RightToLeft = System.Windows.Forms.RightToLeft.Yes; - -```` -````VB.NET -Me.RadGridView1.RightToLeft = System.Windows.Forms.RightToLeft.Yes - -```` - -{{endregion}} + + ![WinForms RadGridView Right-To-Left Support](images/gridview-localization-rtl001.png) # See Also diff --git a/controls/gridview/populating-with-data/bind-to-xml.md b/controls/gridview/populating-with-data/bind-to-xml.md index 4480e3706..7be4838eb 100644 --- a/controls/gridview/populating-with-data/bind-to-xml.md +++ b/controls/gridview/populating-with-data/bind-to-xml.md @@ -37,22 +37,8 @@ This is a simple xml file used in the examples below: You have to create a DataSet instance from the XML file. For the sample XML file above, the created DataSet contains only __one__ DataTable which is set as RadGridView data source. Please refer to this [topic]({%slug winforms/gridview/hierarchical-grid/creating-hierarchy-using-an-xml-data-source%}) if you want to create hierarchy. -{{source=..\SamplesCS\GridView\PopulatingWithData\BindingToXml.cs region=bindingToXML}} -{{source=..\SamplesVB\GridView\PopulatingWithData\BindingToXml.vb region=bindingToXML}} -````C# -DataSet xmlDataSet = new DataSet(); -xmlDataSet.ReadXml("..\\..\\GridView\\PopulatingWithData\\gridXml.xml"); -this.radGridView1.DataSource = xmlDataSet.Tables[0]; - -```` -````VB.NET -Dim xmlDataSet As New DataSet() -xmlDataSet.ReadXml("..\\..\\GridView\\PopulatingWithData\\gridXml.xml") -Me.RadGridView1.DataSource = xmlDataSet.Tables(0) - -```` -{{endregion}} - + + # See Also * [Bindable Types]({%slug winforms/gridview/populating-with-data/bindable-types%}) diff --git a/controls/gridview/populating-with-data/binding-to-a-collection-of-interfaces.md b/controls/gridview/populating-with-data/binding-to-a-collection-of-interfaces.md index a66d51f50..528167fc8 100644 --- a/controls/gridview/populating-with-data/binding-to-a-collection-of-interfaces.md +++ b/controls/gridview/populating-with-data/binding-to-a-collection-of-interfaces.md @@ -17,186 +17,14 @@ There may be a case where you want to bind RadGridView to a collection of interf First, we will need to create a custom __GridViewListSource__: -{{source=..\SamplesCS\GridView\PopulatingwithData\BindingToCollectionOfInterfaces.cs region=GridCode}} -{{source=..\SamplesVB\GridView\PopulatingwithData\BindingToCollectionOfInterfaces.vb region=GridCode}} - -````C# -public class MyGrid : RadGridView -{ - protected override RadGridViewElement CreateGridViewElement() - { - return new MyGridViewElement(); - } -} -public class MyGridViewElement : RadGridViewElement -{ - protected override MasterGridViewTemplate CreateTemplate() - { - return new MyMasterGridViewTemplate(); - } - protected override Type ThemeEffectiveType - { - get - { - return typeof(RadGridViewElement); - } - } -} -public class MyMasterGridViewTemplate : MasterGridViewTemplate -{ - protected override GridViewListSource CreateListSource() - { - return new MyGridViewListSource(this); - } -} -public class MyGridViewListSource : GridViewListSource -{ - private GridViewTemplate template; - public MyGridViewListSource(GridViewTemplate template) - : base(template) - { - this.template = template; - } - public override GridViewRowInfo AddNew() - { - GridObj gridObj = new GridObj(); - IList list = (this as ICurrencyManagerProvider).CurrencyManager.List; - list.Add(gridObj); - IDataItem dataItem = (this.template as IDataItemSource).NewItem(); - if (this.IsDataBound) - { - this.InitializeBoundRow((GridViewRowInfo)dataItem, gridObj); - } - return dataItem as GridViewRowInfo; - } -} - -```` -````VB.NET -Public Class MyGrid - Inherits RadGridView - Protected Overrides Function CreateGridViewElement() As RadGridViewElement - Return New MyGridViewElement() - End Function -End Class -Public Class MyGridViewElement - Inherits RadGridViewElement - Protected Overrides Function CreateTemplate() As MasterGridViewTemplate - Return New MyMasterGridViewTemplate() - End Function - Protected Overrides ReadOnly Property ThemeEffectiveType() As Type - Get - Return GetType(RadGridViewElement) - End Get - End Property -End Class -Public Class MyMasterGridViewTemplate - Inherits MasterGridViewTemplate - Protected Overrides Function CreateListSource() As GridViewListSource - Return New MyGridViewListSource(Me) - End Function -End Class -Public Class MyGridViewListSource - Inherits GridViewListSource - Private template As GridViewTemplate - Public Sub New(template As GridViewTemplate) - MyBase.New(template) - Me.template = template - End Sub - Public Overrides Function AddNew() As GridViewRowInfo - Dim gridObj As New GridObj() - Dim list As IList = TryCast(Me, ICurrencyManagerProvider).CurrencyManager.List - list.Add(gridObj) - Dim dataItem As IDataItem = TryCast(Me.template, IDataItemSource).NewItem() - If Me.IsDataBound Then - Me.InitializeBoundRow(DirectCast(dataItem, GridViewRowInfo), gridObj) - End If - Return TryCast(dataItem, GridViewRowInfo) - End Function -End Class - -```` - -{{endregion}} - + + + The `GridObj` type is a type, which implements the interface, which you have bound your RadGridView. Consider the following example: -{{source=..\SamplesCS\GridView\PopulatingwithData\BindingToCollectionOfInterfaces.cs region=ExampleCode}} -{{source=..\SamplesVB\GridView\PopulatingwithData\BindingToCollectionOfInterfaces.vb region=ExampleCode}} - -````C# -public BindingToCollectionOfInterfaces() -{ - InitializeComponent(); - MyGrid grid = new MyGrid(); - this.Controls.Add(grid); - grid.Dock = DockStyle.Fill; - IEnumerable dataSource = new BindingList(); - grid.DataSource = dataSource; - grid.AllowAddNewRow = true; -} -public interface IGridObj -{ - int Id { get; set; } - string Name { get; set; } -} -public class GridObj : IGridObj -{ - public int Id { get; set; } - public string Name { get; set; } - public string RandomString { get; set; } -} - -```` -````VB.NET -Public Sub New() - InitializeComponent() - Dim grid As New MyGrid() - Me.Controls.Add(grid) - grid.Dock = DockStyle.Fill - Dim dataSource As IEnumerable(Of IGridObj) = New BindingList(Of IGridObj)() - grid.DataSource = dataSource - grid.AllowAddNewRow = True -End Sub -Public Interface IGridObj - Property Id() As Integer - Property Name() As String -End Interface -Public Class GridObj - Implements IGridObj - Public Property Id() As Integer Implements BindingToCollectionOfInterfaces.IGridObj.Id - Get - Return m_Id - End Get - Set(value As Integer) - m_Id = value - End Set - End Property - Private m_Id As Integer - Public Property Name() As String Implements BindingToCollectionOfInterfaces.IGridObj.Name - Get - Return m_Name - End Get - Set(value As String) - m_Name = value - End Set - End Property - Private m_Name As String - Public Property RandomString() As String - Get - Return m_RandomString - End Get - Set(value As String) - m_RandomString = value - End Set - End Property - Private m_RandomString As String -End Class - -```` - -{{endregion}} - + + + You will notice that we are creating a __BindingList__ of __IGridObject__, because the new items are manually added and this way the grid will be notified for the new objects. # See Also diff --git a/controls/gridview/populating-with-data/binding-to-array-and-arraylist.md b/controls/gridview/populating-with-data/binding-to-array-and-arraylist.md index 80927bbc6..d9fd64f9e 100644 --- a/controls/gridview/populating-with-data/binding-to-array-and-arraylist.md +++ b/controls/gridview/populating-with-data/binding-to-array-and-arraylist.md @@ -22,72 +22,10 @@ The example below creates an __ArrayList__ of generic objects initialized with f ![WinForms RadGridView Binding to a Array List](images/gridview-populating-with-data-binding-to-array-and-arraylist001.png) -{{source=..\SamplesCS\GridView\PopulatingWithData\BindingToArrayAndArrayList.cs region=bindingToSimpleArrayClass}} -{{source=..\SamplesVB\GridView\PopulatingWithData\BindingToArrayAndArrayList.vb region=bindingToSimpleArrayClass}} - -````C# -public class ValueType -{ - T item; - public ValueType() { } - public ValueType(T item) - { - this.item = item; - } - public T ItemProperty - { - get { return this.item; } - set { this.item = value; } - } -} - -```` -````VB.NET -Public Class ValueType(Of T) - Private item As T - Public Sub New() - End Sub - Public Sub New(ByVal item As T) - Me.item = item - End Sub - Public Property ItemProperty() As T - Get - Return Me.item - End Get - Set(ByVal value As T) - Me.item = value - End Set - End Property -End Class - -```` - -{{endregion}} - -{{source=..\SamplesCS\GridView\PopulatingWithData\BindingToArrayAndArrayList.cs region=bindingToSimpleArray}} -{{source=..\SamplesVB\GridView\PopulatingWithData\BindingToArrayAndArrayList.vb region=bindingToSimpleArray}} - -````C# -ArrayList list = new ArrayList(); -for (int i = 0; i < 5; i++) -{ - list.Add(new ValueType("string " + (i + 1).ToString())); -} -this.radGridView1.DataSource = list; - -```` -````VB.NET -Dim list As New ArrayList() -Dim i As Integer = 0 -While i < 5 - list.Add(New ValueType(Of String)("string " + (i + 1).ToString())) - System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1) -End While -Me.RadGridView1.DataSource = list - -```` - -{{endregion}} + + + + ## Binding to an Array of Objects @@ -98,81 +36,10 @@ The example below defines a "MyObject" class containing one integer and one stri ![WinForms RadGridView Binding to an Array of Objects](images/gridview-populating-with-data-binding-to-array-and-arraylist002.png) -{{source=..\SamplesCS\GridView\PopulatingWithData\BindingToArrayAndArrayList.cs region=bindingToArrayOfObjectsClass}} -{{source=..\SamplesVB\GridView\PopulatingWithData\BindingToArrayAndArrayList.vb region=bindingToArrayOfObjectsClass}} - -````C# -public class MyObject -{ - public MyObject(int myInt, string myString) - { - _myInt = myInt; - _myString = myString; - } - private int _myInt; - public int MyInt - { - get { return _myInt; } - set { _myInt = value; } - } - private string _myString; - public string MyString - { - get { return _myString; } - set { _myString = value; } - } -} - -```` -````VB.NET -Public Class MyObject - Public Sub New(ByVal myInt As Integer, ByVal myString As String) - _myInt = myInt - _myString = myString - End Sub - Private _myInt As Integer - Public Property MyInt() As Integer - Get - Return _myInt - End Get - Set(ByVal value As Integer) - _myInt = value - End Set - End Property - Private _myString As String - Public Property MyString() As String - Get - Return _myString - End Get - Set(ByVal value As String) - _myString = value - End Set - End Property -End Class - -```` - -{{endregion}} - -{{source=..\SamplesCS\GridView\PopulatingWithData\BindingToArrayAndArrayList.cs region=bindingToArrayOfObjects}} -{{source=..\SamplesVB\GridView\PopulatingWithData\BindingToArrayAndArrayList.vb region=bindingToArrayOfObjects}} - -````C# -MyObject[] myArray = new MyObject[2] { new MyObject(1, "object one"), new MyObject(2, "object two") }; -radGridView1.DataSource = myArray; - -```` -````VB.NET -Dim myArray As MyObject() = New MyObject(1) {New MyObject(1, "object one"), New MyObject(2, "object two")} - RadGridView1.DataSource = myArray - -```` - -{{endregion}} - - - - + + + + # See Also * [Bind to XML]({%slug winforms/gridview/populating-with-data/bind-to-xml%}) diff --git a/controls/gridview/populating-with-data/binding-to-bindinglist.md b/controls/gridview/populating-with-data/binding-to-bindinglist.md index 1cc73f9d9..efee7625b 100644 --- a/controls/gridview/populating-with-data/binding-to-bindinglist.md +++ b/controls/gridview/populating-with-data/binding-to-bindinglist.md @@ -15,119 +15,10 @@ BindingList is a generic list type that has additional binding support. While yo ![WinForms RadGridView Binding to BindingList](images/gridview-populating-with-data-binding-to-bindinglist001.png) -{{source=..\SamplesCS\GridView\PopulatingWithData\BindingToBindingList.cs region=MyObjectClass}} -{{source=..\SamplesVB\GridView\PopulatingWithData\BindingToBindingList.vb region=MyObjectClass}} - -````C# -public class MyObject -{ - public MyObject() - { - } - public MyObject(int myInt, string myString) - { - _myInt = myInt; - _myString = myString; - } - private int _myInt; - public int MyInt - { - get { return _myInt; } - set { _myInt = value; } - } - private string _myString; - public string MyString - { - get { return _myString; } - set { _myString = value; } - } -} - -```` -````VB.NET -Public Class MyObject - Public Sub New() - End Sub - Public Sub New(ByVal myInt As Integer, ByVal myString As String) - _myInt = myInt - _myString = myString - End Sub - Private _myInt As Integer - Public Property MyInt() As Integer - Get - Return _myInt - End Get - Set(ByVal value As Integer) - _myInt = value - End Set - End Property - Private _myString As String - Public Property MyString() As String - Get - Return _myString - End Get - Set(ByVal value As String) - _myString = value - End Set - End Property -End Class - -```` - -{{endregion}} - -{{source=..\SamplesCS\GridView\PopulatingWithData\BindingToBindingList.cs region=bindingToBindingList}} -{{source=..\SamplesVB\GridView\PopulatingWithData\BindingToBindingList.vb region=bindingToBindingList}} - -````C# -private BindingList myList; -private void Form1_Load(object sender, EventArgs e) -{ - myList = new BindingList(); - myList.Add(new MyObject(1, "Outdoor")); - myList.Add(new MyObject(2, "Hardware")); - myList.Add(new MyObject(3, "Tools")); - myList.Add(new MyObject(4, "Books")); - myList.Add(new MyObject(5, "Appliances")); - myList.RaiseListChangedEvents = true; - myList.ListChanged += new ListChangedEventHandler(myList_ListChanged); - radGridView1.DataSource = myList; -} -void myList_ListChanged(object sender, ListChangedEventArgs e) -{ - MessageBox.Show(e.ListChangedType.ToString() + ": at index: " + e.NewIndex.ToString() + ", \"" + myList[e.NewIndex].MyString + "\""); -} -private void radButton1_Click(object sender, EventArgs e) -{ - myList.Add(new MyObject(6, "Plants")); -} - -```` -````VB.NET -Private myList As BindingList(Of MyObject) -Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load - myList = New BindingList(Of MyObject)() - myList.Add(New MyObject(1, "Outdoor")) - myList.Add(New MyObject(2, "Hardware")) - myList.Add(New MyObject(3, "Tools")) - myList.Add(New MyObject(4, "Books")) - myList.Add(New MyObject(5, "Appliances")) - myList.RaiseListChangedEvents = True - AddHandler myList.ListChanged, AddressOf myList_ListChanged - RadGridView1.DataSource = myList -End Sub -Sub myList_ListChanged(ByVal sender As Object, ByVal e As ListChangedEventArgs) - MessageBox.Show(e.ListChangedType.ToString() + ": at index: " + e.NewIndex.ToString() + ", """ + myList(e.NewIndex).MyString + """") -End Sub -Private Sub RadButton1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadButton1.Click - myList.Add(New MyObject(6, "Plants")) -End Sub - -```` - -{{endregion}} - - + + + + # See Also * [Bind to XML]({%slug winforms/gridview/populating-with-data/bind-to-xml%}) diff --git a/controls/gridview/populating-with-data/binding-to-datareader.md b/controls/gridview/populating-with-data/binding-to-datareader.md index 3ab4ed6a6..0d238c9e0 100644 --- a/controls/gridview/populating-with-data/binding-to-datareader.md +++ b/controls/gridview/populating-with-data/binding-to-datareader.md @@ -13,30 +13,9 @@ previous_url: gridview-populating-with-data-binding-to-datareader To extract values from a data source using a __DataReader,__ use the GridViewTemplate __LoadFrom()__ method to consume an object instance that supports `IDataReader`. The code sample below uses a `OleDbDataReader` reading an `Access` data source: -{{source=..\SamplesCS\GridView\PopulatingWithData\BindingToDataReader.cs region=usingADataReader}} -{{source=..\SamplesVB\GridView\PopulatingWithData\BindingToDataReader.vb region=usingADataReader}} - -````C# -OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\\..\\DataSources\\Nwind.mdb"); -conn.Open(); -OleDbCommand cmd = new OleDbCommand("Select TOP 5 * FROM Customers", conn); -OleDbDataReader reader = cmd.ExecuteReader(); -radGridView1.MasterTemplate.LoadFrom(reader); - -```` -````VB.NET -Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\\..\\DataSources\\Nwind.mdb") -conn.Open() -Dim cmd As New OleDbCommand("Select TOP 5 * FROM Customers", conn) -Dim reader As OleDbDataReader = cmd.ExecuteReader() -RadGridView1.MasterTemplate.LoadFrom(reader) - -```` - -{{endregion}} - - - + + + # See Also * [Bind to XML]({%slug winforms/gridview/populating-with-data/bind-to-xml%}) diff --git a/controls/gridview/populating-with-data/binding-to-entityframework-using-database-first-approach.md b/controls/gridview/populating-with-data/binding-to-entityframework-using-database-first-approach.md index 3b32b812b..b567e25ed 100644 --- a/controls/gridview/populating-with-data/binding-to-entityframework-using-database-first-approach.md +++ b/controls/gridview/populating-with-data/binding-to-entityframework-using-database-first-approach.md @@ -46,41 +46,17 @@ Now, our models should be generated. 1\. Add **RadGridView** to the **Form** and then in the code behind add an instance of the **DbContext** which will provide us access to the data in the database: -{{source=..\SamplesCS\GridView\PopulatingWithData\BindingToEntityFrameworkDatabaseFirst.cs region=addDbContext}} -{{source=..\SamplesVB\GridView\PopulatingWithData\BindingToEntityFrameworkDatabaseFirst.vb region=addDbContext}} - -````C# -NorthwindEntities dbContext = new NorthwindEntities(); - -```` -````VB.NET -Dim dbContext As New NorthwindEntities - -```` - -{{endregion}} + + >note When binding **RadGridView** we will be using the Local property of **DbSet**. The Local property provides access to the data without a query being sent to the database. It is also synchronized with the **DbSet**. For example, if an entry is deleted from the Local property, the next time a query is executed it will be deleted from the database. > 2\. Add the following code to your Form’s constructor: -{{source=..\SamplesCS\GridView\PopulatingWithData\BindingToEntityFrameworkDatabaseFirst.cs region=addDataSource}} -{{source=..\SamplesVB\GridView\PopulatingWithData\BindingToEntityFrameworkDatabaseFirst.vb region=addDataSource}} - -````C# -dbContext.Customers.Load(); -this.radGridView1.DataSource = this.dbContext.Customers.Local.ToBindingList(); - -```` -````VB.NET -dbContext.Customers.Load() -Me.radGridView1.DataSource = Me.dbContext.Customers.Local.ToBindingList() + + -```` - -{{endregion}} - These extension methods are located in the __System.Data.Entity__ namespace. As the **Local** property represents the local data, we need to first load the data from the database. Then, by calling __ToBindingList__ method we make sure that our **RadGridView** and the **Local** data will be synchronized. >note When adding new rows in **RadGridView** by default the *Id* cell of the new rows will be *0* since the data was not send to the database, therefore no *UniqueId* has been assigned yet. @@ -89,53 +65,13 @@ These extension methods are located in the __System.Data.Entity__ namespace. As 3\. Now, we just need to add the relation between the **Customers** and **Orders** tables: -{{source=..\SamplesCS\GridView\PopulatingWithData\BindingToEntityFrameworkDatabaseFirst.cs region=addRelation}} -{{source=..\SamplesVB\GridView\PopulatingWithData\BindingToEntityFrameworkDatabaseFirst.vb region=addRelation}} - -````C# -dbContext.Orders.Load(); -GridViewTemplate template = new GridViewTemplate(); -template.DataSource = dbContext.Orders.Local.ToBindingList(); -this.radGridView1.MasterTemplate.Templates.Add(template); -GridViewRelation relation = new GridViewRelation(this.radGridView1.MasterTemplate); -relation.ChildTemplate = template; -relation.RelationName = "CustomersToOrders"; -relation.ParentColumnNames.Add("CustomerId"); -relation.ChildColumnNames.Add("CustomerId"); -this.radGridView1.Relations.Add(relation); - -```` -````VB.NET -dbContext.Orders.Load() -Dim template As New GridViewTemplate() -template.DataSource = dbContext.Orders.Local.ToBindingList() -Me.radGridView1.MasterTemplate.Templates.Add(template) -Dim relation As New GridViewRelation(Me.radGridView1.MasterTemplate) -relation.ChildTemplate = template -relation.RelationName = "CustomersToOrders" -relation.ParentColumnNames.Add("CustomerId") -relation.ChildColumnNames.Add("CustomerId") -Me.radGridView1.Relations.Add(relation) - -```` - -{{endregion}} + + 4\. The final step is to save the changes to the database when the form closes. For this purpose, we need to subscribe to the form's __Closing__ event and add the following code in the event handler: -{{source=..\SamplesCS\GridView\PopulatingWithData\BindingToEntityFrameworkDatabaseFirst.cs region=saveChanges}} -{{source=..\SamplesVB\GridView\PopulatingWithData\BindingToEntityFrameworkDatabaseFirst.vb region=saveChanges}} - -````C# -this.dbContext.SaveChanges(); - -```` -````VB.NET -Me.dbContext.SaveChanges() - -```` - -{{endregion}} + + Now, if you run your application you should see the hierarchical data. diff --git a/controls/gridview/populating-with-data/binding-to-generic-lists.md b/controls/gridview/populating-with-data/binding-to-generic-lists.md index 4e0cc8548..ac75568e9 100644 --- a/controls/gridview/populating-with-data/binding-to-generic-lists.md +++ b/controls/gridview/populating-with-data/binding-to-generic-lists.md @@ -17,27 +17,8 @@ Generally, you should not try to bind __RadGridView__ to a list of simple types. ![WinForms RadGridView Binding to Lists of Simple Types](images/grid-populating-with-data-binding-to-generic-lists001.png) -{{source=..\SamplesCS\GridView\PopulatingWithData\BindingToGenericLists.cs region=bindingToListOfSimpleTypes}} -{{source=..\SamplesVB\GridView\PopulatingWithData\BindingToGenericLists.vb region=bindingToListOfSimpleTypes}} - -````C# -List list = new List(); -list.Add("One"); -list.Add("Two"); -list.Add("Three"); -radGridView1.DataSource = list; - -```` -````VB.NET -Dim list As New List(Of String)() -list.Add("One") -list.Add("Two") -list.Add("Three") -RadGridView1.DataSource = list - -```` - -{{endregion}} + + ## Binding to Lists of Objects @@ -47,87 +28,10 @@ The example below defines a `MyObject` class containing one integer and one stri ![WinForms RadGridView Binding to Lists of Objects](images/gridview-populating-with-data-binding-to-generic-list002.png) -{{source=..\SamplesCS\GridView\PopulatingWithData\BindingToGenericLists.cs region=objectClass}} -{{source=..\SamplesVB\GridView\PopulatingWithData\BindingToGenericLists.vb region=objectClass}} - -````C# -public class MyObject -{ - public MyObject(int myInt, string myString) - { - _myInt = myInt; - _myString = myString; - } - private int _myInt; - public int MyInt - { - get { return _myInt; } - set { _myInt = value; } - } - private string _myString; - public string MyString - { - get { return _myString; } - set { _myString = value; } - } -} - -```` -````VB.NET -Public Class MyObject - Public Sub New(ByVal myInt As Integer, ByVal myString As String) - _myInt = myInt - _myString = myString - End Sub - Private _myInt As Integer - Public Property MyInt() As Integer - Get - Return _myInt - End Get - Set(ByVal value As Integer) - _myInt = value - End Set - End Property - Private _myString As String - Public Property MyString() As String - Get - Return _myString - End Get - Set(ByVal value As String) - _myString = value - End Set - End Property -End Class - -```` - -{{endregion}} - -{{source=..\SamplesCS\GridView\PopulatingWithData\BindingToGenericLists.cs region=bindingtoObjectsOfSimpleType}} -{{source=..\SamplesVB\GridView\PopulatingWithData\BindingToGenericLists.vb region=bindingtoObjectsOfSimpleType}} - -````C# -List myList = new List(); -myList.Add(new MyObject(1, "Outdoor")); -myList.Add(new MyObject(2, "Hardware")); -myList.Add(new MyObject(3, "Tools")); -myList.Add(new MyObject(4, "Books")); -myList.Add(new MyObject(5, "Appliances")); -radGridView1.DataSource = myList; - -```` -````VB.NET -Dim myList As New List(Of MyObject)() -myList.Add(New MyObject(1, "Outdoor")) -myList.Add(New MyObject(2, "Hardware")) -myList.Add(New MyObject(3, "Tools")) -myList.Add(New MyObject(4, "Books")) -myList.Add(New MyObject(5, "Appliances")) -RadGridView1.DataSource = myList - -```` - -{{endregion}} + + + + # See Also * [Bind to XML]({%slug winforms/gridview/populating-with-data/bind-to-xml%}) diff --git a/controls/gridview/populating-with-data/binding-to-observablecollection.md b/controls/gridview/populating-with-data/binding-to-observablecollection.md index 1bd031f44..04c6f3cf4 100644 --- a/controls/gridview/populating-with-data/binding-to-observablecollection.md +++ b/controls/gridview/populating-with-data/binding-to-observablecollection.md @@ -28,186 +28,27 @@ The example creates an `ObservableCollection` of `Person`, initializes the colle 2\. Add the following sample class to the project: -{{source=..\SamplesCS\GridView\PopulatingwithData\BindingToObservableCollection.cs region=SampleClass}} -{{source=..\SamplesVB\GridView\PopulatingwithData\BindingToObservableCollection.vb region=SampleClass}} - -````C# - -public class Person -{ - public string FirstName { get; set; } - - public string LastName { get; set; } - - public int Age { get; set; } - - public Person(string firstName, string lastName, int age) - { - this.FirstName = firstName; - this.LastName = lastName; - this.Age = age; - } -} - -```` -````VB.NET - -Public Class Person - Public Property FirstName() As String - Get - Return m_FirstName - End Get - Set(value As String) - m_FirstName = value - End Set - End Property - Private m_FirstName As String - Public Property LastName() As String - Get - Return m_LastName - End Get - Set(value As String) - m_LastName = value - End Set - End Property - Private m_LastName As String - Public Property Age() As Integer - Get - Return m_Age - End Get - Set(value As Integer) - m_Age = value - End Set - End Property - Private m_Age As Integer - Public Sub New(firstName As String, lastName As String, age As Integer) - Me.FirstName = firstName - Me.LastName = lastName - Me.Age = age - End Sub -End Class - -```` - -{{endregion}} + + 3\. Define the collection along with the function that initializes it: -{{source=..\SamplesCS\GridView\PopulatingwithData\BindingToObservableCollection.cs region=Collection}} -{{source=..\SamplesVB\GridView\PopulatingwithData\BindingToObservableCollection.vb region=Collection}} - -````C# -private System.Collections.ObjectModel.ObservableCollection people = new System.Collections.ObjectModel.ObservableCollection(); -private void IntilalizeCollection() -{ - people.Add(new Person("Johnathan", "Gartner", 45)); - people.Add(new Person("Jeannine", "Richart", 25)); - people.Add(new Person("Merry", "Sparacino", 15)); - people.Add(new Person("Sandi", "Willman", 32)); - people.Add(new Person("Damion", "Dagley", 51)); -} - -```` -````VB.NET -Private people As New System.Collections.ObjectModel.ObservableCollection(Of Person)() -Private Sub IntilalizeCollection() - people.Add(New Person("Johnathan", "Gartner", 45)) - people.Add(New Person("Jeannine", "Richart", 25)) - people.Add(New Person("Merry", "Sparacino", 15)) - people.Add(New Person("Sandi", "Willman", 32)) - people.Add(New Person("Damion", "Dagley", 51)) -End Sub - -```` - -{{endregion}} + + 4\. Add the following event handlers for the buttons: -{{source=..\SamplesCS\GridView\PopulatingwithData\BindingToObservableCollection.cs region=Add}} -{{source=..\SamplesVB\GridView\PopulatingwithData\BindingToObservableCollection.vb region=Add}} - -````C# -private void Add_Click(object sender, EventArgs e) -{ - people.Add(new Person("Damion", "Dagley", 51)); -} - -```` -````VB.NET -Private Sub Add_Click(sender As Object, e As EventArgs) - people.Add(New Person("Damion", "Dagley", 51)) -End Sub - -```` - -{{endregion}} - -{{source=..\SamplesCS\GridView\PopulatingwithData\BindingToObservableCollection.cs region=Remove}} -{{source=..\SamplesVB\GridView\PopulatingwithData\BindingToObservableCollection.vb region=Remove}} - -````C# -private void Remove_Click(object sender, EventArgs e) -{ - if (people.Count > 0) - { - people.RemoveAt(0); - } -} - -```` -````VB.NET -Private Sub Remove_Click(sender As Object, e As EventArgs) - If people.Count > 0 Then - people.RemoveAt(0) - End If -End Sub - -```` - -{{endregion}} - -{{source=..\SamplesCS\GridView\PopulatingwithData\BindingToObservableCollection.cs region=Move}} -{{source=..\SamplesVB\GridView\PopulatingwithData\BindingToObservableCollection.vb region=Move}} - -````C# -private void Move_Click(object sender, EventArgs e) -{ - people.Move(people.Count - 1, 0); -} - -```` -````VB.NET -Private Sub Move_Click(sender As Object, e As EventArgs) - people.Move(people.Count - 1, 0) -End Sub - -```` - -{{endregion}} + + + + + + 5\. Finally just call the __InitializeCollection__ method to populate the collection and bind the __RadGridView__ to it -{{source=..\SamplesCS\GridView\PopulatingwithData\BindingToObservableCollection.cs region=Binding}} -{{source=..\SamplesVB\GridView\PopulatingwithData\BindingToObservableCollection.vb region=Binding}} - -````C# -private void BindingToObservableCollection_Load(object sender, EventArgs e) -{ - IntilalizeCollection(); - this.radGridView1.DataSource = people; -} - -```` -````VB.NET -Private Sub BindingToObservableCollection_Load(sender As Object, e As EventArgs) Handles MyBase.Load - IntilalizeCollection() - Me.radGridView1.DataSource = people -End Sub - -```` - -{{endregion}} + + Now each change you introduce to the collection by pressing the buttons will be automatically reflected in __RadGridView__. diff --git a/controls/gridview/populating-with-data/binding-to-sub-objects.md b/controls/gridview/populating-with-data/binding-to-sub-objects.md index 2ba5447fa..9fa19ece0 100644 --- a/controls/gridview/populating-with-data/binding-to-sub-objects.md +++ b/controls/gridview/populating-with-data/binding-to-sub-objects.md @@ -23,177 +23,28 @@ Follows the implementation of the Person and the Car classes: #### Defining the Class and Sub Class -{{source=..\SamplesCS\GridView\PopulatingWithData\BindingToSubObjects.cs region=classes}} -{{source=..\SamplesVB\GridView\PopulatingWithData\BindingToSubObjects.vb region=classes}} - -````C# -public class Person -{ - public string _name = ""; - public string _city = ""; - public Car _car = null; - public Person() - { - this._car = new Car(); - } - public Person(string name, string city, Car car) - { - this._name = name; - this._city = city; - this._car = car; - } - public string Name - { - get - { - return this._name; - } - } - public string City - { - get - { - return this._city; - } - } - public Car Car - { - get - { - return this._car; - } - } -} -public class Car -{ - string _model; - int _year; - public Car() - { - } - public Car(string model, int year) - { - this._model = model; - this._year = year; - } - public string Model - { - get - { - return this._model; - } - } - public int Year - { - get - { - return this._year; - } - } -} - -```` -````VB.NET -Public Class Person - Public _name As String = "" - Public _city As String = "" - Public _car As Car = Nothing - Public Sub New() - Me._car = New Car() - End Sub - Public Sub New(name As String, city As String, car As Car) - Me._name = name - Me._city = city - Me._car = car - End Sub - Public ReadOnly Property Name() As String - Get - Return Me._name - End Get - End Property - Public ReadOnly Property City() As String - Get - Return Me._city - End Get - End Property - Public ReadOnly Property Car() As Car - Get - Return Me._car - End Get - End Property -End Class -Public Class Car - Private _model As String - Private _year As Integer - Public Sub New() - End Sub - Public Sub New(model As String, year As Integer) - Me._model = model - Me._year = year - End Sub - Public ReadOnly Property Model() As String - Get - Return Me._model - End Get - End Property - Public ReadOnly Property Year() As Integer - Get - Return Me._year - End Get - End Property -End Class - -```` - -{{endregion}} + + -Lets populate a `BindingList` of `Person` with some objects and bind it to RadGridView. -Binding RadGridView to `Person` automatically creates three columns for all properties of the `Person` object. The value properties are displayed correctly, but the reference property is displayed in "dot" notation (see the third (Car) column in the screenshot below). -{{source=..\SamplesCS\GridView\PopulatingWithData\BindingToSubObjects.cs region=bind radgridview}} -{{source=..\SamplesVB\GridView\PopulatingWithData\BindingToSubObjects.vb region=bind radgridview}} +Lets populate a `BindingList` of `Person` with some objects and bind it to RadGridView. -````C# -BindingList list = new BindingList(); -list.Add(new Person("Jessy Jones", "New York", new Car("BMW", 2011))); -list.Add(new Person("Allan Trenton", "Las Vegas", new Car("Mercedes", 2011))); -list.Add(new Person("Brandon Michels", "Los Angeles", new Car("Lexus", 2010))); -list.Add(new Person("Michael Jordan", "Chicago", new Car("Toyota", 2009))); -list.Add(new Person("Dimitar Berbatov", "Manchester", new Car("Infinity", 2008))); -radGridView1.DataSource = list; +Binding RadGridView to `Person` automatically creates three columns for all properties of the `Person` object. The value properties are displayed correctly, but the reference property is displayed in "dot" notation (see the third (Car) column in the screenshot below). -```` -````VB.NET -Dim list As New BindingList(Of Person) -list.Add(New Person("Jessy Jones", "New York", New Car("BMW", 2011))) -list.Add(New Person("Allan Trenton", "Las Vegas", New Car("Mercedes", 2011))) -list.Add(New Person("Brandon Michels", "Los Angeles", New Car("Lexus", 2010))) -list.Add(New Person("Michael Jordan", "Chicago", New Car("Toyota", 2009))) -list.Add(New Person("Dimitar Berbatov", "Manchester", New Car("Infinity", 2008))) -RadGridView1.DataSource = list + + -```` -{{endregion}} ![WinForms RadGridView Defining Classes](images/gridview-populating-with-data-binding-to-subobjects001.png) Now to setup the sub-property binding of the `Car` column, all you have to do is to declare in the __FieldName__ property of the column, the name of the Car object property that you want to bind the column to (Model or Year), using the __dot__ notation: -{{source=..\SamplesCS\GridView\PopulatingWithData\BindingToSubObjects.cs region=add sub property binding}} -{{source=..\SamplesVB\GridView\PopulatingWithData\BindingToSubObjects.vb region=add sub property binding}} - -````C# -radGridView1.Columns[2].FieldName = "Car.Model"; - -```` -````VB.NET -RadGridView1.Columns(2).FieldName = "Car.Model" + + -```` -{{endregion}} The result is that the `Car` column is now bound to the __Model__ property of the `Car` object diff --git a/controls/gridview/populating-with-data/reflecting-custom-object-changes-in-rgv.md b/controls/gridview/populating-with-data/reflecting-custom-object-changes-in-rgv.md index b427938e1..92cb4fb89 100644 --- a/controls/gridview/populating-with-data/reflecting-custom-object-changes-in-rgv.md +++ b/controls/gridview/populating-with-data/reflecting-custom-object-changes-in-rgv.md @@ -31,153 +31,18 @@ Here are the steps for this scenario: 1\. Create a class called `Student`: -{{source=..\SamplesCS\GridView\PopulatingWithData\Student.cs region=student}} -{{source=..\SamplesVB\GridView\PopulatingWithData\Student.vb region=student}} - -````C# -public class Student -{ - int m_id; - string m_name; - string m_grade; - public Student(int m_id, string m_name, string m_grade) - { - this.m_id = m_id; - this.m_name = m_name; - this.m_grade = m_grade; - } - public int Id - { - get - { - return m_id; - } - set - { - m_id = value; - } - } - public string Name - { - get - { - return m_name; - } - set - { - m_name = value; - } - } - public string Grade - { - get - { - return m_grade; - } - set - { - m_grade = value; - } - } -} - -```` -````VB.NET -Public Class Student - Private m_id As Integer - Private m_name As String - Private m_grade As String - Public Sub New(ByVal m_id As Integer, ByVal m_name As String, ByVal m_grade As String) - Me.m_id = m_id - Me.m_name = m_name - Me.m_grade = m_grade - End Sub - Public Property Id() As Integer - Get - Return m_id - End Get - Set(ByVal value As Integer) - m_id = value - End Set - End Property - Public Property Name() As String - Get - Return m_name - End Get - Set(ByVal value As String) - m_name = value - End Set - End Property - Public Property Grade() As String - Get - Return m_grade - End Get - Set(ByVal value As String) - m_grade = value - End Set - End Property -End Class - -```` - -{{endregion}} + + 2\. Fill a `List` with several `Students` and bind it to RadGridView: -{{source=..\SamplesCS\GridView\PopulatingWithData\ReflectingCustomObjectChanges.cs region=list}} -{{source=..\SamplesVB\GridView\PopulatingWithData\ReflectingCustomObjectChanges.vb region=list}} - -````C# -List collectionOfStudents = new List(); -protected override void OnLoad(EventArgs e) -{ - base.OnLoad(e); - - collectionOfStudents.Add(new Student(0, "Peter", "A+")); - collectionOfStudents.Add(new Student(1, "John", "D-")); - collectionOfStudents.Add(new Student(2, "Antony", "B+")); - collectionOfStudents.Add(new Student(3, "David", "A-")); - collectionOfStudents.Add(new Student(4, "John", "D-")); - this.radGridView1.DataSource = collectionOfStudents; -} - -```` -````VB.NET -Private collectionOfStudents As New List(Of Student)() -Protected Overrides Sub OnLoad(ByVal e As EventArgs) - MyBase.OnLoad(e) - collectionOfStudents.Add(New Student(0, "Peter", "A+")) - collectionOfStudents.Add(New Student(1, "John", "D-")) - collectionOfStudents.Add(New Student(2, "Antony", "B+")) - collectionOfStudents.Add(New Student(3, "David", "A-")) - collectionOfStudents.Add(New Student(4, "John", "D-")) - Me.radGridView1.DataSource = collectionOfStudents -End Sub - -```` - -{{endregion}} + + 3\. On a button click, remove the first `Student` from the collection: -{{source=..\SamplesCS\GridView\PopulatingWithData\ReflectingCustomObjectChanges.cs region=buttonRemove}} -{{source=..\SamplesVB\GridView\PopulatingWithData\ReflectingCustomObjectChanges.vb region=buttonRemove}} - -````C# -private void btnDeleteRecord_Click(object sender, EventArgs e) -{ - collectionOfStudents.RemoveAt(0); -} - -```` -````VB.NET -Private Sub btnDeleteRecord_Click(ByVal sender As Object, ByVal e As EventArgs) - collectionOfStudents.RemoveAt(0) -End Sub - -```` - -{{endregion}} + + The initial view when we start the application is this: @@ -198,80 +63,18 @@ Let's now bind RadGridView to a collection that implements `IBindingList`. A ver 2\. Fill a `BindingList` with several `Students` and bind it to RadGridView: -{{source=..\SamplesCS\GridView\PopulatingWithData\ReflectingCustomObjectChanges.cs region=bindingList}} -{{source=..\SamplesVB\GridView\PopulatingWithData\ReflectingCustomObjectChanges.vb region=bindingList}} - -````C# -BindingList collectionOfStudents = new BindingList(); -protected override void OnLoad(EventArgs e) -{ - base.OnLoad(e); - collectionOfStudents.Add(new Student(0, "Peter", "A+")); - collectionOfStudents.Add(new Student(1, "John", "D-")); - collectionOfStudents.Add(new Student(2, "Antony", "B+")); - collectionOfStudents.Add(new Student(3, "David", "A-")); - collectionOfStudents.Add(new Student(4, "John", "D-")); - this.radGridView1.DataSource = collectionOfStudents; -} - -```` -````VB.NET -Private collectionOfStudents As New BindingList(Of Student)() -Protected Overrides Sub OnLoad(ByVal e As EventArgs) - MyBase.OnLoad(e) - collectionOfStudents.Add(New Student(0, "Peter", "A+")) - collectionOfStudents.Add(New Student(1, "John", "D-")) - collectionOfStudents.Add(New Student(2, "Antony", "B+")) - collectionOfStudents.Add(New Student(3, "David", "A-")) - collectionOfStudents.Add(New Student(4, "John", "D-")) - Me.radGridView1.DataSource = collectionOfStudents -End Sub - -```` - -{{endregion}} + + 3\. On a button click, remove the first Student from the collection: -{{source=..\SamplesCS\GridView\PopulatingWithData\ReflectingCustomObjectChanges.cs region=buttonRemove}} -{{source=..\SamplesVB\GridView\PopulatingWithData\ReflectingCustomObjectChanges.vb region=buttonRemove}} - -````C# -private void btnDeleteRecord_Click(object sender, EventArgs e) -{ - collectionOfStudents.RemoveAt(0); -} - -```` -````VB.NET -Private Sub btnDeleteRecord_Click(ByVal sender As Object, ByVal e As EventArgs) - collectionOfStudents.RemoveAt(0) -End Sub - -```` - -{{endregion}} + + 4\. On a button click of another button, change the `Grade` of the last `Student` in the collection to "F": -{{source=..\SamplesCS\GridView\PopulatingWithData\ReflectingCustomObjectChanges.cs region=setGrade}} -{{source=..\SamplesVB\GridView\PopulatingWithData\ReflectingCustomObjectChanges.vb region=setGrade}} - -````C# -private void btnSetGrade_Click(object sender, EventArgs e) -{ - collectionOfStudents[collectionOfStudents.Count - 1].Grade = "F"; -} - -```` -````VB.NET -Private Sub btnSetGrade_Click(ByVal sender As Object, ByVal e As EventArgs) - collectionOfStudents(collectionOfStudents.Count - 1).Grade = "F" -End Sub - -```` - -{{endregion}} + + Let's now test this case. At the beginning we have this view: @@ -293,208 +96,23 @@ This is the most valid case among the three described cases. Here, we are bindin 1\. Create a class Student that implements `INotifyPropertyChanged`: -{{source=..\SamplesCS\GridView\PopulatingWithData\StudentDynamic.cs region=student}} -{{source=..\SamplesVB\GridView\PopulatingWithData\StudentDynamic.vb region=student}} - -````C# -public class Student : System.ComponentModel.INotifyPropertyChanged -{ - int m_id; - string m_name; - string m_grade; - public event PropertyChangedEventHandler PropertyChanged; - public Student(int m_id, string m_name, string m_grade) - { - this.m_id = m_id; - this.m_name = m_name; - this.m_grade = m_grade; - } - public int Id - { - get - { - return m_id; - } - set - { - if (this.m_id != value) - { - this.m_id = value; - OnPropertyChanged("Id"); - } - } - } - public string Name - { - get - { - return m_name; - } - set - { - if (this.m_name != value) - { - this.m_name = value; - OnPropertyChanged("Name"); - } - } - } - public string Grade - { - get - { - return m_grade; - } - set - { - if (this.m_grade != value) - { - this.m_grade = value; - OnPropertyChanged("Grade"); - } - } - } - - protected virtual void OnPropertyChanged(string propertyName) - { - if (PropertyChanged != null) - { - PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); - } - } -} - -```` -````VB.NET -Public Class Student - Implements System.ComponentModel.INotifyPropertyChanged - Private m_id As Integer - Private m_name As String - Private m_grade As String - Public Event PropertyChanged As PropertyChangedEventHandler Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged - Public Sub New(ByVal m_id As Integer, ByVal m_name As String, ByVal m_grade As String) - Me.m_id = m_id - Me.m_name = m_name - Me.m_grade = m_grade - End Sub - Public Property Id() As Integer - Get - Return m_id - End Get - Set(ByVal value As Integer) - If Me.m_id <> value Then - Me.m_id = value - OnPropertyChanged("Id") - End If - End Set - End Property - Public Property Name() As String - Get - Return m_name - End Get - Set(ByVal value As String) - If Me.m_name <> value Then - Me.m_name = value - OnPropertyChanged("Name") - End If - End Set - End Property - Public Property Grade() As String - Get - Return m_grade - End Get - Set(ByVal value As String) - If Me.m_grade <> value Then - Me.m_grade = value - OnPropertyChanged("Grade") - End If - End Set - End Property - Protected Overridable Sub OnPropertyChanged(ByVal propertyName As String) - RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName)) - End Sub -End Class - -```` - -{{endregion}} + + 2\. Fill a BindingList collection with a few objects of type `Student` and bind RadGridView to it: -{{source=..\SamplesCS\GridView\PopulatingWithData\ReflectingCustomObjectChanges.cs region=bindingList}} -{{source=..\SamplesVB\GridView\PopulatingWithData\ReflectingCustomObjectChanges.vb region=bindingList}} - -````C# -BindingList collectionOfStudents = new BindingList(); -protected override void OnLoad(EventArgs e) -{ - base.OnLoad(e); - collectionOfStudents.Add(new Student(0, "Peter", "A+")); - collectionOfStudents.Add(new Student(1, "John", "D-")); - collectionOfStudents.Add(new Student(2, "Antony", "B+")); - collectionOfStudents.Add(new Student(3, "David", "A-")); - collectionOfStudents.Add(new Student(4, "John", "D-")); - this.radGridView1.DataSource = collectionOfStudents; -} - -```` -````VB.NET -Private collectionOfStudents As New BindingList(Of Student)() -Protected Overrides Sub OnLoad(ByVal e As EventArgs) - MyBase.OnLoad(e) - collectionOfStudents.Add(New Student(0, "Peter", "A+")) - collectionOfStudents.Add(New Student(1, "John", "D-")) - collectionOfStudents.Add(New Student(2, "Antony", "B+")) - collectionOfStudents.Add(New Student(3, "David", "A-")) - collectionOfStudents.Add(New Student(4, "John", "D-")) - Me.radGridView1.DataSource = collectionOfStudents -End Sub - -```` - -{{endregion}} + + 3\. On a button click, remove the first object in the collection: -{{source=..\SamplesCS\GridView\PopulatingWithData\ReflectingCustomObjectChanges.cs region=buttonRemove}} -{{source=..\SamplesVB\GridView\PopulatingWithData\ReflectingCustomObjectChanges.vb region=buttonRemove}} - -````C# -private void btnDeleteRecord_Click(object sender, EventArgs e) -{ - collectionOfStudents.RemoveAt(0); -} - -```` -````VB.NET -Private Sub btnDeleteRecord_Click(ByVal sender As Object, ByVal e As EventArgs) - collectionOfStudents.RemoveAt(0) -End Sub - -```` - -{{endregion}} + + 4\. On a button click of another button, set the `Grade` of the last `Student` to "F": -{{source=..\SamplesCS\GridView\PopulatingWithData\ReflectingCustomObjectChanges.cs region=setGrade}} -{{source=..\SamplesVB\GridView\PopulatingWithData\ReflectingCustomObjectChanges.vb region=setGrade}} - -````C# -private void btnSetGrade_Click(object sender, EventArgs e) -{ - collectionOfStudents[collectionOfStudents.Count - 1].Grade = "F"; -} - -```` -````VB.NET -Private Sub btnSetGrade_Click(ByVal sender As Object, ByVal e As EventArgs) - collectionOfStudents(collectionOfStudents.Count - 1).Grade = "F" -End Sub - -```` - -{{endregion}} + + Let's now test this case. At the beginning we have this view: diff --git a/controls/gridview/populating-with-data/tips-when-binding-to-custom-collections.md b/controls/gridview/populating-with-data/tips-when-binding-to-custom-collections.md index 6759816be..90a288c15 100644 --- a/controls/gridview/populating-with-data/tips-when-binding-to-custom-collections.md +++ b/controls/gridview/populating-with-data/tips-when-binding-to-custom-collections.md @@ -29,35 +29,8 @@ Currently RadGridView supports sorting, filtering and grouping natively. This is These features are not tightly coupled with the column declarations of the grid but with the data that the grid is bound to. To clarify the idea, consider the following scenario. You want to display a list of all files in a directory. For this purpose you use __FileSystemInfo__ from the __System.IO.FileSystemInfo__ namespace. This collection has many properties: __Attributes__, __CreationTime__, __CreationTimeUtc__, __Exists__, __Extension__, __FullName__, __LastAccessTime__, __LastAccessTimeUtc__, __LastWriteTime__, __LastWriteTimeUtc__ and __Name__. This is a long list that you probably don't want to expose in the grid. Instead you define the columns to be displayed and supply the GridView __DataSource__ with the files information: -{{source=..\SamplesCS\GridView\PopulatingWithData\TipsWhenBindingToCustomCollections.cs region=addingColumnsToTheColumnsCollection}} -{{source=..\SamplesVB\GridView\PopulatingWithData\TipsWhenBindingToCustomCollections.vb region=addingColumnsToTheColumnsCollection}} - -````C# -radGridView1.MasterTemplate.AutoGenerateColumns = false; -radGridView1.MasterTemplate.Columns.Add(new GridViewTextBoxColumn("Name")); -radGridView1.MasterTemplate.Columns.Add(new GridViewTextBoxColumn("Attributes")); -radGridView1.MasterTemplate.Columns.Add(new GridViewTextBoxColumn("LastAccessTime")); -radGridView1.MasterTemplate.Columns.Add(new GridViewTextBoxColumn("CreationTime")); -DirectoryInfo directory = new DirectoryInfo("C:\\"); -FileSystemInfo[] filesInDirectory = directory.GetFileSystemInfos(); -radGridView1.DataSource = filesInDirectory; - -```` -````VB.NET -RadGridView1.MasterTemplate.AutoGenerateColumns = False -RadGridView1.MasterTemplate.Columns.Add(New GridViewTextBoxColumn("Name")) -RadGridView1.MasterTemplate.Columns.Add(New GridViewTextBoxColumn("Attributes")) -RadGridView1.MasterTemplate.Columns.Add(New GridViewTextBoxColumn("LastAccessTime")) -RadGridView1.MasterTemplate.Columns.Add(New GridViewTextBoxColumn("CreationTime")) -Dim directory As New DirectoryInfo("C:\") -Dim filesInDirectory As FileSystemInfo() = directory.GetFileSystemInfos() -RadGridView1.DataSource = filesInDirectory - -```` - -{{endregion}} - - + + # See Also * [Bind to XML]({%slug winforms/gridview/populating-with-data/bind-to-xml%}) diff --git a/controls/gridview/populating-with-data/tutorial-binding-to-datatable-or-dataset.md b/controls/gridview/populating-with-data/tutorial-binding-to-datatable-or-dataset.md index 31f13e007..80858013b 100644 --- a/controls/gridview/populating-with-data/tutorial-binding-to-datatable-or-dataset.md +++ b/controls/gridview/populating-with-data/tutorial-binding-to-datatable-or-dataset.md @@ -54,31 +54,8 @@ The following tutorial demonstrates binding to a single database table. For info 11\. Replace the Form_Load event handler with the following code. *The "foreach" code iterates all the columns in the grid and calls BestFit() so that the columns will expand to show the data*. -{{source=..\SamplesCS\GridView\PopulatingWithData\TutorialBindingToDataTableOrDataSet.cs region=bestFitColumns}} -{{source=..\SamplesVB\GridView\PopulatingWithData\TutorialBindingToDataTableOrDataSet.vb region=bestFitColumns}} - -````C# -private void TutorialBindingToDataTableOrDataSet_Load(object sender, EventArgs e) -{ - this.categoriesTableAdapter.Fill(this.nwindDataSet.Categories); - foreach (GridViewDataColumn column in radGridView1.Columns) - { - column.BestFit(); - } -} - -```` -````VB.NET -Private Sub TutorialBindingToDataTableOrDataSet_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load - Me.CategoriesTableAdapter.Fill(Me.NwindDataSet.Categories) - For Each column As GridViewDataColumn In RadGridView1.Columns - column.BestFit() - Next -End Sub - -```` - -{{endregion}} + + 12\. Press __F5__ to run the application. diff --git a/controls/gridview/populating-with-data/unbound-mode.md b/controls/gridview/populating-with-data/unbound-mode.md index 7299ea366..fc011caf3 100644 --- a/controls/gridview/populating-with-data/unbound-mode.md +++ b/controls/gridview/populating-with-data/unbound-mode.md @@ -25,26 +25,8 @@ You can create a grid with empty rows and columns and let the user fill the data The following code demonstrates how to create a grid with two columns and ten rows: -{{source=..\SamplesCS\GridView\PopulatingWithData\UnboundMode.cs region=creatingEmptyGrid}} -{{source=..\SamplesVB\GridView\PopulatingWithData\UnboundMode.vb region=creatingEmptyGrid}} - -````C# - -this.radGridView1.RowCount = 10; -this.radGridView1.Columns.Add(new GridViewTextBoxColumn("A")); -this.radGridView1.Columns.Add(new GridViewTextBoxColumn("B")); -this.radGridView1.MasterTemplate.AllowAddNewRow = false; - -```` -````VB.NET -Me.RadGridView1.RowCount = 10 -Me.RadGridView1.Columns.Add(New GridViewTextBoxColumn("A")) -Me.RadGridView1.Columns.Add(New GridViewTextBoxColumn("B")) -Me.RadGridView1.MasterTemplate.AllowAddNewRow = False - -```` - -{{endregion}} + + The result from the code above is on the screenshot below: @@ -54,36 +36,8 @@ The result from the code above is on the screenshot below: In this scenario, you should add the data for each cell in the row, specifying the cell index or the column name. Note that you should first create the columns: -{{source=..\SamplesCS\GridView\PopulatingWithData\UnboundMode.cs region=addingRowsThroughCellsCollection}} -{{source=..\SamplesVB\GridView\PopulatingWithData\UnboundMode.vb region=addingRowsThroughCellsCollection}} - -````C# - -this.radGridView1.Columns.Add(new GridViewTextBoxColumn("A")); -this.radGridView1.Columns.Add(new GridViewTextBoxColumn("B")); -GridViewRowInfo rowInfo = this.radGridView1.Rows.AddNew(); -rowInfo.Cells[0].Value = "A1"; -rowInfo.Cells[1].Value = "B1"; -rowInfo = this.radGridView1.Rows.AddNew(); -rowInfo.Cells["A"].Value = "A2"; -rowInfo.Cells["B"].Value = "B2"; - -```` -````VB.NET -Public Sub Form1_Load1(sender As Object, e As EventArgs) - Me.RadGridView1.Columns.Add(New GridViewTextBoxColumn("A")) - Me.RadGridView1.Columns.Add(New GridViewTextBoxColumn("B")) - Dim rowInfo As GridViewRowInfo = Me.RadGridView1.Rows.AddNew() - rowInfo.Cells(0).Value = "A1" - rowInfo.Cells(1).Value = "B1" - rowInfo = Me.RadGridView1.Rows.AddNew() - rowInfo.Cells("A").Value = "A2" - rowInfo.Cells("B").Value = "B2" -End Sub - -```` - -{{endregion}} + + The code above results in the following grid: @@ -93,207 +47,15 @@ The code above results in the following grid: You can have the same result as the picture above by adding the rows data using the __Add__ method of the __Rows__ collection: -{{source=..\SamplesCS\GridView\PopulatingWithData\UnboundMode.cs region=addingRowsThroughRowsCollection}} -{{source=..\SamplesVB\GridView\PopulatingWithData\UnboundMode.vb region=addingRowsThroughRowsCollection}} - -````C# - -this.radGridView1.Columns.Add(new GridViewTextBoxColumn("A")); -this.radGridView1.Columns.Add(new GridViewTextBoxColumn("B")); -this.radGridView1.Rows.Add("A1", "B1"); -this.radGridView1.Rows.Add("A2", "B2"); - -```` -````VB.NET -Public Sub Form1_Load2(sender As Object, e As EventArgs) - Me.RadGridView1.Columns.Add(New GridViewTextBoxColumn("A")) - Me.RadGridView1.Columns.Add(New GridViewTextBoxColumn("B")) - Me.RadGridView1.Rows.Add("A1", "B1") - Me.RadGridView1.Rows.Add("A2", "B2") -End Sub - -```` - -{{endregion}} + + ## Hierarchical Grid in Unbound mode Setting the hierarchical grid in unbound mode is quite similar to that for the bound mode with only difference is setting the unbound mode itself. First of all you need to create and the columns you need. After that set up the relation and finally load the data. -{{source=..\SamplesCS\GridView\PopulatingWithData\UnboundMode.cs region=creatingHierarchicalGridInUnboundMode}} -{{source=..\SamplesVB\GridView\PopulatingWithData\UnboundMode.vb region=creatingHierarchicalGridInUnboundMode}} - -````C# - -public void creatingHierarchicalGridInUnboundMode() -{ - //setup the master template - GridViewImageColumn column = new GridViewImageColumn("Photo"); - column.ImageLayout = ImageLayout.Stretch; - radGridView1.MasterTemplate.Columns.Add(column); - GridViewTextBoxColumn textColumn = new GridViewTextBoxColumn("Name"); - textColumn.Width = 150; - radGridView1.MasterTemplate.Columns.Add(textColumn); - radGridView1.MasterTemplate.Columns.Add(new GridViewDecimalColumn("Salary")); - GridViewDateTimeColumn dateTimeColumn = new GridViewDateTimeColumn("Hire Date"); - dateTimeColumn.Width = 100; - dateTimeColumn.TextAlignment = ContentAlignment.MiddleCenter; - radGridView1.MasterTemplate.Columns.Add(dateTimeColumn); - textColumn = new GridViewTextBoxColumn("Title"); - textColumn.Width = 150; - radGridView1.MasterTemplate.Columns.Add(textColumn); - radGridView1.MasterTemplate.Columns.Add(new GridViewCheckBoxColumn("Active")); - radGridView1.MasterTemplate.Columns.Add(new GridViewCommandColumn("Action")); - - //setup the child template - GridViewTemplate template = new GridViewTemplate(); - template.AllowAddNewRow = true; - template.Columns.Add(new GridViewTextBoxColumn("Name")); - template.Columns.Add(new GridViewTextBoxColumn("Product Number")); - template.Columns.Add(new GridViewDecimalColumn("Quantity")); - template.Columns.Add(new GridViewDecimalColumn("Discount")); - template.Columns.Add(new GridViewDecimalColumn("Total")); - radGridView1.MasterTemplate.Templates.Add(template); - - //create the relation - GridViewRelation relation = new GridViewRelation(radGridView1.MasterTemplate); - relation.ChildTemplate = template; - relation.RelationName = "EmployeesOrders"; - relation.ParentColumnNames.Add("Name"); - relation.ChildColumnNames.Add("Name"); - radGridView1.Relations.Add(relation); - - //load data - LoadUnboundData(); -} - -private void LoadUnboundData() -{ - using (radGridView1.DeferRefresh()) - { - for (int i = 0; i < nwindDataSet.Employees.Count; i++) - { - Random random = new Random((int)DateTime.Now.Ticks); - NwindDataSet.EmployeesRow row = nwindDataSet.Employees[i]; - string name = row.FirstName + " " + row.LastName; - radGridView1.MasterTemplate.Rows.Add(GetImageFromData(row.Photo), name, random.Next(45000), row.HireDate, row.Title, (random.Next(100) > 50), "View"); - GridViewTemplate template = radGridView1.MasterTemplate.Templates[0]; - int rowCount = random.Next(20); - for (int j = 0; j < rowCount; j++) - { - template.Rows.Add(name, random.Next(1000), random.Next(50), random.Next(100), random.Next(10000)); - } - } - } -} - -private Image GetImageFromData(byte[] imageData) -{ - const int OleHeaderLength = 78; - - MemoryStream memoryStream = new MemoryStream(); - - if (HasOleContainerHeader(imageData)) - { - memoryStream.Write(imageData, OleHeaderLength, imageData.Length - OleHeaderLength); - } - else - { - memoryStream.Write(imageData, 0, imageData.Length); - } - - Bitmap bitmap = new Bitmap(memoryStream); - - return bitmap.GetThumbnailImage(55, 65, null, new IntPtr()); -} - -private bool HasOleContainerHeader(byte[] imageByteArray) -{ - const byte OleByte0 = 21; - - const byte OleByte1 = 28; - - return (imageByteArray[0] == OleByte0) && (imageByteArray[1] == OleByte1); -} - -```` -````VB.NET -Public Sub creatingHierarchicalGridInUnboundMode() - 'setup the master template - Dim column As New GridViewImageColumn("Photo") - column.ImageLayout = ImageLayout.Stretch - RadGridView1.MasterTemplate.Columns.Add(column) - Dim textColumn As New GridViewTextBoxColumn("Name") - textColumn.Width = 150 - RadGridView1.MasterTemplate.Columns.Add(textColumn) - RadGridView1.MasterTemplate.Columns.Add(New GridViewDecimalColumn("Salary")) - Dim dateTimeColumn As New GridViewDateTimeColumn("Hire Date") - dateTimeColumn.Width = 100 - dateTimeColumn.TextAlignment = ContentAlignment.MiddleCenter - RadGridView1.MasterTemplate.Columns.Add(dateTimeColumn) - textColumn = New GridViewTextBoxColumn("Title") - textColumn.Width = 150 - RadGridView1.MasterTemplate.Columns.Add(textColumn) - RadGridView1.MasterTemplate.Columns.Add(New GridViewCheckBoxColumn("Active")) - RadGridView1.MasterTemplate.Columns.Add(New GridViewCommandColumn("Action")) - 'setup the child template - Dim template As New GridViewTemplate() - template.AllowAddNewRow = True - template.Columns.Add(New GridViewTextBoxColumn("Name")) - template.Columns.Add(New GridViewTextBoxColumn("Product Number")) - template.Columns.Add(New GridViewDecimalColumn("Quantity")) - template.Columns.Add(New GridViewDecimalColumn("Discount")) - template.Columns.Add(New GridViewDecimalColumn("Total")) - RadGridView1.MasterTemplate.Templates.Add(template) - 'create the relation - Dim relation As New GridViewRelation(RadGridView1.MasterTemplate) - relation.ChildTemplate = template - relation.RelationName = "EmployeesOrders" - relation.ParentColumnNames.Add("Name") - relation.ChildColumnNames.Add("Name") - RadGridView1.Relations.Add(relation) - 'load data - LoadUnboundData() -End Sub -Private Sub LoadUnboundData() - Using RadGridView1.DeferRefresh() - For i As Integer = 0 To NwindDataSet.Employees.Count - 1 - Dim now As Long = Date.Now.Ticks - Dim seed As Integer = CType(now And Integer.MaxValue, Integer) - Dim random As New Random(seed) - Dim row As NwindDataSet.EmployeesRow = NwindDataSet.Employees(i) - Dim name As String = row.FirstName & " " & row.LastName - RadGridView1.MasterTemplate.Rows.Add(GetImageFromData(row.Photo), name, random.Next(45000), row.HireDate, row.Title, (random.Next(100) > 50), "View") - Dim template As GridViewTemplate = RadGridView1.MasterTemplate.Templates(0) - Dim rowCount As Integer = random.Next(20) - For j As Integer = 0 To rowCount - 1 - template.Rows.Add(name, random.Next(1000), random.Next(50), random.Next(100), random.Next(10000)) - Next j - Next i - End Using -End Sub -Private Function GetImageFromData(ByVal imageData() As Byte) As Image - Const OleHeaderLength As Integer = 78 - Dim memoryStream As New MemoryStream() - If HasOleContainerHeader(imageData) Then - memoryStream.Write(imageData, OleHeaderLength, imageData.Length - OleHeaderLength) - Else - memoryStream.Write(imageData, 0, imageData.Length) - End If - Dim bitmap As New Bitmap(memoryStream) - Return bitmap.GetThumbnailImage(55, 65, Nothing, New IntPtr()) -End Function -Private Function HasOleContainerHeader(ByVal imageByteArray() As Byte) As Boolean - Const OleByte0 As Byte = 21 - Const OleByte1 As Byte = 28 - Return (imageByteArray(0) = OleByte0) AndAlso (imageByteArray(1) = OleByte1) -End Function - -```` - -{{endregion}} - - + + # See Also * [Bind to XML]({%slug winforms/gridview/populating-with-data/bind-to-xml%}) diff --git a/controls/gridview/populating-with-data/updating-the-database-with-ado.net.md b/controls/gridview/populating-with-data/updating-the-database-with-ado.net.md index 41de6ec94..ac36a7a8c 100644 --- a/controls/gridview/populating-with-data/updating-the-database-with-ado.net.md +++ b/controls/gridview/populating-with-data/updating-the-database-with-ado.net.md @@ -28,62 +28,8 @@ Let's assume that we have an ADO.NET DataTable that loads its data from a `SqlDa This approach allows us to update the database when the end-user changes the current row in RadGridView. To commit the data to the database in this case, we can use the `BindingSource` `CurrentItemChanged` event, but we also need to use one additional member to save the last edited row instance. Here is a solution using this approach: -{{source=..\SamplesCS\GridView\PopulatingWithData\AutoSavingDataBSEventsForm.cs region=bindingSource}} -{{source=..\SamplesVB\GridView\PopulatingWithData\AutoSavingDataBSEventsForm.vb region=bindingSource}} - -````C# -private DataRow lastEditRow = null; -public AutoSavingDataBSEventsForm() -{ - InitializeComponent(); - this.employeesBindingSource.CurrentChanged += new EventHandler(employeesBindingSource_CurrentChanged); -} -private void AutoSavingDataBSEventsForm_Load(object sender, EventArgs e) -{ - // TODO: This line of code loads data into the 'nwindDataSet.Employees' table. You can move, or remove it, as needed. - this.employeesTableAdapter.Fill(this.nwindDataSet.Employees); - object current = this.employeesBindingSource.Current; - if (current != null) - { - this.lastEditRow = ((DataRowView)current).Row; - } -} -void employeesBindingSource_CurrentChanged(object sender, EventArgs e) -{ - DataRow dataRow = ((DataRowView)((BindingSource)sender).Current).Row; - if (lastEditRow != null && lastEditRow.RowState == DataRowState.Modified) - { - this.employeesTableAdapter.Update(lastEditRow); - } - lastEditRow = dataRow; -} - -```` -````VB.NET -Private lastEditRow As DataRow = Nothing -Public Sub New() - InitializeComponent() - AddHandler EmployeesBindingSource.CurrentChanged, AddressOf employeesBindingSource_CurrentChanged -End Sub -Private Sub AutoSavingDataBSEventsForm_Load(ByVal sender As Object, ByVal e As EventArgs) - ' TODO: This line of code loads data into the 'nwindDataSet.Employees' table. You can move, or remove it, as needed. - Me.EmployeesTableAdapter.Fill(Me.NwindDataSet.Employees) - Dim current As Object = Me.EmployeesBindingSource.Current - If current IsNot Nothing Then - Me.lastEditRow = (CType(current, DataRowView)).Row - End If -End Sub -Private Sub employeesBindingSource_CurrentChanged(ByVal sender As Object, ByVal e As EventArgs) - Dim dataRow As DataRow = (CType((CType(sender, BindingSource)).Current, DataRowView)).Row - If lastEditRow IsNot Nothing AndAlso lastEditRow.RowState = DataRowState.Modified Then - Me.EmployeesTableAdapter.Update(lastEditRow) - End If - lastEditRow = dataRow -End Sub - -```` - -{{endregion}} + + ## Updating the database on row added/deleted or when the current row is changed @@ -91,162 +37,25 @@ In the context of RadGridView, we can use a combination of events to produce opt Here is how we can update the database when the end-user __deletes__ a row. Basically, we need to handle the `UserDeletingRow` and `UserDeletedRows` events. If several rows are selected and deleted at once, these events will be fired only once and their `e.Rows` collection will contain all the deleted rows: -{{source=..\SamplesCS\GridView\PopulatingWithData\AutoSavingDataGridEvents.cs region=deletingRows}} -{{source=..\SamplesVB\GridView\PopulatingWithData\AutoSavingDataGridEvents.vb region=deletingRows}} - -````C# -private List lastRemovedRows = new List(); -void radGridView1_UserDeletingRow(object sender, Telerik.WinControls.UI.GridViewRowCancelEventArgs e) -{ - for (int i = 0; i < e.Rows.Length; i++) - { - DataRowView dataRowView = e.Rows[i].DataBoundItem as DataRowView; - if (dataRowView != null) - { - this.lastRemovedRows.Add(dataRowView); - } - } -} -void radGridView1_UserDeletedRow(object sender, Telerik.WinControls.UI.GridViewRowEventArgs e) -{ - DataRow[] rows = new DataRow[this.lastRemovedRows.Count]; - for (int i = 0; i < this.lastRemovedRows.Count; i++) - { - rows[i] = this.lastRemovedRows[i].Row; - } - this.employeesTableAdapter.Update(rows); - this.lastRemovedRows.Clear(); -} - -```` -````VB.NET -Private lastRemovedRows As New List(Of DataRowView)() -Private Sub radGridView1_UserDeletingRow(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewRowCancelEventArgs) Handles RadGridView1.UserDeletingRow - For i As Integer = 0 To e.Rows.Length - 1 - Dim dataRowView As DataRowView = TryCast(e.Rows(i).DataBoundItem, DataRowView) - If dataRowView IsNot Nothing Then - Me.lastRemovedRows.Add(dataRowView) - End If - Next i -End Sub -Private Sub radGridView1_UserDeletedRow(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewRowEventArgs) Handles RadGridView1.UserDeletedRow - Dim rows(Me.lastRemovedRows.Count - 1) As DataRow - For i As Integer = 0 To Me.lastRemovedRows.Count - 1 - rows(i) = Me.lastRemovedRows(i).Row - Next i - Me.EmployeesTableAdapter.Update(rows) - Me.lastRemovedRows.Clear() -End Sub - -```` - -{{endregion}} + + And this is how we can update the database when the user __adds__ a new row. The `UserAddedRow` event should be handled in this case: -{{source=..\SamplesCS\GridView\PopulatingWithData\AutoSavingDataGridEvents.cs region=addingRows}} -{{source=..\SamplesVB\GridView\PopulatingWithData\AutoSavingDataGridEvents.vb region=addingRows}} - -````C# -void radGridView1_UserAddedRow(object sender, Telerik.WinControls.UI.GridViewRowEventArgs e) -{ - DataRowView dataRowView = e.Rows[0].DataBoundItem as DataRowView; - DataRow row = dataRowView.Row; - this.employeesTableAdapter.Update(row); -} - -```` -````VB.NET -Private Sub radGridView1_UserAddedRow(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewRowEventArgs) Handles RadGridView1.UserAddedRow - Dim dataRowView As DataRowView = TryCast(e.Rows(0).DataBoundItem, DataRowView) - Dim row As DataRow = dataRowView.Row - Me.EmployeesTableAdapter.Update(row) -End Sub - -```` - -{{endregion}} + + When the user __changes the current__ row, you can update the database not only by using the `CurrentItemChanged` event of the BindingSource, but by handling the `CurrentRowChanged` event of RadGridView as well: -{{source=..\SamplesCS\GridView\PopulatingWithData\AutoSavingDataGridEvents.cs region=changingCurrentRow}} -{{source=..\SamplesVB\GridView\PopulatingWithData\AutoSavingDataGridEvents.vb region=changingCurrentRow}} - -````C# -void radGridView1_CurrentRowChanged(object sender, Telerik.WinControls.UI.CurrentRowChangedEventArgs e) -{ - if (e.OldRow == null) - { - return; - } - DataRowView dataRowView = e.OldRow.DataBoundItem as DataRowView; - if (dataRowView != null) - { - DataRow dataRow = dataRowView.Row; - if (dataRow.RowState == DataRowState.Modified) - { - this.employeesTableAdapter.Update(dataRow); - } - } -} - -```` -````VB.NET -Private Sub radGridView1_CurrentRowChanged(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.CurrentRowChangedEventArgs) Handles RadGridView1.CurrentRowChanged - If e.OldRow Is Nothing Then - Return - End If - Dim dataRowView As DataRowView = TryCast(e.OldRow.DataBoundItem, DataRowView) - If dataRowView IsNot Nothing Then - Dim dataRow As DataRow = dataRowView.Row - If dataRow.RowState = DataRowState.Modified Then - Me.EmployeesTableAdapter.Update(dataRow) - End If - End If -End Sub - -```` - -{{endregion}} + + ## Updating the database when a single cell value is changed The above solutions will come in handy in many cases. However, in some scenarios the database may have to be updated immediately after the user edits a single cell, without changing the current row. For this case, you have to handle the `CellValueChanged` event as shown below: -{{source=..\SamplesCS\GridView\PopulatingWithData\AutoSavingDataGridEvents.cs region=changingValue}} -{{source=..\SamplesVB\GridView\PopulatingWithData\AutoSavingDataGridEvents.vb region=changingValue}} - -````C# -void radGridView1_CellValueChanged(object sender, Telerik.WinControls.UI.GridViewCellEventArgs e) -{ - IEditableObject editbaleObject = e.Row.DataBoundItem as IEditableObject; - if (editbaleObject != null) - { - editbaleObject.EndEdit(); - } - DataRowView dataRowView = e.Row.DataBoundItem as DataRowView; - if (dataRowView != null) - { - this.employeesTableAdapter.Update(dataRowView.Row); - } -} - -```` -````VB.NET -Private Sub radGridView1_CellValueChanged(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewCellEventArgs) Handles RadGridView1.CellValueChanged - Dim editbaleObject As IEditableObject = TryCast(e.Row.DataBoundItem, IEditableObject) - If editbaleObject IsNot Nothing Then - editbaleObject.EndEdit() - End If - Dim dataRowView As DataRowView = TryCast(e.Row.DataBoundItem, DataRowView) - If dataRowView IsNot Nothing Then - Me.EmployeesTableAdapter.Update(dataRowView.Row) - End If -End Sub - -```` - -{{endregion}} + + `IEditableObject` provides functionality to commit or rollback changes to an object that is used as a data source. The DataTable object supports this functionality. If the current item is changed in the associated `CurrencyManager`, the __EndEdit__ operation is called automatically - it is processed when the current row of RadGridView is changed (to another row). The EndEdit operation in this implementation is needed to commit the changes that happen in the current row itself even if the current row of RadGridView is not changed (to another row). diff --git a/controls/gridview/styling-and-appearance/alternating-row-color.md b/controls/gridview/styling-and-appearance/alternating-row-color.md index 73e7c8602..80ac570fc 100644 --- a/controls/gridview/styling-and-appearance/alternating-row-color.md +++ b/controls/gridview/styling-and-appearance/alternating-row-color.md @@ -17,37 +17,15 @@ In order to enable the feature, you should set the __EnableAlternatingRowColor__ #### Enable alternating row color -{{source=..\SamplesCS\GridView\StylingAndAppearance\AlternatingRowColor1.cs region=alternatingColor}} -{{source=..\SamplesVB\GridView\StylingAndAppearance\AlternatingRowColor1.vb region=alternatingColor}} - -````C# -this.radGridView1.EnableAlternatingRowColor = true; - -```` -````VB.NET -Me.RadGridView1.EnableAlternatingRowColor = True - -```` - -{{endregion}} + + In order to change the default alternating row color, set the __AlternatingRowColor__ property: #### Changing the alternating row color -{{source=..\SamplesCS\GridView\StylingAndAppearance\AlternatingRowColor1.cs region=changeAlternatingRow}} -{{source=..\SamplesVB\GridView\StylingAndAppearance\AlternatingRowColor1.vb region=changeAlternatingRow}} - -````C# -((GridTableElement)this.radGridView1.TableElement).AlternatingRowColor = Color.Yellow; - -```` -````VB.NET -CType(Me.RadGridView1.TableElement, GridTableElement).AlternatingRowColor = Color.Yellow - -```` - -{{endregion}} + + The result is shown on the screenshot below: diff --git a/controls/gridview/styling-and-appearance/html-like-text-formatting.md b/controls/gridview/styling-and-appearance/html-like-text-formatting.md index e98ef42ef..218dae647 100644 --- a/controls/gridview/styling-and-appearance/html-like-text-formatting.md +++ b/controls/gridview/styling-and-appearance/html-like-text-formatting.md @@ -19,31 +19,8 @@ Tags are only parsed if __DisableHTMLRendering__ is set to *false*. If you skip #### HTML-like text formatting -{{source=..\SamplesCS\GridView\StylingAndAppearance\HtmlLikeTextFormatting.cs region=htmlLikeTextFormatting}} -{{source=..\SamplesVB\GridView\StylingAndAppearance\HtmlLikeTextFormatting.vb region=htmlLikeTextFormatting}} - -````C# -DataTable t = new DataTable(); -t.Columns.Add("A"); -t.Rows.Add(" ID: 1"); -t.Rows.Add(" ID: 2"); -t.Rows.Add(" ID: 3"); -this.radGridView1.DataSource = t; -this.radGridView1.Columns[0].DisableHTMLRendering = false; - -```` -````VB.NET -Dim t As New DataTable() -t.Columns.Add("A") -t.Rows.Add(" ID: 1") -t.Rows.Add(" ID: 2") -t.Rows.Add(" ID: 3") -Me.RadGridView1.DataSource = t -Me.RadGridView1.Columns(0).DisableHTMLRendering = False - -```` - -{{endregion}} + + >note Please refer to *HTML-like Text formatting* topic in *Telerik Presentation Framework* section for the list of support tags. > diff --git a/controls/gridview/styling-and-appearance/images.md b/controls/gridview/styling-and-appearance/images.md index c88fe7e34..9f89a9cee 100644 --- a/controls/gridview/styling-and-appearance/images.md +++ b/controls/gridview/styling-and-appearance/images.md @@ -27,50 +27,18 @@ You can change the images using the properties shown below: #### Changing the current row image -{{source=..\SamplesCS\GridView\StylingAndAppearance\ChangingTheCurrentRowIndicator.cs region=changeTheCurrentRowImage}} -{{source=..\SamplesVB\GridView\StylingAndAppearance\ChangingTheCurrentRowIndicator.vb region=changeTheCurrentRowImage}} - -````C# -((GridTableElement)this.radGridView1.TableElement).CurrentRowHeaderImage = Image.FromFile("..\\..\\DataSources\\separator.gif"); -((GridTableElement)this.radGridView1.TableElement).EditRowHeaderImage = Image.FromFile("..\\..\\DataSources\\edit.png"); -((GridTableElement)this.radGridView1.TableElement).ErrorRowHeaderImage = Image.FromFile("..\\..\\DataSources\\error.png"); -((GridTableElement)this.radGridView1.TableElement).NewRowHeaderImage = Image.FromFile("..\\..\\DataSources\\star.png"); - -```` -````VB.NET -DirectCast(Me.RadGridView1.TableElement, GridTableElement).CurrentRowHeaderImage = Image.FromFile("..\\..\\DataSources\\separator.gif") -DirectCast(Me.RadGridView1.TableElement, GridTableElement).EditRowHeaderImage = Image.FromFile("..\\..\\DataSources\\edit.png") -DirectCast(Me.RadGridView1.TableElement, GridTableElement).ErrorRowHeaderImage = Image.FromFile("..\\..\\DataSources\\error.png") -DirectCast(Me.RadGridView1.TableElement, GridTableElement).NewRowHeaderImage = Image.FromFile("..\\..\\DataSources\\star.png") - -```` - -{{endregion}} - + + + ## Setting an image in a column header The following code snippet demonstrates how to set an image for a certain column: #### Set an image in a column header -{{source=..\SamplesCS\GridView\StylingAndAppearance\ChangingTheCurrentRowIndicator.cs region=setColumnHeaderImage}} -{{source=..\SamplesVB\GridView\StylingAndAppearance\ChangingTheCurrentRowIndicator.vb region=setColumnHeaderImage}} - -````C# -radGridView1.Columns["Date"].HeaderImage = Image.FromFile("..\\..\\DataSources\\star.png"); -radGridView1.Columns["Date"].TextImageRelation = TextImageRelation.ImageAboveText; - -```` -````VB.NET -RadGridView1.Columns("Picture Name").HeaderImage = Image.FromFile("..\\..\\DataSources\\star.png") -RadGridView1.Columns("Picture Name").TextImageRelation = TextImageRelation.ImageAboveText - -```` - -{{endregion}} - - - + + + # See Also * [Alternating Row Color]({%slug winforms/gridview/styling-and-appearance/alternating-row-color%}) diff --git a/controls/gridview/view-definitions/column-groups-view.md b/controls/gridview/view-definitions/column-groups-view.md index ed7fa3bcd..e89124120 100644 --- a/controls/gridview/view-definitions/column-groups-view.md +++ b/controls/gridview/view-definitions/column-groups-view.md @@ -53,83 +53,22 @@ First instantiate __ColumnGroupsViewDefinition__ and add some groups. #### Create groups -{{source=..\SamplesCS\GridView\ViewDefinitions\ColumnGroupsView.cs region=createGroups}} -{{source=..\SamplesVB\GridView\ViewDefinitions\ColumnGroupsView.vb region=createGroups}} - -````C# -ColumnGroupsViewDefinition view = new ColumnGroupsViewDefinition(); -view.ColumnGroups.Add(new GridViewColumnGroup("Customer Contact")); -view.ColumnGroups.Add(new GridViewColumnGroup("Details")); -view.ColumnGroups[1].Groups.Add(new GridViewColumnGroup("Address")); -view.ColumnGroups[1].Groups.Add(new GridViewColumnGroup("Contact")); - -```` -````VB.NET -Dim view As New ColumnGroupsViewDefinition() -view.ColumnGroups.Add(New GridViewColumnGroup("Customer Contact")) -view.ColumnGroups.Add(New GridViewColumnGroup("Details")) -view.ColumnGroups(1).Groups.Add(New GridViewColumnGroup("Address")) -view.ColumnGroups(1).Groups.Add(New GridViewColumnGroup("Contact")) - -```` - -{{endregion}} + + Then add at least one row. This row will contain the desired columns. #### Add rows to groups -{{source=..\SamplesCS\GridView\ViewDefinitions\ColumnGroupsView.cs region=addRows}} -{{source=..\SamplesVB\GridView\ViewDefinitions\ColumnGroupsView.vb region=addRows}} - -````C# -view.ColumnGroups[0].Rows.Add(new GridViewColumnGroupRow()); -view.ColumnGroups[0].Rows[0].ColumnNames.Add("CompanyName"); -view.ColumnGroups[0].Rows[0].ColumnNames.Add("ContactName"); -view.ColumnGroups[0].Rows[0].ColumnNames.Add("ContactTitle"); -view.ColumnGroups[1].Groups[0].Rows.Add(new GridViewColumnGroupRow()); -view.ColumnGroups[1].Groups[0].Rows[0].ColumnNames.Add("Address"); -view.ColumnGroups[1].Groups[0].Rows[0].ColumnNames.Add("City"); -view.ColumnGroups[1].Groups[0].Rows[0].ColumnNames.Add("Country"); -view.ColumnGroups[1].Groups[1].Rows.Add(new GridViewColumnGroupRow()); -view.ColumnGroups[1].Groups[1].Rows[0].ColumnNames.Add("Phone"); -view.ColumnGroups[1].Groups[1].Rows[0].ColumnNames.Add("Fax"); - -```` -````VB.NET -view.ColumnGroups(0).Rows.Add(New GridViewColumnGroupRow()) -view.ColumnGroups(0).Rows(0).ColumnNames.Add("CompanyName") -view.ColumnGroups(0).Rows(0).ColumnNames.Add("ContactName") -view.ColumnGroups(0).Rows(0).ColumnNames.Add("ContactTitle") -view.ColumnGroups(1).Groups(0).Rows.Add(New GridViewColumnGroupRow()) -view.ColumnGroups(1).Groups(0).Rows(0).ColumnNames.Add("Address") -view.ColumnGroups(1).Groups(0).Rows(0).ColumnNames.Add("City") -view.ColumnGroups(1).Groups(0).Rows(0).ColumnNames.Add("Country") -view.ColumnGroups(1).Groups(1).Rows.Add(New GridViewColumnGroupRow()) -view.ColumnGroups(1).Groups(1).Rows(0).ColumnNames.Add("Phone") -view.ColumnGroups(1).Groups(1).Rows(0).ColumnNames.Add("Fax") - -```` - -{{endregion}} + + At the end simply set the __ViewDefinitions__ property to the newly created __ViewDefinition__ instance. #### Set the ViewDefinition property of RadGridView -{{source=..\SamplesCS\GridView\ViewDefinitions\ColumnGroupsView.cs region=setTheViewDefinition}} -{{source=..\SamplesVB\GridView\ViewDefinitions\ColumnGroupsView.vb region=setTheViewDefinition}} - -````C# -radGridView1.ViewDefinition = view; - -```` -````VB.NET -RadGridView1.ViewDefinition = view - -```` - -{{endregion}} + + The result is: diff --git a/controls/gridview/view-definitions/html-view.md b/controls/gridview/view-definitions/html-view.md index 9f393ad23..75bf783a8 100644 --- a/controls/gridview/view-definitions/html-view.md +++ b/controls/gridview/view-definitions/html-view.md @@ -19,89 +19,29 @@ To use an HTML view we should instantiate HtmlViewDefinition and add the desired #### Add rows and cells -{{source=..\SamplesCS\GridView\ViewDefinitions\HTMLView1.cs region=addRowsAndCells}} -{{source=..\SamplesVB\GridView\ViewDefinitions\HTMLView1.vb region=addRowsAndCells}} - -````C# -HtmlViewDefinition view = new HtmlViewDefinition(); -view.RowTemplate.Rows.Add(new RowDefinition()); -view.RowTemplate.Rows.Add(new RowDefinition()); -view.RowTemplate.Rows[0].Cells.Add(new CellDefinition("CustomerID")); -view.RowTemplate.Rows[0].Cells.Add(new CellDefinition("CompanyName")); -view.RowTemplate.Rows[0].Cells.Add(new CellDefinition("City")); -view.RowTemplate.Rows[0].Cells.Add(new CellDefinition("Country")); -view.RowTemplate.Rows[1].Cells.Add(new CellDefinition("Phone")); - -```` -````VB.NET -Dim view As New HtmlViewDefinition() -view.RowTemplate.Rows.Add(New RowDefinition()) -view.RowTemplate.Rows.Add(New RowDefinition()) -view.RowTemplate.Rows(0).Cells.Add(New CellDefinition("CustomerID")) -view.RowTemplate.Rows(0).Cells.Add(New CellDefinition("CompanyName")) -view.RowTemplate.Rows(0).Cells.Add(New CellDefinition("City")) -view.RowTemplate.Rows(0).Cells.Add(New CellDefinition("Country")) -view.RowTemplate.Rows(1).Cells.Add(New CellDefinition("Phone")) - -```` - -{{endregion}} + + The __HtmlViewDefinition__ adds row and column spanning feature like in HTML table. This features enables spanning cells across more than one column or row. To specify a column spanning, set the __ColSpan__ property of the __CellDefinition__: #### Set column spans -{{source=..\SamplesCS\GridView\ViewDefinitions\HTMLView1.cs region=setColSpan}} -{{source=..\SamplesVB\GridView\ViewDefinitions\HTMLView1.vb region=setColSpan}} - -````C# -view.RowTemplate.Rows[1].Cells[0].ColSpan = 2; - -```` -````VB.NET -view.RowTemplate.Rows(1).Cells(0).ColSpan = 2 - -```` - -{{endregion}} + + The __RowSpan__ property sets the row spanning: #### Set row spans -{{source=..\SamplesCS\GridView\ViewDefinitions\HTMLView1.cs region=setRowSpan}} -{{source=..\SamplesVB\GridView\ViewDefinitions\HTMLView1.vb region=setRowSpan}} - -````C# -view.RowTemplate.Rows[0].Cells[2].RowSpan = 2; -view.RowTemplate.Rows[0].Cells[3].RowSpan = 2; - -```` -````VB.NET -view.RowTemplate.Rows(0).Cells(2).RowSpan = 2 -view.RowTemplate.Rows(0).Cells(3).RowSpan = 2 - -```` - -{{endregion}} + + You have to set the __Height__ property of the __RowDefinition__ to change the row height: #### Set row height. -{{source=..\SamplesCS\GridView\ViewDefinitions\HTMLView1.cs region=setRowHeight}} -{{source=..\SamplesVB\GridView\ViewDefinitions\HTMLView1.vb region=setRowHeight}} - -````C# -view.RowTemplate.Rows[0].Height = 40; - -```` -````VB.NET -view.RowTemplate.Rows(0).Height = 40 - -```` - -{{endregion}} + + #### Using HTML-like syntax: @@ -121,33 +61,13 @@ view.RowTemplate.Rows(0).Height = 40 #### Use HTML template -{{source=..\SamplesCS\GridView\ViewDefinitions\HTMLView1.cs region=useHtmlTemplate}} -{{source=..\SamplesVB\GridView\ViewDefinitions\HTMLView1.vb region=useHtmlTemplate}} -````C# -view.RowTemplate.ReadXml(@"..\..\GridView\ViewDefinitions\myViewDefinition.htm"); - -```` -````VB.NET -view.RowTemplate.ReadXml("..\..\GridView\ViewDefinitions\myViewDefinition.htm") - -```` - -{{endregion}} + + At the end simply set the __ViewDefinitions__ property to the newly created __ViewDefinition__ instance. -{{source=..\SamplesCS\GridView\ViewDefinitions\HTMLView1.cs region=setTheViewDefinition}} -{{source=..\SamplesVB\GridView\ViewDefinitions\HTMLView1.vb region=setTheViewDefinition}} -````C# -radGridView1.ViewDefinition = view; - -```` -````VB.NET -RadGridView1.ViewDefinition = view - -```` - -{{endregion}} + + >caution You need to assign the view definition to the *ViewDefinition* property of RadGridView as described in the [overview section]({%slug winforms/gridview/view-definitions/overview%}). > diff --git a/controls/gridview/view-definitions/overview.md b/controls/gridview/view-definitions/overview.md index 12feedda0..bfa1e6406 100644 --- a/controls/gridview/view-definitions/overview.md +++ b/controls/gridview/view-definitions/overview.md @@ -15,19 +15,8 @@ You can change __RadGridView__ visual appearance and behavior by using a view #### Assign ViewDefinition -{{source=..\SamplesCS\GridView\ViewDefinitions\Overview.cs region=ViewDefinition}} -{{source=..\SamplesVB\GridView\ViewDefinitions\Overview.vb region=ViewDefinition}} - -````C# -this.radGridView1.ViewDefinition = myDefinition; - -```` -````VB.NET -Me.RadGridView1.ViewDefinition = myDefinition - -```` - -{{endregion}} + + All view definitions implement the __IViewDefinition__ interface and you could create your own definitions, if you wish. Three different view definitions are currently included: diff --git a/controls/gridview/visual-elements/cells/accessing-and-setting-the-currentcell.md b/controls/gridview/visual-elements/cells/accessing-and-setting-the-currentcell.md index cb36469a8..6de8b31ae 100644 --- a/controls/gridview/visual-elements/cells/accessing-and-setting-the-currentcell.md +++ b/controls/gridview/visual-elements/cells/accessing-and-setting-the-currentcell.md @@ -13,23 +13,10 @@ previous_url: gridview-cells-setting-current-cell In order to set the current cell of __RadGridView__, set the __CurrentRow__ and __CurrentColumn__ properties to respective row and column which cross at the desired cell: -{{source=..\SamplesCS\GridView\Cells\SetttingCurrentCell.cs region=settingTheCurrentCell}} -{{source=..\SamplesVB\GridView\Cells\SettingCurrentCell.vb region=settingTheCurrentCell}} + + -````C# -this.radGridView1.CurrentRow = this.radGridView1.Rows[1]; -this.radGridView1.CurrentColumn = this.radGridView1.Columns[1]; -this.Text = this.radGridView1.CurrentCell.Value.ToString(); -```` -````VB.NET -Me.RadGridView1.CurrentRow = Me.RadGridView1.Rows(1) -Me.RadGridView1.CurrentColumn = Me.RadGridView1.Columns(1) -Me.Text = Me.RadGridView1.CurrentCell.Value.ToString() - -```` - -{{endregion}} >caption Figure 1: Changing the current row changes the forms text. @@ -41,19 +28,10 @@ Me.Text = Me.RadGridView1.CurrentCell.Value.ToString() To get an instance of the current cell simply create a variable of type `GridDataCellElement` and assign to it the current cell: -{{source=..\SamplesCS\GridView\Cells\SetttingCurrentCell.cs region=readingTheCurrentCell}} -{{source=..\SamplesVB\GridView\Cells\SettingCurrentCell.vb region=readingTheCurrentCell}} - -````C# -GridDataCellElement cell = radGridView1.CurrentCell; - -```` -````VB.NET -Dim cell As GridDataCellElement = Me.RadGridView1.CurrentCell + + -```` -{{endregion}} >note The **CurrentCell** property can be *null* when you don't have **CurrentRow** or **CurrentColumn.** diff --git a/controls/gridview/visual-elements/cells/accessing-cells.md b/controls/gridview/visual-elements/cells/accessing-cells.md index 5191361e1..54933ac62 100644 --- a/controls/gridview/visual-elements/cells/accessing-cells.md +++ b/controls/gridview/visual-elements/cells/accessing-cells.md @@ -24,22 +24,10 @@ Cells can be accessed by index or the column __Name__ property. In this example we will change a cell value to 10 if it is greater than 10. In this case we assume that there is a "UnitPrice" column and we modify the cell in its first row. -{{source=..\SamplesCS\GridView\Cells\AccessingCells.cs region=accessingCellsByColumnName}} -{{source=..\SamplesVB\GridView\Cells\AccessingCells.vb region=accessingCellsByColumnName}} + + -````C# -if ((decimal)radGridView1.Rows[0].Cells["UnitPrice"].Value > 10) - radGridView1.Rows[0].Cells["UnitPrice"].Value = 10; -```` -````VB.NET -If DirectCast(RadGridView1.Rows(0).Cells("UnitPrice").Value, Decimal) > 10 Then - RadGridView1.Rows(0).Cells("UnitPrice").Value = 10 -End If - -```` - -{{endregion}} >caption Figure 1: Before setting the value. @@ -53,53 +41,19 @@ End If The example below modifies the second cell of the first row and sets a value greater than 10 back to 10. -{{source=..\SamplesCS\GridView\Cells\AccessingCells.cs region=accessingCellsByIndex}} -{{source=..\SamplesVB\GridView\Cells\AccessingCells.vb region=accessingCellsByIndex}} - -````C# -if ((decimal)radGridView1.Rows[0].Cells[5].Value > 10) - radGridView1.Rows[0].Cells[5].Value = 10; - -```` -````VB.NET -If DirectCast(RadGridView1.Rows(0).Cells(5).Value, Decimal) > 10 Then - RadGridView1.Rows(0).Cells(5).Value = 10 -End If + + -```` - -{{endregion}} ## Multiple assignments of cell values When assigning values to several cells subsequently, the __RadGridView__ should be placed between __BeginUpdate__ and __EndUpdate__ method invocations of the desired template. This way of setting multiple assignments is recommended for performance considerations. For example if you have added a sorting descriptor to __RadGridView__ and you enter/modify five cell values without using these methods, the sorting mechanism will recreate the whole grid five times, which will slow it down. On the other hand if this is done between the suggested methods, the sorting mechanism will run only once, right after calling __EndUpdate__ method. -{{source=..\SamplesCS\GridView\Cells\AccessingCells.cs region=updateCells}} -{{source=..\SamplesVB\GridView\Cells\AccessingCells.vb region=updateCells}} - -````C# -radGridView1.TableElement.BeginUpdate(); -radGridView1.Rows[0].Cells["UnitPrice"].Value = 10; -radGridView1.Rows[1].Cells["UnitPrice"].Value = 20; -radGridView1.Rows[2].Cells["UnitPrice"].Value = 30; -radGridView1.Rows[3].Cells["UnitPrice"].Value = 40; -radGridView1.Rows[4].Cells["UnitPrice"].Value = 50; -radGridView1.TableElement.EndUpdate(); - -```` -````VB.NET -Me.RadGridView1.TableElement.BeginUpdate() -RadGridView1.Rows(0).Cells("UnitPrice").Value = 10 -RadGridView1.Rows(1).Cells("UnitPrice").Value = 20 -RadGridView1.Rows(2).Cells("UnitPrice").Value = 30 -RadGridView1.Rows(3).Cells("UnitPrice").Value = 40 -RadGridView1.Rows(4).Cells("UnitPrice").Value = 50 -Me.RadGridView1.TableElement.EndUpdate() - -```` - -{{endregion}} + + + + >caption Figure 3: Setting multiple values. diff --git a/controls/gridview/visual-elements/cells/conditional-formatting-cells.md b/controls/gridview/visual-elements/cells/conditional-formatting-cells.md index 2d1498835..5569748ea 100644 --- a/controls/gridview/visual-elements/cells/conditional-formatting-cells.md +++ b/controls/gridview/visual-elements/cells/conditional-formatting-cells.md @@ -47,27 +47,10 @@ The rule-based formatting objects apply to the cells / rows according to the def The example below detects when a value in the second column `UnitPrice` has a value __greater than 30__. When the condition is met the cell background color is set to *SkyBlue*, the text color is set to *Red* and the text alignment is set to *MiddleRight*. -{{source=..\SamplesCS\GridView\Cells\ConditionalFormattingCells.cs region=conditionalFormattingCells}} -{{source=..\SamplesVB\GridView\Cells\ConditionalFormattingCells.vb region=conditionalFormattingCells}} + + -````C# -ConditionalFormattingObject obj = new ConditionalFormattingObject("MyCondition", ConditionTypes.Greater, "30", "", false); -obj.CellBackColor = Color.SkyBlue; -obj.CellForeColor = Color.Red; -obj.TextAlignment = ContentAlignment.MiddleRight; -this.radGridView1.Columns["UnitPrice"].ConditionalFormattingObjectList.Add(obj); -```` -````VB.NET -Dim obj As New ConditionalFormattingObject("MyCondition", ConditionTypes.Greater, "30", "", False) -obj.CellBackColor = Color.SkyBlue -obj.CellForeColor = Color.Red -obj.TextAlignment = ContentAlignment.MiddleRight -Me.RadGridView1.Columns("UnitPrice").ConditionalFormattingObjectList.Add(obj) - -```` - -{{endregion}} >caption Figure 1: Rule-based formatting objects. @@ -83,25 +66,10 @@ In order to validate an expression, it is suitable to use the [Expression editor The example below detects when a value in the second column `UnitPrice` has a value __greater than 30__ and sets styles to the `ProductName` column. -{{source=..\SamplesCS\GridView\Cells\ConditionalFormattingCells.cs region=expression}} -{{source=..\SamplesVB\GridView\Cells\ConditionalFormattingCells.vb region=expression}} - -````C# -ExpressionFormattingObject obj = new ExpressionFormattingObject("MyCondition", "UnitPrice > 30", false); -obj.CellBackColor = Color.SkyBlue; -obj.CellForeColor = Color.Red; -this.radGridView1.Columns["ProductName"].ConditionalFormattingObjectList.Add(obj); + + -```` -````VB.NET -Dim obj As New ExpressionFormattingObject("MyCondition", "UnitPrice > 30", False) -obj.CellBackColor = Color.SkyBlue -obj.CellForeColor = Color.Red -Me.RadGridView1.Columns("ProductName").ConditionalFormattingObjectList.Add(obj) -```` - -{{endregion}} >caption Figure 2: Expression-based formatting objects. @@ -117,25 +85,10 @@ __RadGridView__ provides a convenient form that the end user can use to create f To access and customize the dialog, you can use the __ConditionalFormattingFormShown__ event. For example, here is how to disallow displaying of non-visible columns in the drop down and also, specify the format of displaying the columns as __name and header text__: -{{source=..\SamplesCS\GridView\Cells\ConditionalFormattingCells.cs region=expression}} -{{source=..\SamplesVB\GridView\Cells\ConditionalFormattingCells.vb region=expression}} - -````C# -ExpressionFormattingObject obj = new ExpressionFormattingObject("MyCondition", "UnitPrice > 30", false); -obj.CellBackColor = Color.SkyBlue; -obj.CellForeColor = Color.Red; -this.radGridView1.Columns["ProductName"].ConditionalFormattingObjectList.Add(obj); - -```` -````VB.NET -Dim obj As New ExpressionFormattingObject("MyCondition", "UnitPrice > 30", False) -obj.CellBackColor = Color.SkyBlue -obj.CellForeColor = Color.Red -Me.RadGridView1.Columns("ProductName").ConditionalFormattingObjectList.Add(obj) + + -```` -{{endregion}} diff --git a/controls/gridview/visual-elements/cells/creating-custom-cells.md b/controls/gridview/visual-elements/cells/creating-custom-cells.md index 1b3d6492e..12834c2c0 100644 --- a/controls/gridview/visual-elements/cells/creating-custom-cells.md +++ b/controls/gridview/visual-elements/cells/creating-custom-cells.md @@ -19,204 +19,37 @@ You can use the following approach to create a custom data cell with a progress 1\. Create a class for the cell which derives from __GridDataCellElement__: -{{source=..\SamplesCS\GridView\Cells\CustomCells.cs region=CustomCellDefinition}} -{{source=..\SamplesVB\GridView\Cells\CustomCells.vb region=CustomCellDefinition}} -````C# - -public class ProgressBarCellElement : GridDataCellElement - -```` -````VB.NET -Public Class ProgressBarCellElement - Inherits GridDataCellElement - -```` - -{{endregion}} - -{{source=..\SamplesCS\GridView\Cells\CustomCells.cs region=createDefaultConstructor}} -{{source=..\SamplesVB\GridView\Cells\CustomCells.vb region=createDefaultConstructor}} - -````C# - -public ProgressBarCellElement(GridViewColumn column, GridRowElement row) : base(column, row) -{ -} - -```` -````VB.NET -Public Sub New(ByVal column As GridViewColumn, ByVal row As GridRowElement) - MyBase.New(column, row) -End Sub - -```` - -{{endregion}} + + + + 2\. Create the __RadProgressBarElement__ and add it as a child of the custom cell.You can achieve this by overriding the __CreateChildElements__ method: -{{source=..\SamplesCS\GridView\Cells\CustomCells.cs region=CreateChildElements}} -{{source=..\SamplesVB\GridView\Cells\CustomCells.vb region=CreateChildElements}} - -````C# - -private RadProgressBarElement radProgressBarElement; - -protected override void CreateChildElements() -{ - base.CreateChildElements(); - - radProgressBarElement = new RadProgressBarElement(); - this.Children.Add(radProgressBarElement); -} - -```` -````VB.NET -Private radProgressBarElement As RadProgressBarElement -Protected Overrides Sub CreateChildElements() - MyBase.CreateChildElements() - radProgressBarElement = New RadProgressBarElement() - Me.Children.Add(radProgressBarElement) -End Sub - -```` - -{{endregion}} + + 3\. Override the __SetContentCore__ method to update the progress bar according to the cell value: -{{source=..\SamplesCS\GridView\Cells\CustomCells.cs region=setContentCore}} -{{source=..\SamplesVB\GridView\Cells\CustomCells.vb region=setContentCore}} - -````C# - -protected override void SetContentCore(object value) -{ - if (this.Value != null && this.Value != DBNull.Value) - { - this.radProgressBarElement.Value1 = Convert.ToInt16(this.Value); - } -} - -```` -````VB.NET -Protected Overrides Sub SetContentCore(ByVal value As Object) - If Me.Value IsNot Nothing AndAlso Me.Value IsNot DBNull.Value Then - Me.radProgressBarElement.Value1 = Convert.ToInt16(Me.Value) - End If -End Sub - -```` - -{{endregion}} + + 4\. The custom cell will have no styles, because there are no defined styles for its type in the themes. You can apply the __GridDataCellElement’s__ styles to it by defining its __ThemeEffectiveType__: -{{source=..\SamplesCS\GridView\Cells\CustomCells.cs region=themeEffectiveType}} -{{source=..\SamplesVB\GridView\Cells\CustomCells.vb region=themeEffectiveType}} - -````C# - -protected override Type ThemeEffectiveType -{ - get - { - return typeof(GridDataCellElement); - } -} - -```` -````VB.NET -Protected Overrides ReadOnly Property ThemeEffectiveType() As Type - Get - Return GetType(GridDataCellElement) - End Get -End Property - -```` - -{{endregion}} + + 5\. Thanks to the UI virtualization mechanism only the currently visible cells are created and they are further reused when needed. A cell element is reused in other rows or columns if it is compatible for them. You can create a custom column and define that the custom cell __IsCompatible__ for that column only. This will prevent the cell from being unintentionally reused by other columns. -{{source=..\SamplesCS\GridView\Cells\CustomCells.cs region=compatibility}} -{{source=..\SamplesVB\GridView\Cells\CustomCells.vb region=compatibility}} - -````C# - -public override bool IsCompatible(GridViewColumn data, object context) -{ - return data is ProgressBarColumn && context is GridDataRowElement; -} - -```` -````VB.NET -Public Overrides Function IsCompatible(ByVal data As GridViewColumn, ByVal context As Object) As Boolean - Return TypeOf data Is ProgressBarColumn AndAlso TypeOf context Is GridDataRowElement -End Function - -```` - -{{endregion}} - -{{source=..\SamplesCS\GridView\Cells\CustomCells.cs region=compatibility1}} -{{source=..\SamplesVB\GridView\Cells\CustomCells.vb region=compatibility1}} - -````C# - -public class ProgressBarColumn : GridViewDataColumn -{ - public ProgressBarColumn(string fieldName) : base(fieldName) - { - } - - public override Type GetCellType(GridViewRowInfo row) - { - if (row is GridViewDataRowInfo) - { - return typeof(ProgressBarCellElement); - } - return base.GetCellType(row); - } -} - -```` -````VB.NET -Public Class ProgressBarColumn - Inherits GridViewDataColumn - Public Sub New(ByVal fieldName As String) - MyBase.New(fieldName) - End Sub - Public Overrides Function GetCellType(ByVal row As GridViewRowInfo) As Type - If TypeOf row Is GridViewDataRowInfo Then - Return GetType(ProgressBarCellElement) - End If - Return MyBase.GetCellType(row) - End Function -End Class - -```` - -{{endregion}} + + + + 6\. Lastly, we need to add the custom column to our grid. The following code snippet demonstrates the usage of the custom column: -{{source=..\SamplesCS\GridView\Cells\CustomCells.cs region=addColumn}} -{{source=..\SamplesVB\GridView\Cells\CustomCells.vb region=addColumn}} -````C# -ProgressBarColumn customColumn = new ProgressBarColumn("Progress column"); -this.radGridView1.Columns.Add(customColumn); - -```` -````VB.NET -Dim customColumn As New ProgressBarColumn("Progress column") -Me.RadGridView1.Columns.Add(customColumn) - -```` - - - -{{endregion}} + + >caption Figure 1: The custom column is now added to the grid. @@ -228,99 +61,13 @@ You can extend the custom cell further by adding a button in it and subscribing 1\. Initialize and add the elements to the cell: -{{source=..\SamplesCS\GridView\Cells\CustomCells.cs region=createChildElementsExample2}} -{{source=..\SamplesVB\GridView\Cells\CustomCells.vb region=createChildElementsExample2}} -````C# - -private RadProgressBarElement radProgressBarElement; -private RadButtonElement radButtonElement; - -protected override void CreateChildElements() -{ - base.CreateChildElements(); - - radProgressBarElement = new RadProgressBarElement(); - this.Children.Add(radProgressBarElement); - - radButtonElement = new RadButtonElement(); - radButtonElement.Text = "Restart"; - radButtonElement.Margin = new System.Windows.Forms.Padding(0, 1, 3, 1); - radButtonElement.Click += new EventHandler(radButtonElement_Click); - this.Children.Add(radButtonElement); -} - -protected override void DisposeManagedResources() -{ - radButtonElement.Click -= new EventHandler(radButtonElement_Click); - base.DisposeManagedResources(); -} - -```` -````VB.NET -Private radProgressBarElement As RadProgressBarElement -Private radButtonElement As RadButtonElement -Protected Overrides Sub CreateChildElements() - MyBase.CreateChildElements() - radProgressBarElement = New RadProgressBarElement() - Me.Children.Add(radProgressBarElement) - radButtonElement = New RadButtonElement() - radButtonElement.Text = "Restart" - radButtonElement.Margin = New System.Windows.Forms.Padding(0, 1, 3, 1) - AddHandler radButtonElement.Click, AddressOf radButtonElement_Click - Me.Children.Add(radButtonElement) -End Sub -Protected Overrides Sub DisposeManagedResources() - RemoveHandler radButtonElement.Click, AddressOf radButtonElement_Click - MyBase.DisposeManagedResources() -End Sub - -```` - - - -{{endregion}} - + + 2\. Override the __ArrangeOverride__ method to arrange the children elements of the cell: -{{source=..\SamplesCS\GridView\Cells\CustomCells.cs region=arrangeOverride}} -{{source=..\SamplesVB\GridView\Cells\CustomCells.vb region=arrangeOverride}} -````C# - -protected override SizeF ArrangeOverride(SizeF finalSize) -{ - if (this.Children.Count == 2) - { - float progressBarWidth = finalSize.Width - radButtonElement.DesiredSize.Width; - - RectangleF progressBarRect = new RectangleF(0, 0, progressBarWidth - 1, finalSize.Height); - RectangleF buttonRect = new RectangleF(progressBarWidth + 1, 0, radButtonElement.DesiredSize.Width, finalSize.Height); - - this.Children[0].Arrange(progressBarRect); - this.Children[1].Arrange(buttonRect); - } - - return finalSize; -} - -```` -````VB.NET -Protected Overrides Function ArrangeOverride(ByVal finalSize As SizeF) As SizeF - If Me.Children.Count = 2 Then - Dim progressBarWidth As Single = finalSize.Width - radButtonElement.DesiredSize.Width - Dim progressBarRect As New RectangleF(0, 0, progressBarWidth - 1, finalSize.Height) - Dim buttonRect As New RectangleF(progressBarWidth + 1, 0, radButtonElement.DesiredSize.Width, finalSize.Height) - Me.Children(0).Arrange(progressBarRect) - Me.Children(1).Arrange(buttonRect) - End If - Return finalSize -End Function - -```` - - - -{{endregion}} + + >caption Figure 2: The new custom cell is shown in RadgridView. @@ -336,267 +83,13 @@ When the __EnableGrouping__ property is set to *true* the __GroupPanelElement__ 1\. Create a class that inherits the __GridGroupContentCellElement__. In its __CreateChildElements__ method we will use a __RadDropDownListElement__ which contains the aggregate functions and a __LightVisualElement__ to display the calculated result. In the __SetContent__ method we should display the cell information considering for which row it is currently being used: -{{source=..\SamplesCS\GridView\Cells\CustomCells.cs region=CustomGroupCell}} -{{source=..\SamplesVB\GridView\Cells\CustomCells.vb region=CustomGroupCell}} -````C# -public class CustomGridGroupContentCellElement : GridGroupContentCellElement -{ - private RadDropDownListElement dropDown; - private LightVisualElement textElement; - private LightVisualElement aggregateElement; - private StackLayoutElement stack; - public CustomGridGroupContentCellElement(GridViewColumn column, GridRowElement row) : base(column, row) - { - } - protected override Type ThemeEffectiveType - { - get - { - return typeof(GridGroupContentCellElement); - } - } - protected override void CreateChildElements() - { - base.CreateChildElements(); - stack = new StackLayoutElement(); - stack.Orientation = Orientation.Horizontal; - stack.StretchHorizontally = true; - stack.Margin = new Padding(0, 2, 5, 0); - textElement = new LightVisualElement(); - dropDown = new RadDropDownListElement(); - dropDown.DropDownStyle = Telerik.WinControls.RadDropDownStyle.DropDownList; - aggregateElement = new LightVisualElement(); - dropDown.SelectedIndexChanged += SelectedIndexChanged; - dropDown.Items.AddRange(new List(new string[] - { - "Sum", - "Avg", - "Min", - "Max", - "Count", - "Last" - })); - stack.Children.Add(textElement); - stack.Children.Add(dropDown); - stack.Children.Add(aggregateElement); - this.Children.Add(stack); - } - public override void SetContent() - { - base.SetContent(); - GridViewGroupRowInfo row = this.RowInfo as GridViewGroupRowInfo; - if (row != null) - { - this.textElement.Text = row.HeaderText; - if (row.Tag != null) - { - dropDown.SelectedIndexChanged -= SelectedIndexChanged; - dropDown.SelectedIndex = (int)row.Tag; - dropDown.SelectedIndexChanged += SelectedIndexChanged; - } - else - { - dropDown.SelectedIndexChanged -= SelectedIndexChanged; - dropDown.SelectedIndex = -1; - dropDown.SelectedIndexChanged += SelectedIndexChanged; - } - } - switch (dropDown.Text) - { - case "Sum": - this.aggregateElement.Text = GetSum(row).ToString(); - break; - case "Avg": - this.aggregateElement.Text = (GetSum(row) / row.ChildRows.Count).ToString(); - break; - case "Min": - this.aggregateElement.Text = GetMin(row).ToString(); - break; - case "Max": - this.aggregateElement.Text = GetMax(row).ToString(); - break; - case "Count": - this.aggregateElement.Text = row.ChildRows.Count.ToString(); - break; - case "Last": - this.aggregateElement.Text = row.ChildRows.Last().Cells["ProductName"].Value.ToString(); - break; - default: - this.aggregateElement.Text = "No aggregate function"; - break; - } - this.Text = string.Empty; - } - private void SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e) - { - this.RowInfo.Tag = dropDown.SelectedIndex; - } - private decimal GetSum(GridViewGroupRowInfo row) - { - decimal sum = 0; - foreach (GridViewRowInfo childRow in row.ChildRows) - { - sum = sum + (decimal)childRow.Cells["UnitPrice"].Value; - } - return sum; - } - private decimal GetMin(GridViewGroupRowInfo row) - { - decimal min = decimal.MaxValue; - foreach (GridViewRowInfo childRow in row.ChildRows) - { - if ((decimal)childRow.Cells["UnitPrice"].Value < min) - { - min = (decimal)childRow.Cells["UnitPrice"].Value; - } - } - return min; - } - private decimal GetMax(GridViewGroupRowInfo row) - { - decimal max = decimal.MinValue; - foreach (GridViewRowInfo childRow in row.ChildRows) - { - if ((decimal)childRow.Cells["UnitPrice"].Value > max) - { - max = (decimal)childRow.Cells["UnitPrice"].Value; - } - } - return max; - } -} - -```` -````VB.NET -Public Class CustomGridGroupContentCellElement - Inherits GridGroupContentCellElement - Private dropDown As RadDropDownListElement - Private textElement As LightVisualElement - Private aggregateElement As LightVisualElement - Private stack As StackLayoutElement - Public Sub New(column As GridViewColumn, row As GridRowElement) - MyBase.New(column, row) - End Sub - Protected Overrides ReadOnly Property ThemeEffectiveType() As Type - Get - Return GetType(GridGroupContentCellElement) - End Get - End Property - Protected Overrides Sub CreateChildElements() - MyBase.CreateChildElements() - stack = New StackLayoutElement() - stack.Orientation = Orientation.Horizontal - stack.StretchHorizontally = True - stack.Margin = New Padding(0, 2, 5, 0) - textElement = New LightVisualElement() - dropDown = New RadDropDownListElement() - dropDown.DropDownStyle = Telerik.WinControls.RadDropDownStyle.DropDownList - aggregateElement = New LightVisualElement() - AddHandler dropDown.SelectedIndexChanged, AddressOf SelectedIndexChanged - dropDown.Items.AddRange(New List(Of String)(New String() {"Sum", "Avg", "Min", "Max", "Count", "Last"})) - stack.Children.Add(textElement) - stack.Children.Add(dropDown) - stack.Children.Add(aggregateElement) - Me.Children.Add(stack) - End Sub - Public Overrides Sub SetContent() - MyBase.SetContent() - Dim row As GridViewGroupRowInfo = TryCast(Me.RowInfo, GridViewGroupRowInfo) - If row IsNot Nothing Then - Me.textElement.Text = row.HeaderText - If row.Tag IsNot Nothing Then - RemoveHandler dropDown.SelectedIndexChanged, AddressOf SelectedIndexChanged - dropDown.SelectedIndex = DirectCast(row.Tag, Integer) - AddHandler dropDown.SelectedIndexChanged, AddressOf SelectedIndexChanged - Else - RemoveHandler dropDown.SelectedIndexChanged, AddressOf SelectedIndexChanged - dropDown.SelectedIndex = -1 - AddHandler dropDown.SelectedIndexChanged, AddressOf SelectedIndexChanged - End If - End If - Select Case dropDown.Text - Case "Sum" - Me.aggregateElement.Text = GetSum(row) - Case "Avg" - Me.aggregateElement.Text = GetSum(row) / row.ChildRows.Count - Case "Min" - Me.aggregateElement.Text = GetMin(row) - Case "Max" - Me.aggregateElement.Text = GetMax(row) - Case "Count" - Me.aggregateElement.Text = row.ChildRows.Count - Case "Last" - Me.aggregateElement.Text = row.ChildRows.Last().Cells("ProductName").Value.ToString() - Case Else - Me.aggregateElement.Text = "No aggregate function" - Exit Select - End Select - Me.Text = String.Empty - End Sub - Private Sub SelectedIndexChanged(sender As Object, e As Data.PositionChangedEventArgs) - Me.RowInfo.Tag = dropDown.SelectedIndex - End Sub - Private Function GetSum(row As GridViewGroupRowInfo) As Decimal - Dim sum As Decimal = 0 - For Each childRow As GridViewRowInfo In row.ChildRows - sum = sum + childRow.Cells("UnitPrice").Value - Next - Return sum - End Function - Private Function GetMin(row As GridViewGroupRowInfo) As Decimal - Dim min As Decimal = Decimal.MaxValue - For Each childRow As GridViewRowInfo In row.ChildRows - If childRow.Cells("UnitPrice").Value < min Then - min = childRow.Cells("UnitPrice").Value - End If - Next - Return min - End Function - Private Function GetMax(row As GridViewGroupRowInfo) As Decimal - Dim max As Decimal = Decimal.MinValue - For Each childRow As GridViewRowInfo In row.ChildRows - If childRow.Cells("UnitPrice").Value > max Then - max = childRow.Cells("UnitPrice").Value - End If - Next - Return max - End Function -End Class - -```` - - - -{{endregion}} + + 2\. Subscribe to the __CreateCell__ event where we should replace the default __GridGroupContentCellElement__ with the custom one: -{{source=..\SamplesCS\GridView\Cells\CustomCells.cs region=ReplaceCustomGroupCell}} -{{source=..\SamplesVB\GridView\Cells\CustomCells.vb region=ReplaceCustomGroupCell}} -````C# - -private void gridCustomGroupCell_CreateCell(object sender, GridViewCreateCellEventArgs e) -{ - if (e.CellType == typeof(GridGroupContentCellElement)) - { - e.CellElement = new CustomGridGroupContentCellElement(e.Column, e.Row); - } -} - -```` -````VB.NET -Private Sub gridCustomGroupCell_CreateCell(sender As Object, e As GridViewCreateCellEventArgs) Handles gridCustomGroupCell.CreateCell - If e.CellType = GetType(GridGroupContentCellElement) Then - e.CellElement = New CustomGridGroupContentCellElement(e.Column, e.Row) - End If -End Sub - -```` - - - -{{endregion}} - + + # See Also diff --git a/controls/gridview/visual-elements/cells/formating-examples/child-tabs.md b/controls/gridview/visual-elements/cells/formating-examples/child-tabs.md index 431d34bca..ad7cf89d6 100644 --- a/controls/gridview/visual-elements/cells/formating-examples/child-tabs.md +++ b/controls/gridview/visual-elements/cells/formating-examples/child-tabs.md @@ -21,103 +21,8 @@ When __RadGridView__ displays hierarchical data, you expand/collapse child level #### Accessing the child tabs in the ViewCellFormatting event. -{{source=..\SamplesCS\GridView\Cells\HideChildTabs.cs region=HideTabs}} -{{source=..\SamplesVB\GridView\Cells\HideChildTabs.vb region=HideTabs}} - -````C# -private void radGridView1_ViewCellFormatting(object sender, CellFormattingEventArgs e) -{ - GridDetailViewCellElement cell = e.CellElement as GridDetailViewCellElement; - GridGroupExpanderCellElement expanderCell = e.CellElement as GridGroupExpanderCellElement; - if (expanderCell != null && e.CellElement.RowElement is GridDataRowElement) - { - GridViewHierarchyRowInfo hierarchyRow = (GridViewHierarchyRowInfo)expanderCell.RowInfo; - if (!IsExpandable(hierarchyRow)) - { - expanderCell.Expander.Visibility = Telerik.WinControls.ElementVisibility.Hidden; - } - else - { - expanderCell.Expander.Visibility = Telerik.WinControls.ElementVisibility.Visible; - } - } - else if (cell != null) - { - GridViewHierarchyRowInfo hierarchyRow = (GridViewHierarchyRowInfo)((GridViewDetailsRowInfo)cell.RowInfo).Owner; - for (int i = 0; i < cell.PageViewElement.Items.Count; i++) - { - RadPageViewItem item = cell.PageViewElement.Items[i]; - GridViewInfo viewInfo = hierarchyRow.Views[i]; - item.Text = "Child Template " + i; - if (viewInfo.ChildRows.Count == 0) - { - if (i == 0 && i < cell.PageViewElement.Items.Count - 1) - { - cell.PageViewElement.Items[i + 1].IsSelected = true; - } - item.Visibility = Telerik.WinControls.ElementVisibility.Collapsed; - } - else - { - item.Visibility = Telerik.WinControls.ElementVisibility.Visible; - } - } - } -} -private bool IsExpandable(GridViewHierarchyRowInfo hierarchyRow) -{ - foreach (GridViewInfo view in hierarchyRow.Views) - { - if (view.ChildRows.Count > 0) - { - return true; - } - } - - return false; -} - -```` -````VB.NET -Private Sub radGridView1_ViewCellFormatting(sender As Object, e As CellFormattingEventArgs) - Dim cell As GridDetailViewCellElement = TryCast(e.CellElement, GridDetailViewCellElement) - Dim expanderCell As GridGroupExpanderCellElement = TryCast(e.CellElement, GridGroupExpanderCellElement) - If expanderCell IsNot Nothing AndAlso TypeOf e.CellElement.RowElement Is GridDataRowElement Then - Dim hierarchyRow As GridViewHierarchyRowInfo = DirectCast(expanderCell.RowInfo, GridViewHierarchyRowInfo) - If Not IsExpandable(hierarchyRow) Then - expanderCell.Expander.Visibility = Telerik.WinControls.ElementVisibility.Hidden - Else - expanderCell.Expander.Visibility = Telerik.WinControls.ElementVisibility.Visible - End If - ElseIf cell IsNot Nothing Then - Dim hierarchyRow As GridViewHierarchyRowInfo = DirectCast(DirectCast(cell.RowInfo, GridViewDetailsRowInfo).Owner, GridViewHierarchyRowInfo) - For i As Integer = 0 To cell.PageViewElement.Items.Count - 1 - Dim item As RadPageViewItem = cell.PageViewElement.Items(i) - Dim viewInfo As GridViewInfo = hierarchyRow.Views(i) - item.Text = "Child Template " & i - If viewInfo.ChildRows.Count = 0 Then - If i = 0 AndAlso i < cell.PageViewElement.Items.Count - 1 Then - cell.PageViewElement.Items(i + 1).IsSelected = True - End If - item.Visibility = Telerik.WinControls.ElementVisibility.Collapsed - Else - item.Visibility = Telerik.WinControls.ElementVisibility.Visible - End If - Next - End If -End Sub -Private Function IsExpandable(hierarchyRow As GridViewHierarchyRowInfo) As Boolean - For Each view As GridViewInfo In hierarchyRow.Views - If view.ChildRows.Count > 0 Then - Return True - End If - Next - Return False -End Function - -```` - -{{endregion}} + + # See Also * [Formatting GridViewCommandColumn]({%slug winforms/gridview/cells/formatting-command-column%}) diff --git a/controls/gridview/visual-elements/cells/formating-examples/command-cell.md b/controls/gridview/visual-elements/cells/formating-examples/command-cell.md index 01c4b58f3..743966391 100644 --- a/controls/gridview/visual-elements/cells/formating-examples/command-cell.md +++ b/controls/gridview/visual-elements/cells/formating-examples/command-cell.md @@ -13,51 +13,8 @@ Sometimes, you may need to change the appearance of the buttons that appear in t Let's say that you have a number of employees. Only one employee is Vice President of the company, while the others are managers and sales representatives. In RadGridView you have a GridViewCommandColumn, the buttons of which allow the end-users to edit the details of all records, except the one that belongs to the Vice President. So, depending on the value of the Title cell, you should set the __Enabled__ property of the respective RadButtonElement to *true* or *false*. Here is how we can achieve that: -{{source=..\SamplesCS\GridView\Cells\FormattingCellsButtons.cs region=buttonCell}} -{{source=..\SamplesVB\GridView\Cells\FormattingCellsButtons.vb region=buttonCell}} - -````C# -void radGridView1_CellFormatting(object sender, CellFormattingEventArgs e) -{ - if (e.CellElement.ColumnInfo is GridViewCommandColumn) - { - // This is how we get the RadButtonElement instance from the cell - RadButtonElement button = (RadButtonElement)e.CellElement.Children[0]; - if (e.CellElement.RowInfo.Cells["Title"].Value != null) - { - string title = e.CellElement.RowInfo.Cells["Title"].Value.ToString(); - if (title == "Vice President, Sales") - { - button.Enabled = false; - } - else - { - button.Enabled = true; - } - } - } -} - -```` -````VB.NET -Private Sub radGridView1_CellFormatting(ByVal sender As Object, ByVal e As CellFormattingEventArgs) Handles RadGridView1.CellFormatting - If TypeOf e.CellElement.ColumnInfo Is GridViewCommandColumn Then - 'This is how we get the RadButtonElement instance from the cell - Dim button As RadButtonElement = CType(e.CellElement.Children(0), RadButtonElement) - If e.CellElement.RowInfo.Cells("Title").Value IsNot Nothing Then - Dim title As String = e.CellElement.RowInfo.Cells("Title").Value.ToString() - If title = "Vice President, Sales" Then - button.Enabled = False - Else - button.Enabled = True - End If - End If - End If -End Sub - -```` - -{{endregion}} + + >caption Figure 1: Styling the command cell button. diff --git a/controls/gridview/visual-elements/cells/formating-examples/group-rows.md b/controls/gridview/visual-elements/cells/formating-examples/group-rows.md index 8f6aee473..379fb6f3b 100644 --- a/controls/gridview/visual-elements/cells/formating-examples/group-rows.md +++ b/controls/gridview/visual-elements/cells/formating-examples/group-rows.md @@ -14,47 +14,10 @@ To modify the text alignment and the back color in the group rows use the follo #### Formatting group rows -{{source=..\SamplesCS\GridView\Cells\FormattingCells.cs region=viewCellFormatting2}} -{{source=..\SamplesVB\GridView\Cells\FormattingCells.vb region=viewCellFormatting2}} + + -````C# -void radGridView1_ViewCellFormatting2(object sender, CellFormattingEventArgs e) -{ - if (e.CellElement.RowInfo is GridViewGroupRowInfo) - { - e.CellElement.DrawFill = true; - e.CellElement.BackColor = Color.Aquamarine; - e.CellElement.TextAlignment = ContentAlignment.MiddleRight; - e.CellElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid; - } - else - { - e.CellElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.TextAlignmentProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local); - } -} -```` -````VB.NET -Private Sub RadGridView1_ViewCellFormatting2(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.CellFormattingEventArgs) Handles RadGridView1.ViewCellFormatting - If TypeOf e.CellElement.RowInfo Is GridViewGroupRowInfo Then - e.CellElement.DrawFill = True - e.CellElement.BackColor = Color.Aquamarine - e.CellElement.TextAlignment = ContentAlignment.MiddleRight - e.CellElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid - Else - e.CellElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.TextAlignmentProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local) - End If -End Sub - -```` - -{{endregion}} >caption Figure 1: Formatting group rows. diff --git a/controls/gridview/visual-elements/cells/formating-examples/row-numbers.md b/controls/gridview/visual-elements/cells/formating-examples/row-numbers.md index 50e77bf99..e27461311 100644 --- a/controls/gridview/visual-elements/cells/formating-examples/row-numbers.md +++ b/controls/gridview/visual-elements/cells/formating-examples/row-numbers.md @@ -18,38 +18,8 @@ By default, **RadGridView** displays a current row indicator in the row header r #### Handling the ViewCellFormatting event -{{source=..\SamplesCS\GridView\Cells\GridViewRowNumbers.cs region=RowNumbers}} -{{source=..\SamplesVB\GridView\Cells\GridViewRowNumbers.vb region=RowNumbers}} - -````C# - -private void radGridView1_ViewCellFormatting(object sender, CellFormattingEventArgs e) -{ - if (e.CellElement is GridRowHeaderCellElement && e.Row is GridViewDataRowInfo) - { - e.CellElement.Text = (e.CellElement.RowIndex + 1).ToString(); - e.CellElement.TextImageRelation = TextImageRelation.ImageBeforeText; - } - else - { - e.CellElement.ResetValue(LightVisualElement.TextImageRelationProperty, ValueResetFlags.Local); - } -} - -```` -````VB.NET -Private Sub radGridView1_ViewCellFormatting(sender As Object, e As CellFormattingEventArgs) - If TypeOf e.CellElement Is GridRowHeaderCellElement AndAlso TypeOf e.Row Is GridViewDataRowInfo Then - e.CellElement.Text = (e.CellElement.RowIndex + 1).ToString() - e.CellElement.TextImageRelation = TextImageRelation.ImageBeforeText - Else - e.CellElement.ResetValue(LightVisualElement.TextImageRelationProperty, ValueResetFlags.Local) - End If -End Sub - -```` - -{{endregion}} + + >note The **RowIndex** property internally uses the **ChildRows** collection. This collection returns the data rows that are currently represented by RadGridView in the order in which they appear. The collection is modified every time a data operation (grouping, sorting, filtering) occurs. Similar to filtering, sorting and grouping, the ChildRows collection is affected by the paging as well and it contains only the records on the current page. A common scenario is to access the real row index when the paging is enabled in the order the items appear in the grid. @@ -90,21 +60,8 @@ It is necessary to increase the header row's width in order to have enough space #### Adjust the RowHeaderColumnWidth -{{source=..\SamplesCS\GridView\Cells\GridViewRowNumbers.cs region=RowHeaderWidth}} -{{source=..\SamplesVB\GridView\Cells\GridViewRowNumbers.vb region=RowHeaderWidth}} - -````C# - -this.radGridView1.TableElement.RowHeaderColumnWidth = 50; - -```` -````VB.NET -Me.RadGridView1.TableElement.RowHeaderColumnWidth = 50 - -```` - -{{endregion}} - + + # See Also * [Formatting GridViewCommandColumn]({%slug winforms/gridview/cells/formatting-command-column%}) diff --git a/controls/gridview/visual-elements/cells/formating-examples/style-property.md b/controls/gridview/visual-elements/cells/formating-examples/style-property.md index c4036504e..e6861751a 100644 --- a/controls/gridview/visual-elements/cells/formating-examples/style-property.md +++ b/controls/gridview/visual-elements/cells/formating-examples/style-property.md @@ -33,59 +33,13 @@ Using the __Style__ property allows you to define cell’s style properties: The example below shows how to customize the __Font__ and __BackColor__ of a cell. -{{source=..\SamplesCS\GridView\Cells\FormattingCells.cs region=CellStyleMethod}} -{{source=..\SamplesVB\GridView\Cells\FormattingCells.vb region=CellStyleMethod}} - -````C# -Font myFont = new Font(new FontFamily("Calibri"), 12.0F, FontStyle.Bold); -private void StyleCell(GridViewCellInfo cell) -{ - cell.Style.Font = myFont; - cell.Style.CustomizeFill = true; - cell.Style.GradientStyle = GradientStyles.Solid; - cell.Style.BackColor = Color.FromArgb(162, 215, 255); -} - -```` -````VB.NET -Private myFont As New Font(New FontFamily("Calibri"), 12.0F, FontStyle.Bold) -Private Sub StyleCell(cell As GridViewCellInfo) - cell.Style.Font = myFont - cell.Style.CustomizeFill = True - cell.Style.GradientStyle = GradientStyles.Solid - cell.Style.BackColor = Color.FromArgb(162, 215, 255) -End Sub -'#End Region -Private Sub FormattingCells_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load - 'TODO: This line of code loads data into the 'NwindDataSet.Cars' table. You can move, or remove it, as needed. - Me.CarsTableAdapter.Fill(Me.NwindDataSet.Cars) - RadGridView1.Columns("Picture").Width = 80 - RadGridView1.Rows(0).Height = 60 - RadGridView1.Rows(1).Height = 60 - RadGridView1.Rows(2).Height = 60 - RadGridView1.Rows(3).Height = 60 - '#region CellStyleMethodCall - Me.StyleCell(Me.RadGridView1.Rows(1).Cells(1)) - -```` - -{{endregion}} + + Here is how to call this method of a certain cell: -{{source=..\SamplesCS\GridView\Cells\FormattingCells.cs region=CellStyleMethodCall}} -{{source=..\SamplesVB\GridView\Cells\FormattingCells.vb region=CellStyleMethodCall}} - -````C# -this.StyleCell(this.radGridView1.Rows[1].Cells[1]); - -```` -````VB.NET -Me.StyleCell(Me.RadGridView1.Rows(1).Cells(1)) - -```` - -{{endregion}} + + >caption Figure 1: Format using the Style property. diff --git a/controls/gridview/visual-elements/cells/formatting-cells.md b/controls/gridview/visual-elements/cells/formatting-cells.md index 25dd2e43b..98b869ad8 100644 --- a/controls/gridview/visual-elements/cells/formatting-cells.md +++ b/controls/gridview/visual-elements/cells/formatting-cells.md @@ -23,35 +23,10 @@ The __CellFormatting__ event is used to access and change the styles of the *dat #### Changing the data cells font color -{{source=..\SamplesCS\GridView\Cells\FormattingCells.cs region=cellFormattingExample1}} -{{source=..\SamplesVB\GridView\Cells\FormattingCells.vb region=cellFormattingExample1}} - -````C# -void radGridView1_CellFormatting1(object sender, Telerik.WinControls.UI.CellFormattingEventArgs e) -{ - if (e.CellElement.ColumnInfo.Name == "KBytes") - { - e.CellElement.ForeColor = Color.Red; - } - else - { - e.CellElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local); - } -} - -```` -````VB.NET -Private Sub RadGridView1_CellFormatting1(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.CellFormattingEventArgs) Handles RadGridView1.CellFormatting - If e.CellElement.ColumnInfo.Name = "KBytes" Then - e.CellElement.ForeColor = Color.Red - Else - e.CellElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local) - End If -End Sub - -```` - -{{endregion}} + + + + >caption Figure 1: Changing the cells fore color. @@ -67,69 +42,10 @@ This is an advanced example of using **CellFormatting** event to highlight certa #### Formatting cells -{{source=..\SamplesCS\GridView\Cells\FormattingCells.cs region=cellFormattingExample2}} -{{source=..\SamplesVB\GridView\Cells\FormattingCells.vb region=cellFormattingExample2}} - -````C# -void radGridView1_CellFormatting2(object sender, Telerik.WinControls.UI.CellFormattingEventArgs e) -{ - if (e.CellElement.ColumnInfo.HeaderText == "Id") - { - if (e.CellElement.RowInfo.Cells["BMP"].Value != null) - { - if ((bool)e.CellElement.RowInfo.Cells["BMP"].Value == true) - { - e.CellElement.DrawFill = true; - e.CellElement.ForeColor = Color.Blue; - e.CellElement.NumberOfColors = 1; - e.CellElement.BackColor = Color.Aqua; - } - else - { - e.CellElement.DrawFill = true; - e.CellElement.ForeColor = Color.Yellow; - e.CellElement.NumberOfColors = 1; - e.CellElement.BackColor = Color.Green; - } - } - } - else - { - e.CellElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.NumberOfColorsProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local); - } -} - -```` -````VB.NET -Private Sub RadGridView1_CellFormatting2(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.CellFormattingEventArgs) Handles RadGridView1.CellFormatting - If e.CellElement.ColumnInfo.HeaderText = "Id" Then - If e.CellElement.RowInfo.Cells("BMP").Value IsNot Nothing Then - If CBool(e.CellElement.RowInfo.Cells("BMP").Value) = True Then - e.CellElement.DrawFill = True - e.CellElement.ForeColor = Color.Blue - e.CellElement.NumberOfColors = 1 - e.CellElement.BackColor = Color.Aqua - Else - e.CellElement.DrawFill = True - e.CellElement.ForeColor = Color.Yellow - e.CellElement.NumberOfColors = 1 - e.CellElement.BackColor = Color.Green - End If - End If - Else - e.CellElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.NumberOfColorsProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local) - End If -End Sub - -```` - -{{endregion}} + + + + ## Formatting non-data cells @@ -141,52 +57,10 @@ For example, to change the font of the header cells and the group cells use th #### Formatting non-data rows -{{source=..\SamplesCS\GridView\Cells\FormattingCells.cs region=viewCellFormatting1}} -{{source=..\SamplesVB\GridView\Cells\FormattingCells.vb region=viewCellFormatting1}} - -````C# -Font newFont = new Font("Arial", 12f, FontStyle.Bold); -void radGridView1_ViewCellFormatting1(object sender, CellFormattingEventArgs e) -{ - if (e.CellElement is GridHeaderCellElement || e.CellElement is GridGroupContentCellElement) - { - e.CellElement.Font = newFont; - e.CellElement.ForeColor = Color.Blue; - } - else - { - e.CellElement.ResetValue(LightVisualElement.FontProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local); - } - //hiding the text from the filter cells - GridFilterCellElement filterCell = e.CellElement as GridFilterCellElement; - if (filterCell != null) - { - filterCell.FilterOperatorText.Visibility = Telerik.WinControls.ElementVisibility.Collapsed; - } -} - -```` -````VB.NET -Dim newFont = New Font("Arial", 12.0F, FontStyle.Bold) -Private Sub RadGridView1_ViewCellFormatting1(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.CellFormattingEventArgs) Handles RadGridView1.ViewCellFormatting - If TypeOf e.CellElement Is GridHeaderCellElement OrElse TypeOf e.CellElement Is GridGroupContentCellElement Then - e.CellElement.Font = newFont - e.CellElement.ForeColor = Color.Blue - Else - e.CellElement.ResetValue(LightVisualElement.FontProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local) - End If - 'hiding the text from the filter cells - Dim filterCell As GridFilterCellElement = TryCast(e.CellElement, GridFilterCellElement) - If filterCell IsNot Nothing Then - filterCell.FilterOperatorText.Visibility = Telerik.WinControls.ElementVisibility.Collapsed - End If -End Sub - -```` - -{{endregion}} + + + + >caption Figure 3: Formatting non-data rows. @@ -198,64 +72,17 @@ Sometimes you may need to format the cells on a specific user action, for exampl * First, you should handle the **CellFormatting** event and set the back color of the cells whose text matches the text in the **RadTextBox**. -{{source=..\SamplesCS\GridView\Cells\FormattingCellsOnDemand.cs region=cellFormatting}} -{{source=..\SamplesVB\GridView\Cells\FormattingCellsOnDemand.vb region=cellFormatting}} - -````C# -void radGridView1_CellFormatting(object sender, Telerik.WinControls.UI.CellFormattingEventArgs e) -{ - if (e.CellElement.Text == this.radTextBox1.Text) - { - e.CellElement.DrawFill = true; - e.CellElement.BackColor = Color.Yellow; - e.CellElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid; - } - else - { - e.CellElement.ResetValue(LightVisualElement.DrawFillProperty, Telerik.WinControls.ValueResetFlags.Local); - e.CellElement.ResetValue(VisualElement.BackColorProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local); - } -} - -```` -````VB.NET -Private Sub RadGridView1_CellFormatting(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.CellFormattingEventArgs) Handles RadGridView1.CellFormatting - If e.CellElement.Text = Me.RadTextBox1.Text Then - e.CellElement.DrawFill = True - e.CellElement.BackColor = Color.Yellow - e.CellElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid - Else - e.CellElement.ResetValue(LightVisualElement.DrawFillProperty, Telerik.WinControls.ValueResetFlags.Local) - e.CellElement.ResetValue(VisualElement.BackColorProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local) - End If -End Sub - -```` - -{{endregion}} + + -* The user types some text, but then you should somehow notify **RadGridView** that it needs to refresh itself. This is done by calling the __Update__ method of the **TableElement**, passing the *StateChanged* argument as a parameter. -{{source=..\SamplesCS\GridView\Cells\FormattingCellsOnDemand.cs region=buttonClick}} -{{source=..\SamplesVB\GridView\Cells\FormattingCellsOnDemand.vb region=buttonClick}} -````C# -void searchButton_Click(object sender, EventArgs e) -{ - this.radGridView1.TableElement.Update(GridUINotifyAction.StateChanged); -} +* The user types some text, but then you should somehow notify **RadGridView** that it needs to refresh itself. This is done by calling the __Update__ method of the **TableElement**, passing the *StateChanged* argument as a parameter. -```` -````VB.NET -Private Sub searchButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles searchButton.Click - Me.RadGridView1.TableElement.Update(GridUINotifyAction.StateChanged) -End Sub + + -```` -{{endregion}} As a result of the update call, the **CellFormatting** event (and the other formatting events as well) will be triggered and you will get the following results: diff --git a/controls/gridview/visual-elements/cells/gridviewcellinfo.md b/controls/gridview/visual-elements/cells/gridviewcellinfo.md index a552fe446..79df07417 100644 --- a/controls/gridview/visual-elements/cells/gridviewcellinfo.md +++ b/controls/gridview/visual-elements/cells/gridviewcellinfo.md @@ -27,34 +27,8 @@ __GridViewCellInfo__ also includes an __EnsureVisible()__ method that scrolls th #### Using GridViewCellInfo -{{source=..\SamplesCS\GridView\Cells\GridViewCellInfo1.cs region=GridViewCellInfo}} -{{source=..\SamplesVB\GridView\Cells\GridViewCellInfo1.vb region=GridViewCellInfo}} - -````C# -GridViewRowInfo lastRow = radGridView1.Rows[radGridView1.Rows.Count - 1]; -GridViewCellInfo cell = lastRow.Cells["BMP"]; -lastRow.EnsureVisible(); -if (cell.ColumnInfo.GetType() == typeof(GridViewCheckBoxColumn)) -{ - cell.Value = false; -} -cell.EnsureVisible(); - -```` -````VB.NET -Dim lastRow As GridViewRowInfo = RadGridView1.Rows(RadGridView1.Rows.Count - 1) -Dim cell As GridViewCellInfo = lastRow.Cells("BMP") -lastRow.EnsureVisible() -If cell.ColumnInfo.GetType().Equals(GetType(GridViewCheckBoxColumn)) Then - cell.Value = False - End If - cell.EnsureVisible() - -```` - -{{endregion}} - - + + # See Also * [Accessing and Setting the CurrentCell]({%slug winforms/gridview/cells/accessing-and-setting-the-currentcell%}) diff --git a/controls/gridview/visual-elements/cells/iterating-cells.md b/controls/gridview/visual-elements/cells/iterating-cells.md index aca635a5f..ee72d4d89 100644 --- a/controls/gridview/visual-elements/cells/iterating-cells.md +++ b/controls/gridview/visual-elements/cells/iterating-cells.md @@ -13,36 +13,8 @@ previous_url: gridview-cells-iterating-cells You can iterate through the cells of each row using the __Cells__ collection of [GridViewCellInfo]({%slug winforms/gridview/cells/gridviewcellinfo%}). The example below firstly iterates the rows of the grid, then the cells for each row: -{{source=..\SamplesCS\GridView\Cells\IteratingCells.cs region=iteratingCells}} -{{source=..\SamplesVB\GridView\Cells\IteratingCells.vb region=iteratingCells}} - -````C# -foreach (GridViewRowInfo rowInfo in radGridView1.Rows) -{ - foreach (GridViewCellInfo cellInfo in rowInfo.Cells) - { - if ((cellInfo.ColumnInfo.Name == "Title") - || (cellInfo.ColumnInfo.Name == "FirstName") - || (cellInfo.ColumnInfo.Name == "LastName")) - { - cellInfo.Value = "Test Value"; - } - } -} - -```` -````VB.NET -For Each rowInfo As GridViewRowInfo In RadGridView1.Rows - For Each cellInfo As GridViewCellInfo In rowInfo.Cells - If (cellInfo.ColumnInfo.Name = "Title") OrElse (cellInfo.ColumnInfo.Name = "FirstName") OrElse (cellInfo.ColumnInfo.Name = "LastName") Then - cellInfo.Value = "Test Value" - End If - Next -Next - -```` - -{{endregion}} + + >note __RadGridView__ uses virtualization for its visual elements. This means that only the rows that are currently visible have a visual element. When the grid is scrolled up and down the visual elements are reused. Because of the virtualization, it is safe to use the __CellElement__ only inside the __CellFormatting__ event and only for the current cell. > diff --git a/controls/gridview/visual-elements/cells/painting-and-drawing-in-cells.md b/controls/gridview/visual-elements/cells/painting-and-drawing-in-cells.md index 6fc214737..b2d5df8e3 100644 --- a/controls/gridview/visual-elements/cells/painting-and-drawing-in-cells.md +++ b/controls/gridview/visual-elements/cells/painting-and-drawing-in-cells.md @@ -18,44 +18,8 @@ There are cases when you need to manually draw in a cell in order to extend the The following example demonstrates how to use the __CellPaint__ event to change the appearance of the cells in a "UnitPrice" column. We would like to add a custom drawn red asterisk to values less than 20, a green asterisk to values higher than 20, and no asterisk when the cell's value is zero: -{{source=..\SamplesCS\GridView\Cells\PaintingAndDrawingInCells.cs region=paintingAndDrawingInCells}} -{{source=..\SamplesVB\GridView\Cells\PaintingAndDrawingInCells.vb region=paintingAndDrawingInCells}} - -````C# -void radGridView1_CellPaint(object sender, Telerik.WinControls.UI.GridViewCellPaintEventArgs e) -{ - if (e.Cell != null && e.Cell.RowInfo is GridViewDataRowInfo && e.Cell.ColumnInfo.Name == "UnitPrice") - { - double value = Convert.ToDouble(e.Cell.Value); - if (value == 0) - { - return; - } - Brush brush = value < 20 ? Brushes.Red : Brushes.Green; - using (Font font = new Font("Segoe UI", 17)) - { - e.Graphics.DrawString("*", font, brush, Point.Empty); - } - } -} - -```` -````VB.NET -Private Sub RadGridView1_CellPaint(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewCellPaintEventArgs) Handles RadGridView1.CellPaint - If e.Cell IsNot Nothing AndAlso TypeOf e.Cell.RowInfo Is GridViewDataRowInfo AndAlso e.Cell.ColumnInfo.Name = "UnitPrice" Then - Dim value As Double = Convert.ToDouble(e.Cell.Value) - If value = 0 Then - Return - End If - Dim brush As Brush = If(value < 20, Brushes.Red, Brushes.Green) - Using font As New Font("Segoe UI", 17) - e.Graphics.DrawString("*", font, brush, Point.Empty) - End Using - End If - -```` - -{{endregion}} + + >caption Figure 1: Painting in cells diff --git a/controls/gridview/visual-elements/cells/tooltips.md b/controls/gridview/visual-elements/cells/tooltips.md index 1f55e2646..8228b15c1 100644 --- a/controls/gridview/visual-elements/cells/tooltips.md +++ b/controls/gridview/visual-elements/cells/tooltips.md @@ -17,29 +17,8 @@ There are two ways to assign tooltips to cells in __RadGridView__, namely settin The code snippet below demonstrates how you can assign a tooltip to a data cell. -{{source=..\SamplesCS\GridView\Cells\ToolTips1.cs region=CellFormatting}} -{{source=..\SamplesVB\GridView\Cells\ToolTips1.vb region=CellFormatting}} - -````C# -void radGridView1_CellFormatting(object sender, Telerik.WinControls.UI.CellFormattingEventArgs e) -{ - if (e.Row is GridViewDataRowInfo) - { - e.CellElement.ToolTipText = "Tooltip: " + e.CellElement.Text; - } -} - -```` -````VB.NET -Private Sub RadGridView1_CellFormatting(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.CellFormattingEventArgs) Handles RadGridView1.CellFormatting - If TypeOf e.Row Is GridViewDataRowInfo Then - e.CellElement.ToolTipText = "Tooltip: " & e.CellElement.Text - End If -End Sub - -```` - -{{endregion}} + + >caption Figure 1: Using the formatting event to set the tooltips. @@ -49,31 +28,8 @@ End Sub The code snippet below demonstrates how you can use __ToolTipTextNeeded__ event handler to set __ToolTipText__ for the given __CellElement__. -{{source=..\SamplesCS\GridView\Cells\ToolTips1.cs region=ToolTipTextNeeded}} -{{source=..\SamplesVB\GridView\Cells\ToolTips1.vb region=ToolTipTextNeeded}} - -````C# -private void radGridView1_ToolTipTextNeeded(object sender, Telerik.WinControls.ToolTipTextNeededEventArgs e) -{ - GridDataCellElement cell = sender as GridDataCellElement; - if (cell != null && cell.ColumnInfo.Name == "Name") - { - e.ToolTipText = cell.Value.ToString(); - } -} - -```` -````VB.NET -Private Sub RadGridView1_ToolTipTextNeeded(sender As Object, e As Telerik.WinControls.ToolTipTextNeededEventArgs) Handles RadGridView1.ToolTipTextNeeded - Dim cell As GridDataCellElement = TryCast(sender, GridDataCellElement) - If cell IsNot Nothing AndAlso cell.ColumnInfo.Name = "Name" Then - e.ToolTipText = cell.Value.ToString() - End If -End Sub - -```` - -{{endregion}} + + >caption Figure 2: Using the ToolTipTextNeeded event. diff --git a/controls/gridview/visual-elements/columns/accessing-and-iterating-through-columns.md b/controls/gridview/visual-elements/columns/accessing-and-iterating-through-columns.md index c4a4900ad..1bb81c19b 100644 --- a/controls/gridview/visual-elements/columns/accessing-and-iterating-through-columns.md +++ b/controls/gridview/visual-elements/columns/accessing-and-iterating-through-columns.md @@ -19,19 +19,8 @@ For example, the code snippet below sets the width of an image column named "Pic #### Accessing RadGridView columns -{{source=..\SamplesCS\GridView\Columns\AccessingAndIteratingThroughColumns.cs region=accessingColumns}} -{{source=..\SamplesVB\GridView\Columns\AccessingAndIteratingThroughColumns.vb region=accessingColumns}} - -````C# -((GridViewImageColumn)this.radGridView1.Columns["Picture"]).Width = 110; - -```` -````VB.NET -DirectCast(Me.RadGridView1.Columns("Picture"), GridViewImageColumn).Width = 110 - -```` - -{{endregion}} + + ## Iterating through Columns @@ -39,40 +28,8 @@ You can iterate through grid columns by using the __Columns__ collection of Grid #### Iterating through RadGridView columns -{{source=..\SamplesCS\GridView\Columns\AccessingAndIteratingThroughColumns.cs region=iteratingColumns}} -{{source=..\SamplesVB\GridView\Columns\AccessingAndIteratingThroughColumns.vb region=iteratingColumns}} - -````C# -int i = 0; -foreach (GridViewColumn column in radGridView1.Columns) -{ - if (column is GridViewDataColumn) - { - GridViewDataColumn col = column as GridViewDataColumn; - if (col != null) - { - col.Width = 90; - col.HeaderText = "Column count : " + i.ToString(); - i++; - } - } -} - -```` -````VB.NET -Dim i As Integer = 0 -For Each column As GridViewColumn In RadGridView1.Columns - If TypeOf column Is GridViewDataColumn Then - Dim col As GridViewDataColumn = TryCast(column, GridViewDataColumn) - col.Width = 90 - col.HeaderText = "Column count: " + i.ToString - i = i + 1 - End If -Next - -```` - -{{endregion}} + + >caption Figure 1: Iterating columns and setting their HeaderText. @@ -84,69 +41,9 @@ Iterating through hierarchical RadGridView is possible by iterating through the #### Iterating through hierarchical RadGridView columns -{{source=..\SamplesCS\GridView\Columns\AccessingAndIteratingThroughColumns2.cs region=iterateColumnsInHierarchy}} -{{source=..\SamplesVB\GridView\Columns\AccessingAndIteratingThroughColumns2.vb region=iterateColumnsInHierarchy}} - -````C# -private void AccessingAndIteratingThroughColumns2_Load(object sender, EventArgs e) -{ - this.order_DetailsTableAdapter.Fill(this.nwindDataSet.Order_Details); - this.ordersTableAdapter.Fill(this.nwindDataSet.Orders); - this.customersTableAdapter.Fill(this.nwindDataSet.Customers); - radGridView1.AutoGenerateHierarchy = true; - radGridView1.DataSource = this.nwindDataSet; - radGridView1.DataMember = "Customers"; - int count = 0; - foreach (GridViewDataColumn dataColumn in this.GetAllColumns(this.radGridView1.MasterTemplate)) - { - dataColumn.WrapText = true; - dataColumn.HeaderText = "Column count: " + count++; - } -} -public List GetAllColumns(GridViewTemplate template) -{ - List allColumns = new List(); - allColumns.AddRange(template.Columns); - foreach (GridViewTemplate childTemplate in template.Templates) - { - List childColumns = this.GetAllColumns(childTemplate); - allColumns.AddRange(childColumns); - } - return allColumns; -} - -```` -````VB.NET -Private Sub AccessingAndIteratingThroughColumns2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load - Me.Order_DetailsTableAdapter.Fill(Me.NwindDataSet.Order_Details) - Me.OrdersTableAdapter.Fill(Me.NwindDataSet.Orders) - Me.CustomersTableAdapter.Fill(Me.NwindDataSet.Customers) - RadGridView1.AutoGenerateHierarchy = True - RadGridView1.DataSource = Me.NwindDataSet - RadGridView1.DataMember = "Customers" - - Dim count As Integer = 0 - For Each dataColumn As GridViewDataColumn In Me.GetAllColumns(Me.RadGridView1.MasterTemplate) - dataColumn.WrapText = True - dataColumn.HeaderText = "Column count: " & System.Math.Max(System.Threading.Interlocked.Increment(count), count - 1) - Next - End Sub -Public Function GetAllColumns(ByVal template As GridViewTemplate) As List(Of GridViewDataColumn) - Dim allColumns As New List(Of GridViewDataColumn)() - - allColumns.AddRange(template.Columns) - - For Each childTemplate As GridViewTemplate In template.Templates - Dim childColumns As List(Of GridViewDataColumn) = Me.GetAllColumns(childTemplate) - allColumns.AddRange(childColumns) - Next - - Return allColumns - End Function - -```` - -{{endregion}} + + + # See Also * [Calculated Columns (Column Expressions)]({%slug winforms/gridview/columns/calculated-columns-(column-expressions)%}) diff --git a/controls/gridview/visual-elements/columns/calculated-column-expressions.md b/controls/gridview/visual-elements/columns/calculated-column-expressions.md index f0b37c326..512ede911 100644 --- a/controls/gridview/visual-elements/columns/calculated-column-expressions.md +++ b/controls/gridview/visual-elements/columns/calculated-column-expressions.md @@ -17,27 +17,8 @@ The following code snippet demonstrates how the standard deviation of the *Con #### Creating a calculated column -{{source=..\SamplesCS\GridView\Columns\CalculatedColumn.cs region=calculatedColumn}} -{{source=..\SamplesVB\GridView\Columns\CalculatedColumn.vb region=calculatedColumn}} - -````C# -GridViewDecimalColumn col = new GridViewDecimalColumn(); -col.Name = "Calculated Column"; -col.HeaderText = "Order value"; -radGridView1.Columns.Add(col); -radGridView1.Columns["Calculated Column"].Expression = "UnitsOnOrder * UnitPrice"; - -```` -````VB.NET -Dim col = New GridViewDecimalColumn() -col.Name = "Calculated Column" -col.HeaderText = "Order value" -RadGridView1.Columns.Add(col) -RadGridView1.Columns("Calculated Column").Expression = "UnitsOnOrder * UnitPrice" - -```` - -{{endregion}} + + >caption Figure 1: The last column values are calculated dynamically. diff --git a/controls/gridview/visual-elements/columns/column-types/gridviewbrowsecolumn.md b/controls/gridview/visual-elements/columns/column-types/gridviewbrowsecolumn.md index 621b50f07..dd11d6dde 100644 --- a/controls/gridview/visual-elements/columns/column-types/gridviewbrowsecolumn.md +++ b/controls/gridview/visual-elements/columns/column-types/gridviewbrowsecolumn.md @@ -17,37 +17,8 @@ __GridViewBrowseColumn__ allows __RadGridView__ to edit file paths using __OpenF __GridViewBrowseColumn__ is never auto-generated. The following code snippet demonstrates how to create and add the column to RadGridView and also add some sample data for it: -{{source=..\SamplesCS\GridView\Columns\GridViewBrowseColumn1.cs region=addBrowseColumn}} -{{source=..\SamplesVB\GridView\Columns\GridViewBrowseColumn1.vb region=addBrowseColumn}} - -````C# -GridViewBrowseColumn column = new GridViewBrowseColumn("Browse column"); -this.radGridView1.Columns.Add(column); -this.radGridView1.Rows.Add(@"C:\Music\Sting\If You Love Somebody Set Them Free.wav"); -this.radGridView1.Rows.Add(@"C:\Music\Sting\Russians.wav"); -this.radGridView1.Rows.Add(@"C:\Music\Sting\Fortress Around Your Heart.wav"); -this.radGridView1.Rows.Add(@"C:\Music\Sting\Love Is the Seventh Wave.wav"); -this.radGridView1.Rows.Add(@"C:\Music\Sheryl Crow\Run, Baby, Run.wav"); -this.radGridView1.Rows.Add(@"C:\Music\Sheryl Crow\Leaving Las Vegas.wav"); -this.radGridView1.Rows.Add(@"C:\Music\Sheryl Crow\Strong Enough.wav"); - -```` -````VB.NET -Dim column As New GridViewBrowseColumn("Browse column") -Me.radGridView1.Columns.Add(column) -Me.radGridView1.Rows.Add("C:\Music\Sting\If You Love Somebody Set Them Free.wav") -Me.radGridView1.Rows.Add("C:\Music\Sting\Russians.wav") -Me.radGridView1.Rows.Add("C:\Music\Sting\Fortress Around Your Heart.wav") -Me.radGridView1.Rows.Add("C:\Music\Sting\Love Is the Seventh Wave.wav") -Me.radGridView1.Rows.Add("C:\Music\Sheryl Crow\Run, Baby, Run.wav") -Me.radGridView1.Rows.Add("C:\Music\Sheryl Crow\Leaving Las Vegas.wav") -Me.radGridView1.Rows.Add("C:\Music\Sheryl Crow\Strong Enough.wav") - -```` - -{{endregion}} - - + + # See Also * [GridViewCalculatorColumn]({%slug winforms/gridview/columns/column-types/gridviewcalculatorcolumn%}) diff --git a/controls/gridview/visual-elements/columns/column-types/gridviewcalculatorcolumn.md b/controls/gridview/visual-elements/columns/column-types/gridviewcalculatorcolumn.md index 6752f835b..c1560c445 100644 --- a/controls/gridview/visual-elements/columns/column-types/gridviewcalculatorcolumn.md +++ b/controls/gridview/visual-elements/columns/column-types/gridviewcalculatorcolumn.md @@ -17,37 +17,8 @@ __GridViewCalculatorColumn__ allows RadGridView to edit numbers using popup with __GridViewCalculatorColumn__ is never auto-generated. The following code snippet demonstrates how to create and add the column to RadGridView and also add some sample data in it: -{{source=..\SamplesCS\GridView\Columns\GridViewCalculatorColumn1.cs region=addCalculatorColumn}} -{{source=..\SamplesVB\GridView\Columns\GridViewCalculatorColumn1.vb region=addCalculatorColumn}} - -````C# -GridViewCalculatorColumn column = new GridViewCalculatorColumn("Calculator column"); -this.radGridView1.Columns.Add(column); -this.radGridView1.Rows.Add(3.14159); -this.radGridView1.Rows.Add(2.71828); -this.radGridView1.Rows.Add(1.41421); -this.radGridView1.Rows.Add(0.57721); -this.radGridView1.Rows.Add(4.66920); -this.radGridView1.Rows.Add(3.27582); -this.radGridView1.Rows.Add(0.56714); - -```` -````VB.NET -Dim column As New GridViewCalculatorColumn("Calculator column") -Me.radGridView1.Columns.Add(column) -Me.radGridView1.Rows.Add(3.14159) -Me.radGridView1.Rows.Add(2.71828) -Me.radGridView1.Rows.Add(1.41421) -Me.radGridView1.Rows.Add(0.57721) -Me.radGridView1.Rows.Add(4.6692) -Me.radGridView1.Rows.Add(3.27582) -Me.radGridView1.Rows.Add(0.56714) - -```` - -{{endregion}} - - + + # See Also * [GridViewBrowseColumn]({%slug winforms/gridview/columns/column-types/gridviewbrowsecolumn%}) diff --git a/controls/gridview/visual-elements/columns/column-types/gridviewcheckboxcolumn.md b/controls/gridview/visual-elements/columns/column-types/gridviewcheckboxcolumn.md index 73319c7ed..ad344ab47 100644 --- a/controls/gridview/visual-elements/columns/column-types/gridviewcheckboxcolumn.md +++ b/controls/gridview/visual-elements/columns/column-types/gridviewcheckboxcolumn.md @@ -17,118 +17,34 @@ __GridViewCheckBoxColumn__ displays and allows editing of boolean data. The valu #### Create and add GridViewCheckBoxColumn -{{source=..\SamplesCS\GridView\Columns\GridViewCheckBoxColumn1.cs region=addCheckBoxColumn}} -{{source=..\SamplesVB\GridView\Columns\GridViewCheckBoxColumn1.vb region=addCheckBoxColumn}} - -````C# -GridViewCheckBoxColumn checkBoxColumn = new GridViewCheckBoxColumn(); -checkBoxColumn.DataType = typeof(int); -checkBoxColumn.Name = "DiscontinuedColumn"; -checkBoxColumn.FieldName = "Discontinued"; -checkBoxColumn.HeaderText = "Discontinued?"; -radGridView1.MasterTemplate.Columns.Add(checkBoxColumn); - -```` -````VB.NET -Dim checkBoxColumn As New GridViewCheckBoxColumn() -checkBoxColumn.DataType = GetType(Integer) -checkBoxColumn.Name = "DiscontinuedColumn" -checkBoxColumn.FieldName = "Discontinued" -checkBoxColumn.HeaderText = "Discontinued?" -RadGridView1.MasterTemplate.Columns.Add(checkBoxColumn) - -```` - -{{endregion}} + + The column has also a built-in functionality for checking all check boxes in it, via check box placed in the column header cell. By setting the __EnableHeaderCheckBox__ property to *true* you will enable the embedded in the header cell **RadCheckBoxElement**. -{{source=..\SamplesCS\GridView\Columns\GridViewCheckBoxColumn1.cs region=EnableHeaderCheckBox}} -{{source=..\SamplesVB\GridView\Columns\GridViewCheckBoxColumn1.vb region=EnableHeaderCheckBox}} - -````C# -checkBoxColumn.EnableHeaderCheckBox = true; - -```` -````VB.NET -checkBoxColumn.EnableHeaderCheckBox = True - -```` - -{{endregion}} + + ## ValueChanged event __ValueChanged__ event can be used in particular about check box state change. You have to check the active editor type as in the example below: -{{source=..\SamplesCS\GridView\Columns\GridViewCheckBoxColumn1.cs region=valueChanged}} -{{source=..\SamplesVB\GridView\Columns\GridViewCheckBoxColumn1.vb region=valueChanged}} - -````C# -void radGridView1_ValueChanged(object sender, EventArgs e) -{ - if (this.radGridView1.ActiveEditor is RadCheckBoxEditor) - { - Console.WriteLine(this.radGridView1.CurrentCell.RowIndex); - Console.WriteLine(this.radGridView1.ActiveEditor.Value); - } -} - -```` -````VB.NET -Private Sub RadGridView1_ValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles RadGridView1.ValueChanged - If TypeOf Me.RadGridView1.ActiveEditor Is RadCheckBoxEditor Then - Console.WriteLine(Me.RadGridView1.CurrentCell.RowIndex) - Console.WriteLine(Me.RadGridView1.ActiveEditor.Value) - End If -End Sub - -```` - -{{endregion}} + + ## HeaderCellToggleStateChanged event To handle the toggle state change of the embedded check box in the header cell you should use the __HeaderCellToggleStateChanged__ event of RadGridView. -{{source=..\SamplesCS\GridView\Columns\GridViewCheckBoxColumn1.cs region=HeaderCellToggleStateChanged}} -{{source=..\SamplesVB\GridView\Columns\GridViewCheckBoxColumn1.vb region=HeaderCellToggleStateChanged}} - -````C# -void radGridView1_HeaderCellToggleStateChanged(object sender, GridViewHeaderCellEventArgs e) -{ - Console.WriteLine(e.Column.Name); - Console.WriteLine(e.State); -} - -```` -````VB.NET -Private Sub radGridView1_HeaderCellToggleStateChanged(sender As Object, e As GridViewHeaderCellEventArgs) - Console.WriteLine(e.Column.Name) - Console.WriteLine(e.State) -End Sub - -```` - -{{endregion}} + + ## EditMode The __EditMode__ property controls when the value of the editor will be submitted to the cell. By default, the current behavior is kept (*OnValidate*) and the value will be submitted only when the current cell changes or the grid looses focus. The new value (*OnValueChange*) will submit the value immediately after the editor value changes. -{{source=..\SamplesCS\GridView\Columns\GridViewCheckBoxColumn1.cs region=EditMode}} -{{source=..\SamplesVB\GridView\Columns\GridViewCheckBoxColumn1.vb region=EditMode}} - -````C# -checkBoxColumn.EditMode = EditMode.OnValueChange; - -```` -````VB.NET -checkBoxColumn.EditMode = EditMode.OnValueChange - -```` - -{{endregion}} + + ## GridViewCheckBoxColumn's Properties diff --git a/controls/gridview/visual-elements/columns/column-types/gridviewcolorcolumn.md b/controls/gridview/visual-elements/columns/column-types/gridviewcolorcolumn.md index 324b6f59a..20dd13c7d 100644 --- a/controls/gridview/visual-elements/columns/column-types/gridviewcolorcolumn.md +++ b/controls/gridview/visual-elements/columns/column-types/gridviewcolorcolumn.md @@ -17,35 +17,8 @@ __GridViewColorColumn__ allows **RadGridView** to edit colors using [RadColorDia __GridViewColorColumn__ is auto-generated for __Color__ properties in the RadGridView.**DataSource**. The following code snippet demonstrates how to create it manually, add it to **RadGridView** and populate it with data: -{{source=..\SamplesCS\GridView\Columns\GridViewColorColumn1.cs region=addColorColumn}} -{{source=..\SamplesVB\GridView\Columns\GridViewColorColumn1.vb region=addColorColumn}} - -````C# -GridViewColorColumn column = new GridViewColorColumn("Color column"); -this.radGridView1.Columns.Add(column); -this.radGridView1.Rows.Add("Red"); -this.radGridView1.Rows.Add("Orange"); -this.radGridView1.Rows.Add("Yellow"); -this.radGridView1.Rows.Add("Green"); -this.radGridView1.Rows.Add("Blue"); -this.radGridView1.Rows.Add("Indigo"); -this.radGridView1.Rows.Add("Violet"); - -```` -````VB.NET -Dim column As New GridViewColorColumn("Color column") -Me.radGridView1.Columns.Add(column) -Me.radGridView1.Rows.Add("Red") -Me.radGridView1.Rows.Add("Orange") -Me.radGridView1.Rows.Add("Yellow") -Me.radGridView1.Rows.Add("Green") -Me.radGridView1.Rows.Add("Blue") -Me.radGridView1.Rows.Add("Indigo") -Me.radGridView1.Rows.Add("Violet") - -```` - -{{endregion}} + + ## GridColorPickerEditor diff --git a/controls/gridview/visual-elements/columns/column-types/gridviewcomboboxcolumn.md b/controls/gridview/visual-elements/columns/column-types/gridviewcomboboxcolumn.md index f907bc547..a8ad4fe22 100644 --- a/controls/gridview/visual-elements/columns/column-types/gridviewcomboboxcolumn.md +++ b/controls/gridview/visual-elements/columns/column-types/gridviewcomboboxcolumn.md @@ -49,35 +49,8 @@ The useful methods for **GridViewComboBoxColumn** are: #### Adding and binding GridViewComboBoxColumn -{{source=..\SamplesCS\GridView\Columns\GridViewComboBoxColumn1.cs region=addComboBoxColumn}} -{{source=..\SamplesVB\GridView\Columns\GridViewComboBoxColumn1.vb region=addComboBoxColumn}} - -````C# -GridViewComboBoxColumn supplierColumn = new GridViewComboBoxColumn(); -supplierColumn.Name = "SupplierColumn"; -supplierColumn.HeaderText = "Supplier"; -supplierColumn.DataSource = this.suppliersBindingSource; -supplierColumn.ValueMember = "SupplierID"; -supplierColumn.DisplayMember = "ContactName"; -supplierColumn.FieldName = "SupplierID"; -supplierColumn.Width = 200; -this.radGridView1.Columns.Add(supplierColumn); - -```` -````VB.NET -Dim supplierColumn As GridViewComboBoxColumn = New GridViewComboBoxColumn -supplierColumn.Name = "SupplierColumn" -supplierColumn.HeaderText = "Supplier" -supplierColumn.DataSource = Me.SuppliersBindingSource -supplierColumn.ValueMember = "SupplierID" -supplierColumn.DisplayMember = "ContactName" -supplierColumn.FieldName = "SupplierID" -supplierColumn.Width = 200 -Me.RadGridView1.Columns.Add(supplierColumn) - -```` - -{{endregion}} + + >important If you want to set initial values, you should match the __GridViewComboBoxColumn__ to a column which has appropriate values in it. To do this, you should set the __FieldName__ of the __GridViewComboBoxColumn__ to be the same as the name of the existing column. @@ -85,23 +58,8 @@ The displayed text in a cell can be retrieved by calling the __GetLookupValue__ #### Get Cell Text -{{source=..\SamplesCS\GridView\Columns\GridViewComboBoxColumn1.cs region=GetLookupValue}} -{{source=..\SamplesVB\GridView\Columns\GridViewComboBoxColumn1.vb region=GetLookupValue}} - -````C# -GridViewComboBoxColumn comboBoxColumn = this.radGridView1.Columns["column"] as GridViewComboBoxColumn; -object value = this.radGridView1.Rows[0].Cells["SupplierColumn"].Value; -string text = (string)comboBoxColumn.GetLookupValue(value); - -```` -````VB.NET -Dim comboBoxColumn As GridViewComboBoxColumn = TryCast(Me.radGridView1.Columns("column"), GridViewComboBoxColumn) -Dim value As Object = Me.radGridView1.Rows(0).Cells("SupplierColumn").Value -Dim text As String = DirectCast(comboBoxColumn.GetLookupValue(value), String) - -```` - -{{endregion}} + + >important The stored values inside the cells belonging to this column corresponds to the **ValueMember** field that is specified. In the above example, **SupplierID** is applied as ValueMember. Hence, the cells stores the numeric IDs of the suppliers. In case you are using unbound mode for the grid and the grid rows are programmatically added, you have to specify again a value that corresponds to the specified **ValueMember**. @@ -109,31 +67,8 @@ In order to access the __RadDropDownListEditor__, you should subscribe to the _ #### Modify the DropDownList editor -{{source=..\SamplesCS\GridView\Columns\GridViewComboBoxColumn1.cs region=modifyTheComboBoxEditor}} -{{source=..\SamplesVB\GridView\Columns\GridViewComboBoxColumn1.vb region=modifyTheComboBoxEditor}} - -````C# -void radGridView1_CellEditorInitialized(object sender, GridViewCellEventArgs e) -{ - RadDropDownListEditor editor = this.radGridView1.ActiveEditor as RadDropDownListEditor; - if (editor != null) - { - ((RadDropDownListEditorElement)((RadDropDownListEditor)this.radGridView1.ActiveEditor).EditorElement).RightToLeft = true; - } -} - -```` -````VB.NET -Private Sub RadGridView1_CellEditorInitialized(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewCellEventArgs) Handles RadGridView1.CellEditorInitialized - Dim editor As RadDropDownListEditor = TryCast(Me.RadGridView1.ActiveEditor, RadDropDownListEditor) - If Not editor Is Nothing Then - CType((CType(Me.RadGridView1.ActiveEditor, RadDropDownListEditor)).EditorElement, RadDropDownListEditorElement).RightToLeft = True - End If -End Sub - -```` - -{{endregion}} + + ## Binding to array of strings @@ -141,60 +76,8 @@ The following example demonstrates a case where the combo box is bound to a colu #### Bind to array of string -{{source=..\SamplesCS\GridView\Columns\GridViewComboBoxColumn1.cs region=BindToArray}} -{{source=..\SamplesVB\GridView\Columns\GridViewComboBoxColumn1.vb region=BindToArray}} - -````C# -//Create the data source and fill some data -DataTable table = new DataTable(); -table.Columns.Add("Phone", typeof(string)); -table.Rows.Add("Mobile"); -table.Rows.Add("Business"); -table.Rows.Add("Business"); -table.Rows.Add("Fax"); -table.Rows.Add("Fax"); -table.Rows.Add("Fax"); -//allow the grid to genetate its columns -this.radGridView1.MasterTemplate.AutoGenerateColumns = false; -//set the grid data source -this.radGridView1.DataSource = table; - -//create the combo box column -GridViewComboBoxColumn comboColumn = new GridViewComboBoxColumn("Phone"); -//set the column data source - the possible column values -comboColumn.DataSource = new String[] { "Mobile", "Business", "Fax" }; -//set the FieldName - the column will retrieve the value from "Phone" column in the data table -comboColumn.FieldName = "Phone"; -//add the column to the grid -radGridView1.Columns.Add(comboColumn); - -```` -````VB.NET -'Create the data source and fill some data -Dim table As New DataTable() -table.Columns.Add("Phone", GetType(String)) -table.Rows.Add("Mobile") -table.Rows.Add("Business") -table.Rows.Add("Business") -table.Rows.Add("Fax") -table.Rows.Add("Fax") -table.Rows.Add("Fax") -'allow the grid to genetate its columns -Me.RadGridView1.MasterTemplate.AutoGenerateColumns = False -'set the grid data source -Me.RadGridView1.DataSource = table -'create the combo box column -Dim comboColumn As New GridViewComboBoxColumn("Phone") -'set the column data source - the possible column values -comboColumn.DataSource = New [String]() {"Mobile", "Business", "Fax"} -'set the FieldName - the column will retrieve the value from "Phone" column in the data table -comboColumn.FieldName = "Phone" -'add the column to the grid -RadGridView1.Columns.Add(comboColumn) - -```` - -{{endregion}} + + ## Binding to collection of custom object @@ -206,124 +89,8 @@ The example below extends the previous sample, where we bound the combo column t #### Binding to collection of custom object -{{source=..\SamplesCS\GridView\Columns\GridViewComboBoxColumn2.cs region=BindToObject}} -{{source=..\SamplesVB\GridView\Columns\GridViewComboBoxColumn2.vb region=BindToObject}} - -````C# -public partial class GridViewComboBoxColumn2 : Form -{ - public GridViewComboBoxColumn2() - { - InitializeComponent(); - DataTable table = new DataTable(); - table.Columns.Add("Text", typeof(string)); - table.Columns.Add("Phone", typeof(string)); - table.Columns.Add("Another ComboBox column", typeof(int)); - table.Rows.Add("Text 1", "Mobile", 1); - table.Rows.Add("Text 2", "Business", 1); - table.Rows.Add("Text 3", "Business", 2); - table.Rows.Add("Text 4", "Fax", 1); - this.radGridView1.MasterTemplate.AutoGenerateColumns = false; - radGridView1.Columns.Add(new GridViewTextBoxColumn("Text")); - GridViewComboBoxColumn comboCol = new GridViewComboBoxColumn("Phone"); - comboCol.DataSource = new String[] { "Mobile", "Business", "Fax" }; - comboCol.FieldName = "Phone"; - radGridView1.Columns.Add(comboCol); - GridViewComboBoxColumn colboCol2 = new GridViewComboBoxColumn("Another ComboBox column"); - colboCol2.FieldName = "Another ComboBox column"; - colboCol2.ValueMember = "Id"; - colboCol2.DisplayMember = "MyString"; - BindingList list = new BindingList(); - ComboBoxDataSourceObject object1 = new ComboBoxDataSourceObject(); - object1.Id = 1; - object1.MyString = "First object"; - list.Add(object1); - ComboBoxDataSourceObject object2 = new ComboBoxDataSourceObject(); - object2.Id = 2; - object2.MyString = "Second object"; - list.Add(object2); - colboCol2.DataSource = list; - radGridView1.Columns.Add(colboCol2); - this.radGridView1.DataSource = table; - } -} -public class ComboBoxDataSourceObject -{ - private string myString; - public string MyString - { - get { return myString; } - set { myString = value; } - } - private int id; - public int Id - { - get { return id; } - set { id = value; } - } -} - -```` -````VB.NET -Public Class GridViewComboBoxColumn2 - Public Sub New() - InitializeComponent() - Dim table As New DataTable() - table.Columns.Add("Text", GetType(String)) - table.Columns.Add("Phone", GetType(String)) - table.Columns.Add("Another ComboBox column", GetType(Integer)) - table.Rows.Add("Text 1", "Mobile", 1) - table.Rows.Add("Text 2", "Business", 1) - table.Rows.Add("Text 3", "Business", 2) - table.Rows.Add("Text 4", "Fax", 1) - Me.RadGridView1.MasterTemplate.AutoGenerateColumns = False - RadGridView1.Columns.Add(New GridViewTextBoxColumn("Text")) - Dim comboCol As New GridViewComboBoxColumn("Phone") - comboCol.DataSource = New [String]() {"Mobile", "Business", "Fax"} - comboCol.FieldName = "Phone" - RadGridView1.Columns.Add(comboCol) - Dim colboCol2 As New GridViewComboBoxColumn("Another ComboBox column") - colboCol2.FieldName = "Another ComboBox column" - colboCol2.ValueMember = "Id" - colboCol2.DisplayMember = "MyString" - Dim list As New BindingList(Of ComboBoxDataSourceObject)() - Dim object1 As New ComboBoxDataSourceObject() - object1.Id = 1 - object1.MyString = "First object" - list.Add(object1) - Dim object2 As New ComboBoxDataSourceObject() - object2.Id = 2 - object2.MyString = "Second object" - list.Add(object2) - colboCol2.DataSource = list - RadGridView1.Columns.Add(colboCol2) - Me.RadGridView1.DataSource = table - End Sub -End Class -Public Class ComboBoxDataSourceObject - Private myString_ As String - Public Property MyString() As String - Get - Return myString_ - End Get - Set(value As String) - myString_ = value - End Set - End Property - Private m_id As Integer - Public Property Id() As Integer - Get - Return m_id - End Get - Set(value As Integer) - m_id = value - End Set - End Property -End Class - -```` - -{{endregion}} + + ##  Customizing DropDownList editors in RadGridView @@ -331,146 +98,8 @@ You have to handle the **EditorRequired** event. This event is fired every time ####  Customizing DropDownList editors in RadGridView -{{source=..\SamplesCS\GridView\Columns\GridViewComboBoxColumn3.cs region=customizeDropDownListEditor}} -{{source=..\SamplesVB\GridView\Columns\GridViewComboBoxColumn3.vb region=customizeDropDownListEditor}} - -````C# -public GridViewComboBoxColumn3() -{ - InitializeComponent(); - GridViewComboBoxColumn customerColumn = new GridViewComboBoxColumn(); - customerColumn.Name = "CustomerColumn"; - customerColumn.HeaderText = "Customer"; - customerColumn.DataSource = this.customersBindingSource; - customerColumn.ValueMember = "CustomerID"; - customerColumn.DisplayMember = "ContactName"; - customerColumn.FieldName = "CustomerID"; - customerColumn.Width = 200; - this.radGridView1.Columns.Add(customerColumn); - radGridView1.EditorRequired += new EditorRequiredEventHandler(radGridView1_EditorRequired); -} -MyDropDownListEditor myComboEditor = new MyDropDownListEditor(); -void radGridView1_EditorRequired(object sender, EditorRequiredEventArgs e) -{ - if (e.EditorType == typeof(RadDropDownListEditor)) - { - e.Editor = new MyDropDownListEditor(); - } -} -private void GridViewComboBoxColumn3_Load(object sender, EventArgs e) -{ - // TODO: This line of code loads data into the 'nwindDataSet.Customers' table. You can move, or remove it, as needed. - this.customersTableAdapter.Fill(this.nwindDataSet.Customers); -} - } -public class MyDropDownListEditor : RadDropDownListEditor - { -protected override RadElement CreateEditorElement() -{ - return new MyDropDownListEditorElement(); -} - } -public class MyDropDownListEditorElement : RadDropDownListEditorElement - { -protected override void OnLoaded() -{ - base.OnLoaded(); - this.ListElement.CreatingVisualItem += new CreatingVisualListItemEventHandler(ListElement_CreatingVisualItem); - -} -private void ListElement_CreatingVisualItem(object sender, CreatingVisualListItemEventArgs args) -{ - // add button element - RadListVisualItem visualItem = new RadListVisualItem(); - visualItem.Padding = new Padding(12, 0, 0, 0); - visualItem.NumberOfColors = 1; - visualItem.BackColor = Color.Yellow; - RadButtonElement button = new RadButtonElement(); - button.MinSize = new Size(12, 12); - button.MaxSize = button.MinSize; - button.Text = "x"; - button.TextAlignment = ContentAlignment.MiddleLeft; - button.Click += new EventHandler(button_Click); - visualItem.Children.Add(button); - args.VisualItem = visualItem; - -} -private void button_Click(object sender, EventArgs e) -{ - BindingSource source = (BindingSource)this.DataSource; - source.Remove(source.Current); - this.SelectedIndex = -1; -} - } - -```` -````VB.NET -Public Class GridViewComboBoxColumn3 - Public Sub New() - InitializeComponent() - Dim customerColumn As GridViewComboBoxColumn = New GridViewComboBoxColumn - customerColumn.Name = "CustomerColumn" - customerColumn.HeaderText = "Customer" - customerColumn.DataSource = Me.CustomersBindingSource - customerColumn.ValueMember = "CustomerID" - customerColumn.DisplayMember = "ContactName" - customerColumn.FieldName = "CustomerID" - customerColumn.Width = 200 - Me.RadGridView1.Columns.Add(customerColumn) - End Sub - Private Sub GridViewComboBoxColumn3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load - 'TODO: This line of code loads data into the 'NwindDataSet.Customers' table. You can move, or remove it, as needed. - Me.CustomersTableAdapter.Fill(Me.NwindDataSet.Customers) - End Sub - Private Sub RadGridView1_EditorRequired(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.EditorRequiredEventArgs) Handles RadGridView1.EditorRequired - If e.EditorType Is GetType(RadDropDownListEditor) Then - e.Editor = New MyDropDownListEditor() - End If - End Sub -End Class -Public Class MyDropDownListEditor - Inherits RadDropDownListEditor - Protected Overrides Function CreateEditorElement() As RadElement - Return New MyDropDownListEditorElement() - End Function -End Class - -Public Class MyDropDownListEditorElement - Inherits RadDropDownListEditorElement - Protected Overrides Sub OnLoaded() - MyBase.OnLoaded() - AddHandler Me.ListElement.CreatingVisualItem, AddressOf ListElement_CreatingVisualItem - End Sub - - Private Sub ListElement_CreatingVisualItem(ByVal sender As Object, ByVal args As CreatingVisualListItemEventArgs) - ' add button element - Dim visualItem As New RadListVisualItem() - visualItem.Padding = New Padding(12, 0, 0, 0) - visualItem.NumberOfColors = 1 - visualItem.BackColor = Color.Yellow - - Dim button As New RadButtonElement() - button.MinSize = New Size(12, 12) - button.MaxSize = button.MinSize - button.Text = "x" - button.TextAlignment = ContentAlignment.MiddleLeft - AddHandler button.Click, AddressOf button_Click - visualItem.Children.Add(button) - args.VisualItem = visualItem - - End Sub - - Private Sub button_Click(ByVal sender As Object, ByVal e As EventArgs) - ' Remove the item from the DataSource collection - Dim source = DirectCast(Me.DataSource, BindingSource) - source.Remove(source.Current) - Me.SelectedIndex = -1 - End Sub -End Class - -```` - -{{endregion}} + + >caption Figure 2: The items styles are now changed. diff --git a/controls/gridview/visual-elements/columns/column-types/gridviewcommandcolumn.md b/controls/gridview/visual-elements/columns/column-types/gridviewcommandcolumn.md index c44cc269a..2efea1c2e 100644 --- a/controls/gridview/visual-elements/columns/column-types/gridviewcommandcolumn.md +++ b/controls/gridview/visual-elements/columns/column-types/gridviewcommandcolumn.md @@ -19,59 +19,8 @@ The example below creates two __GridViewCommandColumns__. The first has __UseDe #### Add GridViewCommandColumn to the grid. -{{source=..\SamplesCS\GridView\Columns\GridViewCommandColumn1.cs region=addCommandColumn}} -{{source=..\SamplesVB\GridView\Columns\GridViewCommandColumn1.vb region=addCommandColumn}} - -````C# -public GridViewCommandColumn1() -{ - InitializeComponent(); - GridViewCommandColumn commandColumn = new GridViewCommandColumn(); - commandColumn.Name = "CommandColumn"; - commandColumn.UseDefaultText = false; - commandColumn.FieldName = "ProductName"; - commandColumn.HeaderText = "Order"; - radGridView1.MasterTemplate.Columns.Add(commandColumn); - GridViewCommandColumn commandColumn2 = new GridViewCommandColumn(); - commandColumn2.Name = "CommandColumn2"; - commandColumn2.UseDefaultText = true; - commandColumn2.DefaultText = "Order"; - commandColumn2.FieldName = "ProductName"; - commandColumn2.HeaderText = "Order"; - radGridView1.MasterTemplate.Columns.Add(commandColumn2); - radGridView1.CommandCellClick += new CommandCellClickEventHandler(radGridView1_CommandCellClick); -} -void radGridView1_CommandCellClick(object sender, EventArgs e) -{ - MessageBox.Show("You ordered " + ((sender as GridCommandCellElement)).Value); -} - -```` -````VB.NET -Public Sub New() - InitializeComponent() - Dim commandColumn As New GridViewCommandColumn() - commandColumn.Name = "CommandColumn" - commandColumn.UseDefaultText = False - commandColumn.FieldName = "ProductName" - commandColumn.HeaderText = "Order" - RadGridView1.MasterTemplate.Columns.Add(commandColumn) - Dim commandColumn2 As New GridViewCommandColumn() - commandColumn2.Name = "CommandColumn2" - commandColumn2.UseDefaultText = True - commandColumn2.DefaultText = "Order" - commandColumn2.FieldName = "ProductName" - commandColumn2.HeaderText = "Order" - RadGridView1.MasterTemplate.Columns.Add(commandColumn2) - AddHandler RadGridView1.CommandCellClick, AddressOf radGridView1_CommandCellClick -End Sub -Sub radGridView1_CommandCellClick(ByVal sender As Object, ByVal e As EventArgs) - MessageBox.Show("You ordered " + ((TryCast(sender, GridCommandCellElement))).Value) -End Sub - -```` - -{{endregion}} + + ## Buttons Styles diff --git a/controls/gridview/visual-elements/columns/column-types/gridviewdatetimecolumn.md b/controls/gridview/visual-elements/columns/column-types/gridviewdatetimecolumn.md index 752cd8021..cadd3374b 100644 --- a/controls/gridview/visual-elements/columns/column-types/gridviewdatetimecolumn.md +++ b/controls/gridview/visual-elements/columns/column-types/gridviewdatetimecolumn.md @@ -19,137 +19,27 @@ __GridViewDateTimeColumn__ provides date entry and formatting for DateTime data #### Formatting the date. -{{source=..\SamplesCS\GridView\Columns\GridViewDateTimeColumn1.cs region=addDateTimeColumn}} -{{source=..\SamplesVB\GridView\Columns\GridViewDateTimeColumn1.vb region=addDateTimeColumn}} - -````C# -GridViewDateTimeColumn dateTimeColumn = new GridViewDateTimeColumn(); -dateTimeColumn.Name = "DateTimeColumn"; -dateTimeColumn.HeaderText = "Order date"; -dateTimeColumn.FieldName = "OrderDate"; -dateTimeColumn.FormatString = "{0:D}"; - -```` -````VB.NET -Dim dateTimeColumn As New GridViewDateTimeColumn() -dateTimeColumn.Name = "DateTimeColumn" -dateTimeColumn.HeaderText = "Order date" -dateTimeColumn.FieldName = "OrderDate" -dateTimeColumn.FormatString = "{0:D}" - -```` - -{{endregion}} + + >note The formatting for date and time values also responds to globalization settings. -{{source=..\SamplesCS\GridView\Columns\GridViewDateTimeColumn2.cs region=settingCurrentCulture}} -{{source=..\SamplesVB\GridView\Columns\GridViewDateTimeColumn2.vb region=settingCurrentCulture}} - -````C# -System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("fr-BE"); -GridViewDateTimeColumn dateTimeColumn = new GridViewDateTimeColumn(); -dateTimeColumn.Name = "DateTimeColumn"; -dateTimeColumn.HeaderText = "Order date"; -dateTimeColumn.FieldName = "OrderDate"; -dateTimeColumn.FormatString = "{0:D}"; -radGridView1.MasterTemplate.Columns.Add(dateTimeColumn); - -```` -````VB.NET -System.Threading.Thread.CurrentThread.CurrentCulture = New System.Globalization.CultureInfo("fr-BE") - Dim dateTimeColumn As New GridViewDateTimeColumn() - dateTimeColumn.Name = "DateTimeColumn" - dateTimeColumn.HeaderText = "Order date" - dateTimeColumn.FieldName = "OrderDate" - dateTimeColumn.FormatString = "{0:D}" - RadGridView1.MasterTemplate.Columns.Add(dateTimeColumn) - -```` - -{{endregion}} + + The code below demonstrates how to change date formatting in edit mode (while the cell is being edited). There are two ways to achieve that - by setting the __Format__ property of the column to *Custom* and the __CustomFormat__ property of the column to a desired format, or by setting the same properties of the editor itself. Please note that we are using the __CellEditorInitialized__ event which is fired when the initialization of an editor is done in order to access the editor: -{{source=..\SamplesCS\GridView\Columns\GridViewDateTimeColumn1.cs region=changeEditorDateFormat}} -{{source=..\SamplesVB\GridView\Columns\GridViewDateTimeColumn1.vb region=changeEditorDateFormat}} - -````C# -GridViewDateTimeColumn dateTimeColumn1 = new GridViewDateTimeColumn(); -dateTimeColumn1.Name = "DateTimeColumn"; -dateTimeColumn1.HeaderText = "Order date"; -dateTimeColumn1.FieldName = "OrderDate"; -dateTimeColumn1.Format = DateTimePickerFormat.Custom; -dateTimeColumn1.CustomFormat = "t"; - -```` -````VB.NET -Private Sub radGridView1_CellEditorInitialized(ByVal sender As Object, ByVal e As GridViewCellEventArgs) - Dim editor As RadDateTimeEditor = TryCast(Me.RadGridView1.ActiveEditor, RadDateTimeEditor) - If editor IsNot Nothing Then - 'Pick up one of the default formats - DirectCast(DirectCast(Me.RadGridView1.ActiveEditor, RadDateTimeEditor).EditorElement, RadDateTimeEditorElement).Format = DateTimePickerFormat.[Short] - 'Or set a custom date format - DirectCast(DirectCast(Me.RadGridView1.ActiveEditor, RadDateTimeEditor).EditorElement, RadDateTimeEditorElement).CustomFormat = "t" - End If -End Sub - -```` - -{{endregion}} - - -{{source=..\SamplesCS\GridView\Columns\GridViewDateTimeColumn1.cs region=changeEditorDateFormat1}} -{{source=..\SamplesVB\GridView\Columns\GridViewDateTimeColumn1.vb region=changeEditorDateFormat1}} - -````C# -void radGridView1_CellEditorInitialized(object sender, GridViewCellEventArgs e) -{ - RadDateTimeEditor editor = this.radGridView1.ActiveEditor as RadDateTimeEditor; - if (editor != null) - { - //Pick up one of the default formats - ((RadDateTimeEditorElement)((RadDateTimeEditor)this.radGridView1.ActiveEditor).EditorElement).Format = DateTimePickerFormat.Short; - - //Or set a custom date format - ((RadDateTimeEditorElement)((RadDateTimeEditor)this.radGridView1.ActiveEditor).EditorElement).CustomFormat = "t"; - } -} - -```` -````VB.NET -Private Sub radGridView1_CellEditorInitialized(ByVal sender As Object, ByVal e As GridViewCellEventArgs) - Dim editor As RadDateTimeEditor = TryCast(Me.RadGridView1.ActiveEditor, RadDateTimeEditor) - If editor IsNot Nothing Then - 'Pick up one of the default formats - DirectCast(DirectCast(Me.RadGridView1.ActiveEditor, RadDateTimeEditor).EditorElement, RadDateTimeEditorElement).Format = DateTimePickerFormat.[Short] - 'Or set a custom date format - DirectCast(DirectCast(Me.RadGridView1.ActiveEditor, RadDateTimeEditor).EditorElement, RadDateTimeEditorElement).CustomFormat = "t" - End If -End Sub - -```` - -{{endregion}} - + + + + If we do not use the `CellEditorInitialized`, but `CellBeginEdit` (it is fired before `CellEditorInitialized`), our __Format__ setting will be overridden by the initialization of the editor. You can also change the way the dates in the column are filtered. This is how the column can be adjusted to filter only by __Dates__. -{{source=..\SamplesCS\GridView\Columns\GridViewDateTimeColumn1.cs region=changeFilteringMode}} -{{source=..\SamplesVB\GridView\Columns\GridViewDateTimeColumn1.vb region=changeFilteringMode}} - -````C# -dateTimeColumn1.FilteringMode = GridViewTimeFilteringMode.Date; - -```` -````VB.NET -dateTimeColumn1.FilteringMode = GridViewTimeFilteringMode.Date - -```` - -{{endregion}} + + ## DateTimeKind property diff --git a/controls/gridview/visual-elements/columns/column-types/gridviewdecimalcolumn.md b/controls/gridview/visual-elements/columns/column-types/gridviewdecimalcolumn.md index 7e47d0f26..b5bfcf9ac 100644 --- a/controls/gridview/visual-elements/columns/column-types/gridviewdecimalcolumn.md +++ b/controls/gridview/visual-elements/columns/column-types/gridviewdecimalcolumn.md @@ -17,91 +17,22 @@ __GridViewDecimalColumn__ allows decimal data to be displayed and edited. __Grid #### Add GridViewDecimalColumn to the grid. -{{source=..\SamplesCS\GridView\Columns\GridViewDecimalColumn1.cs region=addingDecimalColumn}} -{{source=..\SamplesVB\GridView\Columns\GridViewDecimalColumn1.vb region=addingDecimalColumn}} - -````C# -GridViewDecimalColumn decimalColumn = new GridViewDecimalColumn(); -decimalColumn.Name = "DecimalColumn"; -decimalColumn.HeaderText = "Unit Price"; -decimalColumn.FieldName = "UnitPrice"; -decimalColumn.DecimalPlaces = 3; -radGridView1.MasterTemplate.Columns.Add(decimalColumn); - -```` -````VB.NET -Dim decimalColumn As New GridViewDecimalColumn() -decimalColumn.Name = "DecimalColumn" -decimalColumn.HeaderText = "Unit Price" -decimalColumn.FieldName = "UnitPrice" -decimalColumn.DecimalPlaces = 3 -RadGridView1.MasterTemplate.Columns.Add(decimalColumn) - -```` - -{{endregion}} + + ## Setting a default value for empty cells You may provide a default value using the following code: -{{source=..\SamplesCS\GridView\Columns\GridViewDecimalColumn1.cs region=settingTheDefaultValue}} -{{source=..\SamplesVB\GridView\Columns\GridViewDecimalColumn1.vb region=settingTheDefaultValue}} - -````C# -void radGridView1_CellEditorInitialized(object sender, GridViewCellEventArgs e) -{ - GridSpinEditor spinEditor = this.radGridView1.ActiveEditor as GridSpinEditor; - if (spinEditor != null) - { - if (spinEditor.Value == null) - { - spinEditor.Value = 0.0; - } - } -} - -```` -````VB.NET -Private Sub RadGridView1_CellEditorInitialized(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewCellEventArgs) - Dim spinEditor As GridSpinEditor = TryCast(Me.RadGridView1.ActiveEditor, GridSpinEditor) - If spinEditor IsNot Nothing Then - spinEditor.Value = 0 - End If -End Sub - -```` - -{{endregion}} - + + ##  Disable the up and down buttons of the spin editor The code below demonstrates how you can disable the up and down arrow buttons. Using the commented code you can completely hide them. -{{source=..\SamplesCS\GridView\Columns\GridViewDecimalColumn1.cs region=ShowUpDownButtons}} -{{source=..\SamplesVB\GridView\Columns\GridViewDecimalColumn1.vb region=ShowUpDownButtons}} - -````C# -void radGridView1_CellEditorInitialized1(object sender, GridViewCellEventArgs e) -{ - GridSpinEditor spinEditor = this.radGridView1.ActiveEditor as GridSpinEditor; - ((RadSpinEditorElement)spinEditor.EditorElement).ShowUpDownButtons = false; -} - -```` -````VB.NET -Private Sub RadGridView1_CellEditorInitialized1(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewCellEventArgs) - Dim spinEditor As GridSpinEditor = TryCast(Me.RadGridView1.ActiveEditor, GridSpinEditor) - If spinEditor IsNot Nothing Then - Dim element As RadSpinEditorElement = spinEditor.EditorElement - element.ShowUpDownButtons = False - End If -End Sub - -```` - -{{endregion}} + + ## Setting decimal places @@ -111,38 +42,15 @@ __Setting decimal places to the spin editor__ You can define how many places after the decimal point the value in the spin editor should have by setting the __DecimalPlaces__ property of GridViewDecimalColumn: -{{source=..\SamplesCS\GridView\Columns\GridViewDecimalColumn1.cs region=decimalPlacesEditor}} -{{source=..\SamplesVB\GridView\Columns\GridViewDecimalColumn1.vb region=decimalPlacesEditor}} - -````C# -decimalColumn.DecimalPlaces = 3; - -```` -````VB.NET -decimalColumn.DecimalPlaces = 3 - -```` - -{{endregion}} - + + __Setting decimal places to the column cells__ In order to define how the values should be displayed by the cells of the GridViewDecimalColumn in the sense of their decimal places, we should set the __FormatString__ property of the column: -{{source=..\SamplesCS\GridView\Columns\GridViewDecimalColumn1.cs region=decimalPlacesCell}} -{{source=..\SamplesVB\GridView\Columns\GridViewDecimalColumn1.vb region=decimalPlacesCell}} - -````C# -decimalColumn.FormatString = "{0:N2}"; - -```` -````VB.NET -decimalColumn.FormatString = "{0:N2}" - -```` - -{{endregion}} + + >note For a list of the standard numeric format strings, see [Standard Numeric Format Strings](http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx) > diff --git a/controls/gridview/visual-elements/columns/column-types/gridviewhyperlinkcolumn.md b/controls/gridview/visual-elements/columns/column-types/gridviewhyperlinkcolumn.md index 180d0a414..b23cb0955 100644 --- a/controls/gridview/visual-elements/columns/column-types/gridviewhyperlinkcolumn.md +++ b/controls/gridview/visual-elements/columns/column-types/gridviewhyperlinkcolumn.md @@ -15,36 +15,8 @@ __GridViewHyperlinkColumn__ allows __RadGridView__ to display, format, edit and Here is how to create and populate __GridViewHyperlinkColumn__: -{{source=..\SamplesCS\GridView\Columns\GridViewHyperlinkColumn1.cs region=addHyperlinkColumn}} -{{source=..\SamplesVB\GridView\Columns\GridViewHyperlinkColumn1.vb region=addHyperlinkColumn}} - -````C# -GridViewHyperlinkColumn column = new GridViewHyperlinkColumn("Hyperlink column"); -this.radGridView1.Columns.Add(column); - -this.radGridView1.Rows.Add("http://www.telerik.com"); -this.radGridView1.Rows.Add("http://www.microsoft.com"); -this.radGridView1.Rows.Add("http://www.google.com"); -this.radGridView1.Rows.Add("http://www.cnn.com"); -this.radGridView1.Rows.Add("http://www.bbc.com"); -this.radGridView1.Rows.Add("http://www.telerikwatch.com/"); -this.radGridView1.Rows.Add("http://www.wikipedia.com"); - -```` -````VB.NET -Dim column As New GridViewHyperlinkColumn("Hyperlink column") -Me.radGridView1.Columns.Add(column) -Me.radGridView1.Rows.Add("http://www.telerik.com") -Me.radGridView1.Rows.Add("http://www.microsoft.com") -Me.radGridView1.Rows.Add("http://www.google.com") -Me.radGridView1.Rows.Add("http://www.cnn.com") -Me.radGridView1.Rows.Add("http://www.bbc.com") -Me.radGridView1.Rows.Add("http://www.telerikwatch.com/") -Me.radGridView1.Rows.Add("http://www.wikipedia.com") - -```` - -{{endregion}} + + ![WinForms RadGridView GridViewHyperlinkColumn](images/gridview-columns-gridviewhyperlinkcolumn001.png) @@ -80,33 +52,8 @@ The mouse cursor transforms into ‘*hand*’ when hovering hyperlink from the c The hyperlink cells can be further customized through the **CellFormating** event of the **RadGridView**. In the event handler, we can check if the **e.CellElement** property is a **GridHyperlinkCellElement** element. If yes, we can modify the look of the cell. -{{source=..\SamplesCS\GridView\Columns\GridViewHyperlinkColumn1.cs region=CustomizeHyperlinkColumnCell}} -{{source=..\SamplesVB\GridView\Columns\GridViewHyperlinkColumn1.vb region=CustomizeHyperlinkColumnCell}} - -````C# -private void RadGridView1_CellFormatting(object sender, Telerik.WinControls.UI.CellFormattingEventArgs e) -{ - GridHyperlinkCellElement cell = e.CellElement as GridHyperlinkCellElement; - if (cell != null) - { - cell.ContentElement.ForeColor = Color.Red; - } -} - -```` -````VB.NET -Private Sub RadGridView1_CellFormatting(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.CellFormattingEventArgs) - Dim cell As GridHyperlinkCellElement = TryCast(e.CellElement, GridHyperlinkCellElement) - - If cell IsNot Nothing Then - cell.ContentElement.ForeColor = Color.Red - End If -End Sub - -```` - -{{endregion}} - + + ## Events @@ -118,58 +65,8 @@ Here are the __GridViewHyperlinkColumn__ specific events: The following example demonstrates how to replace the default **GridViewTextBoxColumn** with a **GridViewHyperlinkColumn** which stores emails. When an email hyperlink is clicked, a mail message is opened in the default Mail application: -{{source=..\SamplesCS\GridView\Columns\GridViewHyperlinkColumn1.cs region=EmailColumn}} -{{source=..\SamplesVB\GridView\Columns\GridViewHyperlinkColumn1.vb region=EmailColumn}} - -````C# - -public void SetupEmailsColumn() -{ - DataTable table = new DataTable(); - table.Columns.Add("textColumn"); - table.Rows.Add("asd@asd.com"); - table.Rows.Add("qwe@qwe.com"); - this.radGridView1.DataSource = table; - // how let's replace the column with a hyperlink column - this.radGridView1.Columns.RemoveAt(0); - GridViewHyperlinkColumn hyperlinkCol = new GridViewHyperlinkColumn(); - hyperlinkCol.FieldName = "textColumn"; - this.radGridView1.Columns.Add(hyperlinkCol); - this.radGridView1.Columns[0].Width = 200; - this.radGridView1.HyperlinkOpening += RadGridView1_HyperlinkOpening; -} - -private void RadGridView1_HyperlinkOpening(object sender, HyperlinkOpeningEventArgs e) -{ - System.Diagnostics.Process.Start("mailto:" + e.Cell.Value); -} - - -```` -````VB.NET - Public Sub SetupEmailsColumn() - Dim table As DataTable = New DataTable() - table.Columns.Add("textColumn") - table.Rows.Add("asd@asd.com") - table.Rows.Add("qwe@qwe.com") - Me.radGridView1.DataSource = table - Me.radGridView1.Columns.RemoveAt(0) - Dim hyperlinkCol As GridViewHyperlinkColumn = New GridViewHyperlinkColumn() - hyperlinkCol.FieldName = "textColumn" - Me.radGridView1.Columns.Add(hyperlinkCol) - Me.radGridView1.Columns(0).Width = 200 - AddHandler Me.radGridView1.HyperlinkOpening, AddressOf RadGridView1_HyperlinkOpening -End Sub - -Private Sub RadGridView1_HyperlinkOpening(ByVal sender As Object, ByVal e As HyperlinkOpeningEventArgs) - System.Diagnostics.Process.Start("mailto:" & e.Cell.Value) -End Sub - - -```` - -{{endregion}} - + + # See Also diff --git a/controls/gridview/visual-elements/columns/column-types/gridviewimagecolumn.md b/controls/gridview/visual-elements/columns/column-types/gridviewimagecolumn.md index d3ee90b93..7ee82d780 100644 --- a/controls/gridview/visual-elements/columns/column-types/gridviewimagecolumn.md +++ b/controls/gridview/visual-elements/columns/column-types/gridviewimagecolumn.md @@ -25,54 +25,15 @@ Supported image formats are those supported by the `Image` class of the .NET Fra #### Create GridViewImageColumn -{{source=..\SamplesCS\GridView\Columns\GridViewImageColumn1.cs region=addImageColumn}} -{{source=..\SamplesVB\GridView\Columns\GridViewImageColumn1.vb region=addImageColumn}} - -````C# -GridViewImageColumn imageColumn = new GridViewImageColumn(); -imageColumn.Name = "ImageColumn"; -imageColumn.FieldName = "Photo"; -imageColumn.HeaderText = "Picture"; -imageColumn.ImageLayout = ImageLayout.Zoom; -radGridView1.MasterTemplate.Columns.Insert(4, imageColumn); - -```` -````VB.NET -Dim imageColumn As New GridViewImageColumn -imageColumn.Name = "ImageColumn" -imageColumn.FieldName = "Photo" -imageColumn.HeaderText = "Picture" -imageColumn.ImageLayout = ImageLayout.Zoom -RadGridView1.MasterTemplate.Columns.Add(imageColumn) - -```` - -{{endregion}} + + If the **GridViewImageColumn** is mapped to a property coming from the **DataBoundItem** via the specified **FieldName** (used in bound mode), the cells values will be automatically populated. For unbound mode, it is possible to add Image values to cells as it is demonstrated in the following code snippet: #### Add image value to a cell -{{source=..\SamplesCS\GridView\Columns\GridViewImageColumn1.cs region=AddCellValue}} -{{source=..\SamplesVB\GridView\Columns\GridViewImageColumn1.vb region=AddCellValue}} - -````C# -GridViewRowInfo row = this.radGridView1.Rows.AddNew(); -row.Cells["ImageColumn"].Value = Properties.Resources.TV_car; - -row = this.radGridView1.Rows.AddNew(); -row.Cells["ImageColumn"].Value = Image.FromFile(@"..\..\logo.png"); - -```` -````VB.NET -Dim row As GridViewRowInfo = Me.RadGridView1.Rows.AddNew() -row.Cells("ImageColumn").Value = My.Resources.TV_car1 -row = Me.RadGridView1.Rows.AddNew() -row.Cells("ImageColumn").Value = Image.FromFile("..\..\logo.png") - -```` - -{{endregion}} + + ## Image Layout @@ -82,21 +43,8 @@ __GridViewImageColumn__ also implements resizing functionality where sizing is c * __None:__ The image is positioned at the top left corner of the cell. This value can be used in a combination with the value of the ImageAlignment property to specify the position of an image in a cell: -{{source=..\SamplesCS\GridView\Columns\GridViewImageColumn1.cs region=none}} -{{source=..\SamplesVB\GridView\Columns\GridViewImageColumn1.vb region=none}} - -````C# -imageColumn.ImageLayout = ImageLayout.None; -imageColumn.ImageAlignment = ContentAlignment.BottomRight; - -```` -````VB.NET -imageColumn.ImageLayout = ImageLayout.None -imageColumn.ImageAlignment = ContentAlignment.BottomRight - -```` - -{{endregion}} + + * __Tile:__ The image is repeated. diff --git a/controls/gridview/visual-elements/columns/column-types/gridviewmaskboxcolumn.md b/controls/gridview/visual-elements/columns/column-types/gridviewmaskboxcolumn.md index 381550fe2..5b002e2fb 100644 --- a/controls/gridview/visual-elements/columns/column-types/gridviewmaskboxcolumn.md +++ b/controls/gridview/visual-elements/columns/column-types/gridviewmaskboxcolumn.md @@ -21,37 +21,8 @@ You can set a *mask* to GridViewMaskBoxColumn using its __Mask__ and __MaskType_ #### Add GridViewMaskBoxColumn to the grid. -{{source=..\SamplesCS\GridView\Columns\GridViewMaskBoxColumn1.cs region=addMaskBoxColumn}} -{{source=..\SamplesVB\GridView\Columns\GridViewMaskBoxColumn1.vb region=addMaskBoxColumn}} - -````C# -GridViewMaskBoxColumn maskBoxColumn = new GridViewMaskBoxColumn(); -maskBoxColumn.Name = "Price"; -maskBoxColumn.FieldName = "UnitPrice"; -maskBoxColumn.HeaderText = "Unit Price"; -maskBoxColumn.MaskType = MaskType.Numeric; -maskBoxColumn.Mask = "C"; -maskBoxColumn.TextAlignment = ContentAlignment.BottomRight; -maskBoxColumn.FormatString = "{0:C}"; -maskBoxColumn.DataType = typeof(decimal); -radGridView1.MasterTemplate.Columns.Add(maskBoxColumn); - -```` -````VB.NET -Dim maskBoxColumn As New GridViewMaskBoxColumn() -maskBoxColumn.Name = "Price" -maskBoxColumn.FieldName = "UnitPrice" -maskBoxColumn.HeaderText = "Unit Price" -maskBoxColumn.MaskType = MaskType.Numeric -maskBoxColumn.Mask = "C" -maskBoxColumn.TextAlignment = ContentAlignment.BottomRight -maskBoxColumn.FormatString = "{0:C}" -maskBoxColumn.DataType = GetType(Decimal) -RadGridView1.MasterTemplate.Columns.Add(maskBoxColumn) - -```` - -{{endregion}} + + >note The **GridViewMaskBoxColumn** also supports null values and this functionality can be enabled by setting the **EnableNullValueInput** property of the column to *true*. The default value of the property is set to *false*. Once this is enabled you can use `Ctrl + Delete` or `Ctrl + 0` to clear the value in the editor. diff --git a/controls/gridview/visual-elements/columns/column-types/gridviewmulticomboboxcolumn.md b/controls/gridview/visual-elements/columns/column-types/gridviewmulticomboboxcolumn.md index 01835858e..80ae5c7f5 100644 --- a/controls/gridview/visual-elements/columns/column-types/gridviewmulticomboboxcolumn.md +++ b/controls/gridview/visual-elements/columns/column-types/gridviewmulticomboboxcolumn.md @@ -19,78 +19,15 @@ The following example demonstrates how to [manually generate columns for RadGrid First of all, we should bind the GridViewMultiComboBoxColumn: -{{source=..\SamplesCS\GridView\Columns\GridViewMultiComboBoxColumn1.cs region=addColumn}} -{{source=..\SamplesVB\GridView\Columns\GridViewMultiComboBoxColumn1.vb region=addColumn}} - -````C# -GridViewMultiComboBoxColumn col = new GridViewMultiComboBoxColumn(); -col.DataSource = orderDetailsBindingSource; -col.DisplayMember = "Quantity"; -col.ValueMember = "OrderID"; -col.FieldName = "OrderID"; -col.HeaderText = "Custom"; -this.radGridView1.Columns.Add(col); -this.radGridView1.CellBeginEdit += new GridViewCellCancelEventHandler(radGridView1_CellBeginEdit); - -```` -````VB.NET -Dim col As GridViewMultiComboBoxColumn = New GridViewMultiComboBoxColumn() -col.DataSource = orderDetailsBindingSource -col.DisplayMember = "Quantity" -col.ValueMember = "OrderID" -col.FieldName = "OrderID" -col.HeaderText = "Custom" -Me.RadGridView1.Columns.Add(col) -AddHandler RadGridView1.CellBeginEdit, AddressOf radGridView1_CellBeginEdit - -```` - -{{endregion}} + + Then, we make the necessary implementation in the CellBeginEdit event handler: #### Setup the editor -{{source=..\SamplesCS\GridView\Columns\GridViewMultiComboBoxColumn1.cs region=setupTheEditor}} -{{source=..\SamplesVB\GridView\Columns\GridViewMultiComboBoxColumn1.vb region=setupTheEditor}} - -````C# -bool isColumnAdded; -void radGridView1_CellBeginEdit(object sender, GridViewCellCancelEventArgs e) -{ - if (this.radGridView1.CurrentColumn is GridViewMultiComboBoxColumn) - { - if (!isColumnAdded) - { - isColumnAdded = true; - RadMultiColumnComboBoxElement editor = (RadMultiColumnComboBoxElement)this.radGridView1.ActiveEditor; - editor.EditorControl.MasterTemplate.AutoGenerateColumns = false; - editor.EditorControl.Columns.Add(new GridViewTextBoxColumn("OrderID")); - editor.EditorControl.Columns.Add(new GridViewTextBoxColumn("Quantity")); - editor.AutoSizeDropDownToBestFit = true; - } - } -} - -```` -````VB.NET -Private isColumnAdded As Boolean -Private Sub radGridView1_CellBeginEdit(ByVal sender As Object, ByVal e As GridViewCellCancelEventArgs) - If TypeOf Me.radGridView1.CurrentColumn Is GridViewMultiComboBoxColumn Then - If (Not isColumnAdded) Then - isColumnAdded = True - Dim editor As RadMultiColumnComboBoxElement = CType(Me.radGridView1.ActiveEditor, RadMultiColumnComboBoxElement) - editor.EditorControl.MasterTemplate.AutoGenerateColumns = False - editor.EditorControl.Columns.Add(New GridViewTextBoxColumn("OrderID")) - editor.EditorControl.Columns.Add(New GridViewTextBoxColumn("Quantity")) - editor.AutoSizeDropDownToBestFit = True - End If - End If -End Sub - -```` - -{{endregion}} + + Please note that we have a 'dirty' flag, because the editors in RadGridView are reused. If we do not have such a flag, new OrderID and Quantity columns will be added each time a RadMultiColumnComboBoxElement editor is opened. diff --git a/controls/gridview/visual-elements/columns/column-types/gridviewratingcolumn.md b/controls/gridview/visual-elements/columns/column-types/gridviewratingcolumn.md index e53d0fe6e..b3534e418 100644 --- a/controls/gridview/visual-elements/columns/column-types/gridviewratingcolumn.md +++ b/controls/gridview/visual-elements/columns/column-types/gridviewratingcolumn.md @@ -19,31 +19,8 @@ __GridViewRatingColumn__ allows you to represent and edit numeric value as ratin The following code snippet demonstrates how to create and add __GridViewRatingColumn__ to RadGridView and also add some sample data in it: -{{source=..\SamplesCS\GridView\Columns\GridViewRatingColumn1.cs region=RatingColumn}} -{{source=..\SamplesVB\GridView\Columns\GridViewRatingColumn1.vb region=RatingColumn}} - -````C# -GridViewRatingColumn column = new GridViewRatingColumn("Rating Column"); -radGridView1.Columns.Add(column); -radGridView1.Rows.Add(20); -radGridView1.Rows.Add(35); -radGridView1.Rows.Add(70); -radGridView1.Rows.Add(3); -radGridView1.Rows.Add(18); - -```` -````VB.NET -Dim column As New GridViewRatingColumn("Rating Column") -radGridView1.Columns.Add(column) -radGridView1.Rows.Add(20) -radGridView1.Rows.Add(35) -radGridView1.Rows.Add(70) -radGridView1.Rows.Add(3) -radGridView1.Rows.Add(18) - -```` - -{{endregion}} + + ## Properties diff --git a/controls/gridview/visual-elements/columns/column-types/gridviewselectcolumn.md b/controls/gridview/visual-elements/columns/column-types/gridviewselectcolumn.md index c6e03a421..7799a9fd2 100644 --- a/controls/gridview/visual-elements/columns/column-types/gridviewselectcolumn.md +++ b/controls/gridview/visual-elements/columns/column-types/gridviewselectcolumn.md @@ -23,20 +23,8 @@ To show **GridViewSelectColumn** it is necessary to set the **ShowSelectColumn** ![WinForms RadGridView GridViewSelectColumn](images/gridview-columns-gridviewselectcolumn001.png) -{{source=..\SamplesCS\GridView\Columns\GridViewSelectColumn.cs region=ShowSelectColumn}} -{{source=..\SamplesVB\GridView\Columns\GridViewSelectColumn.vb region=ShowSelectColumn}} - -````C# -this.radGridView1.ShowSelectColumn = true; - -```` -````VB.NET -Me.RadGridView1.ShowSelectColumn = True - -```` - -{{endregion}} - + + >note **GridViewSelectColumn** is only supported in GridViewSelectionMode.**FullRowSelect**. In *FullRowSelect* mode the user is able to select full rows in the grid, while in *CellSelect* mode it is possible to select single cells. For more information see [Row selection]({%slug winforms/gridview/selection/basic-selection%}). @@ -48,20 +36,8 @@ If the *MultiSelect* property is enabled, users can make a [multiple selection i In some cases, the user may need to use multiple row selection through the **GridViewSelectColumn** only. The **UseCheckboxRowSelectionOnly** property defines whether the user can select rows only via the checkboxes. When **UseCheckboxRowSelectionOnly** is set to *true*, the selection only via checkboxes is allowed. Thus, if you click with the mouse over different rows they will not get selected, until you check the corresponding checkbox from the **GridViewSelectColumn**. -{{source=..\SamplesCS\GridView\Columns\GridViewSelectColumn.cs region=CheckboxRowSelection}} -{{source=..\SamplesVB\GridView\Columns\GridViewSelectColumn.vb region=CheckboxRowSelection}} - -````C# -this.radGridView1.MasterTemplate.UseCheckboxRowSelectionOnly = true; - -```` -````VB.NET -Me.RadGridView1.MasterTemplate.UseCheckboxRowSelectionOnly = True - -```` - -{{endregion}} - + + >note The **UseCheckboxRowSelectionOnly** will only be considered if **ShowSelectColumn** is set to *true*. @@ -73,19 +49,8 @@ Me.RadGridView1.MasterTemplate.UseCheckboxRowSelectionOnly = True ![WinForms RadGridView GridViewSelectColumn](images/gridview-columns-gridviewselectcolumn002.png) -{{source=..\SamplesCS\GridView\Columns\GridViewSelectColumn.cs region=SelectColumninHierarchy}} -{{source=..\SamplesVB\GridView\Columns\GridViewSelectColumn.vb region=SelectColumninHierarchy}} - -````C# -this.radGridView1.MasterTemplate.Templates[0].ShowSelectColumn = true; - -```` -````VB.NET -Me.RadGridView1.MasterTemplate.Templates(0).ShowSelectColumn = True - -```` - -{{endregion}} + + >note This feature is also available in other functionalities that RadGridView offers such as grouping, filtering, searching, paging. @@ -93,20 +58,8 @@ Me.RadGridView1.MasterTemplate.Templates(0).ShowSelectColumn = True **SelectColumnWidth** property gets or sets the width of the GridViewSelectColumn. -{{source=..\SamplesCS\GridView\Columns\GridViewSelectColumn.cs region=SetSelectColumnWidth}} -{{source=..\SamplesVB\GridView\Columns\GridViewSelectColumn.vb region=SetSelectColumnWidth}} - -````C# -this.radGridView1.TableElement.SelectColumnWidth = 50; - -```` -````VB.NET -Me.RadGridView1.TableElement.SelectColumnWidth = 50 - -```` - -{{endregion}} - + + #### Events diff --git a/controls/gridview/visual-elements/columns/column-types/gridviewsparklinecolumn.md b/controls/gridview/visual-elements/columns/column-types/gridviewsparklinecolumn.md index 3676491c1..9f2b853cd 100644 --- a/controls/gridview/visual-elements/columns/column-types/gridviewsparklinecolumn.md +++ b/controls/gridview/visual-elements/columns/column-types/gridviewsparklinecolumn.md @@ -115,9 +115,6 @@ Dim row As GridViewRowInfo = Me.radGridView1.Rows.AddNew() row.Cells("Line").Value = values ```` - -{{endregion}} - ## SparkDataNeeded event The **SparkDataNeeded** event can be used to dynamically populate or change data at run-time. It is fired right before creating the data points inside the sparkline element in the cell. @@ -157,9 +154,6 @@ Private Sub SparkLineColumn_SparkDataNeeded(ByVal sender As Object, ByVal e As S End Sub ```` - -{{endregion}} - ## Binding GridViewSparklineColumn You can bind the **GridViewSparklineColumn** to any IEnumerable collection of numeric data types. To do this, you should set the **FieldName** of the **GridViewSparklineColumn** to be the same as the name of the appopriate existing column in the data source. The example below binds the grid to DataTable via the **DataSource** property. To prevent the grid from traversing all data fields in that collection, I set the **GridViewTemplate.AutoGenerateColumns** property to *False*. @@ -219,10 +213,6 @@ this.radGridView1.Columns.Add(sparkLineColumn); Me.RadGridView1.Columns.Add(sparkLineColumn) ```` - -{{endregion}} - - ## Customize GridViewSparklineColumn **GridViewSparklineColumn** can be customized by making use of **CellFormatting** event. Here is an example how to make the even rows in **GridViewSparklineColumn** to desplay bar series, and the odd rows to display line series. Due to the UI Virtualization, an `if-else` statement is used to reset the series. @@ -300,9 +290,6 @@ Private Sub RadGridView1_CellFormatting(ByVal sender As Object, ByVal e As CellF End Sub ```` - -{{endregion}} - ## GridViewSparklineColumn's Properties |Property|Description| diff --git a/controls/gridview/visual-elements/columns/column-types/gridviewtextboxcolumn.md b/controls/gridview/visual-elements/columns/column-types/gridviewtextboxcolumn.md index 26e4f6fcc..d81f72b90 100644 --- a/controls/gridview/visual-elements/columns/column-types/gridviewtextboxcolumn.md +++ b/controls/gridview/visual-elements/columns/column-types/gridviewtextboxcolumn.md @@ -19,50 +19,15 @@ When a user begins editing a cell, a textbox editor is provided to handle the us #### Add GridViewTextBoxColumn to the grid. -{{source=..\SamplesCS\GridView\Columns\GridViewTextBoxColumn1.cs region=addTextBoxColumn}} -{{source=..\SamplesVB\GridView\Columns\GridViewTextBoxColumn1.vb region=addTextBoxColumn}} - -````C# -GridViewTextBoxColumn textBoxColumn = new GridViewTextBoxColumn(); -textBoxColumn.Name = "TextBoxColumn"; -textBoxColumn.HeaderText = "Product Name"; -textBoxColumn.FieldName = "ProductName"; -textBoxColumn.MaxLength = 50; -textBoxColumn.TextAlignment = ContentAlignment.BottomRight; -radGridView1.MasterTemplate.Columns.Add(textBoxColumn); - -```` -````VB.NET -Dim textBoxColumn As New GridViewTextBoxColumn() -textBoxColumn.Name = "TextBoxColumn" -textBoxColumn.HeaderText = "Product Name" -textBoxColumn.FieldName = "ProductName" -textBoxColumn.MaxLength = 50 -textBoxColumn.TextAlignment = ContentAlignment.BottomRight -RadGridView1.MasterTemplate.Columns.Add(textBoxColumn) - -```` - -{{endregion}} + + ## Character casing GridViewTextBoxColumn editor - *RadTextBoxEditor* - supports character casing. To enable this functionality you need to set __ColumnCharecterCasing__ property of the desired GridViewTextBoxColumn column: -{{source=..\SamplesCS\GridView\Columns\GridViewTextBoxColumn1.cs region=characterCasting}} -{{source=..\SamplesVB\GridView\Columns\GridViewTextBoxColumn1.vb region=characterCasting}} - -````C# -((GridViewTextBoxColumn)this.radGridView1.Columns[0]).ColumnCharacterCasing = CharacterCasing.Upper; - -```` -````VB.NET -DirectCast(Me.RadGridView1.Columns(0), GridViewTextBoxColumn).ColumnCharacterCasing = CharacterCasing.Upper - -```` - -{{endregion}} - + + >note ColumnCarecterCasing property affects only the editor and does not change the values in your data base. For instance, if your data base contains text which is lower case or partially lower case, and you set the **ColumnCharacterCasing** to upper case, the data will not be change. However, if the user starts editing a cell, the editor will only allow upper case symbols and all lower case symbols will be converted to upper case ones. > diff --git a/controls/gridview/visual-elements/columns/column-types/gridviewtimespancolumn.md b/controls/gridview/visual-elements/columns/column-types/gridviewtimespancolumn.md index 3db186902..57a7df63f 100644 --- a/controls/gridview/visual-elements/columns/column-types/gridviewtimespancolumn.md +++ b/controls/gridview/visual-elements/columns/column-types/gridviewtimespancolumn.md @@ -20,25 +20,8 @@ The __FormatString__ property sets the format of the TimeSpan when the cell is n #### Formatting the TimeSpan. -{{source=..\SamplesCS\GridView\Columns\GridViewTimeSpanColumn1.cs region=addTimeSpanColumn}} -{{source=..\SamplesVB\GridView\Columns\GridViewTimeSpanColumn1.vb region=addTimeSpanColumn}} - -````C# -GridViewTimeSpanColumn gridViewTimeSpanColumn1 = new GridViewTimeSpanColumn(); -gridViewTimeSpanColumn1.FormatString = "hh-mm-ss"; -gridViewTimeSpanColumn1.Format = "mm:ss"; -this.radGridView1.Columns.Add(gridViewTimeSpanColumn1); - -```` -````VB.NET -Dim gridViewTimeSpanColumn1 As GridViewTimeSpanColumn = New GridViewTimeSpanColumn() -gridViewTimeSpanColumn1.FormatString = "hh-mm-ss" -gridViewTimeSpanColumn1.Format = "mm:ss" -Me.RadGridView1.Columns.Add(gridViewTimeSpanColumn1) - -```` - -{{endregion}} + + >caption Figure 2: Formatted editor's value @@ -46,34 +29,8 @@ Me.RadGridView1.Columns.Add(gridViewTimeSpanColumn1) There are two ways to change the TimeSpan format when the cell enters edit mode - either by setting the above mentioned **Format** property of the column or by handling the RadGridView.**CellEditorInitialized** event and applying the desired format to the **GridTimeSpanPickerEditor**. It is fired when the initialization of an editor is performed: -{{source=..\SamplesCS\GridView\Columns\GridViewTimeSpanColumn1.cs region=changeEditorFormat}} -{{source=..\SamplesVB\GridView\Columns\GridViewTimeSpanColumn1.vb region=changeEditorFormat}} - -````C# - -private void radGridView1_CellEditorInitialized(object sender, GridViewCellEventArgs e) -{ - GridTimeSpanPickerEditor editor = e.ActiveEditor as GridTimeSpanPickerEditor; - if (editor != null) - { - RadTimeSpanPickerElement element = editor.EditorElement as RadTimeSpanPickerElement; - element.Format = "mm:ss"; - } -} - -```` -````VB.NET -Private Sub radGridView1_CellEditorInitialized(ByVal sender As Object, ByVal e As GridViewCellEventArgs) - Dim editor As GridTimeSpanPickerEditor = TryCast(e.ActiveEditor, GridTimeSpanPickerEditor) - If editor IsNot Nothing Then - Dim element As RadTimeSpanPickerElement = TryCast(editor.EditorElement, RadTimeSpanPickerElement) - element.Format = "mm:ss" - End If -End Sub - -```` - -{{endregion}} + + >important If we do not use the **CellEditorInitialized** event, but the **CellBeginEdit** event (which is fired before **CellEditorInitialized**), our **Format** setting will be overridden by the initialization of the editor. diff --git a/controls/gridview/visual-elements/columns/columns-events.md b/controls/gridview/visual-elements/columns/columns-events.md index 8ed58d414..f23439f39 100644 --- a/controls/gridview/visual-elements/columns/columns-events.md +++ b/controls/gridview/visual-elements/columns/columns-events.md @@ -34,30 +34,8 @@ You can use the following properties of the **GridViewAutoGeneratingColumnEventA The following example demonstrates how you can cancel the creation of a specific column: -{{source=..\SamplesCS\GridView\Columns\Columns.cs region=AutoGeneratingColumn}} -{{source=..\SamplesVB\GridView\Columns\Columns.vb region=AutoGeneratingColumn}} - -````C# -private void RadGridView1_AutoGeneratingColumn(object sender, GridViewAutoGeneratingColumnEventArgs e) -{ - if (e.Column.HeaderText == "CreationDate") - { - e.Cancel = true; - } -} - -```` -````VB.NET - -Private Sub RadGridView1_AutoGeneratingColumn(ByVal sender As Object, ByVal e As GridViewAutoGeneratingColumnEventArgs) - If e.Column.HeaderText = "CreationDate" Then - e.Cancel = True - End If -End Sub - -```` - -{{endregion}} + + >Changing the DataType property of the column will not be respected in the AutoGeneratingColumn event handler. diff --git a/controls/gridview/visual-elements/columns/converting-data-types.md b/controls/gridview/visual-elements/columns/converting-data-types.md index 5aa5884b4..23415ef77 100644 --- a/controls/gridview/visual-elements/columns/converting-data-types.md +++ b/controls/gridview/visual-elements/columns/converting-data-types.md @@ -21,150 +21,8 @@ As a quick example, let’s say that we want to convert char values Y and N to T #### ToggleState converter -{{source=..\SamplesCS\GridView\Columns\ConvertingDataTypes.cs region=convertTypes}} -{{source=..\SamplesVB\GridView\Columns\ConvertingDataTypes.vb region=convertTypes}} - -````C# - -public class ToggleStateConverter : TypeConverter -{ - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) - { - return destinationType == typeof(ToggleState) || destinationType == typeof(bool); - } - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) - { - if (value is char && destinationType == typeof(ToggleState)) - { - char charValue = (char)value; - switch (charValue) - { - case 'Y': - return ToggleState.On; - case 'N': - return ToggleState.Off; - default: - return ToggleState.Indeterminate; - } - } - else if (value is bool && destinationType == typeof(char)) - { - bool boolValue = (bool)value; - switch (boolValue) - { - case true: - return 'Y'; - case false: - return 'N'; - default: - return 'M'; - } - } - return base.ConvertTo(context, culture, value, destinationType); - } - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) - { - return sourceType == typeof(ToggleState) || sourceType == typeof(bool); - } - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) - { - ToggleState state; - bool boolValue; - if (value is ToggleState) - { - state = (ToggleState)value; - switch (state) - { - case ToggleState.On: - return 'Y'; - case ToggleState.Off: - return 'N'; - default: - return 'M'; - } - } - else if (value is bool) - { - boolValue = (bool)value; - switch (boolValue) - { - case true: - return 'Y'; - case false: - return 'N'; - default: - return 'M'; - } - } - return base.ConvertFrom(context, culture, value); - } -} - -```` -````VB.NET -Public Class ToggleStateConverter - Inherits TypeConverter - Public Overrides Function CanConvertTo(context As ITypeDescriptorContext, destinationType As Type) As Boolean - Return destinationType Is GetType(ToggleState) OrElse destinationType Is GetType(Boolean) - End Function - Public Overrides Function ConvertTo(context As ITypeDescriptorContext, culture As CultureInfo, value As Object, destinationType As Type) As Object - If TypeOf value Is Char AndAlso destinationType Is GetType(ToggleState) Then - Dim charValue As Char = CChar(value) - Select Case charValue - Case "Y"c - Return ToggleState.On - Case "N"c - Return ToggleState.Off - Case Else - Return ToggleState.Indeterminate - End Select - ElseIf TypeOf value Is Boolean AndAlso destinationType Is GetType(Char) Then - Dim boolValue As Boolean = CBool(value) - Select Case boolValue - Case True - Return "Y"c - Case False - Return "N"c - Case Else - Return "M"c - End Select - End If - Return MyBase.ConvertTo(context, culture, value, destinationType) - End Function - Public Overrides Function CanConvertFrom(context As ITypeDescriptorContext, sourceType As Type) As Boolean - Return sourceType Is GetType(ToggleState) OrElse sourceType Is GetType(Boolean) - End Function - Public Overrides Function ConvertFrom(context As ITypeDescriptorContext, culture As CultureInfo, value As Object) As Object - Dim state As ToggleState - Dim boolValue As Boolean - If TypeOf value Is ToggleState Then - state = CType(value, ToggleState) - Select Case state - Case ToggleState.On - Return "Y"c - Case ToggleState.Off - Return "N"c - Case Else - Return "M"c - End Select - ElseIf TypeOf value Is Boolean Then - boolValue = CBool(value) - Select Case boolValue - Case True - Return "Y"c - Case False - Return "N"c - Case Else - Return "M"c - End Select - End If - Return MyBase.ConvertFrom(context, culture, value) - End Function -End Class - -```` - -{{endregion}} + + ## Applying Type Converters @@ -176,29 +34,8 @@ The first approach to apply type converters is to create the desired column and #### Applying TypeConverter -{{source=..\SamplesCS\GridView\Columns\ConvertingDataTypes.cs region=applyingTypeConverters}} -{{source=..\SamplesVB\GridView\Columns\ConvertingDataTypes.vb region=applyingTypeConverters}} - -````C# - -private void ConvertingDataTypes_Load(object sender, EventArgs e) -{ - GridViewCheckBoxColumn checkBox = new GridViewCheckBoxColumn("Organic", "IsOrganic"); - checkBox.DataTypeConverter = new ToggleStateConverter(); - this.radGridView1.Columns.Add(checkBox); -} - -```` -````VB.NET -Private Sub ConvertingDataTypes_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load - Dim checkBox As New GridViewCheckBoxColumn("Organic", "IsOrganic") - checkBox.DataTypeConverter = New ToggleStateConverter() - Me.RadGridView1.Columns.Add(checkBox) -End Sub - -```` - -{{endregion}} + + __Applying System.ComponentModel.TypeConverterAttribute to the incompatible property of the business object used as a data source__ @@ -206,99 +43,8 @@ The second way to add type converters is to use the __TypeConverterAttribute__, #### Custom class with TypeConverter attribute -{{source=..\SamplesCS\GridView\Columns\ConvertingDataTypes.cs region=classProduct}} -{{source=..\SamplesVB\GridView\Columns\ConvertingDataTypes.vb region=classProduct}} - -````C# - -public class Product -{ - public int ProductID { get; set; } - - public string ProductName { get; set; } - - public string Category { get; set; } - - public int UnitsInStock { get; set; } - public double UnitPrice { get; set; } - - [TypeConverter(typeof(ToggleStateConverter))] - public char IsOrganic { get; set; } - public double DeliveryDate { get; set; } -} - -```` -````VB.NET -Public Class Product - Public Property ProductID() As Integer - Get - Return m_ProductID - End Get - Set(ByVal value As Integer) - m_ProductID = value - End Set - End Property - Private m_ProductID As Integer - Public Property ProductName() As String - Get - Return m_ProductName - End Get - Set(ByVal value As String) - m_ProductName = value - End Set - End Property - Private m_ProductName As String - Public Property Category() As String - Get - Return m_Category - End Get - Set(ByVal value As String) - m_Category = value - End Set - End Property - Private m_Category As String - Public Property UnitsInStock() As Integer - Get - Return m_UnitsInStock - End Get - Set(ByVal value As Integer) - m_UnitsInStock = value - End Set - End Property - Private m_UnitsInStock As Integer - Public Property UnitPrice() As Double - Get - Return m_UnitPrice - End Get - Set(ByVal value As Double) - m_UnitPrice = value - End Set - End Property - Private m_UnitPrice As Double - _ - Public Property IsOrganic() As Char - Get - Return m_IsOrganic - End Get - Set(ByVal value As Char) - m_IsOrganic = value - End Set - End Property - Private m_IsOrganic As Char - Public Property DeliveryDate() As Double - Get - Return m_DeliveryDate - End Get - Set(ByVal value As Double) - m_DeliveryDate = value - End Set - End Property - Private m_DeliveryDate As Double -End Class - -```` - -{{endregion}} + + ## Handling Null Values @@ -306,20 +52,8 @@ The RadGridView’s conversation layer can handle null values. You can specify t #### Handling null values -{{source=..\SamplesCS\GridView\Columns\ConvertingDataTypes.cs region=handlingNullValues}} -{{source=..\SamplesVB\GridView\Columns\ConvertingDataTypes.vb region=handlingNullValues}} - -````C# - -this.radGridView1.Columns["ProductName"].DataSourceNullValue = "ENTER PRODUCT NAME"; - -```` -````VB.NET -Me.RadGridView1.Columns("ProductName").DataSourceNullValue = "ENTER PRODUCT NAME" - -```` - -{{endregion}} + + ## Using the TypeConverter when sorting. @@ -330,45 +64,9 @@ The type converter can be used when the column is sorted as well. To enable this #### Handling null values when sorting -{{source=..\SamplesCS\GridView\Columns\ConvertingDataTypes.cs region=Float}} -{{source=..\SamplesVB\GridView\Columns\ConvertingDataTypes.vb region=Float}} - -````C# -public class CustomFloatConverter : TypeConverter -{ - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) - { - return destinationType == typeof(float); - } - - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) - { - if (destinationType == typeof(float) && (value == null || value is DBNull)) - { - return float.MinValue; - } - return value; - } -} - -```` -````VB.NET -Public Class CustomFloatConverter - Inherits TypeConverter - Public Overrides Function CanConvertTo(ByVal context As ITypeDescriptorContext, ByVal destinationType As Type) As Boolean - Return destinationType Is GetType(Single) - End Function - Public Overrides Function ConvertTo(ByVal context As ITypeDescriptorContext, ByVal culture As CultureInfo, ByVal value As Object, ByVal destinationType As Type) As Object - If destinationType Is GetType(Single) AndAlso (value Is Nothing OrElse TypeOf value Is DBNull) Then - Return Single.MinValue - End If - Return value - End Function -End Class - -```` - -{{endregion}} + + + # See Also * [Accessing and Iterating through Columns]({%slug winforms/gridview/columns/accessing-and-iterating-through-columns%}) diff --git a/controls/gridview/visual-elements/columns/data-formatting.md b/controls/gridview/visual-elements/columns/data-formatting.md index c03ab32fd..cca44b011 100644 --- a/controls/gridview/visual-elements/columns/data-formatting.md +++ b/controls/gridview/visual-elements/columns/data-formatting.md @@ -28,25 +28,8 @@ Here is a sample covering these properties: #### Formatting data -{{source=..\SamplesCS\GridView\Columns\DataFormatting1.cs region=dataFormatting}} -{{source=..\SamplesVB\GridView\Columns\DataFormatting1.vb region=dataFormatting}} - -````C# -GridViewDecimalColumn unitPriceColumn = this.radGridView1.Columns["UnitPrice"] as GridViewDecimalColumn; -unitPriceColumn.FormatString = "Price: {0:C}"; -unitPriceColumn.FormatInfo = CultureInfo.CreateSpecificCulture("en-GB"); -unitPriceColumn.NullValue = 0; - -```` -````VB.NET -Dim unitPriceColumn As GridViewDecimalColumn = TryCast(Me.RadGridView1.Columns("UnitPrice"), GridViewDecimalColumn) - unitPriceColumn.FormatString = "Price: {0:C}" - unitPriceColumn.FormatInfo = CultureInfo.CreateSpecificCulture("en-GB") - unitPriceColumn.NullValue = 0 - -```` - -{{endregion}} + + >caption Figure 1: The data in the middle is formated. @@ -61,23 +44,9 @@ The __TextAlignment__ property defines the text alignment for the column. #### Using the column text properties -{{source=..\SamplesCS\GridView\Columns\DataFormatting1.cs region=textProperties}} -{{source=..\SamplesVB\GridView\Columns\DataFormatting1.vb region=textProperties}} - -````C# -GridViewDataColumn productNameColumn = this.radGridView1.Columns["ProductName"]; -productNameColumn.WrapText = true; -productNameColumn.TextAlignment = ContentAlignment.BottomRight; - -```` -````VB.NET -Dim productNameColumn = Me.RadGridView1.Columns("ProductName") -productNameColumn.WrapText = True -productNameColumn.TextAlignment = ContentAlignment.BottomRight - -```` + + -{{endregion}} # See Also * [Accessing and Iterating through Columns]({%slug winforms/gridview/columns/accessing-and-iterating-through-columns%}) diff --git a/controls/gridview/visual-elements/columns/generating-columns.md b/controls/gridview/visual-elements/columns/generating-columns.md index 6f2837b45..5d1a6bbee 100644 --- a/controls/gridview/visual-elements/columns/generating-columns.md +++ b/controls/gridview/visual-elements/columns/generating-columns.md @@ -27,106 +27,8 @@ However, if you wish to prevent the creation of a column for it, use the __Syste #### Automatic column generation -{{source=..\SamplesCS\GridView\Columns\GeneratingColumns.cs region=autoGenerateColumns}} -{{source=..\SamplesVB\GridView\Columns\GeneratingColumns.vb region=autoGenerateColumns}} - -````C# -public GeneratingColumns() -{ - InitializeComponent(); - - BindingSource source = new BindingSource(); - List firstName = new List { "John", "Jim", "Jason", "Barbara", "Ben", "Thomas", "Antonio"}; - List lastName = new List { "Baumer", "Davidson", "Jones", "Jolie", "Pitt", "Ashword", "Moreno" }; - for (int i = 0; i < 7; i++) - { - source.Add(new Employee(i, firstName[i], lastName[i], i + 20)); - } - radGridView1.DataSource = source; -} -public class Employee -{ - public Employee(int id, string fn, string ln, int age) - { - this.EmployeeId = id; - this.FirstName = fn; - this.LastName = ln; - this.Age = age; - } - //the next attribute prevents the EmployeeId column from showing - [Browsable(false)] - public int EmployeeId { get; set; } - public string FirstName { get; set; } - public string LastName { get; set; } - public int Age { get; set; } -} - -```` -````VB.NET -Public Sub New() - InitializeComponent() - Dim source As New BindingSource() - - Dim firstName As String() = {"John", "Jim", "Jason", "Barbara", "Ben", "Thomas", "Antonio"} - Dim lastName As String() = {"Baumer", "Davidson", "Jones", "Jolie", "Pitt", "Ashword", "Moreno"} - - For i As Integer = 0 To 6 - source.Add(New Employee(i, firstName(i), lastName(i), i + 20)) - Next - RadGridView1.DataSource = source - -End Sub -Public Class Employee - Public Sub New(ByVal id As Integer, ByVal fn As String, ByVal ln As String, ByVal age As Integer) - Me.EmployeeId = id - Me.FirstName = fn - Me.LastName = ln - Me.Age = age - End Sub - - 'the next attribute prevents the EmployeeId column from showing - _ - Public Property EmployeeId() As Integer - Get - Return m_EmployeeId - End Get - Set(ByVal value As Integer) - m_EmployeeId = value - End Set - End Property - Private m_EmployeeId As Integer - Public Property FirstName() As String - Get - Return m_FirstName - End Get - Set(ByVal value As String) - m_FirstName = value - End Set - End Property - Private m_FirstName As String - Public Property LastName() As String - Get - Return m_LastName - End Get - Set(ByVal value As String) - m_LastName = value - End Set - End Property - Private m_LastName As String - Public Property Age() As Integer - Get - Return m_Age - End Get - Set(ByVal value As Integer) - m_Age = value - End Set - End Property - Private m_Age As Integer - End Class - -```` - -{{endregion}} + + >note Ensure that your property is browsable in order to show the respective bound data. The **Browsable** attribute set to *false* will make the property on which it is used not bindable. This will prevent other controls which use the [CurrencyManager](https://msdn.microsoft.com/en-us/library/system.windows.forms.currencymanager(v=vs.110).aspx) for extracting properties to bind to such a class. @@ -140,57 +42,8 @@ Setting the __AutoGenerateColumns__ property to *false* allows the developer to #### Adding Columns in Code at Run Time -{{source=..\SamplesCS\GridView\Columns\GeneratingColumns2.cs region=manualColumnGeneration}} -{{source=..\SamplesVB\GridView\Columns\GeneratingColumns2.vb region=manualColumnGeneration}} - -````C# -radGridView1.AutoGenerateColumns = false; -radGridView1.DataSource = categoriesBindingSource; - -GridViewTextBoxColumn textBoxColumn = new GridViewTextBoxColumn(); -textBoxColumn.Name = "TextBoxColumn"; -textBoxColumn.HeaderText = "Product Description"; -textBoxColumn.FieldName = "Description"; -textBoxColumn.MaxLength = 50; -textBoxColumn.TextAlignment = ContentAlignment.BottomRight; -textBoxColumn.Width = 250; -radGridView1.MasterTemplate.Columns.Add(textBoxColumn); -GridViewComboBoxColumn categoryColumn = new GridViewComboBoxColumn(); -categoryColumn.DataType = typeof(string); -categoryColumn.Name = "CategoryColumn"; -categoryColumn.FieldName = "CategoryName"; -categoryColumn.HeaderText = "Category"; -categoryColumn.ValueMember = "CategoryID"; -categoryColumn.DisplayMember = "CategoryName"; -categoryColumn.Width = 150; -radGridView1.MasterTemplate.Columns.Add(categoryColumn); - -```` -````VB.NET -RadGridView1.AutoGenerateColumns = False - RadGridView1.DataSource = CategoriesBindingSource - - Dim textBoxColumn As New GridViewTextBoxColumn() - textBoxColumn.Name = "TextBoxColumn" - textBoxColumn.HeaderText = "Product Description" - textBoxColumn.FieldName = "Description" - textBoxColumn.MaxLength = 50 - textBoxColumn.TextAlignment = ContentAlignment.BottomRight - textBoxColumn.Width = 250 - RadGridView1.MasterTemplate.Columns.Add(textBoxColumn) - Dim categoryColumn As New GridViewComboBoxColumn() - categoryColumn.DataType = GetType(String) - categoryColumn.Name = "CategoryColumn" - categoryColumn.FieldName = "CategoryName" - categoryColumn.HeaderText = "Category" - categoryColumn.ValueMember = "CategoryID" - categoryColumn.DisplayMember = "CategoryName" - categoryColumn.Width = 150 - RadGridView1.MasterTemplate.Columns.Add(categoryColumn) - -```` - -{{endregion}} + + #### Adding Columns at Design time diff --git a/controls/gridview/visual-elements/columns/pinning-and-unpinning-columns.md b/controls/gridview/visual-elements/columns/pinning-and-unpinning-columns.md index fa9bf8020..37419cf59 100644 --- a/controls/gridview/visual-elements/columns/pinning-and-unpinning-columns.md +++ b/controls/gridview/visual-elements/columns/pinning-and-unpinning-columns.md @@ -17,22 +17,8 @@ Columns in RadGridView can be pinned which will result in the pinned columns bei #### Pinning a single columns -{{source=..\SamplesCS\GridView\Columns\PinningAndUnpinningColumns.cs region=pinningColumns}} -{{source=..\SamplesVB\GridView\Columns\PinningAndUnpinningColumns.vb region=pinningColumns}} - -````C# -radGridView1.Columns[2].IsPinned = true; -radGridView1.Columns["FirstName"].IsPinned = true; - -```` -````VB.NET -Me.RadGridView1.Columns(2).IsPinned = True -'or you can use -Me.RadGridView1.Columns("FirstName").IsPinned = True - -```` - -{{endregion}} + + >caption Figure 1: The left-most column is pinned. @@ -44,23 +30,8 @@ Multiple column pinning is also possible. Simply set either the __IsPinned__ pro #### Pinning multiple columns -{{source=..\SamplesCS\GridView\Columns\PinningAndUnpinningColumns.cs region=pinMultipleColumns}} -{{source=..\SamplesVB\GridView\Columns\PinningAndUnpinningColumns.vb region=pinMultipleColumns}} - -````C# -radGridView1.Columns["Photo"].PinPosition = Telerik.WinControls.UI.PinnedColumnPosition.Left; -radGridView1.Columns["FirstName"].PinPosition = Telerik.WinControls.UI.PinnedColumnPosition.Left; -radGridView1.Columns["LastName"].PinPosition = Telerik.WinControls.UI.PinnedColumnPosition.Left; - -```` -````VB.NET -Me.RadGridView1.Columns("Photo").PinPosition = Telerik.WinControls.UI.PinnedColumnPosition.Left -Me.RadGridView1.Columns("FirstName").PinPosition = Telerik.WinControls.UI.PinnedColumnPosition.Left -Me.RadGridView1.Columns("LastName").PinPosition = Telerik.WinControls.UI.PinnedColumnPosition.Left - -```` - -{{endregion}} + + >caption Figure 2: More than one column can be pinned as well. ![WinForms RadGridView More than one column can be pinned as well](images/gridview-columns-pinning-and-unpinning-columns002.png) diff --git a/controls/gridview/visual-elements/columns/reordering-columns.md b/controls/gridview/visual-elements/columns/reordering-columns.md index 455ce577e..565ba7941 100644 --- a/controls/gridview/visual-elements/columns/reordering-columns.md +++ b/controls/gridview/visual-elements/columns/reordering-columns.md @@ -16,19 +16,8 @@ previous_url: gridview-columns-reordering-columns #### Allow or disallow column reordering -{{source=..\SamplesCS\GridView\Columns\ReorderingColumns.cs region=allowReoder}} -{{source=..\SamplesVB\GridView\Columns\ReorderingColumns.vb region=allowReoder}} - -````C# -radGridView1.AllowColumnReorder = true; - -```` -````VB.NET -RadGridView1.AllowColumnReorder = True - -```` - -{{endregion}} + + >caption Figure 1: Reorder columns in RadGridView @@ -40,21 +29,8 @@ In order to reorder columns in RadGridView programmatically you should use the * #### Reordering columns programmatically -{{source=..\SamplesCS\GridView\Columns\ReorderingColumns.cs region=reorderColumns}} -{{source=..\SamplesVB\GridView\Columns\ReorderingColumns.vb region=reorderColumns}} - -````C# -radGridView1.Columns.Move(5, 0); -radGridView1.Columns.Move(4, 1); - -```` -````VB.NET -RadGridView1.Columns.Move(5, 0) -RadGridView1.Columns.Move(4, 1) - -```` - -{{endregion}} + + # See Also * [Accessing and Iterating through Columns]({%slug winforms/gridview/columns/accessing-and-iterating-through-columns%}) diff --git a/controls/gridview/visual-elements/columns/resizing-columns-programatically.md b/controls/gridview/visual-elements/columns/resizing-columns-programatically.md index 5c9ca8d2a..8504cf6d2 100644 --- a/controls/gridview/visual-elements/columns/resizing-columns-programatically.md +++ b/controls/gridview/visual-elements/columns/resizing-columns-programatically.md @@ -25,53 +25,20 @@ There are two ways to disable resizing of columns in the user interface: * To restrict the user from resizing all columns, set the __AllowColumnResize__ property of **RadGridView** to `false`: -{{source=..\SamplesCS\GridView\Columns\ResizingColumns.cs region=AllowColumnResize}} -{{source=..\SamplesVB\GridView\Columns\ResizingColumns.vb region=AllowColumnResize}} - -````C# -this.radGridView1.AllowColumnResize = false; - -```` -````VB.NET -Me.RadGridView1.AllowColumnResize = False - -```` - -{{endregion}} + + * To restrict the user from resizing a particular column, set the __AllowResize__ property of the column to `false`: -{{source=..\SamplesCS\GridView\Columns\ResizingColumns.cs region=AllowResize}} -{{source=..\SamplesVB\GridView\Columns\ResizingColumns.vb region=AllowResize}} - -````C# -this.radGridView1.Columns["Photo"].AllowResize = false; - -```` -````VB.NET -Me.RadGridView1.Columns("Photo").AllowResize = False - -```` - -{{endregion}} + + ## Programmatically resizing columns You can set the column width individually for each column. Note that the visible width will always include some data even if you set the width to very small values. To resize the columns programmatically, you can use the __Width__ property. For example: -{{source=..\SamplesCS\GridView\Columns\ResizingColumns.cs region=resizingColumn}} -{{source=..\SamplesVB\GridView\Columns\ResizingColumns.vb region=resizingColumn}} - -````C# -this.radGridView1.Columns["Photo"].Width = 100; - -```` -````VB.NET -Me.RadGridView1.Columns("Photo").Width = 100 - -```` - -{{endregion}} + + ## Setting size limits diff --git a/controls/gridview/visual-elements/columns/working-with-columnchooser.md b/controls/gridview/visual-elements/columns/working-with-columnchooser.md index e01f51428..674c239ea 100644 --- a/controls/gridview/visual-elements/columns/working-with-columnchooser.md +++ b/controls/gridview/visual-elements/columns/working-with-columnchooser.md @@ -19,19 +19,8 @@ The **AllowColumnChooser** property determines whether the ColumnChooser is avai >note Column Chooser is enabled by default in RadGridView. To disable it, set **AllowColumnChooser** property to false. -{{source=..\SamplesCS\GridView\Columns\WorkingWithColumnChooser.cs region=AllowColumnChooser}} -{{source=..\SamplesVB\GridView\Columns\WorkingWithColumnChooser.vb region=AllowColumnChooser}} - -````C# -radGridView1.MasterTemplate.AllowColumnChooser = false; - -```` -````VB.NET -RadGridView1.MasterTemplate.AllowColumnChooser = False - -```` - -{{endregion}} + + ## Opening the ColumnChooser @@ -102,37 +91,15 @@ __AllowHide:__ This property determines whether the column is allowed to be move #### Determines if the specified column is allowed to be dragged to the column chooser dialog -{{source=..\SamplesCS\GridView\Columns\WorkingWithColumnChooser.cs region=AllowHide}} -{{source=..\SamplesVB\GridView\Columns\WorkingWithColumnChooser.vb region=AllowHide}} - -````C# -radGridView1.Columns["CategoryName"].AllowHide = false; - -```` -````VB.NET -RadGridView1.Columns("CategoryName").AllowHide = False - -```` - -{{endregion}} + + __VisibleInColumnChooser:__ By setting this property for each column you determine whether the column will be visible in the Column Chooser when dragged to it. By default this property is set to *true* for all columns: #### Determines if the specified column is going to be visible in the column chooser dialog -{{source=..\SamplesCS\GridView\Columns\WorkingWithColumnChooser.cs region=VisibleInColumnChooser}} -{{source=..\SamplesVB\GridView\Columns\WorkingWithColumnChooser.vb region=VisibleInColumnChooser}} - -````C# -radGridView1.Columns["Picture"].VisibleInColumnChooser = false; - -```` -````VB.NET -RadGridView1.Columns("Picture").VisibleInColumnChooser = False - -```` - -{{endregion}} + + __ColumnChooserSortOrder:__ Gets or sets the column chooser sort order. @@ -142,21 +109,8 @@ In order to customize the Column Chooser you can access it directly from the ins #### Accessing and customizing the column chooser -{{source=..\SamplesCS\GridView\Columns\WorkingWithColumnChooser.cs region=customizeColumnChooser}} -{{source=..\SamplesVB\GridView\Columns\WorkingWithColumnChooser.vb region=customizeColumnChooser}} - -````C# -radGridView1.ColumnChooser.DesktopLocation = new Point(100,100); -radGridView1.ColumnChooser.Font = new Font("Segoe", 15, FontStyle.Bold); - -```` -````VB.NET -RadGridView1.ColumnChooser.DesktopLocation = New Point(100, 100) -RadGridView1.ColumnChooser.Font = New Font("Segoe", 15, FontStyle.Bold) - -```` - -{{endregion}} + + ### Enable the filtering functionality @@ -164,26 +118,8 @@ If the grid contains many hidden columns it is convenient to filter them so you #### Enable filtering in the Column Chooser -{{source=..\SamplesCS\GridView\Columns\WorkingWithColumnChooser.cs region=EnableChooserFiltering}} -{{source=..\SamplesVB\GridView\Columns\WorkingWithColumnChooser.vb region=EnableChooserFiltering}} -````C# -private void RadGridView1_ColumnChooserCreated(object sender, ColumnChooserCreatedEventArgs e) -{ - e.ColumnChooser.EnableFilter = true; -} - -```` -````VB.NET -Private Sub RadGridView1_ColumnChooserCreated(ByVal sender As Object, ByVal e As ColumnChooserCreatedEventArgs) - e.ColumnChooser.EnableFilter = True -End Sub - -```` - - - -{{endregion}} - + + # See Also diff --git a/controls/gridview/visual-elements/rows/adding-and-inserting-rows.md b/controls/gridview/visual-elements/rows/adding-and-inserting-rows.md index 61e0a850c..144dbc5a1 100644 --- a/controls/gridview/visual-elements/rows/adding-and-inserting-rows.md +++ b/controls/gridview/visual-elements/rows/adding-and-inserting-rows.md @@ -50,27 +50,12 @@ Public Sub New() End Sub ```` - -{{endregion}} - - The RadGridView.Rows.__AddNew()__ method adds an empty row and allows the user to enter a value for each column cells’: #### Add an empty row -{{source=..\SamplesCS\GridView\Rows\AddingAndInsertingRows.cs region=addNewRow}} -{{source=..\SamplesVB\GridView\Rows\AddingAndInsertingRows.vb region=addNewRow}} - -````C# -radGridView1.Rows.AddNew(); - -```` -````VB.NET -RadGridView1.Rows.AddNew() - -```` - -{{endregion}} + + >caption Figure 1: Add a blank new row @@ -80,19 +65,8 @@ The RadGridView.Rows.__Add(value-for-first-column, value-for-second-column, valu #### Add a new row with values -{{source=..\SamplesCS\GridView\Rows\AddingAndInsertingRows.cs region=addRow}} -{{source=..\SamplesVB\GridView\Rows\AddingAndInsertingRows.vb region=addRow}} - -````C# -radGridView1.Rows.Add("Adding New Row", 12.5, DateTime.Now, true); - -```` -````VB.NET -RadGridView1.Rows.Add("Adding New Row", 12.5, DateTime.Now, True) - -```` - -{{endregion}} + + >caption Figure 2: Add new row with data in it @@ -102,29 +76,8 @@ You can also add rows by creating an instance of __GridViewDataRowInfo__ and add #### Add a GridViewDataRowInfo -{{source=..\SamplesCS\GridView\Rows\AddingAndInsertingRows.cs region=addRowWithRowInfo}} -{{source=..\SamplesVB\GridView\Rows\AddingAndInsertingRows.vb region=addRowWithRowInfo}} - -````C# -GridViewDataRowInfo rowInfo = new GridViewDataRowInfo(this.radGridView1.MasterView); -rowInfo.Cells[0].Value = "GridViewDataRowInfo"; -rowInfo.Cells[1].Value = 11.4; -rowInfo.Cells[2].Value = DateTime.Now.AddDays(5); -rowInfo.Cells[3].Value = true; -radGridView1.Rows.Add(rowInfo); - -```` -````VB.NET -Dim rowInfo As New GridViewDataRowInfo(Me.RadGridView1.MasterView) -rowInfo.Cells(0).Value = "GridViewDataRowInfo" -rowInfo.Cells(1).Value = 11.4 -rowInfo.Cells(2).Value = DateTime.Now.AddDays(5) -rowInfo.Cells(3).Value = True -RadGridView1.Rows.Add(rowInfo) - -```` - -{{endregion}} + + >caption Figure 3: Add new row by creating an instance first @@ -136,27 +89,8 @@ Rows can be inserted at a specified position by using the __Insert__ method of t #### Insert a GridViewDataRowInfo -{{source=..\SamplesCS\GridView\Rows\AddingAndInsertingRows.cs region=insertRow}} -{{source=..\SamplesVB\GridView\Rows\AddingAndInsertingRows.vb region=insertRow}} - -````C# -GridViewDataRowInfo dataRowInfo = new GridViewDataRowInfo(this.radGridView1.MasterView); -dataRowInfo.Cells[0].Value = "Inserted Row"; -dataRowInfo.Cells[1].Value = 1156.54; -dataRowInfo.Cells[2].Value = DateTime.Now.AddDays(14); -radGridView1.Rows.Insert(2, dataRowInfo); - -```` -````VB.NET -Dim dataRowInfo As New GridViewDataRowInfo(Me.RadGridView1.MasterView) -rowInfo.Cells(0).Value = "Inserted Row" -rowInfo.Cells(1).Value = 1154.54 -rowInfo.Cells(2).Value = DateTime.Now.AddDays(14) -RadGridView1.Rows.Insert(2, dataRowInfo) - -```` - -{{endregion}} + + >caption Figure 4: Insert row to a specific position diff --git a/controls/gridview/visual-elements/rows/conditional-formatting-rows.md b/controls/gridview/visual-elements/rows/conditional-formatting-rows.md index 2d1db9f30..c4e8a4277 100644 --- a/controls/gridview/visual-elements/rows/conditional-formatting-rows.md +++ b/controls/gridview/visual-elements/rows/conditional-formatting-rows.md @@ -51,26 +51,8 @@ This example looks for the same condition as the [cell formatting example]({%slu ![WinForms RadGridView Conditional Formatting Rows](images/gridview-rows-conditional-formatting-rows001.png) -{{source=..\SamplesCS\GridView\Rows\ConditionalFormattingRows.cs region=conditionalFormatting}} -{{source=..\SamplesVB\GridView\Rows\ConditionalFormattingRows.vb region=conditionalFormatting}} - -````C# -ConditionalFormattingObject obj = new ConditionalFormattingObject("MyCondition", ConditionTypes.Greater, "30", "", true); -obj.CellForeColor = Color.Red; -obj.RowBackColor = Color.SkyBlue; -this.radGridView1.Columns["UnitPrice"].ConditionalFormattingObjectList.Add(obj); - -```` -````VB.NET -Dim obj = New ConditionalFormattingObject("MyCondition", ConditionTypes.Greater, "30", "", True) -obj.CellForeColor = Color.Red -obj.RowBackColor = Color.SkyBlue -Me.RadGridView1.Columns("Unit Price").ConditionalFormattingObjectList.Add(obj) - -```` - -{{endregion}} - + + >caution The declarative nature of Conditional Formatting limits the situations in which it can be used. While the provided functionality covers most scenarios, there are situations in which you will need to use [events]({%slug winforms/gridview/rows/formatting-rows%}). > diff --git a/controls/gridview/visual-elements/rows/creating-custom-rows.md b/controls/gridview/visual-elements/rows/creating-custom-rows.md index 342bbbf6b..f25b7e725 100644 --- a/controls/gridview/visual-elements/rows/creating-custom-rows.md +++ b/controls/gridview/visual-elements/rows/creating-custom-rows.md @@ -17,35 +17,8 @@ __RadGridView__ provides a variety of visual cells per row with different functi Consider the __RadGridView__ is populated with data form Northwind.Products table. -{{source=..\SamplesCS\GridView\Rows\CreateCustomNewRow.cs region=PopulateData}} -{{source=..\SamplesVB\GridView\Rows\CreateCustomNewRow.vb region=PopulateData}} - -````C# -public static object DataSource; -private void CreateCustomNewRow_Load(object sender, EventArgs e) -{ - this.productsTableAdapter.Fill(this.nwindDataSet.Products); - DataSource = this.nwindDataSet.Products.Take(20); - - this.radGridView1.TableElement.ViewInfo.TableAddNewRow.Height = 250; - this.radGridView1.DataSource = this.nwindDataSet.Products; - this.radGridView1.AutoSizeColumnsMode = Telerik.WinControls.UI.GridViewAutoSizeColumnsMode.Fill; -} - -```` -````VB.NET -Public Shared DataSource As Object -Private Sub CreateCustomNewRow_Load(sender As Object, e As EventArgs) Handles MyBase.Load - Me.ProductsTableAdapter.Fill(Me.NwindDataSet.Products) - DataSource = Me.NwindDataSet.Products.Take(20) - Me.RadGridView1.TableElement.ViewInfo.TableAddNewRow.Height = 250 - Me.RadGridView1.DataSource = Me.NwindDataSet.Products - Me.RadGridView1.AutoSizeColumnsMode = Telerik.WinControls.UI.GridViewAutoSizeColumnsMode.Fill -End Sub - -```` - -{{endregion}} + + >note In order to enlarge the new row's height, you can set the TableElement.ViewInfo.TableAddNewRow. __Height__ property. > @@ -62,152 +35,20 @@ On the new row we will display a __RadChartViewElement__ visualizing the Product 1\. Create a descendant of the __GridRowElement__ and override its __CreateChildElements__ where you should add a single __GridCellElement__ that contains the chart. The __IsCompatible__ method determines for which __GridViewRowInfo__ the custom row element is applicable: -{{source=..\SamplesCS\GridView\Rows\CreateCustomNewRow.cs region=RowElement}} -{{source=..\SamplesVB\GridView\Rows\CreateCustomNewRow.vb region=RowElement}} - -````C# -public class CustomGridRowElement : GridRowElement -{ - private GridCellElement cellElement; - private RadChartElement radChartElement; - - public CustomGridRowElement() - { - } - - protected override void CreateChildElements() - { - base.CreateChildElements(); - this.cellElement = new GridCellElement(null, this); - this.cellElement.StretchHorizontally = true; - this.cellElement.StretchVertically = true; - this.Children.Add(cellElement); - - this.radChartElement = new RadChartElement(); - - LineSeries series = new LineSeries(); - - this.radChartElement.View.ShowSmartLabels = true; - this.radChartElement.ShowLegend = true; - this.radChartElement.View.Series.Add(series); - this.cellElement.Children.Add(this.radChartElement); - this.cellElement.ClipDrawing = true; - - series.CategoryMember = "CategoryID"; - series.ValueMember = "UnitPrice"; - series.DataSource = DataSource; - } - - public override bool IsCompatible(GridViewRowInfo data, object context) - { - return data is CustomGridViewRowInfo; - } -} - -```` -````VB.NET -Public Class CustomGridRowElement - Inherits GridRowElement - Private cellElement As GridCellElement - Private radChartElement As RadChartElement - Public Sub New() - End Sub - Protected Overrides Sub CreateChildElements() - MyBase.CreateChildElements() - Me.cellElement = New GridCellElement(Nothing, Me) - Me.cellElement.StretchHorizontally = True - Me.cellElement.StretchVertically = True - Me.Children.Add(cellElement) - Me.radChartElement = New RadChartElement() - Dim series As New LineSeries() - Me.radChartElement.View.ShowSmartLabels = True - Me.radChartElement.ShowLegend = True - Me.radChartElement.View.Series.Add(series) - Me.cellElement.Children.Add(Me.radChartElement) - Me.cellElement.ClipDrawing = True - series.CategoryMember = "CategoryID" - series.ValueMember = "UnitPrice" - series.DataSource = DataSource - End Sub - Public Overrides Function IsCompatible(data As GridViewRowInfo, context As Object) As Boolean - Return TypeOf data Is CustomGridViewRowInfo - End Function -End Class - -```` - -{{endregion}} + + 2\. Create a descendant of the __GridViewNewRowInfo__ and specify that it uses the row element from the previous step by overriding its __RowElementType__ property. -{{source=..\SamplesCS\GridView\Rows\CreateCustomNewRow.cs region=RowInfo}} -{{source=..\SamplesVB\GridView\Rows\CreateCustomNewRow.vb region=RowInfo}} - -````C# - -public class CustomGridViewRowInfo : GridViewNewRowInfo -{ - public CustomGridViewRowInfo(GridViewInfo viewInfo) : base(viewInfo) - { - } - - public override Type RowElementType - { - get - { - return typeof(CustomGridRowElement); - } - } -} - -```` -````VB.NET -Public Class CustomGridViewRowInfo - Inherits GridViewNewRowInfo - Public Sub New(viewInfo As GridViewInfo) - MyBase.New(viewInfo) - End Sub - Public Overrides ReadOnly Property RowElementType() As Type - Get - Return GetType(CustomGridRowElement) - End Get - End Property -End Class - -```` - -{{endregion}} + + 3\. The last step is to subscribe to the __CreateRowInfo__ event and replace the default __GridViewNewRowInfo__ with your custom one. >important You should subscribe to the **CreateRowInfo** event at design time in order to ensure that the event will be fired when a data row have to be created. -{{source=..\SamplesCS\GridView\Rows\CreateCustomNewRow.cs region=ReplaceRow}} -{{source=..\SamplesVB\GridView\Rows\CreateCustomNewRow.vb region=ReplaceRow}} - -````C# - -private void radGridView1_CreateRowInfo(object sender, GridViewCreateRowInfoEventArgs e) -{ - if (e.RowInfo is GridViewNewRowInfo) - { - e.RowInfo = new CustomGridViewRowInfo(e.ViewInfo); - } -} - -```` -````VB.NET -Private Sub radGridView1_CreateRowInfo(sender As Object, e As GridViewCreateRowInfoEventArgs) Handles RadGridView1.CreateRowInfo - If TypeOf e.RowInfo Is GridViewNewRowInfo Then - e.RowInfo = New CustomGridViewRowInfo(e.ViewInfo) - End If -End Sub - -```` - -{{endregion}} - - + + # See Also * [Adding and Inserting Rows]({%slug winforms/gridview/rows/adding-and-inserting-rows%}) diff --git a/controls/gridview/visual-elements/rows/drag-and-drop.md b/controls/gridview/visual-elements/rows/drag-and-drop.md index 3768b0b3d..4fe8a9983 100644 --- a/controls/gridview/visual-elements/rows/drag-and-drop.md +++ b/controls/gridview/visual-elements/rows/drag-and-drop.md @@ -29,125 +29,20 @@ To get started: 3. Modify the class to extend the RadGridView control through inheritance. -{{source=..\SamplesCS\GridView\Rows\DragAndDropRadGrid.cs region=Definition}} -{{source=..\SamplesVB\GridView\Rows\DragAndDropRadGrid.vb region=Definition}} - -````C# -public class DragAndDropRadGrid : RadGridView - -```` -````VB.NET -Public Class DragAndDropRadGrid - Inherits RadGridView - -```` - -{{endregion}} + + The drag and drop functionality is made easy using the built-in __RadGridViewDragDropService__ as the plumbing code is already handled, you only need to handle events emanating from this service. Create a default constructor for the __DragAndDropRadGrid__ class. In this constructor we will grab a reference to the __RadDragDropService__ and generate event handler stubs for a few of the service’s events. -{{source=..\SamplesCS\GridView\Rows\DragAndDropRadGrid.cs region=Constructor}} -{{source=..\SamplesVB\GridView\Rows\DragAndDropRadGrid.vb region=Constructor}} - -````C# -public DragAndDropRadGrid() -{ - this.MultiSelect = true; - - //handle drag and drop events for the grid through the DragDrop service - RadDragDropService svc = - this.GridViewElement.GetService(); - svc.PreviewDragStart += svc_PreviewDragStart; - svc.PreviewDragDrop += svc_PreviewDragDrop; - svc.PreviewDragOver += svc_PreviewDragOver; - - //register the custom row selection behavior - var gridBehavior = this.GridBehavior as BaseGridBehavior; - gridBehavior.UnregisterBehavior(typeof(GridViewDataRowInfo)); - gridBehavior.RegisterBehavior(typeof(GridViewDataRowInfo), new RowSelectionGridBehavior()); -} - -public override string ThemeClassName -{ - get - { - return typeof(RadGridView).FullName; - } -} - -```` -````VB.NET -Public Sub New() - Me.MultiSelect = True - 'handle drag and drop events for the grid through the DragDrop service - Dim svc As RadDragDropService = Me.GridViewElement.GetService(Of RadDragDropService)() - AddHandler svc.PreviewDragStart, AddressOf svc_PreviewDragStart - AddHandler svc.PreviewDragDrop, AddressOf svc_PreviewDragDrop - AddHandler svc.PreviewDragOver, AddressOf svc_PreviewDragOver - 'register the custom row selection behavior - Dim gridBehavior = TryCast(Me.GridBehavior, BaseGridBehavior) - gridBehavior.UnregisterBehavior(GetType(GridViewDataRowInfo)) - gridBehavior.RegisterBehavior(GetType(GridViewDataRowInfo), New RowSelectionGridBehavior()) -End Sub -Public Overrides Property ThemeClassName As String - Get - Return GetType(RadGridView).FullName - End Get - Set(value As String) - MyBase.ThemeClassName = value - End Set -End Property - -```` - -{{endregion}} + + ## Starting the Drag and Drop Service using behaviors In order to start the drag and drop service when the user clicks on a row with the left mouse button, it is necessary to create a custom grid behavior. To do this, create a new class that inherits the __GridDataRowBehavior__ class. In addition the drag and drop service allows you to disable the auto scrolling while dragging functionality: -{{source=..\SamplesCS\GridView\Rows\DragAndDropRadGrid.cs region=GridBehavior}} -{{source=..\SamplesVB\GridView\Rows\DragAndDropRadGrid.vb region=GridBehavior}} - -````C# - -//initiates drag and drop service for clicked rows -public class RowSelectionGridBehavior : GridDataRowBehavior -{ - protected override bool OnMouseDownLeft(MouseEventArgs e) - { - GridDataRowElement row = this.GetRowAtPoint(e.Location) as GridDataRowElement; - if (row != null) - { - RadGridViewDragDropService svc = this.GridViewElement.GetService(); - svc.AllowAutoScrollColumnsWhileDragging = false; - svc.AllowAutoScrollRowsWhileDragging = false; - svc.Start(row); - } - return base.OnMouseDownLeft(e); - } -} - -```` -````VB.NET -'initiates drag and drop service for clicked rows -Public Class RowSelectionGridBehavior - Inherits GridDataRowBehavior - Protected Overrides Function OnMouseDownLeft(ByVal e As MouseEventArgs) As Boolean - Dim row As GridDataRowElement = TryCast(Me.GetRowAtPoint(e.Location), GridDataRowElement) - If Not row Is Nothing Then - Dim svc As RadGridViewDragDropService = Me.GridViewElement.GetService(Of RadGridViewDragDropService)() - svc.AllowAutoScrollColumnsWhileDragging = False - svc.AllowAutoScrollRowsWhileDragging = False - svc.Start(row) - End If - Return MyBase.OnMouseDownLeft(e) - End Function -End Class - -```` - -{{endregion}} + + It is important to register this behavior in our grid. Build the solution and our custom grid is now setup and ready to use. You can locate it in the Visual Studio toolbox when in the design view of a form. @@ -157,140 +52,18 @@ It is important to register this behavior in our grid. Build the solution and ou The __PreviewDragStart__ event is fired once the Drag and Drop service on the grid is started. In this case, we simply want to tell the drag and drop service if the drag operation can move forward. Implement the __PreviewDragStart__ event handler as follows: -{{source=..\SamplesCS\GridView\Rows\DragAndDropRadGrid.cs region=PreviewDragStart}} -{{source=..\SamplesVB\GridView\Rows\DragAndDropRadGrid.vb region=PreviewDragStart}} - -````C# - -//required to initiate drag and drop when grid is in bound mode -private void svc_PreviewDragStart(object sender, PreviewDragStartEventArgs e) -{ - e.CanStart = true; -} - -```` -````VB.NET -'required to initiate drag and drop when grid is in bound mode -Private Sub svc_PreviewDragStart(ByVal sender As Object, ByVal e As PreviewDragStartEventArgs) - e.CanStart = True -End Sub - -```` - -{{endregion}} + + The next event we will handle is the __PreviewDragOver__ event. This event allows you to control on what targets the row being dragged can be dropped on. In this case, as long as it’s being dropped somewhere on the target grid, we are good with it. Implement the handler as follows: -{{source=..\SamplesCS\GridView\Rows\DragAndDropRadGrid.cs region=PreviewDragOver}} -{{source=..\SamplesVB\GridView\Rows\DragAndDropRadGrid.vb region=PreviewDragOver}} - -````C# - -private void svc_PreviewDragOver(object sender, RadDragOverEventArgs e) -{ - if (e.DragInstance is GridDataRowElement) - { - e.CanDrop = e.HitTarget is GridDataRowElement || - e.HitTarget is GridTableElement || - e.HitTarget is GridSummaryRowElement; - } -} - -```` -````VB.NET -Private Sub svc_PreviewDragOver(ByVal sender As Object, ByVal e As RadDragOverEventArgs) - If TypeOf e.DragInstance Is GridDataRowElement Then - e.CanDrop = TypeOf e.HitTarget Is GridDataRowElement OrElse - TypeOf e.HitTarget Is GridTableElement OrElse - TypeOf e.HitTarget Is GridSummaryRowElement - End If -End Sub - -```` - -{{endregion}} + + The last event we want to handle in our implementation is the __PreviewDragDrop__ event. This event allows you to get a handle on all the aspects of the drag and drop operation, the source (drag) grid, the destination (target) grid, as well as the row being dragged. This is where we will initiate the actual physical move of the row(s) from one grid to the other. Implement the handler as follows: -{{source=..\SamplesCS\GridView\Rows\DragAndDropRadGrid.cs region=PreviewDragDrop}} -{{source=..\SamplesVB\GridView\Rows\DragAndDropRadGrid.vb region=PreviewDragDrop}} - -````C# - -//gather drag/source grid and target/destination information and initiate the move of selected rows -private void svc_PreviewDragDrop(object sender, RadDropEventArgs e) -{ - var rowElement = e.DragInstance as GridDataRowElement; - if (rowElement == null) - { - return; - } - e.Handled = true; - - var dropTarget = e.HitTarget as RadItem; - var targetGrid = dropTarget.ElementTree.Control as RadGridView; - if (targetGrid == null) - { - return; - } - - var dragGrid = rowElement.ElementTree.Control as RadGridView; - if (targetGrid != dragGrid) - { - e.Handled = true; - //append dragged rows to the end of the target grid - int index = targetGrid.RowCount; - - //Grab every selected row from the source grid, including the current row - List rows = - dragGrid.SelectedRows.ToList(); - if (dragGrid.CurrentRow != null) - { - GridViewRowInfo row = dragGrid.CurrentRow; - if (!rows.Contains(row)) - rows.Add(row); - } - this.MoveRows(targetGrid, dragGrid, rows, index); - } -} - -```` -````VB.NET -'gather drag/source grid and target/destination information and initiate the move of selected rows -Private Sub svc_PreviewDragDrop(ByVal sender As Object, ByVal e As RadDropEventArgs) - Dim rowElement = TryCast(e.DragInstance, GridDataRowElement) - If rowElement Is Nothing Then - Return - End If - e.Handled = True - Dim dropTarget = TryCast(e.HitTarget, RadItem) - Dim targetGrid = TryCast(dropTarget.ElementTree.Control, RadGridView) - If targetGrid Is Nothing Then - Return - End If - Dim dragGrid = TryCast(rowElement.ElementTree.Control, RadGridView) - If Not targetGrid Is dragGrid Then - e.Handled = True - 'append dragged rows to the end of the target grid - Dim index As Integer = targetGrid.RowCount - 'Grab every selected row from the source grid, including the current row - Dim rows As New List(Of GridViewRowInfo) - For Each row As GridViewRowInfo In dragGrid.SelectedRows - rows.Add(row) - Next - If Not dragGrid.CurrentRow Is Nothing Then - Dim row As GridViewRowInfo = dragGrid.CurrentRow - If (Not rows.Contains(row)) Then - rows.Add(row) - End If - End If - Me.MoveRows(targetGrid, dragGrid, rows, index) - End If -End Sub - -```` - -{{endregion}} + + ## Moving the data from one source to the other @@ -304,120 +77,8 @@ You will notice at the end of the __PreviewDragDrop__ handler that we need to cr It is in the __MoveRows__ method where the physical moving of the data happens. Basically what we need in this method is to add the data into the target data source, and remove it from the source data source in order to complete the drag and drop operation under the covers. Implement the MoveRows method as follows: -{{source=..\SamplesCS\GridView\Rows\DragAndDropRadGrid.cs region=MoveRows}} -{{source=..\SamplesVB\GridView\Rows\DragAndDropRadGrid.vb region=MoveRows}} - -````C# - -private void MoveRows(RadGridView targetGrid, RadGridView dragGrid, - IList dragRows, int index) -{ - dragGrid.BeginUpdate(); - targetGrid.BeginUpdate(); - for (int i = dragRows.Count - 1; i >= 0; i--) - { - GridViewRowInfo row = dragRows[i]; - if (row is GridViewSummaryRowInfo) - { - continue; - } - if (targetGrid.DataSource == null) - { - //unbound scenario - GridViewRowInfo newRow = targetGrid.Rows.NewRow(); - foreach (GridViewCellInfo cell in row.Cells) - { - if (newRow.Cells[cell.ColumnInfo.Name] != null) - newRow.Cells[cell.ColumnInfo.Name].Value = cell.Value; - } - - targetGrid.Rows.Insert(index, newRow); - - row.IsSelected = false; - dragGrid.Rows.Remove(row); - } - else if (typeof(DataSet).IsAssignableFrom(targetGrid.DataSource.GetType())) - { - //bound to a dataset scenario - var sourceTable = ((DataSet)dragGrid.DataSource).Tables[0]; - var targetTable = ((DataSet)targetGrid.DataSource).Tables[0]; - - var newRow = targetTable.NewRow(); - foreach (GridViewCellInfo cell in row.Cells) - { - newRow[cell.ColumnInfo.Name] = cell.Value; - } - - sourceTable.Rows.Remove(((DataRowView)row.DataBoundItem).Row); - targetTable.Rows.InsertAt(newRow, index); - } - else if (typeof(IList).IsAssignableFrom(targetGrid.DataSource.GetType())) - { - //bound to a list of objects scenario - var targetCollection = (IList)targetGrid.DataSource; - var sourceCollection = (IList)dragGrid.DataSource; - sourceCollection.Remove(row.DataBoundItem); - targetCollection.Add(row.DataBoundItem); - } - else - { - throw new ApplicationException("Unhandled Scenario"); - } - index++; - } - dragGrid.EndUpdate(true); - targetGrid.EndUpdate(true); -} - -```` -````VB.NET -Private Sub MoveRows(ByVal targetGrid As RadGridView, ByVal dragGrid As RadGridView, ByVal dragRows As IList(Of GridViewRowInfo), ByVal index As Integer) - dragGrid.BeginUpdate() - targetGrid.BeginUpdate() - For i As Integer = dragRows.Count - 1 To 0 Step -1 - Dim row As GridViewRowInfo = dragRows(i) - If TypeOf row Is GridViewSummaryRowInfo Then - Continue For - End If - If targetGrid.DataSource Is Nothing Then - 'unbound scenario - Dim newRow As GridViewRowInfo = targetGrid.Rows.NewRow() - For Each cell As GridViewCellInfo In row.Cells - If Not newRow.Cells(cell.ColumnInfo.Name) Is Nothing Then - newRow.Cells(cell.ColumnInfo.Name).Value = cell.Value - End If - Next cell - targetGrid.Rows.Insert(index, newRow) - row.IsSelected = False - dragGrid.Rows.Remove(row) - ElseIf GetType(DataSet).IsAssignableFrom(targetGrid.DataSource.GetType()) Then - 'bound to a dataset scenario - Dim sourceTable = (CType(dragGrid.DataSource, DataSet)).Tables(0) - Dim targetTable = (CType(targetGrid.DataSource, DataSet)).Tables(0) - Dim newRow = targetTable.NewRow() - For Each cell As GridViewCellInfo In row.Cells - newRow(cell.ColumnInfo.Name) = cell.Value - Next cell - sourceTable.Rows.Remove((CType(row.DataBoundItem, DataRowView)).Row) - targetTable.Rows.InsertAt(newRow, index) - ElseIf GetType(IList).IsAssignableFrom(targetGrid.DataSource.GetType()) Then - 'bound to a list of objects scenario - Dim targetCollection = CType(targetGrid.DataSource, IList) - Dim sourceCollection = CType(dragGrid.DataSource, IList) - sourceCollection.Remove(row.DataBoundItem) - targetCollection.Add(row.DataBoundItem) - Else - Throw New ApplicationException("Unhandled Scenario") - End If - index += 1 - Next i - dragGrid.EndUpdate(True) - targetGrid.EndUpdate(True) -End Sub - -```` - -{{endregion}} + + ## Using our new control @@ -427,268 +88,28 @@ Open the designer for Form1 and layout your form by dragging two instances of ou Initialize some settings of the grids in the default constructor of the form as follows, we’ll also add a method to reset the grids: -{{source=..\SamplesCS\GridView\Rows\DragAndDropRadGridForm1.cs region=Form1}} -{{source=..\SamplesVB\GridView\Rows\DragAndDropRadGridForm1.vb region=Form1}} - -````C# -public DragAndDropRadGridForm1() -{ - InitializeComponent(); - leftGrid.ShowGroupPanel = false; - rightGrid.ShowGroupPanel = false; - leftGrid.AllowAddNewRow = false; - rightGrid.AllowAddNewRow = false; - leftGrid.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill; - rightGrid.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill; -} -private void ResetGrids() -{ - leftGrid.DataSource = null; - leftGrid.Rows.Clear(); - leftGrid.Columns.Clear(); - rightGrid.DataSource = null; - rightGrid.Rows.Clear(); - rightGrid.Columns.Clear(); -} - -```` -````VB.NET -Public Sub New() - InitializeComponent() - leftGrid.ShowGroupPanel = False - rightGrid.ShowGroupPanel = False - leftGrid.AllowAddNewRow = False - rightGrid.AllowAddNewRow = False - leftGrid.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill - rightGrid.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill -End Sub -Private Sub ResetGrids() - leftGrid.DataSource = Nothing - leftGrid.Rows.Clear() - leftGrid.Columns.Clear() - rightGrid.DataSource = Nothing - rightGrid.Rows.Clear() - rightGrid.Columns.Clear() -End Sub - -```` - -{{endregion}} + + First we will implement the usage of our custom grid in an unbound scenario. To do this, double-click on the Unbound button to implement its click event handler as follows: -{{source=..\SamplesCS\GridView\Rows\DragAndDropRadGridForm1.cs region=Unbound}} -{{source=..\SamplesVB\GridView\Rows\DragAndDropRadGridForm1.vb region=Unbound}} - -````C# -private void btnUnbound_Click(object sender, EventArgs e) -{ - ResetGrids(); - PrepareUnboundGrid(leftGrid); - leftGrid.Rows.Add("Carey", "Payette"); - leftGrid.Rows.Add("Michael", "Crump"); - leftGrid.Rows.Add("Jeff", "Fritz"); - PrepareUnboundGrid(rightGrid); - rightGrid.Rows.Add("Phil", "Japikse"); - rightGrid.Rows.Add("Jesse", "Liberty"); - rightGrid.Rows.Add("Iris", "Classon"); -} -private void PrepareUnboundGrid(RadGridView grid) -{ - //setup columns - GridViewTextBoxColumn firstName = new GridViewTextBoxColumn("FirstName", "FirstName"); - firstName.HeaderText = "First Name"; - GridViewTextBoxColumn lastName = new GridViewTextBoxColumn("LastName", "LastName"); - lastName.HeaderText = "Last Name"; - grid.Columns.AddRange(firstName, lastName); -} - -```` -````VB.NET -Private Sub btnUnbound_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnUnbound.Click - ResetGrids() - PrepareUnboundGrid(leftGrid) - leftGrid.Rows.Add("Carey", "Payette") - leftGrid.Rows.Add("Michael", "Crump") - leftGrid.Rows.Add("Jeff", "Fritz") - PrepareUnboundGrid(rightGrid) - rightGrid.Rows.Add("Phil", "Japikse") - rightGrid.Rows.Add("Jesse", "Liberty") - rightGrid.Rows.Add("Iris", "Classon") -End Sub -Private Sub PrepareUnboundGrid(ByVal grid As RadGridView) - 'setup columns - Dim firstName As GridViewTextBoxColumn = New GridViewTextBoxColumn("FirstName", "FirstName") - firstName.HeaderText = "First Name" - Dim lastName As GridViewTextBoxColumn = New GridViewTextBoxColumn("LastName", "LastName") - lastName.HeaderText = "Last Name" - grid.Columns.AddRange(firstName, lastName) -End Sub - -```` - -{{endregion}} + + Next we will implement the usage of our grid when it is bound to a BindingList. Double-click on the Bound to Objects button, and implement it as follows: -{{source=..\SamplesCS\GridView\Rows\DragAndDropRadGridForm1.cs region=BoundObjects}} -{{source=..\SamplesVB\GridView\Rows\DragAndDropRadGridForm1.vb region=BoundObjects}} - -````C# -private void btnBoundObjects_Click(object sender, EventArgs e) -{ - ResetGrids(); - BindingList dataList1 = new BindingList(); - dataList1.Add(new Player() { FirstName = "Carey", LastName = "Payette" }); - dataList1.Add(new Player() { FirstName = "Michael", LastName = "Crump" }); - dataList1.Add(new Player() { FirstName = "Jeff", LastName = "Fritz" }); - BindingList dataList2 = new BindingList(); - dataList2.Add(new Player() { FirstName = "Phil", LastName = "Japikse" }); - dataList2.Add(new Player() { FirstName = "Jesse", LastName = "Liberty" }); - dataList2.Add(new Player() { FirstName = "Iris", LastName = "Classon" }); - leftGrid.DataSource = dataList1; - rightGrid.DataSource = dataList2; -} - -```` -````VB.NET -Private Sub btnBoundObjects_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnBoundObjects.Click - ResetGrids() - Dim dataList1 As New BindingList(Of Player)() - dataList1.Add(New Player() With { _ - .FirstName = "Carey", _ - .LastName = "Payette" _ - }) - dataList1.Add(New Player() With { _ - .FirstName = "Michael", _ - .LastName = "Crump" _ - }) - dataList1.Add(New Player() With { _ - .FirstName = "Jeff", _ - .LastName = "Fritz" _ - }) - Dim dataList2 As New BindingList(Of Player)() - dataList2.Add(New Player() With { _ - .FirstName = "Phil", _ - .LastName = "Japikse" _ - }) - dataList2.Add(New Player() With { _ - .FirstName = "Jesse", _ - .LastName = "Liberty" _ - }) - dataList2.Add(New Player() With { _ - .FirstName = "Iris", _ - .LastName = "Classon" _ - }) - leftGrid.DataSource = dataList1 - rightGrid.DataSource = dataList2 -End Sub - -```` - -{{endregion}} - + + Add a Player class to the Form1.cs source file to support this scenario defined as the following: -{{source=..\SamplesCS\GridView\Rows\DragAndDropRadGridForm1.cs region=Player}} -{{source=..\SamplesVB\GridView\Rows\DragAndDropRadGridForm1.vb region=Player}} - -````C# -public class Player -{ - public string FirstName { get; set; } - public string LastName { get; set; } -} - -```` -````VB.NET -Public Class Player - Public Property FirstName() As String - Get - Return m_FirstName - End Get - Set(ByVal value As String) - m_FirstName = value - End Set - End Property - Private m_FirstName As String - Public Property LastName() As String - Get - Return m_LastName - End Get - Set(ByVal value As String) - m_LastName = value - End Set - End Property - Private m_LastName As String -End Class - -```` - -{{endregion}} - + + Lastly we will implement the scenario of when the grids are bound to a DataSet. Implement the click event handler of the Bound to DataSet button as follows: -{{source=..\SamplesCS\GridView\Rows\DragAndDropRadGridForm1.cs region=DataSet}} -{{source=..\SamplesVB\GridView\Rows\DragAndDropRadGridForm1.vb region=DataSet}} - -````C# -private void btnBoundDataSet_Click(object sender, EventArgs e) -{ - ResetGrids(); - DataSet ds1 = new DataSet(); - DataTable team1 = new DataTable(); - team1.Columns.Add("First Name", typeof(string)); - team1.Columns.Add("Last Name", typeof(string)); - team1.Rows.Add("Carey", "Payette"); - team1.Rows.Add("Michael", "Crump"); - team1.Rows.Add("Jeff", "Fritz"); - ds1.Tables.Add(team1); - DataSet ds2 = new DataSet(); - DataTable team2 = new DataTable(); - team2.Columns.Add("First Name", typeof(string)); - team2.Columns.Add("Last Name", typeof(string)); - team2.Rows.Add("Phil", "Japikse"); - team2.Rows.Add("Jesse", "Liberty"); - team2.Rows.Add("Iris", "Classon"); - ds2.Tables.Add(team2); - leftGrid.DataSource = ds1; - leftGrid.DataMember = "Table1"; - rightGrid.DataSource = ds2; - rightGrid.DataMember = "Table1"; -} - -```` -````VB.NET -Private Sub btnBoundDataSet_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnBoundDataSet.Click - ResetGrids() - Dim ds1 As DataSet = New DataSet() - Dim team1 As DataTable = New DataTable() - team1.Columns.Add("First Name", GetType(String)) - team1.Columns.Add("Last Name", GetType(String)) - team1.Rows.Add("Carey", "Payette") - team1.Rows.Add("Michael", "Crump") - team1.Rows.Add("Jeff", "Fritz") - ds1.Tables.Add(team1) - Dim ds2 As DataSet = New DataSet() - Dim team2 As DataTable = New DataTable() - team2.Columns.Add("First Name", GetType(String)) - team2.Columns.Add("Last Name", GetType(String)) - team2.Rows.Add("Phil", "Japikse") - team2.Rows.Add("Jesse", "Liberty") - team2.Rows.Add("Iris", "Classon") - ds2.Tables.Add(team2) - leftGrid.DataSource = ds1 - leftGrid.DataMember = "Table1" - rightGrid.DataSource = ds2 - rightGrid.DataMember = "Table1" -End Sub - -```` - -{{endregion}} + + Go ahead and build and run the application. You are now able to use drag and drop functionality in bound and unbound modes. You are also able to select multiple rows using either the shift or control key, and holding the key down while you drag the rows between the grids. # See Also diff --git a/controls/gridview/visual-elements/rows/formatting-rows.md b/controls/gridview/visual-elements/rows/formatting-rows.md index a8f97301f..4131336c2 100644 --- a/controls/gridview/visual-elements/rows/formatting-rows.md +++ b/controls/gridview/visual-elements/rows/formatting-rows.md @@ -19,43 +19,8 @@ The code snippet below demonstrates changing the background color of rows, which ![WinForms RadGridView Formatted Rows](images/grid-rows-formatting-rows001.png) -{{source=..\SamplesCS\GridView\Rows\FormattingRows.cs region=rowFormatting}} -{{source=..\SamplesVB\GridView\Rows\FormattingRows.vb region=rowFormatting}} - -````C# -private void radGridView1_RowFormatting(object sender, RowFormattingEventArgs e) -{ - if ((bool)e.RowElement.RowInfo.Cells["BMP"].Value == true) - { - e.RowElement.DrawFill = true; - e.RowElement.GradientStyle = GradientStyles.Solid; - e.RowElement.BackColor = Color.Aqua; - } - else - { - e.RowElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local); - e.RowElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local); - e.RowElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local); - } -} - -```` -````VB.NET -Private Sub RadGridView1_RowFormatting(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.RowFormattingEventArgs) Handles RadGridView1.RowFormatting - If e.RowElement.RowInfo.Cells("BMP").Value = True Then - e.RowElement.DrawFill = True - e.RowElement.GradientStyle = GradientStyles.Solid - e.RowElement.BackColor = Color.Aqua - Else - e.RowElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local) - e.RowElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local) - e.RowElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local) - End If -End Sub - -```` - -{{endregion}} + + >note An *if-else* statement is used to reset the value of __BackColorProperty__ if no drawing is required. > @@ -70,49 +35,8 @@ End Sub To customize the non-data rows (header row, new row, filtering row, etc) of **RadGridView**, you need to handle the __ViewRowFormatting__ event. -{{source=..\SamplesCS\GridView\Rows\FormattingRows.cs region=viewRowFormatting}} -{{source=..\SamplesVB\GridView\Rows\FormattingRows.vb region=viewRowFormatting}} - -````C# -void radGridView1_ViewRowFormatting(object sender, RowFormattingEventArgs e) -{ - - if (e.RowElement is GridTableHeaderRowElement) - { - e.RowElement.DrawFill = true; - e.RowElement.BackColor = Color.Navy; - e.RowElement.NumberOfColors = 1; - e.RowElement.ForeColor = Color.White; - } - else - { - e.RowElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local); - e.RowElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local); - e.RowElement.ResetValue(LightVisualElement.NumberOfColorsProperty, ValueResetFlags.Local); - e.RowElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local); - } -} - -```` -````VB.NET -Private Sub RadGridView1_ViewRowFormatting(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.RowFormattingEventArgs) Handles RadGridView1.ViewRowFormatting - If TypeOf e.RowElement Is GridTableHeaderRowElement Then - e.RowElement.DrawFill = True - e.RowElement.BackColor = Color.Navy - e.RowElement.NumberOfColors = 1 - e.RowElement.ForeColor = Color.White - Else - e.RowElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local) - e.RowElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local) - e.RowElement.ResetValue(LightVisualElement.NumberOfColorsProperty, ValueResetFlags.Local) - e.RowElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local) - End If -End Sub - -```` - -{{endregion}} - + + ![WinForms RadGridView Customized Non-Data Rows](images/grid-rows-formatting-rows002.png) diff --git a/controls/gridview/visual-elements/rows/gridviewrowinfo.md b/controls/gridview/visual-elements/rows/gridviewrowinfo.md index 16b42f853..55d9278bc 100644 --- a/controls/gridview/visual-elements/rows/gridviewrowinfo.md +++ b/controls/gridview/visual-elements/rows/gridviewrowinfo.md @@ -39,27 +39,8 @@ The example below demonstrates the behavior of several of these properties: #### Using GridViewRowInfo -{{source=..\SamplesCS\GridView\Rows\GridViewRowInfo1.cs region=GridViewRowInfo}} -{{source=..\SamplesVB\GridView\Rows\GridViewRowInfo1.vb region=GridViewRowInfo}} - -````C# -GridViewRowInfo lastRow = radGridView1.Rows[radGridView1.Rows.Count - 1]; -lastRow.EnsureVisible(); -lastRow.IsSelected = true; -lastRow.Height = 100; -lastRow.AllowResize = false; - -```` -````VB.NET -Dim lastRow As GridViewRowInfo = RadGridView1.Rows(RadGridView1.Rows.Count - 1) -lastRow.EnsureVisible() -lastRow.IsSelected = True -lastRow.Height = 100 -lastRow.AllowResize = False - -```` - -{{endregion}} + + ### Difference between GridViewInfo.Rows and GridViewTemplate.Rows diff --git a/controls/gridview/visual-elements/rows/how-to/autosize-entire-row.md b/controls/gridview/visual-elements/rows/how-to/autosize-entire-row.md index 6f04f2489..fba3a6db6 100644 --- a/controls/gridview/visual-elements/rows/how-to/autosize-entire-row.md +++ b/controls/gridview/visual-elements/rows/how-to/autosize-entire-row.md @@ -18,138 +18,14 @@ In order to return the proper rows height to the grid you need to create a custo #### Sample implementation for the custom row element. -{{source=..\SamplesCS\GridView\Rows\AutoSizeWholeRows.cs region=RowElement}} -{{source=..\SamplesVB\GridView\Rows\AutoSizeWholeRows.vb region=RowElement}} -````C# -public class CustomRowElement : GridDataRowElement -{ - protected override Type ThemeEffectiveType - { - get - { - return typeof(GridDataRowElement); - } - } - protected override SizeF MeasureOverride(SizeF availableSize) - { - SizeF baseSize = base.MeasureOverride(availableSize); - CellElementProvider provider = new CellElementProvider(this.TableElement); - SizeF desiredSize = SizeF.Empty; - foreach (GridViewColumn column in this.ViewTemplate.Columns) - { - if (!this.IsColumnVisible(column)) - { - continue; - } - GridDataCellElement cellElement = provider.GetElement(column, this) as GridDataCellElement; - this.Children.Add(cellElement); - if (cellElement != null) - { - cellElement.Measure(new SizeF(column.Width, float.PositiveInfinity)); - if (desiredSize.Height < cellElement.DesiredSize.Height) - { - desiredSize.Height = cellElement.DesiredSize.Height; - } - } - cellElement.Detach(); - this.Children.Remove(cellElement); - } - SizeF elementSize = this.TableElement.RowScroller.ElementProvider.GetElementSize(this.RowInfo); - int oldHeight = RowInfo.Height == -1 ? (int)elementSize.Height : RowInfo.Height; - this.RowInfo.SuspendPropertyNotifications(); - this.RowInfo.Height = (int)desiredSize.Height; - this.RowInfo.ResumePropertyNotifications(); - if (!this.RowInfo.IsPinned) - { - int delta = RowInfo.Height - oldHeight; - TableElement.RowScroller.UpdateScrollRange(TableElement.RowScroller.Scrollbar.Maximum + delta, false); - } - baseSize.Height = this.RowInfo.Height; - return baseSize; - } - private bool IsColumnVisible(GridViewColumn column) - { - return column.IsVisible; - } -} - -```` -````VB.NET -Public Class CustomRowElement - Inherits GridDataRowElement - Protected Overrides ReadOnly Property ThemeEffectiveType() As Type - Get - Return GetType(GridDataRowElement) - End Get - End Property - Protected Overrides Function MeasureOverride(ByVal availableSize As SizeF) As SizeF - Dim baseSize As SizeF = MyBase.MeasureOverride(availableSize) - Dim provider As New CellElementProvider(Me.TableElement) - Dim desiredSize As SizeF = SizeF.Empty - For Each column As GridViewColumn In Me.ViewTemplate.Columns - If Not Me.IsColumnVisible(column) Then - Continue For - End If - Dim cellElement As GridDataCellElement = TryCast(provider.GetElement(column, Me), GridDataCellElement) - Me.Children.Add(cellElement) - If cellElement IsNot Nothing Then - cellElement.Measure(New SizeF(column.Width, Single.PositiveInfinity)) - If desiredSize.Height < cellElement.DesiredSize.Height Then - desiredSize.Height = cellElement.DesiredSize.Height - End If - End If - cellElement.Detach() - Me.Children.Remove(cellElement) - Next column - Dim elementSize As SizeF = Me.TableElement.RowScroller.ElementProvider.GetElementSize(Me.RowInfo) - Dim oldHeight As Integer = If(RowInfo.Height = -1, CInt(elementSize.Height), RowInfo.Height) - Me.RowInfo.SuspendPropertyNotifications() - Me.RowInfo.Height = CInt(desiredSize.Height) - Me.RowInfo.ResumePropertyNotifications() - If Not Me.RowInfo.IsPinned Then - Dim delta As Integer = RowInfo.Height - oldHeight - TableElement.RowScroller.UpdateScrollRange(TableElement.RowScroller.Scrollbar.Maximum + delta, False) - End If - baseSize.Height = Me.RowInfo.Height - Return baseSize - End Function - Private Function IsColumnVisible(ByVal column As GridViewColumn) As Boolean - Return column.IsVisible - End Function -End Class - -```` - -{{endregion}} - + + ### Using the custom row element. The final step is to replace the default row elements. This can be achieved in the __CreateRow__ event handler. -{{source=..\SamplesCS\GridView\Rows\AutoSizeWholeRows.cs region=ChangeRow}} -{{source=..\SamplesVB\GridView\Rows\AutoSizeWholeRows.vb region=ChangeRow}} - -````C# -void radGridView1_CreateRow(object sender, GridViewCreateRowEventArgs e) -{ - if (e.RowType == typeof(GridDataRowElement)) - { - e.RowType = typeof(CustomRowElement); - } -} - -```` -````VB.NET -Private Sub radGridView1_CreateRow(ByVal sender As Object, ByVal e As GridViewCreateRowEventArgs) - If e.RowType Is GetType(GridDataRowElement) Then - e.RowType = GetType(CustomRowElement) - End If -End Sub - -```` - -{{endregion}} - + + A complete solution which adds cached height is available in our [SDK repository](https://github.com/telerik/winforms-sdk/tree/master/GridView/AutoSizeEntireRow). diff --git a/controls/gridview/visual-elements/rows/iterating-rows.md b/controls/gridview/visual-elements/rows/iterating-rows.md index 86aefbdae..6e640967b 100644 --- a/controls/gridview/visual-elements/rows/iterating-rows.md +++ b/controls/gridview/visual-elements/rows/iterating-rows.md @@ -13,174 +13,30 @@ previous_url: gridview-rows-iterating-rows You can iterate through grid rows using the __Rows__ collection of __GridViewRowInfo__ objects. The example below selects the last row, then iterates looking for selected rows. When the selected row is found, the __GridViewRowInfo.EnsureVisible()__ method scrolls the row into the view: -{{source=..\SamplesCS\GridView\Rows\IteratingRows.cs region=iteratingRows}} -{{source=..\SamplesVB\GridView\Rows\IteratingRows.vb region=iteratingRows}} - -````C# -GridViewRowInfo lastRow1 = radGridView1.Rows[radGridView1.Rows.Count - 1]; -lastRow1.IsSelected = true; -foreach (GridViewRowInfo rowInfo in radGridView1.Rows) -{ - if (rowInfo.IsSelected) - { - rowInfo.EnsureVisible(); - } -} - -```` -````VB.NET -Dim lastRow As GridViewRowInfo = RadGridView1.Rows(RadGridView1.Rows.Count - 1) -lastRow.IsSelected = True -For Each rowInfo As GridViewRowInfo In RadGridView1.Rows - If rowInfo.IsSelected Then - rowInfo.EnsureVisible() - End If -Next - -```` - -{{endregion}} + + ## Finding a grid row by a value of one of its cells You could search for a specific value in __RadGridView__ by iterating through the rows and compare cells value. In the example below, you search for __searchedStr__ in __MyColumnName__ column: -{{source=..\SamplesCS\GridView\Rows\IteratingRows.cs region=findAGridRowByCellValue}} -{{source=..\SamplesVB\GridView\Rows\IteratingRows.vb region=findAGridRowByCellValue}} - -````C# -string searchedStr = "Picture 2"; -for (int r = 0; r < radGridView1.RowCount; r++) -{ - if (radGridView1.Rows[r].Cells["Picture Name"].Value.ToString().ToUpper().Equals(searchedStr.ToUpper())) - { - MessageBox.Show("Found a match"); - //do something - } -} - -```` -````VB.NET -Dim searchedStr As String = "Picture 2" -For row As Integer = 0 To RadGridView1.RowCount - 1 - If RadGridView1.Rows(row).Cells("Picture Name").Value.ToString().ToUpper().Equals(searchedStr.ToUpper()) Then - 'do something - MessageBox.Show("Found a match") - End If -Next - -```` - -{{endregion}} + + ## Iterating all rows in a self-reference hierarchy When you have a hierarchical grid with many templates you can use a recursive method to iterate trough all rows: -{{source=..\SamplesCS\GridView\Rows\IteratingRows.cs region=hierarchy}} -{{source=..\SamplesVB\GridView\Rows\IteratingRows.vb region=hierarchy}} - -````C# -public void IterateAllRows(IEnumerable rowsCollection) -{ - foreach (GridViewDataRowInfo row in rowsCollection) - { - Debug.WriteLine(row.Cells[0].Value);//This rows is used for demonstration only! - if (row.HasChildRows()) - { - IterateAllRows(row.ChildRows); - } - } -} - -```` -````VB.NET -Public Sub IterateAllRows(rowsCollection As IEnumerable(Of GridViewRowInfo)) - For Each row As GridViewDataRowInfo In rowsCollection - Debug.WriteLine(row.Cells(0).Value) - If row.HasChildRows() Then - IterateAllRows(row.ChildRows) - End If - Next -End Sub - -```` - -{{endregion}} - + + ## Iterating hierarchical grid. You can iterate through grid rows using the __Rows__ collection of __RadGridView__ objects. The example below cycles through the rows of the grid, modifies the values for certain cells in the different hierarchy levels and counts the rows and cells in the whole **RadGridView**. -{{source=..\SamplesCS\GridView\Rows\IteratingRows.cs region=IteratingHierarchicalRows}} -{{source=..\SamplesVB\GridView\Rows\IteratingRows.vb region=IteratingHierarchicalRows}} - -````C# -private void radButton1_Click(object sender, EventArgs e) -{ - int count = 0; - int i = 0; - foreach (GridViewDataRowInfo dataRow in this.GetAllRows(this.radGridView1.MasterTemplate)) - { - count++; - foreach (GridViewCellInfo cell in dataRow.Cells) - { - if (cell.ColumnInfo.Name == "CompanyName" || cell.ColumnInfo.Name == "ShipCountry") - { - cell.Value = "TEST"; - } - if (cell.ColumnInfo.Name == "UnitPrice") - { - cell.Value = 1.11111; - } - i++; - } - } -} -public List GetAllRows(GridViewTemplate template) -{ - List allRows = new List(); - allRows.AddRange(template.Rows); - foreach (GridViewTemplate childTemplate in template.Templates) - { - List childRows = this.GetAllRows(childTemplate); - allRows.AddRange(childRows); - } - return allRows; -} - -```` -````VB.NET -Private Sub radButton1_Click(sender As Object, e As EventArgs) - Dim count As Integer = 0 - Dim i As Integer = 0 - For Each dataRow As GridViewDataRowInfo In Me.GetAllRows(Me.RadGridView1.MasterTemplate) - count += 1 - For Each cell As GridViewCellInfo In dataRow.Cells - If cell.ColumnInfo.Name = "CompanyName" OrElse cell.ColumnInfo.Name = "ShipCountry" Then - cell.Value = "TEST" - End If - If cell.ColumnInfo.Name = "UnitPrice" Then - cell.Value = 1.11111 - End If - i += 1 - Next - Next -End Sub -Public Function GetAllRows(template As GridViewTemplate) As List(Of GridViewRowInfo) - Dim allRows As New List(Of GridViewRowInfo)() - allRows.AddRange(template.Rows) - For Each childTemplate As GridViewTemplate In template.Templates - Dim childRows As List(Of GridViewRowInfo) = Me.GetAllRows(childTemplate) - allRows.AddRange(childRows) - Next - Return allRows -End Function - -```` - -{{endregion}} + + + # See Also * [Adding and Inserting Rows]({%slug winforms/gridview/rows/adding-and-inserting-rows%}) diff --git a/controls/gridview/visual-elements/rows/new-row.md b/controls/gridview/visual-elements/rows/new-row.md index 1b81a3ca9..a1e2a4db0 100644 --- a/controls/gridview/visual-elements/rows/new-row.md +++ b/controls/gridview/visual-elements/rows/new-row.md @@ -19,36 +19,13 @@ previous_url: gridview-rows-new-row By default, the new row is visible to the end-user. You can explicitly set it to visible by setting the __AllowAddNewRow__ property to *true*: -{{source=..\SamplesCS\GridView\Rows\NewRow.cs region=enablingNewRow}} -{{source=..\SamplesVB\GridView\Rows\NewRow.vb region=enablingNewRow}} - -````C# -this.radGridView1.AllowAddNewRow = true; - -```` -````VB.NET -Me.RadGridView1.AllowAddNewRow = True - -```` - -{{endregion}} + + If you want to hide the `New Row`, just set the __AllowAddNewRow__ to *false* and RadGridView will look as shown below: -{{source=..\SamplesCS\GridView\Rows\NewRow.cs region=disablingNewRow}} -{{source=..\SamplesVB\GridView\Rows\NewRow.vb region=disablingNewRow}} - -````C# -this.radGridView1.AllowAddNewRow = false; - -```` -````VB.NET -Me.RadGridView1.AllowAddNewRow = False - -```` - -{{endregion}} - + + >note The GridViewTemplate.**SelectNewRowAsCurrent** property controls if the new row will be made current if there are no other rows in the grid. @@ -56,55 +33,20 @@ Me.RadGridView1.AllowAddNewRow = False For the text displayed in the new row of __RadGridView__ you have the option to set it directly to the corresponding template. This allows you to have a different text on the new row of each level of your hierarchical grid. -{{source=..\SamplesCS\GridView\Rows\NewRow.cs region=TemplateNewRowText}} -{{source=..\SamplesVB\GridView\Rows\NewRow.vb region=TemplateNewRowText}} - -````C# -this.radGridView1.MasterTemplate.NewRowText = "Click here to add a new category"; -this.radGridView1.MasterTemplate.Templates[0].NewRowText = "Click here to add a new product"; - -```` -````VB.NET -Me.RadGridView1.MasterTemplate.NewRowText = "Click here to add a new category" -Me.RadGridView1.MasterTemplate.Templates(0).NewRowText = "Click here to add a new product" - -```` - -{{endregion}} + + ## New Row Position The `New Row` can be pinned to top or bottom. By default, the new row is pinned to top. You can explicitly set its position to top by setting the __AddNewRowPosition__ to *Top*: -{{source=..\SamplesCS\GridView\Rows\NewRow.cs region=positionTop}} -{{source=..\SamplesVB\GridView\Rows\NewRow.vb region=positionTop}} - -````C# -this.radGridView1.AddNewRowPosition = SystemRowPosition.Top; - -```` -````VB.NET -Me.RadGridView1.AddNewRowPosition = SystemRowPosition.Top - -```` - -{{endregion}} + + In order to pin the new row to bottom, you should set the __AddNewRowPosition__ to *Bottom*: -{{source=..\SamplesCS\GridView\Rows\NewRow.cs region=positionBottom}} -{{source=..\SamplesVB\GridView\Rows\NewRow.vb region=positionBottom}} - -````C# -this.radGridView1.AddNewRowPosition = SystemRowPosition.Bottom; - -```` -````VB.NET -Me.RadGridView1.AddNewRowPosition = SystemRowPosition.Bottom - -```` - -{{endregion}} + + ![WinForms RadGridView New Row Position](images/gridview-rows-new-row003.png) @@ -112,19 +54,8 @@ Me.RadGridView1.AddNewRowPosition = SystemRowPosition.Bottom If you, for some reason, want to access the `New Row`, you can do it by getting the __TableAddNewRow__ object from the *view* you are in. Let's say that you want to programmatically make the `New Row` current. Here is how to do that for the main view: -{{source=..\SamplesCS\GridView\Rows\NewRow.cs region=makingNewRowCurrent}} -{{source=..\SamplesVB\GridView\Rows\NewRow.vb region=makingNewRowCurrent}} - -````C# -this.radGridView1.CurrentRow = this.radGridView1.MasterView.TableAddNewRow; - -```` -````VB.NET -Me.RadGridView1.CurrentRow = Me.RadGridView1.MasterView.TableAddNewRow - -```` - -{{endregion}} + + In case your RadGridView is data-bound, it will try to set the CurrentRow to the first data row after it is filled with data.Therefore, you have to set the CurrentRow to TableAddNewRow after you bind the grid (after the Fill call of the TableAdapter in case you are following the ADO.NET approach for data-binding). @@ -134,26 +65,8 @@ __DefaultValuesNeeded__ is one of the events that you will probably use in your Let's have a RadGridView instance bound to the Employees table of the Northwind database. We assume that most of the employees that will be added in the future will be "Sales Representative". Moreover, the headquarters of the company is located in London, so most probably the new employees will have London as their city. Taking these assumptions into considerations, we will subscribe to the DefaultValuesNeeded event and will set the "Sales Representative" for the Title column and London for the City column: -{{source=..\SamplesCS\GridView\Rows\NewRow.cs region=defaultValuesNeeded}} -{{source=..\SamplesVB\GridView\Rows\NewRow.vb region=defaultValuesNeeded}} - -````C# -void radGridView1_DefaultValuesNeeded(object sender, GridViewRowEventArgs e) -{ - e.Row.Cells["Title"].Value = "Sales Representative"; - e.Row.Cells["City"].Value = "London"; -} - -```` -````VB.NET -Private Sub RadGridView1_DefaultValuesNeeded(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewRowEventArgs) Handles RadGridView1.DefaultValuesNeeded - e.Row.Cells("Title").Value = "Sales Representative" - e.Row.Cells("City").Value = "London" -End Sub - -```` - -{{endregion}} + + As a result, when the end-user clicks the new row, the following values will be filled in for him: @@ -163,44 +76,15 @@ As a result, when the end-user clicks the new row, the following values will be It is possible to add default values in all of the fields. However, by default you cannot add the row if no cells are changed. Since **R2 2017 SP1** this can be achieved by setting the __AddWithDefaultValues__ property. The following code snippet demonstrates how you can access and set this property: -{{source=..\SamplesCS\GridView\Rows\NewRow.cs region=AddOnlyDefault}} -{{source=..\SamplesVB\GridView\Rows\NewRow.vb region=AddOnlyDefault}} -````C# -private void RadGridView1_DefaultValuesNeeded(object sender, GridViewRowEventArgs e) -{ - var args = e as DefaultValuesNeededEventArgs; - args.AddWithDefaultValues = true; -} - -```` -````VB.NET -Private Sub RadGridView1_DefaultValuesNeeded1(ByVal sender As Object, ByVal e As GridViewRowEventArgs) - Dim args = TryCast(e, DefaultValuesNeededEventArgs) - args.AddWithDefaultValues = True -End Sub - -```` - - -{{endregion}} + + ## Adding rows to the underlying data source In some cases, you may need RadGridView to create a record in the underlying data source after the end-user commits the new row. In other cases, you may want to have a new record created immediately after the end-user starts editing the new row. RadGridView supports both modes. The behavior of RadGridView in this situation is determined by the __AddNewBoundRowBeforeEdit__property: -{{source=..\SamplesCS\GridView\Rows\NewRow.cs region=addNewBoundRowBeforeEdit}} -{{source=..\SamplesVB\GridView\Rows\NewRow.vb region=addNewBoundRowBeforeEdit}} - -````C# -this.radGridView1.MasterTemplate.AddNewBoundRowBeforeEdit = true; - -```` -````VB.NET -Me.RadGridView1.MasterTemplate.AddNewBoundRowBeforeEdit = True - -```` - -{{endregion}} + + As you can see in the code snippet above, __AddNewBoundRowBeforeEdit__ is a boolean property and here is what RadGridView does depending on its values: @@ -213,20 +97,8 @@ As you can see in the code snippet above, __AddNewBoundRowBeforeEdit__ is a bool The `Enter` key may behave differently in the new row depending on the value of the __NewRowEnterKeyMode__ property. By default, when the end-user presses `Enter` while being in the new row, the new row is committed, and the row next to the new row becomes current. Here is how the default value can be set explicitly: -{{source=..\SamplesCS\GridView\Rows\NewRow.cs region=enterMovesToNextRow}} -{{source=..\SamplesVB\GridView\Rows\NewRow.vb region=enterMovesToNextRow}} - -````C# -this.radGridView1.NewRowEnterKeyMode = RadGridViewNewRowEnterKeyMode.EnterMovesToNextRow; - -```` -````VB.NET -Me.RadGridView1.NewRowEnterKeyMode = RadGridViewNewRowEnterKeyMode.EnterMovesToNextRow - -```` - -{{endregion}} - + + The rest of the values available to the __NewRowEnterKeyMode__ property are: @@ -245,98 +117,20 @@ In the examples below we will demonstrate what you can do by using the UserAddin __UserAddingRow__ Let's say that the Address column should allow no more than 30 characters per cell. If the end-user types 40 characters in the Address cell of the new row and tries to commit this row, he will get a warning message box that the length of his input exceeds the allowed one, and the new row will not be committed. This can be achieved with the following code snippet: -{{source=..\SamplesCS\GridView\Rows\NewRow.cs region=userAddingRow}} -{{source=..\SamplesVB\GridView\Rows\NewRow.vb region=userAddingRow}} - -````C# -void radGridView1_UserAddingRow(object sender, GridViewRowCancelEventArgs e) -{ - if (e.Rows[0].Cells["Address"].Value != null) - { - if (e.Rows[0].Cells["Address"].Value.ToString().Length > 30) - { - RadMessageBox.Show("The text in the Address field is long. Please provide shorter address."); - e.Cancel = true; - } - } -} - -```` -````VB.NET -Private Sub RadGridView1_UserAddingRow(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewRowCancelEventArgs) Handles RadGridView1.UserAddingRow - If e.Rows(0).Cells("Address").Value IsNot Nothing Then - If e.Rows(0).Cells("Address").Value.ToString().Length > 30 Then - RadMessageBox.Show("The text in the Address field is long. Please provide shorter address.") - e.Cancel = True - End If - End If -End Sub - -```` - -{{endregion}} + + __UserAddedRow__ This event comes in handy when you want to update your data base right after the end-user has added a new row. Assuming that we are following the standard ADO.NET approach (DataTable\TableAdapter), in the following example we take the row that the end-user has just added, and we process it to the data base, by passing the row to the Update method of the TableAdapter: -{{source=..\SamplesCS\GridView\Rows\NewRow.cs region=userAddedRow}} -{{source=..\SamplesVB\GridView\Rows\NewRow.vb region=userAddedRow}} - -````C# -void radGridView1_UserAddedRow(object sender, GridViewRowEventArgs e) -{ - DataRow[] rows = new DataRow[e.Rows.Length]; - for (int i = 0; i < e.Rows.Length; i++) - { - DataRowView dataRowView = e.Rows[i].DataBoundItem as DataRowView; - if (dataRowView != null) - { - rows[i] = dataRowView.Row; - } - } - this.employeesTableAdapter.Update(rows); -} - -```` -````VB.NET -Private Sub RadGridView1_UserAddedRow(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewRowEventArgs) Handles RadGridView1.UserAddedRow - Dim rows(e.Rows.Length - 1) As DataRow - For i As Integer = 0 To e.Rows.Length - 1 - Dim dataRowView As DataRowView = TryCast(e.Rows(i).DataBoundItem, DataRowView) - If dataRowView IsNot Nothing Then - rows(i) = dataRowView.Row - End If - Next i - Me.EmployeesTableAdapter.Update(rows) -End Sub - -```` - -{{endregion}} + + ## Cancel Add New Row Generally, the user can cancel adding or editing a row by pressing the escape key. However, in a case the user is editing a new row, to cancel adding a new row, the Escape button need to be pressed twice. The first Escape cancels cell edit and the second one cancels the whole process of adding new row. If this behavior does not meet your requirement, you can easily customize the behavior through adding a [GridViewCommandColumn]({%slug winforms/gridview/columns/column-types/gridviewcommandcolumn%}). By subscribing to the __CommandCellClick__ event of the RadGridView, you can call the __CancelAddNewRow()__ of the __TableAddNewRow__ property. The following sample snippet demonstrate the event handler of the customization. -{{source=..\SamplesCS\GridView\Rows\NewRow.cs region=CancelAddNewRow}} -{{source=..\SamplesVB\GridView\Rows\NewRow.vb region=CancelAddNewRow}} - -````C# -private void RadGridView1_CommandCellClick(object sender, GridViewCellEventArgs e) -{ - this.radGridView1.MasterView.TableAddNewRow.CancelAddNewRow(); -} - -```` -````VB.NET -Private Sub RadGridView1_CommandCellClick(ByVal sender As Object, ByVal e As GridViewCellEventArgs) - Me.RadGridView1.MasterView.TableAddNewRow.CancelAddNewRow() -End Sub - -```` - -{{endregion}} - - + + # See Also * [Adding and Inserting Rows]({%slug winforms/gridview/rows/adding-and-inserting-rows%}) diff --git a/controls/gridview/visual-elements/rows/painting-rows.md b/controls/gridview/visual-elements/rows/painting-rows.md index b729139d6..339d9c67f 100644 --- a/controls/gridview/visual-elements/rows/painting-rows.md +++ b/controls/gridview/visual-elements/rows/painting-rows.md @@ -13,19 +13,8 @@ previous_url: gridview-rows-painting-rows __RowPaint__ event occurs when a row needs to be painted. If you want to allow the event to fire, you should set the __EnableCustomDrawing__ to *true*. The scenario for using the __RowPaint__ event is applied when you want to apply custom painting to extend the row appearance. -{{source=..\SamplesCS\GridView\Rows\RowPainting.cs region=enableCustomDrawing}} -{{source=..\SamplesVB\GridView\Rows\RowPainting.vb region=enableCustomDrawing}} - -````C# -radGridView1.EnableCustomDrawing = true; - -```` -````VB.NET -RadGridView1.EnableCustomDrawing = True - -```` - -{{endregion}} + + The following example demonstrates how to use the __RowPaint__ event to set up the row appearance depending on *"UnitsInStock"* cell value. If the cell value is more than *20*, no custom painting is applied and the row is drawn as it is by default. Otherwise an additional border is drawn inside the row to show that this product units in stock is getting lower (less than *20*). @@ -34,49 +23,8 @@ The following example demonstrates how to use the __RowPaint__ event to set up t #### Paint border when specific criteria is met. -{{source=..\SamplesCS\GridView\Rows\RowPainting.cs region=handlingRowPaint}} -{{source=..\SamplesVB\GridView\Rows\RowPainting.vb region=handlingRowPaint}} - -````C# -private void radGridView1_RowPaint(object sender, GridViewRowPaintEventArgs e) -{ - GridDataRowElement dataRow = e.Row as GridDataRowElement; - if (dataRow != null) - { - double value = Convert.ToDouble(dataRow.RowInfo.Cells["UnitsInStock"].Value); - if (value > 20) - { - return; - } - Pen pen = value < 0 ? Pens.Purple : Pens.RoyalBlue; - Size rowSize = dataRow.Size; - rowSize.Height -= 6; - rowSize.Width -= 5; - e.Graphics.DrawRectangle(pen, new Rectangle(new Point(2, 2), rowSize)); - } -} - -```` -````VB.NET -Private Sub radGridView1_RowPaint(ByVal sender As Object, ByVal e As GridViewRowPaintEventArgs) Handles RadGridView1.RowPaint - Dim dataRow As GridDataRowElement = TryCast(e.Row, GridDataRowElement) - If dataRow IsNot Nothing Then - Dim value As Integer = Convert.ToInt32(dataRow.RowInfo.Cells("UnitsInStock").Value) - If value > 20 Then - Return - End If - Dim pen As Pen = If(value < 0, Pens.Purple, Pens.RoyalBlue) - Dim rowSize As Size = dataRow.Size - rowSize.Height -= 6 - rowSize.Width -= 5 - e.Graphics.DrawRectangle(pen, New Rectangle(New Point(2, 2), rowSize)) - End If -End Sub - -```` - -{{endregion}} - + + ![WinForms RadGridView Draw Rect Around the Row](images/gridview-rows-painting-rows001.png) # See Also diff --git a/controls/gridview/visual-elements/rows/pinned-rows.md b/controls/gridview/visual-elements/rows/pinned-rows.md index 79bf4e7f4..ca38113da 100644 --- a/controls/gridview/visual-elements/rows/pinned-rows.md +++ b/controls/gridview/visual-elements/rows/pinned-rows.md @@ -13,60 +13,20 @@ previous_url: gridview-rows-pinned-rows RadGridView rows can be pinned so that the rows appear anchored to the top or bottom of the grid. To pin a particular row, set the row __PinPosition__ to one of the enumerated options -PinnedRowPosition.__Bottom__ or PinnedRowPosition.__Top__: -{{source=..\SamplesCS\GridView\Rows\PinnedRows.cs region=pinnedRows}} -{{source=..\SamplesVB\GridView\Rows\PinnedRows.vb region=pinnedRows}} - -````C# -radGridView1.Rows[0].PinPosition = PinnedRowPosition.Bottom; -radGridView1.Rows[4].PinPosition = PinnedRowPosition.Top; - -```` -````VB.NET -RadGridView1.Rows(0).PinPosition = PinnedRowPosition.Bottom -RadGridView1.Rows(4).PinPosition = PinnedRowPosition.Top - -```` - -{{endregion}} + + By using this code the __IsPinned__ property automatically gets a value true for the desired row. Another way of pinning a row is to set directly the __IsPinned__ property of a Rows collection item to True. Please note that doing so will pin the row to the top of RadGridView. -{{source=..\SamplesCS\GridView\Rows\PinnedRows.cs region=isPinned}} -{{source=..\SamplesVB\GridView\Rows\PinnedRows.vb region=isPinned}} - -````C# -radGridView1.Rows[3].IsPinned = true; - -```` -````VB.NET -RadGridView1.Rows(3).IsPinned = True - -```` - -{{endregion}} + + The example below shows pinning all selected rows in the grid: -{{source=..\SamplesCS\GridView\Rows\PinnedRows.cs region=pinAllRows}} -{{source=..\SamplesVB\GridView\Rows\PinnedRows.vb region=pinAllRows}} - -````C# -foreach (GridViewRowInfo row in radGridView1.SelectedRows) -{ - row.PinPosition = PinnedRowPosition.Bottom; -} - -```` -````VB.NET -For Each row In RadGridView1.SelectedRows - row.PinPosition = PinnedRowPosition.Bottom -Next - -```` - -{{endregion}} + + __RadGridView__ rows can be pinned so that the rows appear anchored to the top of the grid. To pin a particular row, set the __IsPinned__ property of a __Rows__ collection item to *true*. diff --git a/controls/gridview/visual-elements/rows/removing-rows.md b/controls/gridview/visual-elements/rows/removing-rows.md index f5144b8dc..c1fd4da08 100644 --- a/controls/gridview/visual-elements/rows/removing-rows.md +++ b/controls/gridview/visual-elements/rows/removing-rows.md @@ -15,73 +15,29 @@ In order to remove a single row from __RadGridView__, you should simply call the #### Remove Row -{{source=..\SamplesCS\GridView\Rows\RemovingRows.cs region=removeRow}} -{{source=..\SamplesVB\GridView\Rows\RemovingRows.vb region=removeRow}} - -````C# -this.radGridView1.Rows.Remove(rowToRemove); - -```` -````VB.NET -Me.RadGridView1.Rows.Remove(rowToRemove) - -```` - -{{endregion}} + + If you want to remove a row at a specific position, call __RemoveAt__ method and pass the row index. #### Remove Row With Index -{{source=..\SamplesCS\GridView\Rows\RemovingRows.cs region=removeRowAt}} -{{source=..\SamplesVB\GridView\Rows\RemovingRows.vb region=removeRowAt}} - -````C# -this.radGridView1.Rows.RemoveAt(0); - -```` -````VB.NET -Me.RadGridView1.Rows.RemoveAt(0) - -```` - -{{endregion}} + + As to removing all rows, make a loop and remove the rows with the __RemoveAt__ method. Note: If your __RadGridView__ is bound to a __BindingList__, the __BindingList__ will be updated automatically. However, if __RadGridView__ is bound to data set, you should call the __Update__ method. Here is an example with the NorthWind data set and its `carsTableAdapter` #### Update Adapter -{{source=..\SamplesCS\GridView\Rows\RemovingRows.cs region=callingUpdate}} -{{source=..\SamplesVB\GridView\Rows\RemovingRows.vb region=callingUpdate}} - -````C# -this.carsTableAdapter.Update(this.nwindDataSet.Cars); - -```` -````VB.NET -Me.CarsTableAdapter.Update(Me.NwindDataSet.Cars) - -```` - -{{endregion}} + + An alternative to removing all the rows would be to use the __Clear__ method of the Rows collection as it will be a more efficient solution since the grid's events will be suspended and you will write less code: #### Clearing Rows -{{source=..\SamplesCS\GridView\Rows\RemovingRows.cs region=clearRows}} -{{source=..\SamplesVB\GridView\Rows\RemovingRows.vb region=clearRows}} - -````C# -this.radGridView1.Rows.Clear(); - -```` -````VB.NET -Me.RadGridView1.Rows.Clear() - -```` - -{{endregion}} + + # See Also diff --git a/controls/gridview/visual-elements/rows/reordering-system-rows.md b/controls/gridview/visual-elements/rows/reordering-system-rows.md index 654767ab3..8ebe093e8 100644 --- a/controls/gridview/visual-elements/rows/reordering-system-rows.md +++ b/controls/gridview/visual-elements/rows/reordering-system-rows.md @@ -33,25 +33,8 @@ In order to perform system rows reordering, you can use the RadGridView.MasterVi #### Reordering System Rows -{{source=..\SamplesCS\GridView\Rows\ReorderingSystemRows.cs region=ReorderingSystemRows}} -{{source=..\SamplesVB\GridView\Rows\ReorderingSystemRows.vb region=ReorderingSystemRows}} - -````C# -this.radGridView1.MasterView.SystemRows.Move(1, 2); -this.radGridView1.MasterView.SystemRows.Move(2, 3); -this.radGridView1.GridViewElement.TableElement.InvalidateMeasure(true); -this.radGridView1.GridViewElement.TableElement.UpdateLayout(); - -```` -````VB.NET -Me.RadGridView1.MasterView.SystemRows.Move(1, 2) -Me.RadGridView1.MasterView.SystemRows.Move(2, 3) -Me.RadGridView1.GridViewElement.TableElement.InvalidateMeasure(True) -Me.RadGridView1.GridViewElement.TableElement.UpdateLayout() - -```` - -{{endregion}} + + >note The layout needs to be invalidated and updated in order to reflect the changes. > diff --git a/controls/gridview/visual-elements/rows/resizing-rows.md b/controls/gridview/visual-elements/rows/resizing-rows.md index e3886e74e..a0578b074 100644 --- a/controls/gridview/visual-elements/rows/resizing-rows.md +++ b/controls/gridview/visual-elements/rows/resizing-rows.md @@ -23,9 +23,6 @@ previous_url: gridview-rows-resizing-rows Me.RadGridView1.TableElement.RowHeight = 50 ```` - -{{endregion}} - ![WinForms RadGridView Resized Rows](images/row-resizing001.png) >note **GridViewRowInfo** offers three properties that allow you specifying the height of an individual data row: **Height**, **MinHeight**, **MaxHeight**. It controls the current height of the row, its minimum and maximum height respectively. @@ -42,9 +39,6 @@ this.radGridView1.TableElement.SearchRowHeight = 50; Me.RadGridView1.TableElement.SearchRowHeight = 50 ```` - -{{endregion}} - ![WinForms RadGridView Search Row Height](images/row-resizing002.png) #### New Row Height @@ -57,9 +51,6 @@ this.radGridView1.MasterView.TableAddNewRow.Height = 50; Me.RadGridView1.MasterView.TableAddNewRow.Height = 50 ```` - -{{endregion}} - ![WinForms RadGridView New Row Height](images/row-resizing003.png) #### TableHeader Height @@ -72,9 +63,6 @@ this.radGridView1.TableElement.TableHeaderHeight = 50; Me.RadGridView1.TableElement.TableHeaderHeight = 50 ```` - -{{endregion}} - ![WinForms RadGridView TableHeader Height](images/row-resizing004.png) #### Pinned Row Height @@ -93,9 +81,6 @@ Me.RadGridView1.Rows(2).IsPinned = True Me.RadGridView1.MasterView.PinnedRows(1).Height = 50 ```` - -{{endregion}} - ![WinForms RadGridView Pinned Row Height](images/row-resizing005.png) #### Filtering Row Height @@ -110,9 +95,6 @@ Me.RadGridView1.MasterTemplate.EnableFiltering = True Me.RadGridView1.TableElement.FilterRowHeight = 50 ```` - -{{endregion}} - ![WinForms RadGridView Filtering Row Height](images/row-resizing006.png) #### Group Header Height @@ -125,9 +107,6 @@ this.radGridView1.TableElement.GroupHeaderHeight = 50; Me.RadGridView1.TableElement.GroupHeaderHeight = 50 ```` - -{{endregion}} - ![WinForms RadGridView Group Header Height](images/row-resizing007.png) #### Summary Row Height @@ -139,9 +118,6 @@ this.radGridView1.MasterView.SummaryRows[0].Height = 50; Me.RadGridView1.MasterView.SummaryRows(0).Height = 50 ```` - -{{endregion}} - ![WinForms RadGridView Summary Row Height](images/row-resizing008.png) # See Also diff --git a/controls/gridview/visual-elements/rows/row-behaviors.md b/controls/gridview/visual-elements/rows/row-behaviors.md index d0a0d1b0a..8b2b26fac 100644 --- a/controls/gridview/visual-elements/rows/row-behaviors.md +++ b/controls/gridview/visual-elements/rows/row-behaviors.md @@ -29,265 +29,30 @@ By implementing a specific custom row behavior, developers can change the defaul Let’s start with constructing a hierarchical __RadGridView__ and populate it with data. -{{source=..\SamplesCS\GridView\Rows\RowBehaviorsForm.cs region=FillHierarchicalData}} -{{source=..\SamplesVB\GridView\Rows\RowBehaviorsForm.vb region=FillHierarchicalData}} - -````C# - -public RowBehaviorsForm() -{ - InitializeComponent(); - - //Fill data - DataTable items = new DataTable("Items"); - items.Columns.Add("Id", typeof(int)); - items.Columns.Add("Title", typeof(string)); - items.Columns.Add("IsActive", typeof(bool)); - - DataTable subItems = new DataTable("SubItems"); - subItems.Columns.Add("Id", typeof(int)); - subItems.Columns.Add("Name", typeof(string)); - subItems.Columns.Add("ItemId", typeof(int)); - - for (int i = 1; i <= 3; i++) - { - items.Rows.Add(i, "Item" + i, i % 2 == 0); - - for (int j = 1000; j <= 1005; j++) - { - subItems.Rows.Add(j, "SubItem" + j, i); - } - } - - //Set up grid hierarchy - radGridView1.DataSource = items; - radGridView1.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill; - - GridViewTemplate template = new GridViewTemplate(); - template.ReadOnly = true; - template.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill; - - GridViewRelation relation = new GridViewRelation(radGridView1.MasterTemplate, template); - relation.ParentColumnNames.Add("Id"); - relation.ChildColumnNames.Add("ItemId"); - radGridView1.MasterTemplate.Templates.Add(template); - radGridView1.Relations.Add(relation); - template.ReadOnly = false; - template.DataSource = subItems; -} - -```` -````VB.NET -Sub New() - InitializeComponent() - 'Fill data - Dim items As New DataTable("Items") - items.Columns.Add("Id", GetType(Integer)) - items.Columns.Add("Title", GetType(String)) - items.Columns.Add("IsActive", GetType(Boolean)) - Dim subItems As New DataTable("SubItems") - subItems.Columns.Add("Id", GetType(Integer)) - subItems.Columns.Add("Name", GetType(String)) - subItems.Columns.Add("ItemId", GetType(Integer)) - For i As Integer = 1 To 3 - items.Rows.Add(i, "Item" & i, i Mod 2 = 0) - For j As Integer = 1000 To 1005 - subItems.Rows.Add(j, "SubItem" & j, i) - Next - Next - 'Set up grid hierarchy - RadGridView1.DataSource = items - RadGridView1.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill - Dim template As New GridViewTemplate() - template.[ReadOnly] = True - template.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill - Dim relation As New GridViewRelation(RadGridView1.MasterTemplate, template) - relation.ParentColumnNames.Add("Id") - relation.ChildColumnNames.Add("ItemId") - RadGridView1.MasterTemplate.Templates.Add(template) - RadGridView1.Relations.Add(relation) - template.[ReadOnly] = False - template.DataSource = subItems -End Sub - -```` - -{{endregion}} - - - + + By default, when the user hits the __Delete__ key over a certain row, the row is deleted. We will extend this functionality by notifying the user when he tries to delete a parent row, which __ChildRows__ collection is not empty. For this purpose, it is necessary to create a custom grid behavior. To do this, create a new class named __CustomGridHierarchyRowBehavior__. As we are currently using a hierarchical grid, our class should inherit the __GridHierarchyRowBehavior__. Override the __ProcessDeleteKey__ method in order to display a MessageBox and proceed with the delete operation after confirmation only:
![WinForms RadGridView Using Custom Behavior](images/gridview-rows-row-behaviors001.gif) -{{source=..\SamplesCS\GridView\Rows\RowBehaviorsForm.cs region=ProcessDeleteKey}} -{{source=..\SamplesVB\GridView\Rows\RowBehaviorsForm.vb region=ProcessDeleteKey}} - -````C# - -public class CustomGridHierarchyRowBehavior : GridHierarchyRowBehavior -{ - protected override bool ProcessDeleteKey(KeyEventArgs keys) - { - if (this.GridControl.CurrentRow.ChildRows.Count > 0) - { - DialogResult result = MessageBox.Show("The current row has child rows." + - "Are you sure you want to delete the selected row?", "Confirmation", MessageBoxButtons.YesNo); - if (result == DialogResult.No) - { - return true; - } - } - - return base.ProcessDeleteKey(keys); - } -} - -```` -````VB.NET -Public Class CustomGridHierarchyRowBehavior -Inherits GridHierarchyRowBehavior - Protected Overrides Function ProcessDeleteKey(keys As KeyEventArgs) As Boolean - If Me.GridControl.CurrentRow.ChildRows.Count > 0 Then - Dim result As DialogResult = MessageBox.Show("The current row has child rows." & "Are you sure you want to delete the selected row?", "Confirmation", MessageBoxButtons.YesNo) - If result = DialogResult.No Then - Return True - End If - End If - Return MyBase.ProcessDeleteKey(keys) - End Function -End Class - -```` - -{{endregion}} - - - + + Next we will register this behavior in our grid. Add the following code after populating the grid with data: -{{source=..\SamplesCS\GridView\Rows\RowBehaviorsForm.cs region=RegisterBehavior}} -{{source=..\SamplesVB\GridView\Rows\RowBehaviorsForm.vb region=RegisterBehavior}} - -````C# - -//register the custom row behavior -BaseGridBehavior gridBehavior = radGridView1.GridBehavior as BaseGridBehavior; -gridBehavior.UnregisterBehavior(typeof(GridViewHierarchyRowInfo)); -gridBehavior.RegisterBehavior(typeof(GridViewHierarchyRowInfo), new CustomGridHierarchyRowBehavior()); - -```` -````VB.NET -'register the custom row behavior -Dim gridBehavior As BaseGridBehavior = TryCast(RadGridView1.GridBehavior, BaseGridBehavior) -gridBehavior.UnregisterBehavior(GetType(GridViewHierarchyRowInfo)) -gridBehavior.RegisterBehavior(GetType(GridViewHierarchyRowInfo), New CustomGridHierarchyRowBehavior()) - -```` - -{{endregion}} - - - + + The next modification we are going to introduce is to override the __OnMouseDownLeft__ method and show the context menu for the __GridCheckBoxCellElement__, associated with the mouse location. First, it is necessary to use the grid navigator to process selection of the cell element, positioned at the mouse location. Afterwards, show the context menu for the specific cell: -{{source=..\SamplesCS\GridView\Rows\RowBehaviorsForm.cs region=MouseDownLeft}} -{{source=..\SamplesVB\GridView\Rows\RowBehaviorsForm.vb region=MouseDownLeft}} - -````C# - -protected override bool OnMouseDownLeft(MouseEventArgs e) -{ - GridCellElement cellElement = this.GetCellAtPoint(e.Location); - if (cellElement != null && cellElement is GridCheckBoxCellElement) - { - GridRowElement rowElement = cellElement.RowElement; - this.Navigator.BeginSelection(this.GetMouseNavigationContext(e)); - this.Navigator.Select(rowElement.RowInfo, cellElement.ColumnInfo); - this.Navigator.EndSelection(); - - if (!cellElement.IsInValidState(true)) - { - cellElement = this.GetCellAtPoint(e.Location); - } - if (cellElement != null) - { - GridViewElement.ContextMenuManager.ShowContextMenu(cellElement); - } - return true; - } - - return base.OnMouseDownLeft(e); -} - -```` -````VB.NET -Protected Overrides Function OnMouseDownLeft(e As MouseEventArgs) As Boolean - Dim cellElement As GridCellElement = Me.GetCellAtPoint(e.Location) - If cellElement IsNot Nothing AndAlso TypeOf cellElement Is GridCheckBoxCellElement Then - Dim rowElement As GridRowElement = cellElement.RowElement - Me.Navigator.BeginSelection(Me.GetMouseNavigationContext(e)) - Me.Navigator.[Select](rowElement.RowInfo, cellElement.ColumnInfo) - Me.Navigator.EndSelection() - If Not cellElement.IsInValidState(True) Then - cellElement = Me.GetCellAtPoint(e.Location) - End If - If cellElement IsNot Nothing Then - GridViewElement.ContextMenuManager.ShowContextMenu(cellElement) - End If - Return True - End If - Return MyBase.OnMouseDownLeft(e) -End Function - -```` - -{{endregion}} - + + ![WinForms RadGridView Show Context Menu](images/gridview-rows-row-behaviors002.png) __RadGridView__ supports rows/cells navigation by default, using the arrow keys. It is possible to customize this behavior as well. In the __CustomGridHierarchyRowBehavior__ class override the __ProcessKey__ method and stop the base grid logic for navigation upwards/downwards if the current row belongs to the __MasterTemplate__ and its *“IsActive”* cell value is set to *false*: -{{source=..\SamplesCS\GridView\Rows\RowBehaviorsForm.cs region=ProcessKey}} -{{source=..\SamplesVB\GridView\Rows\RowBehaviorsForm.vb region=ProcessKey}} - -````C# - -public override bool ProcessKey(KeyEventArgs keys) -{ - if (keys.KeyCode == Keys.Up || keys.KeyCode == Keys.Down) - { - DataRowView rowView = this.GridControl.CurrentRow.DataBoundItem as DataRowView; - if (rowView != null && this.GridControl.CurrentRow.ViewTemplate == this.MasterTemplate) - { - if ((bool)rowView.Row["IsActive"] == false) - { - return true; - } - } - } - return base.ProcessKey(keys); -} - -```` -````VB.NET -Public Overrides Function ProcessKey(keys__1 As KeyEventArgs) As Boolean - If keys__1.KeyCode = Keys.Up OrElse keys__1.KeyCode = Keys.Down Then - Dim rowView As DataRowView = TryCast(Me.GridControl.CurrentRow.DataBoundItem, DataRowView) - If rowView IsNot Nothing AndAlso Me.GridControl.CurrentRow.ViewTemplate.Equals(Me.MasterTemplate) Then - If CBool(rowView.Row("IsActive")) = False Then - Return True - End If - End If - End If - Return MyBase.ProcessKey(keys__1) -End Function - -```` - -{{endregion}} + + Following the demonstrated approach, developers can customize not only the hierarchy rows, but the new row for example, implementing a custom __GridNewRowBehavior__ and registering it for the __GridViewNewRowInfo__. # See Also diff --git a/controls/gridview/visual-elements/rows/rows-vs-childrows.md b/controls/gridview/visual-elements/rows/rows-vs-childrows.md index 1e9eb7159..e3b8888bd 100644 --- a/controls/gridview/visual-elements/rows/rows-vs-childrows.md +++ b/controls/gridview/visual-elements/rows/rows-vs-childrows.md @@ -25,73 +25,13 @@ Let's start with a RadGridView bound to the `Employees` data table of the well-k 1\. First, let's add the columns: -{{source=..\SamplesCS\GridView\Rows\RowsChildRows.cs region=addingColumn}} -{{source=..\SamplesVB\GridView\Rows\RowsChildRows.vb region=addingColumn}} - -````C# -GridViewTextBoxColumn rowsIDColumn = new GridViewTextBoxColumn(); -rowsIDColumn.HeaderText = "Rows IDs"; -rowsIDColumn.Name = "RowsIDs"; -this.radGridView1.Columns.Add(rowsIDColumn); -GridViewTextBoxColumn childRowsIDColumn = new GridViewTextBoxColumn(); -childRowsIDColumn.HeaderText = "ChildRows IDs"; -childRowsIDColumn.Name = "ChildRowsIDs"; -this.radGridView1.Columns.Add(childRowsIDColumn); - -```` -````VB.NET -Dim rowsIDColumn As New GridViewTextBoxColumn() -rowsIDColumn.HeaderText = "Rows IDs" -rowsIDColumn.Name = "RowsIDs" -Me.RadGridView1.Columns.Add(rowsIDColumn) -Dim childRowsIDColumn As New GridViewTextBoxColumn() -childRowsIDColumn.HeaderText = "ChildRows IDs" -childRowsIDColumn.Name = "ChildRowsIDs" -Me.RadGridView1.Columns.Add(childRowsIDColumn) - -```` - -{{endregion}} + + 2\. Then, let's fill these columns with integers based on the order of the rows in the __Rows__ and the __ChildRows__ collections: -{{source=..\SamplesCS\GridView\Rows\RowsChildRows.cs region=fillingColumns}} -{{source=..\SamplesVB\GridView\Rows\RowsChildRows.vb region=fillingColumns}} - -````C# -private void radButton1_Click(object sender, EventArgs e) -{ - SetIDs(); -} -private void SetIDs() -{ - for (int i = 0; i < this.radGridView1.Rows.Count; i++) - { - this.radGridView1.Rows[i].Cells["RowsIDs"].Value = i.ToString(); - } - for (int i = 0; i < this.radGridView1.ChildRows.Count; i++) - { - this.radGridView1.ChildRows[i].Cells["ChildRowsIDs"].Value = i.ToString(); - } -} - -```` -````VB.NET -Private Sub radButton1_Click(ByVal sender As Object, ByVal e As EventArgs) - SetIDs() -End Sub -Private Sub SetIDs() - For i As Integer = 0 To Me.RadGridView1.Rows.Count - 1 - Me.RadGridView1.Rows(i).Cells("RowsIDs").Value = i.ToString() - Next i - For i As Integer = 0 To Me.RadGridView1.ChildRows.Count - 1 - Me.RadGridView1.ChildRows(i).Cells("ChildRowsIDs").Value = i.ToString() - Next i -End Sub - -```` - -{{endregion}} + + ![WinForms RadGridView Populating the Grid](images/gridview-rows-rows-vs-childrows001.png) @@ -100,25 +40,8 @@ As you can see in the screenshot above, in a grid with no data operations applie 3\. Let's now filter RadGridView. For example, let's type 'rep' in the Title column. RadGridView will return only those rows which have the value 'Sales Representative' in their Title cells. When the filter data operation occurs, the FilterChanged event is fired, and in its event handler we refill our two columns with indices using the same method that we used before - SetIDs(). -{{source=..\SamplesCS\GridView\Rows\RowsChildRows.cs region=filterChanged}} -{{source=..\SamplesVB\GridView\Rows\RowsChildRows.vb region=filterChanged}} - -````C# -void radGridView1_FilterChanged(object sender, Telerik.WinControls.UI.GridViewCollectionChangedEventArgs e) -{ - SetIDs(); -} - -```` -````VB.NET -Private Sub radGridView1_FilterChanged(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewCollectionChangedEventArgs) - SetIDs() -End Sub - -```` - -{{endregion}} - + + ![WinForms RadGridView Filter the Control](images/gridview-rows-rows-vs-childrows002.png) @@ -127,24 +50,8 @@ As you can see in the screenshot above, the indices of the rows do not match any 4\. Let's now sort the records that we get from Step 3 by sorting by the First Name column. The `SortChanged` event is fired and we refill the two custom columns with indices: -{{source=..\SamplesCS\GridView\Rows\RowsChildRows.cs region=sortChanged}} -{{source=..\SamplesVB\GridView\Rows\RowsChildRows.vb region=sortChanged}} - -````C# -void radGridView1_SortChanged(object sender, Telerik.WinControls.UI.GridViewCollectionChangedEventArgs e) -{ - SetIDs(); -} - -```` -````VB.NET -Private Sub radGridView1_SortChanged(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewCollectionChangedEventArgs) - SetIDs() -End Sub - -```` - -{{endregion}} + + ![WinForms RadGridView Filtered Data](images/gridview-rows-rows-vs-childrows003.png) @@ -153,75 +60,15 @@ The result is expected and follows the explanation in step 3. The rows in the __ 5\. Finally, let's group the filtered and sorted data by the City column. The GroupChanged event is fired and in the GroupChanged event handler we again fill the two columns with indices: -{{source=..\SamplesCS\GridView\Rows\RowsChildRows.cs region=groupByChanged}} -{{source=..\SamplesVB\GridView\Rows\RowsChildRows.vb region=groupByChanged}} - -````C# -void radGridView1_GroupByChanged(object sender, GridViewCollectionChangedEventArgs e) -{ - SetIDs(); -} - -```` -````VB.NET -Private Sub radGridView1_GroupByChanged(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewCollectionChangedEventArgs) - SetIDs() -End Sub - -```` - -{{endregion}} + + ![WinForms RadGridView Grouping the Control](images/gridview-rows-rows-vs-childrows005.png) However, as you can see, something seems wrong, because the data in the ChildRows IDs cells does not make sense. Why is this so? This is, because now the ChildRows collection of RadGridView has four rows and they are the group header rows. Each of these groups rows has a ChildRows collection which contains the actual grouped data rows. So, if we slightly modify the body of the SetIDs method as shown below, we will get the correct and expected result. In short, we access the group header rows and change their text according to the order in which they appear in the ChildRows collections. Further, we iterate over the ChildRows collections of the group header rows and set the indices to the data rows: -{{source=..\SamplesCS\GridView\Rows\RowsChildRows.cs region=updatedSet}} -{{source=..\SamplesVB\GridView\Rows\RowsChildRows.vb region=updatedSet}} - -````C# -private void SetIDs() -{ - for (int i = 0; i < this.radGridView1.Rows.Count; i++) - { - this.radGridView1.Rows[i].Cells["RowsIDs"].Value = i.ToString(); - } - for (int i = 0; i < this.radGridView1.ChildRows.Count; i++) - { - this.radGridView1.ChildRows[i].Cells["ChildRowsIDs"].Value = i.ToString(); - GridViewGroupRowInfo groupRowInfo = this.radGridView1.ChildRows[i] as GridViewGroupRowInfo; - if (groupRowInfo != null) - { - groupRowInfo.HeaderText = groupRowInfo.HeaderText + " " + i.ToString(); - for (int p = 0; p < this.radGridView1.ChildRows[i].ChildRows.Count; p++) - { - this.radGridView1.ChildRows[i].ChildRows[p].Cells["ChildRowsIDs"].Value = p.ToString(); - } - } - } -} - -```` -````VB.NET -Private Sub SetIDs() - For i As Integer = 0 To Me.radGridView1.Rows.Count - 1 - Me.radGridView1.Rows(i).Cells("RowsIDs").Value = i.ToString() - Next i - For i As Integer = 0 To Me.radGridView1.ChildRows.Count - 1 - Me.radGridView1.ChildRows(i).Cells("ChildRowsIDs").Value = i.ToString() - Dim groupRowInfo As GridViewGroupRowInfo = TryCast(Me.radGridView1.ChildRows(i), GridViewGroupRowInfo) - If groupRowInfo IsNot Nothing Then - groupRowInfo.HeaderText = groupRowInfo.HeaderText & " " & i.ToString() - For p As Integer = 0 To Me.radGridView1.ChildRows(i).ChildRows.Count - 1 - Me.radGridView1.ChildRows(i).ChildRows(p).Cells("ChildRowsIDs").Value = p.ToString() - Next p - End If - Next i -End Sub - -```` - -{{endregion}} + + ![WinForms RadGridView Modify Group Headers](images/gridview-rows-rows-vs-childrows006.png) diff --git a/controls/gridview/visual-elements/rows/search-row.md b/controls/gridview/visual-elements/rows/search-row.md index 281cd4a20..8c8664fab 100644 --- a/controls/gridview/visual-elements/rows/search-row.md +++ b/controls/gridview/visual-elements/rows/search-row.md @@ -13,20 +13,8 @@ previous_url: gridview-rows-search-row __RadGridView__ offers a build-in search functionality available for both end users and developers. The search mechanism executes in a separate thread which leaves the UI responsive at all times. To enable the search row for end users all you have to do is set the __AllowSearchRow__ property of __RadGridView__ to *true*: -{{source=..\SamplesCS\GridView\Rows\SearchRow.cs region=AllowSearchRow}} -{{source=..\SamplesVB\GridView\Rows\SearchRow.vb region=AllowSearchRow}} - -````C# -this.radGridView1.AllowSearchRow = true; - -```` -````VB.NET -Me.RadGridView1.AllowSearchRow = True - -```` - -{{endregion}} - + + ![WinForms RadGridView Search Row](images/gridview-rows-search-row001.png) @@ -62,35 +50,13 @@ The available properties to tweak the search experience and performance and how To change the highlight color you should use the __HighlightColor__ property of the TableElement. -{{source=..\SamplesCS\GridView\Rows\SearchRow.cs region=ChangeHighlightColor}} -{{source=..\SamplesVB\GridView\Rows\SearchRow.vb region=ChangeHighlightColor}} - -````C# -radGridView1.TableElement.SearchHighlightColor = Color.LightBlue; - -```` -````VB.NET -RadGridView1.TableElement.SearchHighlightColor = Color.LightBlue - -```` - -{{endregion}} + + You can also use the search functionality programmatically without showing the search row, just by using its API. -{{source=..\SamplesCS\GridView\Rows\SearchRow.cs region=GetSearchRow}} -{{source=..\SamplesVB\GridView\Rows\SearchRow.vb region=GetSearchRow}} - -````C# -GridViewSearchRowInfo searchRow = this.radGridView1.MasterView.TableSearchRow; - -```` -````VB.NET -Dim searchRow As GridViewSearchRowInfo = Me.RadGridView1.MasterView.TableSearchRow - -```` - -{{endregion}} + + To manually search, call the __Search__ method and pass the search criteria as a parameter. To get the search results you have to subscribe to the __SearchProgressChanged__ event. In the event handler you will have to handle three cases: @@ -121,21 +87,8 @@ You can suspend/resume the search temporarily by using the __SuspendSearch__ and ### Suspend the search operation -{{source=..\SamplesCS\GridView\Rows\SearchRow.cs region=Suspend}} -{{source=..\SamplesVB\GridView\Rows\SearchRow.vb region=Suspend}} - -````C# -radGridView1.MasterView.TableSearchRow.SuspendSearch(); -radGridView1.MasterView.TableSearchRow.ResumeSearch(); - -```` -````VB.NET -RadGridView1.MasterView.TableSearchRow.SuspendSearch() -RadGridView1.MasterView.TableSearchRow.ResumeSearch() - -```` - -{{endregion}} + + # See Also diff --git a/controls/gridview/visual-elements/rows/selected-rows-and-current-row.md b/controls/gridview/visual-elements/rows/selected-rows-and-current-row.md index e8a8adc4e..a1147d33c 100644 --- a/controls/gridview/visual-elements/rows/selected-rows-and-current-row.md +++ b/controls/gridview/visual-elements/rows/selected-rows-and-current-row.md @@ -15,35 +15,13 @@ previous_url: gridview-rows-selected-rows-and-current-row The property __IsSelected__ determines whether a row is selected. For example, to select a row programmatically use the following code snippet: -{{source=..\SamplesCS\GridView\Rows\SelectedRowAndCurrentRow.cs region=selectingARow}} -{{source=..\SamplesVB\GridView\Rows\SelectedRowAndCurrentRow.vb region=selectingARow}} - -````C# -rowToSelect.IsSelected = true; - -```` -````VB.NET -rowToSelect.IsSelected = True - -```` - -{{endregion}} + + All currently selected rows are included in the __SelectedRows__ collection. If you clear this collection and send an update message to __RadGridView__, this will essentially unselect all rows: -{{source=..\SamplesCS\GridView\Rows\SelectedRowAndCurrentRow.cs region=unselectAllRows}} -{{source=..\SamplesVB\GridView\Rows\SelectedRowAndCurrentRow.vb region=unselectAllRows}} - -````C# -radGridView1.ClearSelection(); - -```` -````VB.NET -Me.RadGridView1.ClearSelection() - -```` - -{{endregion}} + + ## IsCurrent @@ -53,19 +31,8 @@ Most themes visualize the current and the selected rows with the same style alth Use the following code snippet to remove the current row: -{{source=..\SamplesCS\GridView\Rows\SelectedRowAndCurrentRow.cs region=currentRow}} -{{source=..\SamplesVB\GridView\Rows\SelectedRowAndCurrentRow.vb region=currentRow}} - -````C# -this.radGridView1.CurrentRow = null; - -```` -````VB.NET -Me.RadGridView1.CurrentRow = Nothing - -```` - -{{endregion}} + + # See Also * [Adding and Inserting Rows]({%slug winforms/gridview/rows/adding-and-inserting-rows%}) diff --git a/controls/gridview/visual-elements/rows/summary-rows.md b/controls/gridview/visual-elements/rows/summary-rows.md index 74e159e7f..3627c8c13 100644 --- a/controls/gridview/visual-elements/rows/summary-rows.md +++ b/controls/gridview/visual-elements/rows/summary-rows.md @@ -19,31 +19,8 @@ To add summary rows to your application, start by initializing a new instance of The following example demonstrates the steps to create a top pinned summary row that shows the count of the **RadGridView** rows: -{{source=..\SamplesCS\GridView\Rows\SummaryRows.cs region=addingSummaryRow}} -{{source=..\SamplesVB\GridView\Rows\SummaryRows.vb region=addingSummaryRow}} - -````C# -GridViewSummaryItem summaryItem = new GridViewSummaryItem(); -summaryItem.Name = "ShipName"; -summaryItem.Aggregate = GridAggregateFunction.Count; -GridViewSummaryRowItem summaryRowItem = new GridViewSummaryRowItem(); -summaryRowItem.Add(summaryItem); -this.radGridView1.SummaryRowsTop.Add(summaryRowItem); -this.radGridView1.SummaryRowsBottom.Add(summaryRowItem); - -```` -````VB.NET -Dim summaryItem As New GridViewSummaryItem() -summaryItem.Name = "ShipName" -summaryItem.Aggregate = GridAggregateFunction.Count -Dim summaryRowItem As New GridViewSummaryRowItem() -summaryRowItem.Add(summaryItem) -Me.RadGridView1.SummaryRowsTop.Add(summaryRowItem) -Me.RadGridView1.SummaryRowsBottom.Add(summaryRowItem) - -```` - -{{endregion}} + + >caption Figure 1: Top pinned summary row @@ -89,26 +66,8 @@ You can use the following predefined aggregates for the __Aggregate__ property: The following example demonstrates how to add several summary items to a summary row and how to use the __FormatString__: -{{source=..\SamplesCS\GridView\Rows\SummaryRows.cs region=formatString}} -{{source=..\SamplesVB\GridView\Rows\SummaryRows.vb region=formatString}} - -````C# -GridViewSummaryItem summaryItemShipName = new GridViewSummaryItem("ShipName", "{0}", GridAggregateFunction.Last); -GridViewSummaryItem summaryItemFreight = new GridViewSummaryItem("Freight", "Max Freight = {0}", GridAggregateFunction.Max); -GridViewSummaryRowItem summaryRowItem = new GridViewSummaryRowItem( - new GridViewSummaryItem[] { summaryItemShipName, summaryItemFreight }); -this.radGridView1.SummaryRowsTop.Add(summaryRowItem); - -```` -````VB.NET -Dim summaryItemShipName As New GridViewSummaryItem("ShipName", "{0}", GridAggregateFunction.Last) -Dim summaryItemFreight As New GridViewSummaryItem("Freight", "Max Freight = {0}", GridAggregateFunction.Max) -Dim summaryRowItem As New GridViewSummaryRowItem(New GridViewSummaryItem() {summaryItemShipName, summaryItemFreight}) -Me.RadGridView1.SummaryRowsTop.Add(summaryRowItem) - -```` - -{{endregion}} + + >caption Figure 2: Format the Summary Item @@ -118,30 +77,8 @@ Me.RadGridView1.SummaryRowsTop.Add(summaryRowItem) The next example demonstrates how to use __AggregateExpression__ to calculate an average value by excluding the __Max__ and __Min__ values: -{{source=..\SamplesCS\GridView\Rows\SummaryRows.cs region=aggregateExpression}} -{{source=..\SamplesVB\GridView\Rows\SummaryRows.vb region=aggregateExpression}} - -````C# -GridViewSummaryItem summaryItem = new GridViewSummaryItem(); -summaryItem.Name = "Freight"; -summaryItem.AggregateExpression = "(Sum(Freight) - Max(Freight) - Min(Freight)) / Count(Freight)"; -GridViewSummaryRowItem summaryRowItem = new GridViewSummaryRowItem(); -summaryRowItem.Add(summaryItem); -this.radGridView1.SummaryRowsTop.Add(summaryRowItem); - -```` -````VB.NET -Dim summaryItem As New GridViewSummaryItem() -summaryItem.Name = "Freight" -summaryItem.AggregateExpression = "(Sum(Freight) - Max(Freight) - Min(Freight)) / Count(Freight)" -Dim summaryRowItem As New GridViewSummaryRowItem() -summaryRowItem.Add(summaryItem) -Me.RadGridView1.SummaryRowsTop.Add(summaryRowItem) - -```` - -{{endregion}} - + + >caption Figure 3: Using AggregateExpression @@ -155,27 +92,8 @@ As of the **R1 2020** version, the template in **RadGridView** offers the **Show The next example demonstrates how to use summary rows in grouping: -{{source=..\SamplesCS\GridView\Rows\SummaryRows.cs region=grouping}} -{{source=..\SamplesVB\GridView\Rows\SummaryRows.vb region=grouping}} - -````C# -this.radGridView1.MasterTemplate.ShowTotals = true; -GridViewSummaryItem summaryItem = new GridViewSummaryItem("Freight", "{0}", GridAggregateFunction.Max); -GridViewSummaryRowItem summaryRowItem = new GridViewSummaryRowItem(); -summaryRowItem.Add(summaryItem); -this.radGridView1.SummaryRowsTop.Add(summaryRowItem); - -```` -````VB.NET -Me.RadGridView1.MasterTemplate.ShowTotals = True -Dim summaryItem As New GridViewSummaryItem("Freight", "{0}", GridAggregateFunction.Max) -Dim summaryRowItem As New GridViewSummaryRowItem() -summaryRowItem.Add(summaryItem) -Me.RadGridView1.SummaryRowsTop.Add(summaryRowItem) - -```` - -{{endregion}} + + >caption Figure 4: Summary rows in a grouped RadGridView @@ -187,31 +105,8 @@ As of the **2024 Q1** version, the template in **RadGridView** offers the **Show In a scenario in which we have nested grouping, the group summary row will appear for each nested group and its parent group when **ShowParentGroupSummaries** property is set to true. To show the group summary row on a specific group, we can set the same **ShowCollapsedGroupSummaries** property which was exposed on a group row level. It has higher priority than the **ShowCollapsedGroupSummaries** that comes from the template. The group row **ShowCollapsedGroupSummaries** property can be set in the CreateRowInfo event handler. However, an important moment here is that first the **ShowCollapsedGroupSummaries** property of the template needs to be set to true, then we can use the below example to remove the group summary row on a nested group. -{{source=..\SamplesCS\GridView\Rows\SummaryRows.cs region=summaryGroup}} -{{source=..\SamplesVB\GridView\Rows\SummaryRows.vb region=summaryGroup}} - -````C# -private void RadGridView1_CreateRowInfo(object sender, GridViewCreateRowInfoEventArgs e) -{ - if (e.RowInfo is GridViewGroupRowInfo) - { - GridViewGroupRowInfo groupRowInfo = e.RowInfo as GridViewGroupRowInfo; - groupRowInfo.ShowCollapsedGroupSummaries = groupRowInfo.GroupLevel == 0; - } -} - -```` -````VB.NET -Private Sub RadGridView1_CreateRowInfo(ByVal sender As Object, ByVal e As GridViewCreateRowInfoEventArgs) - If TypeOf e.RowInfo Is GridViewGroupRowInfo Then - Dim groupRowInfo As GridViewGroupRowInfo = TryCast(e.RowInfo, GridViewGroupRowInfo) - groupRowInfo.ShowCollapsedGroupSummaries = groupRowInfo.GroupLevel = 0 - End If -End Sub - -```` - -{{endregion}} + + ![WinForms RadGridView Summary rows when group are collapsed](images/gridview-rows-summary-rows011.png) @@ -220,55 +115,16 @@ End Sub You can add summary rows in hierarchical views. They are calculated for the child rows in the current view. The following example demonstrates how to add a summary row to the first level of a **RadGridView** hierarchy: -{{source=..\SamplesCS\GridView\Rows\SummaryRows.cs region=hierarchy}} -{{source=..\SamplesVB\GridView\Rows\SummaryRows.vb region=hierarchy}} - -````C# -GridViewSummaryItem summaryItem = new GridViewSummaryItem("Quantity", "Max quantity = {0}", GridAggregateFunction.Max); -GridViewSummaryRowItem summaryRowItem = new GridViewSummaryRowItem(); -summaryRowItem.Add(summaryItem); -this.radGridView1.MasterTemplate.Templates[0].SummaryRowsTop.Add(summaryRowItem); - -```` -````VB.NET -Dim summaryItem As New GridViewSummaryItem("Quantity", "Max quantity = {0}", GridAggregateFunction.Max) -Dim summaryRowItem As New GridViewSummaryRowItem() -summaryRowItem.Add(summaryItem) -Me.RadGridView1.MasterTemplate.Templates(0).SummaryRowsTop.Add(summaryRowItem) - -```` - -{{endregion}} - + + ## Customizing the summary row The **GroupSummaryEvaluate** event is fired after a summary item is calculated and before the summary row is displayed. You can use this event to apply custom formatting to the summary row. The same event is used to format the group header, so it is important to check the __Parent__ in the event arguments, as shown in the example: -{{source=..\SamplesCS\GridView\Rows\SummaryRows.cs region=customFormatting}} -{{source=..\SamplesVB\GridView\Rows\SummaryRows.vb region=customFormatting}} - -````C# -private void radGridView1_GroupSummaryEvaluate(object sender, GroupSummaryEvaluationEventArgs e) -{ - if (e.SummaryItem.Name == "ShipName") - { - e.FormatString = String.Format("There are {0} ships total.", e.Value); - } -} - -```` -````VB.NET -Private Sub radGridView1_GroupSummaryEvaluate(ByVal sender As Object, ByVal e As GroupSummaryEvaluationEventArgs) - If e.SummaryItem.Name = "ShipName" Then - e.FormatString = String.Format("There are {0} ships total.", e.Value) - End If -End Sub - -```` - -{{endregion}} + + >caption Figure 5: Customizing the summary row @@ -281,63 +137,8 @@ You can write your own logic for summary items evaluation by inheriting the **Gr The following example demonstrates how to create a custom summary item that calculates the orders count with *Freight* less than *50*: -{{source=..\SamplesCS\GridView\Rows\SummaryRows.cs region=customSummaryItemUsage}} -{{source=..\SamplesVB\GridView\Rows\SummaryRows.vb region=customSummaryItemUsage}} - -````C# -void CustomSummaryItemUsage() -{ - CustomSummaryItem summaryItem = new CustomSummaryItem("Freight", "The low freight orders are {0}.", GridAggregateFunction.Count); - GridViewSummaryRowItem summaryRowItem = new GridViewSummaryRowItem(); - summaryRowItem.Add(summaryItem); - this.radGridView1.SummaryRowsTop.Add(summaryRowItem); -} -public class CustomSummaryItem : GridViewSummaryItem -{ - public CustomSummaryItem(string name, string formatString, GridAggregateFunction aggregate) - : base(name, formatString, aggregate) - { } - public override object Evaluate(IHierarchicalRow row) - { - int lowFreightsCount = 0; - foreach (GridViewRowInfo childRow in row.ChildRows) - { - if ((decimal)childRow.Cells["Freight"].Value < 50m) - { - lowFreightsCount++; - } - } - return lowFreightsCount; - } -} - -```` -````VB.NET -Private Sub CustomSummaryItemUsage() - Dim summaryItem As New CustomSummaryItem("Freight", "The low freight orders are {0}.", GridAggregateFunction.Count) - Dim summaryRowItem As New GridViewSummaryRowItem() - summaryRowItem.Add(summaryItem) - Me.RadGridView1.SummaryRowsTop.Add(summaryRowItem) -End Sub -Public Class CustomSummaryItem - Inherits GridViewSummaryItem - Public Sub New(ByVal name As String, ByVal formatString As String, ByVal aggregate As GridAggregateFunction) - MyBase.New(name, formatString, aggregate) - End Sub - Public Overrides Function Evaluate(ByVal row As IHierarchicalRow) As Object - Dim lowFreightsCount As Integer = 0 - For Each childRow As GridViewRowInfo In row.ChildRows - If CDec(childRow.Cells("Freight").Value) < 50D Then - lowFreightsCount += 1 - End If - Next childRow - Return lowFreightsCount - End Function -End Class - -```` - -{{endregion}} + + ![WinForms RadGridView Custom SummaryItem](images/gridview-rows-summary-rows007.png) diff --git a/controls/gridview/visual-elements/rows/tag-property.md b/controls/gridview/visual-elements/rows/tag-property.md index c8d058d9f..fc7ef2bae 100644 --- a/controls/gridview/visual-elements/rows/tag-property.md +++ b/controls/gridview/visual-elements/rows/tag-property.md @@ -15,81 +15,20 @@ Each row has a __Tag__ property of type object where you can store a custom obje #### Setting the Tag property of a row -{{source=..\SamplesCS\GridView\Rows\TagProperty.cs region=assignTagProperty}} -{{source=..\SamplesVB\GridView\Rows\TagProperty.vb region=assignTagProperty}} - -````C# - -this.radGridView1.Rows[1].Tag = "Some tag"; - -```` -````VB.NET - -Me.RadGridView1.Rows(1).Tag = "Some tag" - -```` - -{{endregion}} + + #### Setting the Tag property of cells in CellFormatting event. -{{source=..\SamplesCS\GridView\Rows\TagProperty.cs region=setTagInCellFormatting}} -{{source=..\SamplesVB\GridView\Rows\TagProperty.vb region=setTagInCellFormatting}} - -````C# -void radGridView1_CellFormatting(object sender, Telerik.WinControls.UI.CellFormattingEventArgs e) -{ - if (e.CellElement.RowIndex % 2 == 0) - { - e.CellElement.RowInfo.Tag = "Some tag"; - } - else - { - e.CellElement.RowInfo.Tag = "Hide row"; - } -} - -```` -````VB.NET -Private Sub RadGridView1_CellFormatting(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.CellFormattingEventArgs) Handles RadGridView1.CellFormatting - If (e.CellElement.RowIndex Mod 2 = 0) Then - e.CellElement.RowInfo.Tag = "Some tag" - Else - e.CellElement.RowInfo.Tag = "Hide row" - End If -End Sub - -```` - -{{endregion}} + + #### Collapsing all rows with the specified tag The most natural place to use the tag is in some of the row/cell events. For example, to make the content of certain cells invisible use the following code: -{{source=..\SamplesCS\GridView\Rows\TagProperty.cs region=hideRowsWithSpecifiedTag}} -{{source=..\SamplesVB\GridView\Rows\TagProperty.vb region=hideRowsWithSpecifiedTag}} - -````C# -void radGridView1_CellFormatting1(object sender, Telerik.WinControls.UI.CellFormattingEventArgs e) -{ - if (e.CellElement.RowInfo.Tag is String && (string)e.CellElement.RowInfo.Tag == "Hide row") - { - e.CellElement.Visibility = Telerik.WinControls.ElementVisibility.Collapsed; - } -} - -```` -````VB.NET -Private Sub RadGridView1_CellFormatting1(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.CellFormattingEventArgs) Handles RadGridView1.CellFormatting - If TypeOf e.CellElement.RowInfo.Tag Is [String] AndAlso DirectCast(e.CellElement.RowInfo.Tag, String) = "Hide row" Then - e.CellElement.Visibility = Telerik.WinControls.ElementVisibility.Collapsed - End If - End Sub - -```` - -{{endregion}} + + >note Cells also have Tag property but it differs substantially from rows one because of the UI Virtualization. Cells are reused and when you scroll the tag value remains unchanged while cell data value is updated. > diff --git a/controls/heatmap/colorizers.md b/controls/heatmap/colorizers.md index 25f90c650..c7e354d6a 100644 --- a/controls/heatmap/colorizers.md +++ b/controls/heatmap/colorizers.md @@ -20,234 +20,17 @@ In the scenario of Horizontal/Vertical Definition, the colorizer is defined in t Let's start with the following Car class that will be used for the examples in this article: -{{source=..\SamplesCS\HeatMap\HeatMapDefinitions.cs region=CarClass}} -{{source=..\SamplesVB\HeatMap\HeatMapDefinitions.vb region=CarClass}} - -````C# -public class Car -{ - public string Name { get; set; } - public int MilesPerGallon { get; set; } - public int TopSpeed { get; set; } - public int Price { get; set; } - public int HorsePower { get; set; } -} - -```` -````VB.NET - -Public Class Car - Public Property Name As String - Public Property MilesPerGallon As Integer - Public Property TopSpeed As Integer - Public Property Price As Integer - Public Property HorsePower As Integer -End Class - -```` - -{{endregion}} + + + + Now, we will setup a HorizontalDefinition populated with cars like the following example: -{{source=..\SamplesCS\HeatMap\HeatMapDefinitions.cs region=DefaultColorizer}} -{{source=..\SamplesVB\HeatMap\HeatMapDefinitions.vb region=DefaultColorizer}} - -````C# - -public void ApplyDefaultColorizer() -{ - HorizontalDefinition horizontalDefinition1 = new HorizontalDefinition(); - horizontalDefinition1.DataSource = CreateData(); - horizontalDefinition1.HeaderMember = "Name"; - radHeatMap1.Definition = horizontalDefinition1; - radHeatMap1.DescriptionContent = "Cars"; - - MemberMapping memberMapping1 = new MemberMapping(); - memberMapping1.Header = "Price"; - memberMapping1.ValueMember = "Price"; - MemberMapping memberMapping2 = new MemberMapping(); - memberMapping2.Header = "HorsePower"; - memberMapping2.ValueMember = "HorsePower"; - MemberMapping memberMapping3 = new MemberMapping(); - memberMapping3.Header = "TopSpeed"; - memberMapping3.ValueMember = "TopSpeed"; - - horizontalDefinition1.MemberMappings.Add(memberMapping1); - horizontalDefinition1.MemberMappings.Add(memberMapping2); - horizontalDefinition1.MemberMappings.Add(memberMapping3); -} - - -public List CreateData() -{ - var result = new List() -{ - new Car() {Name = "Car 1", Price = 20590, HorsePower = 70, MilesPerGallon = 37, TopSpeed = 60 }, - new Car() {Name = "Car 2", Price = 21990, HorsePower = 70, MilesPerGallon = 37, TopSpeed = 60 }, - new Car() {Name = "Car 3", Price = 23200, HorsePower = 140, MilesPerGallon = 28, TopSpeed = 110 }, - new Car() {Name = "Car 4", Price = 27500, HorsePower = 140, MilesPerGallon = 28, TopSpeed = 110 }, - new Car() {Name = "Car 5", Price = 28200, HorsePower = 160, MilesPerGallon = 31, TopSpeed = 120 }, - new Car() {Name = "Car 6", Price = 29500, HorsePower = 90, MilesPerGallon = 35, TopSpeed = 80 }, - new Car() {Name = "Car 7", Price = 31200, HorsePower = 160, MilesPerGallon = 31, TopSpeed = 120 }, - new Car() {Name = "Car 8", Price = 32200, HorsePower = 90, MilesPerGallon = 35, TopSpeed = 80 }, - new Car() {Name = "Car 9", Price = 35200, HorsePower = 115, MilesPerGallon = 29, TopSpeed = 90 }, - new Car() {Name = "Car 10", Price = 36700, HorsePower = 115, MilesPerGallon = 29, TopSpeed = 90 }, - new Car() {Name = "Car 11", Price = 38200, HorsePower = 130, MilesPerGallon = 24, TopSpeed = 140 }, - new Car() {Name = "Car 12", Price = 39700, HorsePower = 130, MilesPerGallon = 24, TopSpeed = 140 }, - new Car() {Name = "Car 13", Price = 41500, HorsePower = 326, MilesPerGallon = 16, TopSpeed = 150 }, - new Car() {Name = "Car 14", Price = 42200, HorsePower = 326, MilesPerGallon = 16, TopSpeed = 150 }, - new Car() {Name = "Car 15", Price = 43500, HorsePower = 276, MilesPerGallon = 25, TopSpeed = 162 }, - new Car() {Name = "Car 16", Price = 43500, HorsePower = 276, MilesPerGallon = 25, TopSpeed = 162 }, -}; - - return result; -} - -```` -````VB.NET - -Public Sub ApplyDefaultColorizer() - Dim horizontalDefinition1 As HorizontalDefinition = New HorizontalDefinition() - horizontalDefinition1.DataSource = CreateData() - horizontalDefinition1.HeaderMember = "Name" - radHeatMap1.Definition = horizontalDefinition1 - radHeatMap1.DescriptionContent = "Cars" - Dim memberMapping1 As MemberMapping = New MemberMapping() - memberMapping1.Header = "Price" - memberMapping1.ValueMember = "Price" - Dim memberMapping2 As MemberMapping = New MemberMapping() - memberMapping2.Header = "HorsePower" - memberMapping2.ValueMember = "HorsePower" - Dim memberMapping3 As MemberMapping = New MemberMapping() - memberMapping3.Header = "TopSpeed" - memberMapping3.ValueMember = "TopSpeed" - horizontalDefinition1.MemberMappings.Add(memberMapping1) - horizontalDefinition1.MemberMappings.Add(memberMapping2) - horizontalDefinition1.MemberMappings.Add(memberMapping3) -End Sub - -Public Function CreateData() As List(Of Car) - Dim result = New List(Of Car)() From { - New Car() With { - .Name = "Car 1", - .Price = 20590, - .HorsePower = 70, - .MilesPerGallon = 37, - .TopSpeed = 60 - }, - New Car() With { - .Name = "Car 2", - .Price = 21990, - .HorsePower = 70, - .MilesPerGallon = 37, - .TopSpeed = 60 - }, - New Car() With { - .Name = "Car 3", - .Price = 23200, - .HorsePower = 140, - .MilesPerGallon = 28, - .TopSpeed = 110 - }, - New Car() With { - .Name = "Car 4", - .Price = 27500, - .HorsePower = 140, - .MilesPerGallon = 28, - .TopSpeed = 110 - }, - New Car() With { - .Name = "Car 5", - .Price = 28200, - .HorsePower = 160, - .MilesPerGallon = 31, - .TopSpeed = 120 - }, - New Car() With { - .Name = "Car 6", - .Price = 29500, - .HorsePower = 90, - .MilesPerGallon = 35, - .TopSpeed = 80 - }, - New Car() With { - .Name = "Car 7", - .Price = 31200, - .HorsePower = 160, - .MilesPerGallon = 31, - .TopSpeed = 120 - }, - New Car() With { - .Name = "Car 8", - .Price = 32200, - .HorsePower = 90, - .MilesPerGallon = 35, - .TopSpeed = 80 - }, - New Car() With { - .Name = "Car 9", - .Price = 35200, - .HorsePower = 115, - .MilesPerGallon = 29, - .TopSpeed = 90 - }, - New Car() With { - .Name = "Car 10", - .Price = 36700, - .HorsePower = 115, - .MilesPerGallon = 29, - .TopSpeed = 90 - }, - New Car() With { - .Name = "Car 11", - .Price = 38200, - .HorsePower = 130, - .MilesPerGallon = 24, - .TopSpeed = 140 - }, - New Car() With { - .Name = "Car 12", - .Price = 39700, - .HorsePower = 130, - .MilesPerGallon = 24, - .TopSpeed = 140 - }, - New Car() With { - .Name = "Car 13", - .Price = 41500, - .HorsePower = 326, - .MilesPerGallon = 16, - .TopSpeed = 150 - }, - New Car() With { - .Name = "Car 14", - .Price = 42200, - .HorsePower = 326, - .MilesPerGallon = 16, - .TopSpeed = 150 - }, - New Car() With { - .Name = "Car 15", - .Price = 43500, - .HorsePower = 276, - .MilesPerGallon = 25, - .TopSpeed = 162 - }, - New Car() With { - .Name = "Car 16", - .Price = 43500, - .HorsePower = 276, - .MilesPerGallon = 25, - .TopSpeed = 162 - } - } - Return result -End Function - -```` - -{{endregion}} + + + + >caption Default HeatMapGradientColorizer @@ -263,72 +46,10 @@ A colorizer, which contains a set of **GradientStops**. It chooses a color to be Now, this is how a HeatMapGradientColorizer is defined for one of the MemberMappings for the definition: -{{source=..\SamplesCS\HeatMap\HeatMapDefinitions.cs region=ChangeColorizer}} -{{source=..\SamplesVB\HeatMap\HeatMapDefinitions.vb region=ChangeColorizer}} - -````C# - -HorizontalDefinition horizontalDefinition1 = new HorizontalDefinition(); -horizontalDefinition1.DataSource = CreateData(); -horizontalDefinition1.HeaderMember = "Name"; - -radHeatMap1.Definition = horizontalDefinition1; -radHeatMap1.DescriptionContent = "Cars"; - -HeatMapGradientColorizer gradientColorizer1 = new HeatMapGradientColorizer(); -gradientColorizer1.GradientStops.Add(new Telerik.WinControls.Drawing.GradientStop() { Color = Color.FromArgb(255,217,231,241),Position = 0 }); -gradientColorizer1.GradientStops.Add(new Telerik.WinControls.Drawing.GradientStop() { Color = Color.FromArgb(255, 1, 81, 140),Position =1 }); - -MemberMapping memberMapping1 = new MemberMapping(); -memberMapping1.Header = "Price"; -memberMapping1.ValueMember = "Price"; -memberMapping1.Colorizer = gradientColorizer1; - -MemberMapping memberMapping2 = new MemberMapping(); -memberMapping2.Header = "HorsePower"; -memberMapping2.ValueMember = "HorsePower"; -MemberMapping memberMapping3 = new MemberMapping(); -memberMapping3.Header = "TopSpeed"; -memberMapping3.ValueMember = "TopSpeed"; - -horizontalDefinition1.MemberMappings.Add(memberMapping1); -horizontalDefinition1.MemberMappings.Add(memberMapping2); -horizontalDefinition1.MemberMappings.Add(memberMapping3); - -```` -````VB.NET - - Dim horizontalDefinition1 As HorizontalDefinition = New HorizontalDefinition() - horizontalDefinition1.DataSource = CreateData() - horizontalDefinition1.HeaderMember = "Name" - radHeatMap1.Definition = horizontalDefinition1 - radHeatMap1.DescriptionContent = "Cars" - Dim gradientColorizer1 As HeatMapGradientColorizer = New HeatMapGradientColorizer() - gradientColorizer1.GradientStops.Add(New Telerik.WinControls.Drawing.GradientStop() With { - .Color = Color.FromArgb(255, 217, 231, 241), - .Position = 0 - }) - gradientColorizer1.GradientStops.Add(New Telerik.WinControls.Drawing.GradientStop() With { - .Color = Color.FromArgb(255, 1, 81, 140), - .Position = 1 - }) - Dim memberMapping1 As MemberMapping = New MemberMapping() - memberMapping1.Header = "Price" - memberMapping1.ValueMember = "Price" - memberMapping1.Colorizer = gradientColorizer1 - Dim memberMapping2 As MemberMapping = New MemberMapping() - memberMapping2.Header = "HorsePower" - memberMapping2.ValueMember = "HorsePower" - Dim memberMapping3 As MemberMapping = New MemberMapping() - memberMapping3.Header = "TopSpeed" - memberMapping3.ValueMember = "TopSpeed" - horizontalDefinition1.MemberMappings.Add(memberMapping1) - horizontalDefinition1.MemberMappings.Add(memberMapping2) - horizontalDefinition1.MemberMappings.Add(memberMapping3) - -```` - -{{endregion}} + + + + Here is the observed result: @@ -340,103 +61,10 @@ A colorizer, which uses a set of colors, where each of them corresponds to a ran Let’s define an absolute **HeatMapRangeColorizer** and apply it to Miles per Gallon column. -{{source=..\SamplesCS\HeatMap\HeatMapDefinitions.cs region=RangeColorizer}} -{{source=..\SamplesVB\HeatMap\HeatMapDefinitions.vb region=RangeColorizer}} - -````C# -HorizontalDefinition horizontalDefinition1 = new HorizontalDefinition(); -horizontalDefinition1.DataSource = CreateData(); -horizontalDefinition1.HeaderMember = "Name"; - -radHeatMap1.Definition = horizontalDefinition1; -radHeatMap1.DescriptionContent = "Cars"; - -HeatMapRangeColorizer rangeColorizer1 = new HeatMapRangeColorizer() { IsAbsolute = true }; -rangeColorizer1.Colors.Add(new HeatMapRangeColor() { Color = Color.FromArgb(255, 217, 231, 241), From = 19, To = 22 }); -rangeColorizer1.Colors.Add(new HeatMapRangeColor() { Color = Color.FromArgb(255, 164, 194, 216), From = 23, To = 26 }); -rangeColorizer1.Colors.Add(new HeatMapRangeColor() { Color = Color.FromArgb(255, 110, 156, 191), From = 27, To = 30 }); -rangeColorizer1.Colors.Add(new HeatMapRangeColor() { Color = Color.FromArgb(255, 55, 118, 165), From = 31, To = 34 }); -rangeColorizer1.Colors.Add(new HeatMapRangeColor() { Color = Color.FromArgb(255, 1, 81, 140) , From = 35, To = 40 }); - -MemberMapping memberMapping1 = new MemberMapping(); -memberMapping1.Header = "Price"; -memberMapping1.ValueMember = "Price"; - -MemberMapping memberMapping2 = new MemberMapping(); -memberMapping2.Header = "HorsePower"; -memberMapping2.ValueMember = "HorsePower"; - -MemberMapping memberMapping3 = new MemberMapping(); -memberMapping3.Header = "TopSpeed"; -memberMapping3.ValueMember = "TopSpeed"; - -MemberMapping memberMapping4 = new MemberMapping(); -memberMapping4.Header = "MPG"; -memberMapping4.ValueMember = "MilesPerGallon"; -memberMapping4.Colorizer = rangeColorizer1; - -horizontalDefinition1.MemberMappings.Add(memberMapping1); -horizontalDefinition1.MemberMappings.Add(memberMapping2); -horizontalDefinition1.MemberMappings.Add(memberMapping3); -horizontalDefinition1.MemberMappings.Add(memberMapping4); - -```` -````VB.NET - - Dim horizontalDefinition1 As HorizontalDefinition = New HorizontalDefinition() - horizontalDefinition1.DataSource = CreateData() - horizontalDefinition1.HeaderMember = "Name" - radHeatMap1.Definition = horizontalDefinition1 - radHeatMap1.DescriptionContent = "Cars" - Dim rangeColorizer1 As HeatMapRangeColorizer = New HeatMapRangeColorizer() With { - .IsAbsolute = True - } - rangeColorizer1.Colors.Add(New HeatMapRangeColor() With { - .Color = Color.FromArgb(255, 217, 231, 241), - .From = 19, - .[To] = 22 - }) - rangeColorizer1.Colors.Add(New HeatMapRangeColor() With { - .Color = Color.FromArgb(255, 164, 194, 216), - .From = 23, - .[To] = 26 - }) - rangeColorizer1.Colors.Add(New HeatMapRangeColor() With { - .Color = Color.FromArgb(255, 110, 156, 191), - .From = 27, - .[To] = 30 - }) - rangeColorizer1.Colors.Add(New HeatMapRangeColor() With { - .Color = Color.FromArgb(255, 55, 118, 165), - .From = 31, - .[To] = 34 - }) - rangeColorizer1.Colors.Add(New HeatMapRangeColor() With { - .Color = Color.FromArgb(255, 1, 81, 140), - .From = 35, - .[To] = 40 - }) - Dim memberMapping1 As MemberMapping = New MemberMapping() - memberMapping1.Header = "Price" - memberMapping1.ValueMember = "Price" - Dim memberMapping2 As MemberMapping = New MemberMapping() - memberMapping2.Header = "HorsePower" - memberMapping2.ValueMember = "HorsePower" - Dim memberMapping3 As MemberMapping = New MemberMapping() - memberMapping3.Header = "TopSpeed" - memberMapping3.ValueMember = "TopSpeed" - Dim memberMapping4 As MemberMapping = New MemberMapping() - memberMapping4.Header = "MPG" - memberMapping4.ValueMember = "MilesPerGallon" - memberMapping4.Colorizer = rangeColorizer1 - horizontalDefinition1.MemberMappings.Add(memberMapping1) - horizontalDefinition1.MemberMappings.Add(memberMapping2) - horizontalDefinition1.MemberMappings.Add(memberMapping3) - horizontalDefinition1.MemberMappings.Add(memberMapping4) - -```` - -{{endregion}} + + + + Here is the observed result: @@ -449,69 +77,10 @@ It reduces the level of saturation of a given **StartColor** depending on the He This is how HeatMapDesaturationColorizer is defined and applied: -{{source=..\SamplesCS\HeatMap\HeatMapDefinitions.cs region=DesaturationColorizer}} -{{source=..\SamplesVB\HeatMap\HeatMapDefinitions.vb region=DesaturationColorizer}} - -````C# -HorizontalDefinition horizontalDefinition1 = new HorizontalDefinition(); -horizontalDefinition1.DataSource = CreateData(); -horizontalDefinition1.HeaderMember = "Name"; - -radHeatMap1.Definition = horizontalDefinition1; -radHeatMap1.DescriptionContent = "Cars"; - -HeatMapDesaturationColorizer desaturationColorizer1 = new HeatMapDesaturationColorizer() -{ - StartColor = Color.FromArgb(255,1,81,140), - To = 0.1, -}; - -MemberMapping memberMapping1 = new MemberMapping(); -memberMapping1.Header = "Price"; -memberMapping1.ValueMember = "Price"; -memberMapping1.Colorizer = desaturationColorizer1; - -MemberMapping memberMapping2 = new MemberMapping(); -memberMapping2.Header = "HorsePower"; -memberMapping2.ValueMember = "HorsePower"; -MemberMapping memberMapping3 = new MemberMapping(); -memberMapping3.Header = "TopSpeed"; -memberMapping3.ValueMember = "TopSpeed"; - -horizontalDefinition1.MemberMappings.Add(memberMapping1); -horizontalDefinition1.MemberMappings.Add(memberMapping2); -horizontalDefinition1.MemberMappings.Add(memberMapping3); - -```` -````VB.NET - -Dim horizontalDefinition1 As HorizontalDefinition = New HorizontalDefinition() -horizontalDefinition1.DataSource = CreateData() -horizontalDefinition1.HeaderMember = "Name" -radHeatMap1.Definition = horizontalDefinition1 -radHeatMap1.DescriptionContent = "Cars" -Dim desaturationColorizer1 As HeatMapDesaturationColorizer = New HeatMapDesaturationColorizer() With -{ -.StartColor = Color.FromArgb(255, 1, 81, 140), -.[To] = 0.1 -} -Dim memberMapping1 As MemberMapping = New MemberMapping() -memberMapping1.Header = "Price" -memberMapping1.ValueMember = "Price" -memberMapping1.Colorizer = desaturationColorizer1 -Dim memberMapping2 As MemberMapping = New MemberMapping() -memberMapping2.Header = "HorsePower" -memberMapping2.ValueMember = "HorsePower" -Dim memberMapping3 As MemberMapping = New MemberMapping() -memberMapping3.Header = "TopSpeed" -memberMapping3.ValueMember = "TopSpeed" -horizontalDefinition1.MemberMappings.Add(memberMapping1) -horizontalDefinition1.MemberMappings.Add(memberMapping2) -horizontalDefinition1.MemberMappings.Add(memberMapping3) - -```` - -{{endregion}} + + + + And the result is illustrated below: diff --git a/controls/heatmap/custom-painting.md b/controls/heatmap/custom-painting.md index c26979484..bf8339689 100644 --- a/controls/heatmap/custom-painting.md +++ b/controls/heatmap/custom-painting.md @@ -14,172 +14,10 @@ RadHeatMap renders directly its cells calculating the rectangle that each cell o Let's start the example with the following initial setup: -{{source=..\SamplesCS\HeatMap\HeatMapCustomPainting.cs region=InitialState}} -{{source=..\SamplesVB\HeatMap\HeatMapCustomPainting.vb region=InitialState}} + + -````C# - public void PopulateHeatMap() - { - CategoricalDefinition categoricalDefinition1 = new CategoricalDefinition(); - categoricalDefinition1.ColumnGroupMember = "District"; - categoricalDefinition1.DataSource = AddData(); - categoricalDefinition1.RowGroupMember = "Month"; - categoricalDefinition1.ValueMember = "CallsNumber"; - - HeatMapGradientColorizer colorizer = new HeatMapGradientColorizer() - { - RangeMinimum = 2, - RangeMaximum = 108, - GradientStops = - { - new Telerik.WinControls.Drawing.GradientStop(){ Position = 0.0f , Color = ColorTranslator.FromHtml("#FFFFFFFF")}, - new Telerik.WinControls.Drawing.GradientStop(){ Position = 0.2f , Color = ColorTranslator.FromHtml("#FFFFEA84")}, - new Telerik.WinControls.Drawing.GradientStop(){ Position = 1.0f , Color = ColorTranslator.FromHtml("#FFED4506")}, - } - }; - - categoricalDefinition1.Colorizer = colorizer; - this.radHeatMap1.Definition = categoricalDefinition1; - - } - - public BindingSource AddData() - { - BindingSource data = new BindingSource(); - data.Add(new PlotInfo("Parksley", "January", 103)); - data.Add(new PlotInfo("Parksley", "February", 78)); - data.Add(new PlotInfo("Parksley", "March", 89)); - data.Add(new PlotInfo("Parksley", "April", 88)); - data.Add(new PlotInfo("Parksley", "May", 89)); - data.Add(new PlotInfo("Parksley", "June", 102)); - data.Add(new PlotInfo("Parksley", "July", 90)); - data.Add(new PlotInfo("Parksley", "August", 108)); - data.Add(new PlotInfo("Parksley", "September", 98)); - data.Add(new PlotInfo("Parksley", "October", 81)); - data.Add(new PlotInfo("Parksley", "November", 88)); - data.Add(new PlotInfo("Parksley", "December", 99)); - - data.Add(new PlotInfo("Oak Hall", "January", 103)); - data.Add(new PlotInfo("Oak Hall", "February", 85)); - data.Add(new PlotInfo("Oak Hall", "March", 84)); - data.Add(new PlotInfo("Oak Hall", "April", 91)); - data.Add(new PlotInfo("Oak Hall", "May", 96)); - data.Add(new PlotInfo("Oak Hall", "June", 87)); - data.Add(new PlotInfo("Oak Hall", "July", 97)); - data.Add(new PlotInfo("Oak Hall", "August", 81)); - data.Add(new PlotInfo("Oak Hall", "September", 60)); - data.Add(new PlotInfo("Oak Hall", "October", 82)); - data.Add(new PlotInfo("Oak Hall", "November", 78)); - data.Add(new PlotInfo("Oak Hall", "December", 70)); - - data.Add(new PlotInfo("Chincoteague", "January", 66)); - data.Add(new PlotInfo("Chincoteague", "February", 56)); - data.Add(new PlotInfo("Chincoteague", "March", 48)); - data.Add(new PlotInfo("Chincoteague", "April", 53)); - data.Add(new PlotInfo("Chincoteague", "May", 87)); - data.Add(new PlotInfo("Chincoteague", "June", 85)); - data.Add(new PlotInfo("Chincoteague", "July", 100)); - data.Add(new PlotInfo("Chincoteague", "August", 107)); - data.Add(new PlotInfo("Chincoteague", "September", 87)); - data.Add(new PlotInfo("Chincoteague", "October", 72)); - data.Add(new PlotInfo("Chincoteague", "November", 48)); - data.Add(new PlotInfo("Chincoteague", "December", 57)); - - return data; - } - public class PlotInfo - { - public PlotInfo(string district, string month, double calls) - { - this.District = district; - this.Month = month; - this.CallsNumber = calls; - } - - public string District { get; set; } - public string Month { get; set; } - public double CallsNumber { get; set; } - } - -```` -````VB.NET - Public Sub PopulateHeatMap() - Dim categoricalDefinition1 As CategoricalDefinition = New CategoricalDefinition() - categoricalDefinition1.ColumnGroupMember = "District" - categoricalDefinition1.DataSource = AddData() - categoricalDefinition1.RowGroupMember = "Month" - categoricalDefinition1.ValueMember = "CallsNumber" - - Dim colorizer As New HeatMapGradientColorizer With { - .RangeMinimum = 2, - .RangeMaximum = 108 - } - colorizer.GradientStops.Add(New Telerik.WinControls.Drawing.GradientStop(ColorTranslator.FromHtml("#FFFFFFFF"), 0.0F)) - colorizer.GradientStops.Add(New Telerik.WinControls.Drawing.GradientStop(ColorTranslator.FromHtml("#FFFFEA84"), 0.2F)) - colorizer.GradientStops.Add(New Telerik.WinControls.Drawing.GradientStop(ColorTranslator.FromHtml("#FFED4506"), 1.0F)) - - - categoricalDefinition1.Colorizer = colorizer - Me.radHeatMap1.Definition = categoricalDefinition1 - End Sub - - Public Function AddData() As BindingSource - Dim data As BindingSource = New BindingSource() - data.Add(New PlotInfo("Parksley", "January", 103)) - data.Add(New PlotInfo("Parksley", "February", 78)) - data.Add(New PlotInfo("Parksley", "March", 89)) - data.Add(New PlotInfo("Parksley", "April", 88)) - data.Add(New PlotInfo("Parksley", "May", 89)) - data.Add(New PlotInfo("Parksley", "June", 102)) - data.Add(New PlotInfo("Parksley", "July", 90)) - data.Add(New PlotInfo("Parksley", "August", 108)) - data.Add(New PlotInfo("Parksley", "September", 98)) - data.Add(New PlotInfo("Parksley", "October", 81)) - data.Add(New PlotInfo("Parksley", "November", 88)) - data.Add(New PlotInfo("Parksley", "December", 99)) - data.Add(New PlotInfo("Oak Hall", "January", 103)) - data.Add(New PlotInfo("Oak Hall", "February", 85)) - data.Add(New PlotInfo("Oak Hall", "March", 84)) - data.Add(New PlotInfo("Oak Hall", "April", 91)) - data.Add(New PlotInfo("Oak Hall", "May", 96)) - data.Add(New PlotInfo("Oak Hall", "June", 87)) - data.Add(New PlotInfo("Oak Hall", "July", 97)) - data.Add(New PlotInfo("Oak Hall", "August", 81)) - data.Add(New PlotInfo("Oak Hall", "September", 60)) - data.Add(New PlotInfo("Oak Hall", "October", 82)) - data.Add(New PlotInfo("Oak Hall", "November", 78)) - data.Add(New PlotInfo("Oak Hall", "December", 70)) - data.Add(New PlotInfo("Chincoteague", "January", 66)) - data.Add(New PlotInfo("Chincoteague", "February", 56)) - data.Add(New PlotInfo("Chincoteague", "March", 48)) - data.Add(New PlotInfo("Chincoteague", "April", 53)) - data.Add(New PlotInfo("Chincoteague", "May", 87)) - data.Add(New PlotInfo("Chincoteague", "June", 85)) - data.Add(New PlotInfo("Chincoteague", "July", 100)) - data.Add(New PlotInfo("Chincoteague", "August", 107)) - data.Add(New PlotInfo("Chincoteague", "September", 87)) - data.Add(New PlotInfo("Chincoteague", "October", 72)) - data.Add(New PlotInfo("Chincoteague", "November", 48)) - data.Add(New PlotInfo("Chincoteague", "December", 57)) - Return data - End Function - - Public Class PlotInfo - Public Sub New(ByVal district As String, ByVal month As String, ByVal calls As Double) - Me.District = district - Me.Month = month - Me.CallsNumber = calls - End Sub - - Public Property District As String - Public Property Month As String - Public Property CallsNumber As Double - End Class - -```` - -{{endregion}} The achieved result is illustrated below: @@ -189,49 +27,9 @@ The achieved result is illustrated below: Handling the **CellPainting** event offers full control over the rendering process for a particular cell. The **HeatMapCellPaintingEventArgs** gives you access to the Graphics object and you can draw a hover rectangle like demonstrated below: -{{source=..\SamplesCS\HeatMap\HeatMapCustomPainting.cs region=HoverCellPainting}} -{{source=..\SamplesVB\HeatMap\HeatMapCustomPainting.vb region=HoverCellPainting}} - -````C# + + -private void RadHeatMap1_CellPainting(object sender, HeatMapCellPaintingEventArgs e) -{ - CellIndex hoverIndex = this.radHeatMap1.HoveredCellIndex; - if (e.Index == hoverIndex) - { - // Draw dark background below the cell, so the hover effect with transparency is clearly visible - e.Graphics.FillRectangle(Brushes.Black, e.Bounds); - - e.BorderColor = e.BackColor; - e.BackColor = Color.FromArgb(225, e.BackColor); - } - else if (e.ColumnIndex == hoverIndex.ColumnIndex || e.RowIndex == hoverIndex.RowIndex) - { - // Draw dark background below the cell, so the hover effect with transparency is clearly visible - e.Graphics.FillRectangle(Brushes.Black, e.Bounds); - e.BackColor = Color.FromArgb(220, e.BackColor); - } -} - -```` -````VB.NET - -Private Sub RadHeatMap1_CellPainting(ByVal sender As Object, ByVal e As HeatMapCellPaintingEventArgs) - Dim hoverIndex As CellIndex = Me.radHeatMap1.HoveredCellIndex - - If e.Index = hoverIndex Then - e.Graphics.FillRectangle(Brushes.Black, e.Bounds) - e.BorderColor = e.BackColor - e.BackColor = Color.FromArgb(225, e.BackColor) - ElseIf e.ColumnIndex = hoverIndex.ColumnIndex OrElse e.RowIndex = hoverIndex.RowIndex Then - e.Graphics.FillRectangle(Brushes.Black, e.Bounds) - e.BackColor = Color.FromArgb(220, e.BackColor) - End If -End Sub - -```` - -{{endregion}} ![WinForms RadHeatMap CellPainting](images/heatmap-custom-painting002.gif) @@ -244,74 +42,9 @@ The **CellPainted** event occurs when a cell has already been painted. The **HeaderCellPainting** event allows you to draw over the header cells in a similar way like for the data cells with values: -{{source=..\SamplesCS\HeatMap\HeatMapCustomPainting.cs region=HoverHeaderPainting}} -{{source=..\SamplesVB\HeatMap\HeatMapCustomPainting.vb region=HoverHeaderPainting}} - -````C# - -private void RadHeatMap1_HeaderCellPainting(object sender, HeatMapHeaderCellPaintingEventArgs e) -{ - CellIndex selectedIndex = this.radHeatMap1.SelectedCellIndex; - if (e.ColumnIndex == selectedIndex.ColumnIndex || e.RowIndex == selectedIndex.RowIndex) - { - e.BackColor = Color.FromArgb(this.radHeatMap1.Definition.GetColor(selectedIndex)); - e.ForeColor = this.radHeatMap1.Definition.GetForeColor(e.BackColor); - } - else if (e.Index == this.radHeatMap1.HoveredCellIndex) - { - // Get first cell of the row/column and extract its bacoground and foreground colors. - int rowIndex = e.RowIndex; - int columnIndex = e.ColumnIndex; - if (e.RowIndex == -1) // header cells have -1 index. - { - // Column header - rowIndex = 0; - } - - if (e.ColumnIndex == -1) // header cells have -1 index. - { - // Row header - columnIndex = 0; - } - - // If both row and column indices are -1, we are hovering the Description content cell, - // which is positioned in the corner between row and column header cells. - CellIndex index = new CellIndex(rowIndex, columnIndex); - e.BackColor = Color.FromArgb(this.radHeatMap1.Definition.GetColor(index)); - e.ForeColor = this.radHeatMap1.Definition.GetForeColor(e.BackColor); - } -} - -```` -````VB.NET - -Private Sub RadHeatMap1_HeaderCellPainting(ByVal sender As Object, ByVal e As HeatMapHeaderCellPaintingEventArgs) - Dim selectedIndex As CellIndex = Me.radHeatMap1.SelectedCellIndex - - If e.ColumnIndex = selectedIndex.ColumnIndex OrElse e.RowIndex = selectedIndex.RowIndex Then - e.BackColor = Color.FromArgb(Me.radHeatMap1.Definition.GetColor(selectedIndex)) - e.ForeColor = Me.radHeatMap1.Definition.GetForeColor(e.BackColor) - ElseIf e.Index = Me.radHeatMap1.HoveredCellIndex Then - Dim rowIndex As Integer = e.RowIndex - Dim columnIndex As Integer = e.ColumnIndex - - If e.RowIndex = -1 Then - rowIndex = 0 - End If - - If e.ColumnIndex = -1 Then - columnIndex = 0 - End If - - Dim index As CellIndex = New CellIndex(rowIndex, columnIndex) - e.BackColor = Color.FromArgb(Me.radHeatMap1.Definition.GetColor(index)) - e.ForeColor = Me.radHeatMap1.Definition.GetForeColor(e.BackColor) - End If -End Sub - -```` + + -{{endregion}} ![WinForms RadHeatMap WinForms RadHeatMap](images/heatmap-custom-painting003.gif) diff --git a/controls/heatmap/definition-types.md b/controls/heatmap/definition-types.md index 479d09640..ff87f0e61 100644 --- a/controls/heatmap/definition-types.md +++ b/controls/heatmap/definition-types.md @@ -21,51 +21,10 @@ Used to group the data by rows and columns. It has a single colorizer (**HeatMap * **ValueMember**: Gets or sets the name of the property which determines the value of a cell. * **DataSource**: Specifies the data collection. -{{source=..\SamplesCS\HeatMap\HeatMapDefinitions.cs region=CategoricalDefinition}} -{{source=..\SamplesVB\HeatMap\HeatMapDefinitions.vb region=CategoricalDefinition}} - -````C# -DataTable countryInfoTable = new DataTable(); -countryInfoTable.Columns.Add("Country", typeof(string)); -countryInfoTable.Columns.Add("Year", typeof(int)); -countryInfoTable.Columns.Add("HDI", typeof(float)); - -countryInfoTable.Rows.Add("Malta", 1985, 0.720); -countryInfoTable.Rows.Add("Italy", 1990, 0.764); -countryInfoTable.Rows.Add("Spain", 2000, 0.839); -countryInfoTable.Rows.Add("Italy", 2000, 0.825); -countryInfoTable.Rows.Add("Luxembourg", 1995, 0.816); - -CategoricalDefinition categoricalDefinition1 = new CategoricalDefinition(); -categoricalDefinition1.ColumnGroupMember = "Year"; -categoricalDefinition1.DataSource = countryInfoTable; -categoricalDefinition1.RowGroupMember = "Country"; -categoricalDefinition1.ValueMember = "HDI"; - -this.radHeatMap1.Definition = categoricalDefinition1; - -```` -````VB.NET - -Dim countryInfoTable As DataTable = New DataTable() -countryInfoTable.Columns.Add("Country", GetType(String)) -countryInfoTable.Columns.Add("Year", GetType(Integer)) -countryInfoTable.Columns.Add("HDI", GetType(Single)) -countryInfoTable.Rows.Add("Malta", 1985, 0.72) -countryInfoTable.Rows.Add("Italy", 1990, 0.764) -countryInfoTable.Rows.Add("Spain", 2000, 0.839) -countryInfoTable.Rows.Add("Italy", 2000, 0.825) -countryInfoTable.Rows.Add("Luxembourg", 1995, 0.816) -Dim categoricalDefinition1 As CategoricalDefinition = New CategoricalDefinition() -categoricalDefinition1.ColumnGroupMember = "Year" -categoricalDefinition1.DataSource = countryInfoTable -categoricalDefinition1.RowGroupMember = "Country" -categoricalDefinition1.ValueMember = "HDI" -Me.radHeatMap1.Definition = categoricalDefinition1 - -```` - -{{endregion}} + + + + ![WinForms RadHeatMap Categorical Definition](images/heatmap-definition-types001.png) @@ -74,78 +33,10 @@ Me.radHeatMap1.Definition = categoricalDefinition1 Each column is represented by a **MemberMapping**. The latter has **Header**, **ValueMember** and **Colorizer** properties that allow you to have different value members and colorizer for each column of data. The default Colorizer created for the MemberMapping is a **HeatMapGradientColorizer** with two **GradientStop**s. -{{source=..\SamplesCS\HeatMap\HeatMapDefinitions.cs region=HorizontalDefinition}} -{{source=..\SamplesVB\HeatMap\HeatMapDefinitions.vb region=HorizontalDefinition}} - -````C# - -DataTable institutionTable = new DataTable(); -institutionTable.Columns.Add("Name", typeof(string)); -institutionTable.Columns.Add("SmartRank", typeof(double)); -institutionTable.Columns.Add("AcceptanceRate",typeof(double)); -institutionTable.Columns.Add("AverageSATMathScore", typeof(double)); -institutionTable.Rows.Add("Harvard University", 1,8, 27594); -institutionTable.Rows.Add("Princeton University",2,10,7724); -institutionTable.Rows.Add("Yale University", 3, 10, 11701); -institutionTable.Rows.Add("California Institute of Technology",4,17,2175); -institutionTable.Rows.Add("Massachusetts Institute of Technology", 5,12,10566); - -HorizontalDefinition horizontalDefinition1 = new HorizontalDefinition(); -horizontalDefinition1.DataSource = institutionTable; -horizontalDefinition1.HeaderMember = "Name"; -radHeatMap1.Definition = horizontalDefinition1; -radHeatMap1.DescriptionContent = "Institution"; -radHeatMap1.RowHeaderWidth = 250; - -MemberMapping memberMapping1 = new MemberMapping(); -memberMapping1.Header = "Smart Rank"; -memberMapping1.ValueMember = "SmartRank"; -MemberMapping memberMapping2 = new MemberMapping(); -memberMapping2.Header = "Acceptance Rate (%)"; -memberMapping2.ValueMember = "AcceptanceRate"; -MemberMapping memberMapping3 = new MemberMapping(); -memberMapping3.Header = "AVG SAT Math Score"; -memberMapping3.ValueMember = "AverageSATMathScore"; - -horizontalDefinition1.MemberMappings.Add(memberMapping1); -horizontalDefinition1.MemberMappings.Add(memberMapping2); -horizontalDefinition1.MemberMappings.Add(memberMapping3); - -```` -````VB.NET - -Dim institutionTable As DataTable = New DataTable() -institutionTable.Columns.Add("Name", GetType(String)) -institutionTable.Columns.Add("SmartRank", GetType(Double)) -institutionTable.Columns.Add("AcceptanceRate", GetType(Double)) -institutionTable.Columns.Add("AverageSATMathScore", GetType(Double)) -institutionTable.Rows.Add("Harvard University", 1, 8, 27594) -institutionTable.Rows.Add("Princeton University", 2, 10, 7724) -institutionTable.Rows.Add("Yale University", 3, 10, 11701) -institutionTable.Rows.Add("California Institute of Technology", 4, 17, 2175) -institutionTable.Rows.Add("Massachusetts Institute of Technology", 5, 12, 10566) -Dim horizontalDefinition1 As HorizontalDefinition = New HorizontalDefinition() -horizontalDefinition1.DataSource = institutionTable -horizontalDefinition1.HeaderMember = "Name" -radHeatMap1.Definition = horizontalDefinition1 -radHeatMap1.DescriptionContent = "Institution" -radHeatMap1.RowHeaderWidth = 250 -Dim memberMapping1 As MemberMapping = New MemberMapping() -memberMapping1.Header = "Smart Rank" -memberMapping1.ValueMember = "SmartRank" -Dim memberMapping2 As MemberMapping = New MemberMapping() -memberMapping2.Header = "Acceptance Rate (%)" -memberMapping2.ValueMember = "AcceptanceRate" -Dim memberMapping3 As MemberMapping = New MemberMapping() -memberMapping3.Header = "AVG SAT Math Score" -memberMapping3.ValueMember = "AverageSATMathScore" -horizontalDefinition1.MemberMappings.Add(memberMapping1) -horizontalDefinition1.MemberMappings.Add(memberMapping2) -horizontalDefinition1.MemberMappings.Add(memberMapping3) - -```` - -{{endregion}} + + + + ![WinForms RadHeatMap Horizontal Definition](images/heatmap-definition-types002.png) @@ -153,78 +44,10 @@ horizontalDefinition1.MemberMappings.Add(memberMapping3) It is like the horizontal definition, but here the MemberMappings are oriented by rows. -{{source=..\SamplesCS\HeatMap\HeatMapDefinitions.cs region=VerticalDefinition}} -{{source=..\SamplesVB\HeatMap\HeatMapDefinitions.vb region=VerticalDefinition}} - -````C# - -DataTable institutionTable = new DataTable(); -institutionTable.Columns.Add("Name", typeof(string)); -institutionTable.Columns.Add("SmartRank", typeof(double)); -institutionTable.Columns.Add("AcceptanceRate", typeof(double)); -institutionTable.Columns.Add("AverageSATMathScore", typeof(double)); -institutionTable.Rows.Add("Harvard University", 1, 8, 27594); -institutionTable.Rows.Add("Princeton University", 2, 10, 7724); -institutionTable.Rows.Add("Yale University", 3, 10, 11701); -institutionTable.Rows.Add("California Institute of Technology", 4, 17, 2175); -institutionTable.Rows.Add("Massachusetts Institute of Technology", 5, 12, 10566); - -VerticalDefinition verticalDefinition1 = new VerticalDefinition(); -verticalDefinition1.DataSource = institutionTable; -verticalDefinition1.HeaderMember = "Name"; -radHeatMap1.Definition = verticalDefinition1; -radHeatMap1.DescriptionContent = "Institution"; -radHeatMap1.RowHeaderWidth = 150; - -MemberMapping memberMapping1 = new MemberMapping(); -memberMapping1.Header = "Smart Rank"; -memberMapping1.ValueMember = "SmartRank"; -MemberMapping memberMapping2 = new MemberMapping(); -memberMapping2.Header = "Acceptance Rate (%)"; -memberMapping2.ValueMember = "AcceptanceRate"; -MemberMapping memberMapping3 = new MemberMapping(); -memberMapping3.Header = "AVG SAT Math Score"; -memberMapping3.ValueMember = "AverageSATMathScore"; - -verticalDefinition1.MemberMappings.Add(memberMapping1); -verticalDefinition1.MemberMappings.Add(memberMapping2); -verticalDefinition1.MemberMappings.Add(memberMapping3); - -```` -````VB.NET - -Dim institutionTable As DataTable = New DataTable() -institutionTable.Columns.Add("Name", GetType(String)) -institutionTable.Columns.Add("SmartRank", GetType(Double)) -institutionTable.Columns.Add("AcceptanceRate", GetType(Double)) -institutionTable.Columns.Add("AverageSATMathScore", GetType(Double)) -institutionTable.Rows.Add("Harvard University", 1, 8, 27594) -institutionTable.Rows.Add("Princeton University", 2, 10, 7724) -institutionTable.Rows.Add("Yale University", 3, 10, 11701) -institutionTable.Rows.Add("California Institute of Technology", 4, 17, 2175) -institutionTable.Rows.Add("Massachusetts Institute of Technology", 5, 12, 10566) -Dim verticalDefinition1 As VerticalDefinition = New VerticalDefinition() -verticalDefinition1.DataSource = institutionTable -verticalDefinition1.HeaderMember = "Name" -radHeatMap1.Definition = verticalDefinition1 -radHeatMap1.DescriptionContent = "Institution" -radHeatMap1.RowHeaderWidth = 150 -Dim memberMapping1 As MemberMapping = New MemberMapping() -memberMapping1.Header = "Smart Rank" -memberMapping1.ValueMember = "SmartRank" -Dim memberMapping2 As MemberMapping = New MemberMapping() -memberMapping2.Header = "Acceptance Rate (%)" -memberMapping2.ValueMember = "AcceptanceRate" -Dim memberMapping3 As MemberMapping = New MemberMapping() -memberMapping3.Header = "AVG SAT Math Score" -memberMapping3.ValueMember = "AverageSATMathScore" -verticalDefinition1.MemberMappings.Add(memberMapping1) -verticalDefinition1.MemberMappings.Add(memberMapping2) -verticalDefinition1.MemberMappings.Add(memberMapping3) - -```` - -{{endregion}} + + + + ![WinForms RadHeatMap Horizontal Definition](images/heatmap-definition-types003.png) diff --git a/controls/heatmap/getting-started.md b/controls/heatmap/getting-started.md index 5d50d4fc0..8c85b27be 100644 --- a/controls/heatmap/getting-started.md +++ b/controls/heatmap/getting-started.md @@ -41,32 +41,11 @@ This article shows how you can start using **RadHeatMap**. Just drag a RadHeatMa To use the RadHeatMap control you will need to define a model that will describe the data that will be shown. -{{source=..\SamplesCS\HeatMap\HeatMapGettingStarted.cs region=Model}} -{{source=..\SamplesVB\HeatMap\HeatMapGettingStarted.vb region=Model}} + + -````C# -public class TempInfo -{ - public int Year { get; set; } - public string Month { get; set; } - public double Temperature { get; set; } -} -```` -````VB.NET - -Public Class TempInfo - Public Property Year As Integer - Public Property Month As String - Public Property Temperature As Double -End Class - - -```` - -{{endregion}} - ## Setting up the Control The control works with a few different definitions that describe how to data will be shown. In this example, we will use the __CategoricalDefinition__. The definition provides few properties to define what data should be used. @@ -76,70 +55,10 @@ The control works with a few different definitions that describe how to data wil What's left is to create our sample data and set the DataSource property of the __CategoricalDefinition__. Then this definition needs to be applied to the __RadHeatMap.Definition__ property. -{{source=..\SamplesCS\HeatMap\HeatMapGettingStarted.cs region=Populate}} -{{source=..\SamplesVB\HeatMap\HeatMapGettingStarted.vb region=Populate}} - -````C# - -private void PrepareData() -{ - int year = 2018; - string[] months = new string[6] { "Jan", "Feb", "Mar", "Apr", "May", "Jun" }; - var randomNumberGenerator = new Random(); - - var source = new BindingList(); - for (int i = 0; i < months.Length; i++) - { - for (int k = 0; k < 6; k++) - { - var info = new TempInfo() { Year = year + k, Month = months[i], Temperature = randomNumberGenerator.Next(10, 300) }; - source.Add(info); - } - } - CategoricalDefinition categoricalDefinition = new CategoricalDefinition(); - categoricalDefinition.RowGroupMember = "Year"; - categoricalDefinition.ColumnGroupMember = "Month"; - categoricalDefinition.ValueMember = "Temperature"; - categoricalDefinition.DataSource= source; - this.radHeatMap1.DisplayCellText = true; - this.radHeatMap1.Definition = categoricalDefinition; -} - - -```` -````VB.NET - -Private Sub PrepareData() - Dim year As Integer = 2018 - Dim months As String() = New String(5) {"Jan", "Feb", "Mar", "Apr", "May", "Jun"} - Dim randomNumberGenerator = New Random() - Dim source = New BindingList(Of TempInfo)() - - For i As Integer = 0 To months.Length - 1 - - For k As Integer = 0 To 6 - 1 - Dim info = New TempInfo() With { - .Year = year + k, - .Month = months(i), - .Temperature = randomNumberGenerator.[Next](10, 300) - } - source.Add(info) - Next - Next - - Dim categoricalDefinition As CategoricalDefinition = New CategoricalDefinition() - categoricalDefinition.RowGroupMember = "Year" - categoricalDefinition.ColumnGroupMember = "Month" - categoricalDefinition.ValueMember = "Temperature" - categoricalDefinition.DataSource = source - Me.RadHeatMap1.DisplayCellText = True - Me.RadHeatMap1.Definition = categoricalDefinition -End Sub - - -```` - -{{endregion}} + + + + ## See Also diff --git a/controls/heatmap/legend.md b/controls/heatmap/legend.md index bf35865f9..f69f8e42e 100644 --- a/controls/heatmap/legend.md +++ b/controls/heatmap/legend.md @@ -51,44 +51,9 @@ The LegendElement.**VisualItemCreating** event allows you to control whether a l #### Legend -{{source=..\SamplesCS\HeatMap\HeatMapDefinitions.cs region=DisplayLegend}} -{{source=..\SamplesVB\HeatMap\HeatMapDefinitions.vb region=DisplayLegend}} - -````C# - public void DisplyLegend() - { - this.radHeatMap1.LegendElement.VisualItemCreating += this.LegendElement_VisualItemCreating; - this.radHeatMap1.ShowLegend = true; - } - - private void LegendElement_VisualItemCreating(object sender, Telerik.WinControls.UI.HeatMap.LegendItemElementCreatingEventArgs e) - { - if (e.ItemElement is LegendGradientItemElement gradientElement) - { - gradientElement.From = 0.45; - gradientElement.To = 0.95; - } - } - -```` -````VB.NET - - Public Sub DisplyLegend() - AddHandler Me.radHeatMap1.LegendElement.VisualItemCreating, AddressOf Me.LegendElement_VisualItemCreating - Me.radHeatMap1.ShowLegend = True - End Sub - - Private Sub LegendElement_VisualItemCreating(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.HeatMap.LegendItemElementCreatingEventArgs) - Dim gradientElement As LegendGradientItemElement = TryCast(e.ItemElement, LegendGradientItemElement) - - If gradientElement IsNot Nothing Then - gradientElement.From = 0.45 - gradientElement.[To] = 0.95 - End If - End Sub -```` - -{{endregion}} + + + ## See Also diff --git a/controls/heatmap/populating-with-data/data-binding.md b/controls/heatmap/populating-with-data/data-binding.md index 7265dfa5f..a3fb877a0 100644 --- a/controls/heatmap/populating-with-data/data-binding.md +++ b/controls/heatmap/populating-with-data/data-binding.md @@ -18,117 +18,16 @@ In order to demonstrate how to populate a __RadHeatMap__ with data, we will crea #### __Example 1: Setting up the model__ -{{source=..\SamplesCS\HeatMap\HeatMapDataBinding.cs region=Bind_Model}} -{{source=..\SamplesVB\HeatMap\HeatMapDataBinding.vb region=Bind_Model}} + + -````C# -public class TempInfo -{ - public DateTime Year { get; set; } - public string Month { get; set; } - public double Temperature { get; set; } -} -```` -````VB.NET - -Public Class TempInfo - Public Property Year As DateTime - Public Property Month As String - Public Property Temperature As Double -End Class - - -```` - -{{endregion}} - #### __Example 2: Creating Sample Data__ -{{source=..\SamplesCS\HeatMap\HeatMapDataBinding.cs region=Bind_SampleData}} -{{source=..\SamplesVB\HeatMap\HeatMapDataBinding.vb region=Bind_SampleData}} - -````C# -private BindingList PrepareData() -{ - DateTime date = DateTime.Today; - var infos = new BindingList() - { - new TempInfo() { Year = date, Month = "Jan", Temperature = 17}, - new TempInfo() { Year = date, Month = "Feb", Temperature = 8}, - new TempInfo() { Year = date, Month = "Mar", Temperature = 20}, - new TempInfo() { Year = date.AddYears(1), Month = "Jan", Temperature = 5}, - new TempInfo() { Year = date.AddYears(1), Month = "Feb", Temperature = 13}, - new TempInfo() { Year = date.AddYears(1), Month = "Mar", Temperature = 21}, - new TempInfo() { Year = date.AddYears(2), Month = "Jan", Temperature = 14}, - new TempInfo() { Year = date.AddYears(2), Month = "Feb", Temperature = 19}, - new TempInfo() { Year = date.AddYears(2), Month = "Mar", Temperature = 17}, - }; - return infos; -} - - -```` -````VB.NET - -Private Function PrepareData() As BindingList(Of TempInfo) - Dim _date As DateTime = DateTime.Today - Dim infos = New BindingList(Of TempInfo)() From { - New TempInfo() With { - .Year = _date, - .Month = "Jan", - .Temperature = 17 - }, - New TempInfo() With { - .Year = _date, - .Month = "Feb", - .Temperature = 8 - }, - New TempInfo() With { - .Year = _date, - .Month = "Mar", - .Temperature = 20 - }, - New TempInfo() With { - .Year = _date.AddYears(1), - .Month = "Jan", - .Temperature = 5 - }, - New TempInfo() With { - .Year = _date.AddYears(1), - .Month = "Feb", - .Temperature = 13 - }, - New TempInfo() With { - .Year = _date.AddYears(1), - .Month = "Mar", - .Temperature = 21 - }, - New TempInfo() With { - .Year = _date.AddYears(2), - .Month = "Jan", - .Temperature = 14 - }, - New TempInfo() With { - .Year = _date.AddYears(2), - .Month = "Feb", - .Temperature = 19 - }, - New TempInfo() With { - .Year = _date.AddYears(2), - .Month = "Mar", - .Temperature = 17 - } - } - Return infos -End Function - - - -```` - -{{endregion}} + + + ## Definitions @@ -146,40 +45,10 @@ The definition provides few properties to define what data should be used. The __RowGroupMember__ in our example, will point to a __DateTime__ type property. To format the DateTime value, we can use the __RowHeaderTextFormat__ property of the control. The __ColumnGroupMember__ will represent the Month property. What's left is to set our value for the cell through the __ValueMember__, which in our case will be the Temperature property value. #### __Example 3: Categorical Definition__ -{{source=..\SamplesCS\HeatMap\HeatMapDataBinding.cs region=Bind_SampleData_CategoricalDefinition}} -{{source=..\SamplesVB\HeatMap\HeatMapDataBinding.vb region=Bind_SampleData_CategoricalDefinition}} - -````C# - -CategoricalDefinition categoricalDefinition = new CategoricalDefinition(); -categoricalDefinition.RowGroupMember = "Year"; -categoricalDefinition.ColumnGroupMember = "Month"; -categoricalDefinition.ValueMember = "Temperature"; -categoricalDefinition.DataSource = PrepareData(); -this.radHeatMap1.Definition = categoricalDefinition; -this.radHeatMap1.RowHeaderWidth = 40; -this.radHeatMap1.RowHeaderTextFormat = "yyyy"; -this.radHeatMap1.HeaderCellTextAlignment = ContentAlignment.MiddleCenter; - + + -```` -````VB.NET -Dim categoricalDefinition As CategoricalDefinition = New CategoricalDefinition() -categoricalDefinition.RowGroupMember = "Year" -categoricalDefinition.ColumnGroupMember = "Month" -categoricalDefinition.ValueMember = "Temperature" -categoricalDefinition.DataSource = PrepareData() -Me.radHeatMap1.Definition = categoricalDefinition -Me.radHeatMap1.RowHeaderWidth = 40 -Me.radHeatMap1.RowHeaderTextFormat = "yyyy" -Me.radHeatMap1.HeaderCellTextAlignment = ContentAlignment.MiddleCenter - - - -```` - -{{endregion}} ![WinForms RadHeatMapMap Data Binding Categorical Definition](images/heatmap-data-binding01.png) @@ -188,90 +57,10 @@ Me.radHeatMap1.HeaderCellTextAlignment = ContentAlignment.MiddleCenter Alternatively, we can also use a __VerticalDefinition__. We'll set the months as __HeaderPath__ of our HeatMap. Thus the months supplied by the Month property of our underlying source will be visualized as column headers. For each row, we'll display the Temperature and Rain values of the corresponding month. However, this setup may not clearly indicate which month belongs to which year. To address this, we can customize the column headers by subscribing to the HeaderCellPainting event of the control. Within the event handler, we can specifically target the column header row and retrieve information about the associated data item from the first data cell in the column. #### __Example 4: Vertical Definition__ -{{source=..\SamplesCS\HeatMap\HeatMapDataBinding.cs region=Bind_SampleData_VerticalDefinition}} -{{source=..\SamplesVB\HeatMap\HeatMapDataBinding.vb region=Bind_SampleData_VerticalDefinition}} - -````C# - -private void Bind_VerticalDefinition() -{ - HeatMapGradientColorizer heatMapGradientColorizer = new HeatMapGradientColorizer(); - ColorConverter colorConverter = new ColorConverter(); - heatMapGradientColorizer.GradientStops = new List() - { - new GradientStop() { Color=(Color)new ColorConverter().ConvertFromString("#D9E7F1"), Position=0 }, - new GradientStop() { Color=(Color)new ColorConverter().ConvertFromString("#01518C"), Position=1 } - }; - VerticalDefinition verticalDefinition = new VerticalDefinition(); - verticalDefinition.DataSource = PrepareData(); - verticalDefinition.HeaderMember = "Month"; - verticalDefinition.MemberMappings = new MemberMappingsCollection() { - new MemberMapping() { Header = "Temperature in Celsius", ValueMember = "Temperature",}, - new MemberMapping() { Header = "Rain in Centimeters", ValueMember = "Rain", Colorizer = heatMapGradientColorizer } - }; - this.radHeatMap1.HeatMapElement.RowHeaderWidth = 130; - this.radHeatMap1.HeaderCellPainting += RadHeatMap1_HeaderCellPainting; - this.radHeatMap1.Definition = verticalDefinition; -} - -private void RadHeatMap1_HeaderCellPainting(object sender, HeatMapHeaderCellPaintingEventArgs e) -{ - if (e.Index.ColumnIndex > -1 && e.Index.RowIndex == -1) - { - var heatMapItem = this.radHeatMap1.Definition.GetDataItem(new CellIndex(0,e.Index.ColumnIndex)); - var dataBoundItem = heatMapItem.DataBoundItem as TempInfo; - e.Text = dataBoundItem.Year.ToString("yyyy") +" "+ dataBoundItem.Month; - } -} - - -```` -````VB.NET - -Private Sub Bind_VerticalDefinition() - Dim heatMapGradientColorizer As HeatMapGradientColorizer = New HeatMapGradientColorizer() - Dim colorConverter As ColorConverter = New ColorConverter() - heatMapGradientColorizer.GradientStops = New List(Of GradientStop)() From { - New GradientStop() With { - .Color = CType(New ColorConverter().ConvertFromString("#D9E7F1"), Color), - .Position = 0 - }, - New GradientStop() With { - .Color = CType(New ColorConverter().ConvertFromString("#01518C"), Color), - .Position = 1 - } - } - Dim verticalDefinition As VerticalDefinition = New VerticalDefinition() - verticalDefinition.DataSource = PrepareData() - verticalDefinition.HeaderMember = "Month" - verticalDefinition.MemberMappings = New MemberMappingsCollection() From { - New MemberMapping() With { - .Header = "Temperature in Celsius", - .ValueMember = "Temperature" - }, - New MemberMapping() With { - .Header = "Rain in Centimeters", - .ValueMember = "Rain", - .Colorizer = heatMapGradientColorizer - } - } - Me.radHeatMap1.HeatMapElement.RowHeaderWidth = 130 - AddHandler Me.radHeatMap1.HeaderCellPainting, AddressOf RadHeatMap1_HeaderCellPainting - Me.radHeatMap1.Definition = verticalDefinition -End Sub - -Private Sub RadHeatMap1_HeaderCellPainting(ByVal sender As Object, ByVal e As HeatMapHeaderCellPaintingEventArgs) - If e.Index.ColumnIndex > -1 AndAlso e.Index.RowIndex = -1 Then - Dim heatMapItem = Me.radHeatMap1.Definition.GetDataItem(New CellIndex(0, e.Index.ColumnIndex)) - Dim dataBoundItem = TryCast(heatMapItem.DataBoundItem, TempInfo) - e.Text = dataBoundItem.Year.ToString("yyyy") & " " + dataBoundItem.Month - End If -End Sub - - -```` - -{{endregion}} + + + + ![WinForms RadHeatMapMap Data Binding Vertical Definition](images/heatmap-data-binding02.png) @@ -280,92 +69,10 @@ End Sub This definition closely resembles the __VerticalDefinition__, with the distinction that the property value of our underlying source, specifically the __HeaderMember__ property, will be represented as row headers. To accommodate this, we must make adjustments to the __HeaderCellPainting__ event handler to correctly handle the row headers instead of the column headers. #### __Example 5: Horizontal Definition__ -{{source=..\SamplesCS\HeatMap\HeatMapDataBinding.cs region=Bind_SampleData_HorizontalDefinition}} -{{source=..\SamplesVB\HeatMap\HeatMapDataBinding.vb region=Bind_SampleData_HorizontalDefinition}} - -````C# - -private void Bind_HorizontalDefinition() -{ - HeatMapGradientColorizer heatMapGradientColorizer = new HeatMapGradientColorizer(); - ColorConverter colorConverter = new ColorConverter(); - heatMapGradientColorizer.GradientStops = new List() - { - new GradientStop() { Color=(Color)new ColorConverter().ConvertFromString("#D9E7F1"), Position=0 }, - new GradientStop() { Color=(Color)new ColorConverter().ConvertFromString("#01518C"), Position=1 } - }; - HorizontalDefinition horizontalDefinition = new HorizontalDefinition(); - horizontalDefinition.DataSource = PrepareData(); - horizontalDefinition.HeaderMember = "Month"; - horizontalDefinition.MemberMappings = new MemberMappingsCollection() - { - new MemberMapping() { Header = "Temperature in Celsius", ValueMember = "Temperature",}, - new MemberMapping() { Header = "Rain in Centimeters", ValueMember = "Rain", Colorizer = heatMapGradientColorizer } - }; - this.radHeatMap1.HeatMapElement.RowHeaderWidth = 80; - this.radHeatMap1.HeaderCellPainting += RadHeatMap1_HeaderCellPainting1; - this.radHeatMap1.Definition = horizontalDefinition; -} - -private void RadHeatMap1_HeaderCellPainting1(object sender, HeatMapHeaderCellPaintingEventArgs e) -{ - if (e.Index.ColumnIndex == -1 && e.Index.RowIndex > -1) - { - var heatMapItem = this.radHeatMap1.Definition.GetDataItem(new CellIndex(e.Index.RowIndex, 0)); - var dataBoundItem = heatMapItem.DataBoundItem as TempInfo; - e.Text = dataBoundItem.Year.ToString("yyyy") + " " + dataBoundItem.Month; - } -} - - - -```` -````VB.NET - -Private Sub Bind_HorizontalDefinition() - Dim heatMapGradientColorizer As HeatMapGradientColorizer = New HeatMapGradientColorizer() - Dim colorConverter As ColorConverter = New ColorConverter() - heatMapGradientColorizer.GradientStops = New List(Of GradientStop)() From { - New GradientStop() With { - .Color = CType(New ColorConverter().ConvertFromString("#D9E7F1"), Color), - .Position = 0 - }, - New GradientStop() With { - .Color = CType(New ColorConverter().ConvertFromString("#01518C"), Color), - .Position = 1 - } - } - Dim horizontalDefinition As HorizontalDefinition = New HorizontalDefinition() - horizontalDefinition.DataSource = PrepareData() - horizontalDefinition.HeaderMember = "Month" - horizontalDefinition.MemberMappings = New MemberMappingsCollection() From { - New MemberMapping() With { - .Header = "Temperature in Celsius", - .ValueMember = "Temperature" - }, - New MemberMapping() With { - .Header = "Rain in Centimeters", - .ValueMember = "Rain", - .Colorizer = heatMapGradientColorizer - } - } - Me.radHeatMap1.HeatMapElement.RowHeaderWidth = 80 - AddHandler Me.radHeatMap1.HeaderCellPainting, AddressOf RadHeatMap1_HeaderCellPainting1 - Me.radHeatMap1.Definition = horizontalDefinition -End Sub - -Private Sub RadHeatMap1_HeaderCellPainting1(ByVal sender As Object, ByVal e As HeatMapHeaderCellPaintingEventArgs) - If e.Index.ColumnIndex = -1 AndAlso e.Index.RowIndex > -1 Then - Dim heatMapItem = Me.radHeatMap1.Definition.GetDataItem(New CellIndex(e.Index.RowIndex, 0)) - Dim dataBoundItem = TryCast(heatMapItem.DataBoundItem, TempInfo) - e.Text = dataBoundItem.Year.ToString("yyyy") & " " + dataBoundItem.Month - End If -End Sub - - -```` - -{{endregion}} + + + + ![WinForms RadHeatMapMap Data Binding Horizontal Definition](images/heatmap-data-binding03.png) diff --git a/controls/heatmap/populating-with-data/unbound-mode.md b/controls/heatmap/populating-with-data/unbound-mode.md index c78e7d2c2..f4ec60265 100644 --- a/controls/heatmap/populating-with-data/unbound-mode.md +++ b/controls/heatmap/populating-with-data/unbound-mode.md @@ -19,73 +19,10 @@ In this example, we will showcase the usage of the CategoricalDefinition to illu >note RadHeatMap supports __Empty Values__. In situations where you don't have a specific value for a particular category, you can indicate it by using the special object double.NaN. When a category is marked with double.NaN, the RadHeatMap control will visualize it with **no** color. This visual representation helps to indicate the absence of a value for that specific category. Thus, when using a dark theme, the empty cells remain dark, when using light themes, the empty cells remain light. #### __Example 1: Categorical Definition__ -{{source=..\SamplesCS\HeatMap\HeatMapDataBinding.cs region=UnboundMode_CategoricalDefinition}} -{{source=..\SamplesVB\HeatMap\HeatMapDataBinding.vb region=UnboundMode_CategoricalDefinition}} + + -````C# -CategoricalDefinition def = new CategoricalDefinition(); -HeatMapGradientColorizer colorizer = new HeatMapGradientColorizer(); -colorizer.GradientStops.Add(new GradientStop(ColorTranslator.FromHtml("#FFF8696B"), 0.0f)); -colorizer.GradientStops.Add(new GradientStop(ColorTranslator.FromHtml("#FFFFEB84"), 0.3f)); -colorizer.GradientStops.Add(new GradientStop(ColorTranslator.FromHtml("#FF63BE7B"), 1.0f)); -def.Colorizer = colorizer; -def.Items.Add(new CategoricalHeatMapItem("Sweden", 1950, 7015)); -def.Items.Add(new CategoricalHeatMapItem("Sweden", 1960, 7481)); -def.Items.Add(new CategoricalHeatMapItem("Sweden", 1970, 8043)); -def.Items.Add(new CategoricalHeatMapItem("Sweden", 1980, double.NaN)); -def.Items.Add(new CategoricalHeatMapItem("Sweden", 1990, 8601)); -def.Items.Add(new CategoricalHeatMapItem("Sweden", 2000, 8925)); -def.Items.Add(new CategoricalHeatMapItem("Denmark", 1950, 4272)); -def.Items.Add(new CategoricalHeatMapItem("Denmark", 1960, 4582)); -def.Items.Add(new CategoricalHeatMapItem("Denmark", 1970, 4929)); -def.Items.Add(new CategoricalHeatMapItem("Denmark", 1980, 5124)); -def.Items.Add(new CategoricalHeatMapItem("Denmark", 1990, 5141)); -def.Items.Add(new CategoricalHeatMapItem("Denmark", 2000, 5338)); -def.Items.Add(new CategoricalHeatMapItem("Switzerland", 1950, 4695)); -def.Items.Add(new CategoricalHeatMapItem("Switzerland", 1960, double.NaN)); -def.Items.Add(new CategoricalHeatMapItem("Switzerland", 1970, 6268)); -def.Items.Add(new CategoricalHeatMapItem("Switzerland", 1980, 6386)); -def.Items.Add(new CategoricalHeatMapItem("Switzerland", 1990, 6844)); -def.Items.Add(new CategoricalHeatMapItem("Switzerland", 2000, 7278)); -this.radHeatMap1.RowHeaderWidth = 100; -this.radHeatMap1.Definition = def; - - -```` -````VB.NET - -Dim def As CategoricalDefinition = New CategoricalDefinition() -Dim colorizer As HeatMapGradientColorizer = New HeatMapGradientColorizer() -colorizer.GradientStops.Add(New GradientStop(ColorTranslator.FromHtml("#FFF8696B"), 0.0F)) -colorizer.GradientStops.Add(New GradientStop(ColorTranslator.FromHtml("#FFFFEB84"), 0.3F)) -colorizer.GradientStops.Add(New GradientStop(ColorTranslator.FromHtml("#FF63BE7B"), 1.0F)) -def.Colorizer = colorizer -def.Items.Add(New CategoricalHeatMapItem("Sweden", 1950, 7015)) -def.Items.Add(New CategoricalHeatMapItem("Sweden", 1960, 7481)) -def.Items.Add(New CategoricalHeatMapItem("Sweden", 1970, 8043)) -def.Items.Add(New CategoricalHeatMapItem("Sweden", 1980, Double.NaN)) -def.Items.Add(New CategoricalHeatMapItem("Sweden", 1990, 8601)) -def.Items.Add(New CategoricalHeatMapItem("Sweden", 2000, 8925)) -def.Items.Add(New CategoricalHeatMapItem("Denmark", 1950, 4272)) -def.Items.Add(New CategoricalHeatMapItem("Denmark", 1960, 4582)) -def.Items.Add(New CategoricalHeatMapItem("Denmark", 1970, 4929)) -def.Items.Add(New CategoricalHeatMapItem("Denmark", 1980, 5124)) -def.Items.Add(New CategoricalHeatMapItem("Denmark", 1990, 5141)) -def.Items.Add(New CategoricalHeatMapItem("Denmark", 2000, 5338)) -def.Items.Add(New CategoricalHeatMapItem("Switzerland", 1950, 4695)) -def.Items.Add(New CategoricalHeatMapItem("Switzerland", 1960, Double.NaN)) -def.Items.Add(New CategoricalHeatMapItem("Switzerland", 1970, 6268)) -def.Items.Add(New CategoricalHeatMapItem("Switzerland", 1980, 6386)) -def.Items.Add(New CategoricalHeatMapItem("Switzerland", 1990, 6844)) -def.Items.Add(New CategoricalHeatMapItem("Switzerland", 2000, 7278)) -Me.radHeatMap1.RowHeaderWidth = 100 -Me.radHeatMap1.Definition = def - - -```` - -{{endregion}} ![WinForms RadHeatMapMap Unbound Mode CategoricalDefinition](images/heatmap-unbound-mode01.png) @@ -98,215 +35,10 @@ To populate the heatmap with data, we add HeatMapItem objects to the "Items" col >note The only difference between the Horizontal and Vertical definitions is that for the horizontal definition, each item gets a row, while for the vertical – it's a column. #### __Example 2: Horizontal Definition__ -{{source=..\SamplesCS\HeatMap\HeatMapDataBinding.cs region=UnboundMode_HorizontalDefinition}} -{{source=..\SamplesVB\HeatMap\HeatMapDataBinding.vb region=UnboundMode_HorizontalDefinition}} - -````C# - -Color PoorColor = ColorTranslator.FromHtml("#FFE9F3FF"); -Color GoodColor = ColorTranslator.FromHtml("#FF1F78B4"); - -HeatMapRangeColorizer SmartRankColorizer = new HeatMapRangeColorizer() -{ - IsAbsolute = false, - Colors = new HeatMapRangeColorCollection() - { - new HeatMapRangeColor() {From = 0, To = 0.25, Color = Color.Yellow}, - new HeatMapRangeColor() {From = 0.25, To = 0.5, Color = Color.Orange}, - new HeatMapRangeColor() {From = 0.5, To = 0.75, Color = Color.Red}, - new HeatMapRangeColor() {From = 0.75, To = 1, Color = Color.Brown}, - } -}; - -HeatMapDesaturationColorizer AcceptanceRateColorizer = new HeatMapDesaturationColorizer() -{ - StartColor = Color.Green, - From = 1, - To = 0.2 -}; - -HeatMapGradientColorizer EnrolledStudentsColorizer = new HeatMapGradientColorizer(); -EnrolledStudentsColorizer.GradientStops = new List() -{ - new GradientStop() { Position = 0f, Color = Color.Red }, - new GradientStop() { Position = 0.5f, Color = Color.Yellow }, - new GradientStop() { Position = 1f, Color = Color.YellowGreen }, -}; - -HeatMapGradientColorizer SATMathScoreColorizer = new HeatMapGradientColorizer(); -SATMathScoreColorizer.GradientStops = new List() -{ - new GradientStop() { Position = 0f, Color = PoorColor}, - new GradientStop() { Position = 1f, Color = GoodColor}, -}; - -HeatMapGradientColorizer SATVerbalScoreColorizer = new HeatMapGradientColorizer(); -SATVerbalScoreColorizer.GradientStops = new List() -{ - new GradientStop(){ Position = 0f, Color = PoorColor}, - new GradientStop(){ Position = 1f, Color = GoodColor}, -}; - -HeatMapGradientColorizer SATCompositeScoreColorizer = new HeatMapGradientColorizer(); -SATCompositeScoreColorizer.GradientStops = new List() -{ - new GradientStop(){ Position = 0f, Color = PoorColor}, - new GradientStop(){ Position = 1f, Color = GoodColor}, -}; - -VerticalDefinition deff = new VerticalDefinition(); - -deff.MemberMappings = new MemberMappingsCollection() -{ - new MemberMapping() { Header = "Smart Rank", ValueMember = "SmartRank", Colorizer = SmartRankColorizer }, - new MemberMapping() { Header = "Acceptance Rate (%)", ValueMember = "AcceptanceRate", Colorizer = AcceptanceRateColorizer } , - new MemberMapping() { Header = "Total Enrolled Students", ValueMember = "TotalEnrolledStudents", Colorizer = EnrolledStudentsColorizer }, - new MemberMapping() { Header = "AVG SAT Math Score", ValueMember = "AverageSATMathScore", Colorizer = SATMathScoreColorizer }, - new MemberMapping() { Header = "AVG SAT Verbal Score", ValueMember = "AverageSATVerbalScore", Colorizer = SATVerbalScoreColorizer } -}; - -deff.Items.Add(new HeatMapItem("Harvard University", 1, 8, 27594, 740, 745, 33, 98, 38415, 38415, 31728)); -deff.Items.Add(new HeatMapItem("Princeton University", 2, 10, 7724, 745, 740, 33, 99, 36640, 36640, 16502)); -deff.Items.Add(new HeatMapItem("Yale University", 3, 10, 11701, 745, 750, 32, 99, 38300, 38300, 19374)); -deff.Items.Add(new HeatMapItem("California Institute of Technology", 4, 17, 2175, 785, 730, 34, 98, 36282, 36282, 1772)); -deff.Items.Add(new HeatMapItem("Massachusetts Institute of Technology", 5, 12, 10566, 760, 710, 33, 97, 39212, 39212, 9712)); -deff.Items.Add(new HeatMapItem("Stanford University", 6, 9, 19535, 730, 705, 32, 98, 40172, 40172, 13851)); -deff.Items.Add(new HeatMapItem("Williams College", 7, 17, 2101, 710, 710, 31, 96, 41434, 41434, 1784)); -deff.Items.Add(new HeatMapItem("Amherst College", 8, 15, 1794, 710, 710, 31, 96, 40862, 40862, 1641)); -deff.Items.Add(new HeatMapItem("Pomona College", 9, 16, 1560, 735, 740, 32, 97, 38394, 38394, 1700)); -deff.Items.Add(new HeatMapItem("Swarthmore College", 10, 16, 1524, 715, 720, 31, 94, 39600, 39600, 1508)); -deff.Items.Add(new HeatMapItem("University of Chicago", 11, 28, 15152, 705, 715, 31, 98, 42041, 42041, 6575)); -this.radHeatMap1.Definition = deff; - - -```` -````VB.NET - -Dim PoorColor As Color = ColorTranslator.FromHtml("#FFE9F3FF") -Dim GoodColor As Color = ColorTranslator.FromHtml("#FF1F78B4") -Dim SmartRankColorizer As HeatMapRangeColorizer = New HeatMapRangeColorizer() With { - .IsAbsolute = False, - .Colors = New HeatMapRangeColorCollection() From { - New HeatMapRangeColor() With { - .From = 0, - .[To] = 0.25, - .Color = Color.Yellow - }, - New HeatMapRangeColor() With { - .From = 0.25, - .[To] = 0.5, - .Color = Color.Orange - }, - New HeatMapRangeColor() With { - .From = 0.5, - .[To] = 0.75, - .Color = Color.Red - }, - New HeatMapRangeColor() With { - .From = 0.75, - .[To] = 1, - .Color = Color.Brown - } - } -} -Dim AcceptanceRateColorizer As HeatMapDesaturationColorizer = New HeatMapDesaturationColorizer() With { - .StartColor = Color.Green, - .From = 1, - .[To] = 0.2 -} -Dim EnrolledStudentsColorizer As HeatMapGradientColorizer = New HeatMapGradientColorizer() -EnrolledStudentsColorizer.GradientStops = New List(Of GradientStop)() From { - New GradientStop() With { - .Position = 0F, - .Color = Color.Red - }, - New GradientStop() With { - .Position = 0.5F, - .Color = Color.Yellow - }, - New GradientStop() With { - .Position = 1F, - .Color = Color.YellowGreen - } -} -Dim SATMathScoreColorizer As HeatMapGradientColorizer = New HeatMapGradientColorizer() -SATMathScoreColorizer.GradientStops = New List(Of GradientStop)() From { - New GradientStop() With { - .Position = 0F, - .Color = PoorColor - }, - New GradientStop() With { - .Position = 1F, - .Color = GoodColor - } -} -Dim SATVerbalScoreColorizer As HeatMapGradientColorizer = New HeatMapGradientColorizer() -SATVerbalScoreColorizer.GradientStops = New List(Of GradientStop)() From { - New GradientStop() With { - .Position = 0F, - .Color = PoorColor - }, - New GradientStop() With { - .Position = 1F, - .Color = GoodColor - } -} -Dim SATCompositeScoreColorizer As HeatMapGradientColorizer = New HeatMapGradientColorizer() -SATCompositeScoreColorizer.GradientStops = New List(Of GradientStop)() From { - New GradientStop() With { - .Position = 0F, - .Color = PoorColor - }, - New GradientStop() With { - .Position = 1F, - .Color = GoodColor - } -} -Dim deff As VerticalDefinition = New VerticalDefinition() -deff.MemberMappings = New MemberMappingsCollection() From { - New MemberMapping() With { - .Header = "Smart Rank", - .ValueMember = "SmartRank", - .Colorizer = SmartRankColorizer - }, - New MemberMapping() With { - .Header = "Acceptance Rate (%)", - .ValueMember = "AcceptanceRate", - .Colorizer = AcceptanceRateColorizer - }, - New MemberMapping() With { - .Header = "Total Enrolled Students", - .ValueMember = "TotalEnrolledStudents", - .Colorizer = EnrolledStudentsColorizer - }, - New MemberMapping() With { - .Header = "AVG SAT Math Score", - .ValueMember = "AverageSATMathScore", - .Colorizer = SATMathScoreColorizer - }, - New MemberMapping() With { - .Header = "AVG SAT Verbal Score", - .ValueMember = "AverageSATVerbalScore", - .Colorizer = SATVerbalScoreColorizer - } -} -deff.Items.Add(New HeatMapItem("Harvard University", 1, 8, 27594, 740, 745, 33, 98, 38415, 38415, 31728)) -deff.Items.Add(New HeatMapItem("Princeton University", 2, 10, 7724, 745, 740, 33, 99, 36640, 36640, 16502)) -deff.Items.Add(New HeatMapItem("Yale University", 3, 10, 11701, 745, 750, 32, 99, 38300, 38300, 19374)) -deff.Items.Add(New HeatMapItem("California Institute of Technology", 4, 17, 2175, 785, 730, 34, 98, 36282, 36282, 1772)) -deff.Items.Add(New HeatMapItem("Massachusetts Institute of Technology", 5, 12, 10566, 760, 710, 33, 97, 39212, 39212, 9712)) -deff.Items.Add(New HeatMapItem("Stanford University", 6, 9, 19535, 730, 705, 32, 98, 40172, 40172, 13851)) -deff.Items.Add(New HeatMapItem("Williams College", 7, 17, 2101, 710, 710, 31, 96, 41434, 41434, 1784)) -deff.Items.Add(New HeatMapItem("Amherst College", 8, 15, 1794, 710, 710, 31, 96, 40862, 40862, 1641)) -deff.Items.Add(New HeatMapItem("Pomona College", 9, 16, 1560, 735, 740, 32, 97, 38394, 38394, 1700)) -deff.Items.Add(New HeatMapItem("Swarthmore College", 10, 16, 1524, 715, 720, 31, 94, 39600, 39600, 1508)) -deff.Items.Add(New HeatMapItem("University of Chicago", 11, 28, 15152, 705, 715, 31, 98, 42041, 42041, 6575)) -Me.radHeatMap1.Definition = deff - + + -```` -{{endregion}} ![WinForms RadHeatMapMap Unbound Mode HorizontalDefinition](images/heatmap-unbound-mode02.png) diff --git a/controls/heatmap/selection.md b/controls/heatmap/selection.md index 79d670565..3d48c971c 100644 --- a/controls/heatmap/selection.md +++ b/controls/heatmap/selection.md @@ -29,24 +29,9 @@ In addition to these properties, the RadHeatMap control also provides two events * __SelectedCellIndexChanged__: This event is triggered when the index of the selected cell changes. It allows you to respond to changes for the current selected cell and perform any necessary actions or updates. #### __Example 1: Modify Selected Cell__ -{{source=..\SamplesCS\HeatMap\HeatMapDataBinding.cs region=Selection_Border}} -{{source=..\SamplesVB\HeatMap\HeatMapDataBinding.vb region=Selection_Border}} + + -````C# -this.radHeatMap1.SelectedCellBorderColor = Color.Green; -this.radHeatMap1.SelectedCellBorderWidth = 3; - - -```` -````VB.NET - -Me.RadHeatMap1.SelectedCellBorderColor = Color.Green -Me.RadHeatMap1.SelectedCellBorderWidth = 3 - - -```` - -{{endregion}} #### __Figure 1: RadHeatMap with customize selection border__ @@ -57,22 +42,9 @@ Me.RadHeatMap1.SelectedCellBorderWidth = 3 We can set the selected cell through the __SelectedCellIndex__ property. #### __Example 2: Programmatic Selection__ -{{source=..\SamplesCS\HeatMap\HeatMapDataBinding.cs region=SelectedCellIndex}} -{{source=..\SamplesVB\HeatMap\HeatMapDataBinding.vb region=SelectedCellIndex}} - -````C# -this.radHeatMap1.SelectedCellIndex = new CellIndex(2,2); - - -```` -````VB.NET - -Me.RadHeatMap1.SelectedCellIndex = New CellIndex(2,2) - - -```` + + -{{endregion}} ## Hover State diff --git a/controls/heatmap/tooltip-screentip.md b/controls/heatmap/tooltip-screentip.md index 238bd6a66..15c76dbc6 100644 --- a/controls/heatmap/tooltip-screentip.md +++ b/controls/heatmap/tooltip-screentip.md @@ -31,42 +31,10 @@ In this example, we will customize the ScreenTip visual appereance. For this pur #### __Example 1: ScreenTipShowing Event__ -{{source=..\SamplesCS\HeatMap\HeatMapDataBinding.cs region=ScreenTipShowing}} -{{source=..\SamplesVB\HeatMap\HeatMapDataBinding.vb region=ScreenTipShowing}} - -````C# -private void RadHeatMap1_ScreenTipShowing1(object sender, HeatMapScreenTipEventArgs e) -{ - if(e.Index.IsDataCell) - { - var heatMap = sender as RadHeatMapElement; - var heatMapItem = heatMap.Definition.GetDataItem(e.Index); - var dataBoundObject = heatMapItem.DataBoundItem as TempInfo; - e.CaptionText = "Cell Value: " + e.CaptionText; - e.Text = "Row Data: "+dataBoundObject.Year.ToString("yyyy") + " Column Data: " + dataBoundObject.Month; - e.FooterText = "RowIndex: " + e.Index.RowIndex + " ColumnIndex: " + e.Index.ColumnIndex; - } -} - - -```` -````VB.NET - -Private Sub RadHeatMap1_ScreenTipShowing1(ByVal sender As Object, ByVal e As HeatMapScreenTipEventArgs) - If e.Index.IsDataCell Then - Dim heatMap = TryCast(sender, RadHeatMapElement) - Dim heatMapItem = heatMap.Definition.GetDataItem(e.Index) - Dim dataBoundObject = TryCast(heatMapItem.DataBoundItem, TempInfo) - e.CaptionText = "Cell Value: " & e.CaptionText - e.Text = "Row Data: " & dataBoundObject.Year.ToString("yyyy") & " Column Data: " + dataBoundObject.Month - e.FooterText = "RowIndex: " & e.Index.RowIndex & " ColumnIndex: " + e.Index.ColumnIndex - End If -End Sub - - -```` - -{{endregion}} + + + + ![WinForms RadHeatMap ScreenTip ScreenTipShowing](images/heatmap-tooltip-screentip02.png) diff --git a/controls/image-editor/features/adustments.md b/controls/image-editor/features/adustments.md index d646ac5c3..e6132f842 100644 --- a/controls/image-editor/features/adustments.md +++ b/controls/image-editor/features/adustments.md @@ -33,20 +33,10 @@ The Hue can be adjusted with the respective dialog, the values can be from 0 to This can be done in the code behind as well. -{{source=..\SamplesCS\ImageEditor\ImageEditorFeatures.cs region=Hue}} -{{source=..\SamplesVB\ImageEditor\ImageEditorFeatures.vb region=Hue}} -````C# -radImageEditor1.ImageEditorElement.SetHue(200); -radImageEditor1.ImageEditorElement.SaveState(); + + -```` -````VB.NET -radImageEditor1.ImageEditorElement.SetHue(200) -radImageEditor1.ImageEditorElement.SaveState() -```` - -{{endregion}} # Saturation adjustment @@ -58,21 +48,10 @@ The Saturation can be adjusted with the respective dialog the values can be from To do this programmatically use the __SetSaturation__ method. -{{source=..\SamplesCS\ImageEditor\ImageEditorFeatures.cs region=Sat}} -{{source=..\SamplesVB\ImageEditor\ImageEditorFeatures.vb region=Sat}} - -````C# -radImageEditor1.ImageEditorElement.SetSaturation(-50); -radImageEditor1.ImageEditorElement.SaveState(); + + -```` -````VB.NET -radImageEditor1.ImageEditorElement.SetSaturation(-50) -radImageEditor1.ImageEditorElement.SaveState() -```` - -{{endregion}} # Contrast and Brightness adjustment @@ -84,21 +63,10 @@ The Contrast and Brightness can be adjusted with the respective dialog the value This can be done in the code behind as well. -{{source=..\SamplesCS\ImageEditor\ImageEditorFeatures.cs region=Contrast}} -{{source=..\SamplesVB\ImageEditor\ImageEditorFeatures.vb region=Contrast}} - -````C# -radImageEditor1.ImageEditorElement.SetContrastAndBrightness(100, 10); -radImageEditor1.ImageEditorElement.SaveState(); + + -```` -````VB.NET -radImageEditor1.ImageEditorElement.SetContrastAndBrightness(100, 10) -radImageEditor1.ImageEditorElement.SaveState() -```` - -{{endregion}} # Invert Colors @@ -110,21 +78,10 @@ The Invert Color button just inverts the colors in the image pixel by pixel. This action can be performed in code with the following method. -{{source=..\SamplesCS\ImageEditor\ImageEditorFeatures.cs region=Invert}} -{{source=..\SamplesVB\ImageEditor\ImageEditorFeatures.vb region=Invert}} - -````C# -radImageEditor1.ImageEditorElement.InvertColors(); -radImageEditor1.ImageEditorElement.SaveState(); - -```` -````VB.NET -radImageEditor1.ImageEditorElement.InvertColors() -radImageEditor1.ImageEditorElement.SaveState() + + -```` -{{endregion}} # See Also diff --git a/controls/image-editor/features/canvas-resize.md b/controls/image-editor/features/canvas-resize.md index 00e87c76c..1e08692b8 100644 --- a/controls/image-editor/features/canvas-resize.md +++ b/controls/image-editor/features/canvas-resize.md @@ -22,21 +22,10 @@ The following snippet shows how you can use the __ResizeCanvas__ method. You wil #### Use the ResizeCanvas method -{{source=..\SamplesCS\ImageEditor\ImageEditorFeatures.cs region=Canvas}} -{{source=..\SamplesVB\ImageEditor\ImageEditorFeatures.vb region=Canvas}} -````C# -radImageEditor1.ImageEditorElement.ResizeCanvas(500, 500, ContentAlignment.BottomRight, Color.Red); -radImageEditor1.ImageEditorElement.SaveState(); + + -```` -````VB.NET -radImageEditor1.ImageEditorElement.ResizeCanvas(500, 500, ContentAlignment.BottomRight, Color.Red) -radImageEditor1.ImageEditorElement.SaveState() -```` - - -{{endregion}} # See Also diff --git a/controls/image-editor/features/crop.md b/controls/image-editor/features/crop.md index 291c4e47b..5da7c8103 100644 --- a/controls/image-editor/features/crop.md +++ b/controls/image-editor/features/crop.md @@ -20,22 +20,10 @@ To perform a Crop operation use the __Crop__ method. You need to pass a rectangl #### Crop Programmatically -{{source=..\SamplesCS\ImageEditor\ImageEditorFeatures.cs region=Crop}} -{{source=..\SamplesVB\ImageEditor\ImageEditorFeatures.vb region=Crop}} -````C# -radImageEditor1.ImageEditorElement.Crop(new Rectangle(0, 0, 20, 20)); -radImageEditor1.ImageEditorElement.SaveState(); + + -```` -````VB.NET -radImageEditor1.ImageEditorElement.Crop(New Rectangle(0, 0, 20, 20)) -radImageEditor1.ImageEditorElement.SaveState() -```` - - - -{{endregion}} # See Also diff --git a/controls/image-editor/features/drawing.md b/controls/image-editor/features/drawing.md index 0e221bd21..960340d0b 100644 --- a/controls/image-editor/features/drawing.md +++ b/controls/image-editor/features/drawing.md @@ -34,22 +34,10 @@ To draw text click the button and the __DrawText__ dialog will be shown. In it y The following snippet shows how you can add text using the RadImageEditor API. -{{source=..\SamplesCS\ImageEditor\ImageEditorFeatures.cs region=DrawText}} -{{source=..\SamplesVB\ImageEditor\ImageEditorFeatures.vb region=DrawText}} -````C# -radImageEditor1.ImageEditorElement.DrawString("Test", 12, Color.Red, 200, 200, 120); -radImageEditor1.ImageEditorElement.SaveState(); + + -```` -````VB.NET -radImageEditor1.ImageEditorElement.DrawString("Test", 12, Color.Red, 200, 200, 120) -radImageEditor1.ImageEditorElement.SaveState() -```` - - - -{{endregion}} ## Draw Shape @@ -77,28 +65,10 @@ The currently supported shapes are: To draw a shape in the code behind you need to provide a path. The bellow code demonstrates how you ca create a RoundRectShape: -{{source=..\SamplesCS\ImageEditor\ImageEditorFeatures.cs region=DrawShape}} -{{source=..\SamplesVB\ImageEditor\ImageEditorFeatures.vb region=DrawShape}} -````C# -RoundRectShape shape = new RoundRectShape(); -Rectangle rect = new Rectangle(0, 0, 100, 100); -var path = shape.CreatePath(rect); -radImageEditor1.ImageEditorElement.DrawShape(path, Color.Red, Color.Green, 3); -radImageEditor1.ImageEditorElement.SaveState(); - -```` -````VB.NET -Dim shape As New RoundRectShape() -Dim rect As New Rectangle(0, 0, 100, 100) -Dim path = shape.CreatePath(rect) -radImageEditor1.ImageEditorElement.DrawShape(path, Color.Red, Color.Green, 3) -radImageEditor1.ImageEditorElement.SaveState() - -```` - + + -{{endregion}} ## Draw with a Pen diff --git a/controls/image-editor/features/effects.md b/controls/image-editor/features/effects.md index 89142d944..ffa0a0650 100644 --- a/controls/image-editor/features/effects.md +++ b/controls/image-editor/features/effects.md @@ -25,20 +25,10 @@ Once you click the Sharpen button the sharpen dialog will appear and you will be This can be performed programmatically as well. The following snippet shows how you can apply the Sharpen effect. -{{source=..\SamplesCS\ImageEditor\ImageEditorFeatures.cs region=Sharp}} -{{source=..\SamplesVB\ImageEditor\ImageEditorFeatures.vb region=Sharp}} -````C# -radImageEditor1.ImageEditorElement.Sharpen(100); -radImageEditor1.ImageEditorElement.SaveState(); + + -```` -````VB.NET -radImageEditor1.ImageEditorElement.Sharpen(100) -radImageEditor1.ImageEditorElement.SaveState() -```` - -{{endregion}} # Blur @@ -48,20 +38,10 @@ Once you click the Blur button the blur dialog will appear and you will be able This can be performed programmatically as well. The following snippet shows how you can apply the Blur effect. -{{source=..\SamplesCS\ImageEditor\ImageEditorFeatures.cs region=Blur}} -{{source=..\SamplesVB\ImageEditor\ImageEditorFeatures.vb region=Blur}} -````C# -radImageEditor1.ImageEditorElement.Blur(100); -radImageEditor1.ImageEditorElement.SaveState(); - -```` -````VB.NET -radImageEditor1.ImageEditorElement.Blur(100) -radImageEditor1.ImageEditorElement.SaveState() + + -```` -{{endregion}} # See Also diff --git a/controls/image-editor/features/flip.md b/controls/image-editor/features/flip.md index a3b41bf39..f75e53894 100644 --- a/controls/image-editor/features/flip.md +++ b/controls/image-editor/features/flip.md @@ -21,21 +21,10 @@ The following spinet shows how you can access and use the __RotateFlip__ method. #### Flip programmatically -{{source=..\SamplesCS\ImageEditor\ImageEditorFeatures.cs region=Flip}} -{{source=..\SamplesVB\ImageEditor\ImageEditorFeatures.vb region=Flip}} -````C# -radImageEditor1.ImageEditorElement.RotateFlip(RotateFlipType.RotateNoneFlipX); -radImageEditor1.ImageEditorElement.SaveState(); + + -```` -````VB.NET -radImageEditor1.ImageEditorElement.RotateFlip(RotateFlipType.RotateNoneFlipX) -radImageEditor1.ImageEditorElement.SaveState() -```` - - -{{endregion}} # See Also diff --git a/controls/image-editor/features/history.md b/controls/image-editor/features/history.md index a147f576a..d0ba9b075 100644 --- a/controls/image-editor/features/history.md +++ b/controls/image-editor/features/history.md @@ -18,24 +18,8 @@ Undo/Redo commands can be executed from the UI. You can use the methods as well. -{{source=..\SamplesCS\ImageEditor\ImageEditorFeatures.cs region=UndoRedo}} -{{source=..\SamplesVB\ImageEditor\ImageEditorFeatures.vb region=UndoRedo}} -````C# -radImageEditor1.ImageEditorElement.Undo(); -//or -radImageEditor1.ImageEditorElement.Redo(); - -```` -````VB.NET -radImageEditor1.ImageEditorElement.Undo() -'or -radImageEditor1.ImageEditorElement.Redo() - -```` - - - -{{endregion}} + + diff --git a/controls/image-editor/features/resize.md b/controls/image-editor/features/resize.md index 49c44906d..55a604cf4 100644 --- a/controls/image-editor/features/resize.md +++ b/controls/image-editor/features/resize.md @@ -22,19 +22,8 @@ You can resize an image that is loaded inside the image editor with code as well #### Resize Programmatically -{{source=..\SamplesCS\ImageEditor\ImageEditorFeatures.cs region=Resize}} -{{source=..\SamplesVB\ImageEditor\ImageEditorFeatures.vb region=Resize}} -````C# -radImageEditor1.ImageEditorElement.Resize(500, 500); -radImageEditor1.ImageEditorElement.SaveState(); + + -```` -````VB.NET -radImageEditor1.ImageEditorElement.Resize(500, 500) -radImageEditor1.ImageEditorElement.SaveState() -```` - -{{endregion}} - diff --git a/controls/image-editor/features/rotate.md b/controls/image-editor/features/rotate.md index 64f73b0d5..aeb44acdd 100644 --- a/controls/image-editor/features/rotate.md +++ b/controls/image-editor/features/rotate.md @@ -21,21 +21,10 @@ The following spinet shows how you can access and use the __RotateFlip__ method. #### Rotate programmatically -{{source=..\SamplesCS\ImageEditor\ImageEditorFeatures.cs region=Rotate}} -{{source=..\SamplesVB\ImageEditor\ImageEditorFeatures.vb region=Rotate}} -````C# -radImageEditor1.ImageEditorElement.RotateFlip(RotateFlipType.Rotate270FlipNone); -radImageEditor1.ImageEditorElement.SaveState(); + + -```` -````VB.NET -radImageEditor1.ImageEditorElement.RotateFlip(RotateFlipType.Rotate270FlipNone) -radImageEditor1.ImageEditorElement.SaveState() -```` - - -{{endregion}} # See Also diff --git a/controls/image-editor/features/round-corners.md b/controls/image-editor/features/round-corners.md index 5693395a8..8b4b4c6a6 100644 --- a/controls/image-editor/features/round-corners.md +++ b/controls/image-editor/features/round-corners.md @@ -21,21 +21,10 @@ The following snippet shows how you can round the corners with the RoundCorners #### Round Corners in code. -{{source=..\SamplesCS\ImageEditor\ImageEditorFeatures.cs region=Corners}} -{{source=..\SamplesVB\ImageEditor\ImageEditorFeatures.vb region=Corners}} -````C# -radImageEditor1.ImageEditorElement.RoundCorners(100, Color.Red, 2, Color.Green); -radImageEditor1.ImageEditorElement.SaveState(); + + -```` -````VB.NET -radImageEditor1.ImageEditorElement.RoundCorners(100, Color.Red, 2, Color.Green) -radImageEditor1.ImageEditorElement.SaveState() -```` - - -{{endregion}} # See Also diff --git a/controls/image-editor/localization.md b/controls/image-editor/localization.md index dc5f83218..719fd6739 100644 --- a/controls/image-editor/localization.md +++ b/controls/image-editor/localization.md @@ -22,323 +22,18 @@ Below is a sample implementation of an English localization provider: #### Localizing RadImageEditor Strings -{{source=..\SamplesCS\ImageEditor\ImageEditorLocalization.cs region=MyLocalizationProvider}} -{{source=..\SamplesVB\ImageEditor\ImageEditorLocalization.vb region=MyLocalizationProvider}} -````C# -public class MyImageEditorLocalizationProvider : ImageEditorLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case ImageEditorStringId.OpenCommandTooltip: return "Open Image"; - case ImageEditorStringId.SaveCommandTooltip: return "Save Image"; - case ImageEditorStringId.UndoCommandTooltip: return "Undo"; - case ImageEditorStringId.RedoCommandTooltip: return "Redo"; - case ImageEditorStringId.ResizeDialogTitle: return "Resize"; - case ImageEditorStringId.ResizeDialogImageSize: return "Image Size (px)"; - case ImageEditorStringId.ResizeDialogWidth: return "Width"; - case ImageEditorStringId.ResizeDialogHeight: return "Height"; - case ImageEditorStringId.ResizeDialogRelativeSize: return "Relative Size (%)"; - case ImageEditorStringId.ResizeDialogRelativeWidth: return "Width"; - case ImageEditorStringId.ResizeDialogRelativeHeight: return "Height"; - case ImageEditorStringId.ResizeDialogPreserveAspectRatio: return "Preserve Aspect Ratio"; - case ImageEditorStringId.ResizeDialogReset: return "Reset"; - case ImageEditorStringId.CanvasResizeDialogTitle: return "Resize Canvas"; - case ImageEditorStringId.CanvasResizeDialogCanvasSize: return "Canvas Size"; - case ImageEditorStringId.CanvasResizeDialogWidth: return "Width"; - case ImageEditorStringId.CanvasResizeDialogHeight: return "Height"; - case ImageEditorStringId.CanvasResizeDialogImageAlignment: return "Image Alignment"; - case ImageEditorStringId.CanvasResizeDialogBackground: return "Background"; - case ImageEditorStringId.CanvasResizeDialogReset: return "Reset"; - case ImageEditorStringId.RoundCornersDialogTitle: return "Round Corners"; - case ImageEditorStringId.RoundCornersDialogRadius: return "Radius"; - case ImageEditorStringId.RoundCornersDialogBackground: return "Background"; - case ImageEditorStringId.RoundCornersDialogBorderThickness: return "Border Thickness"; - case ImageEditorStringId.RoundCornersDialogBorderColor: return "Border Color"; - case ImageEditorStringId.RoundCornersDialogReset: return "Reset"; - case ImageEditorStringId.CropAccept: return "Accept"; - case ImageEditorStringId.CropCancel: return "Cancel"; - case ImageEditorStringId.DrawTextDialogTitle: return "Draw Text"; - case ImageEditorStringId.DrawTextDialogText: return "Text"; - case ImageEditorStringId.DrawTextDialogYourTextHere: return "Your Text Here..."; - case ImageEditorStringId.DrawTextDialogFontSize: return "Font Size"; - case ImageEditorStringId.DrawTextDialogTextColort: return "Text Colort"; - case ImageEditorStringId.DrawTextDialogHorizontalPosition: return "Horizontal Position"; - case ImageEditorStringId.DrawTextDialogVerticalPosition: return "Vertical Position"; - case ImageEditorStringId.DrawTextDialogRotation: return "Rotation"; - case ImageEditorStringId.DrawTextDialogReset: return "Reset"; - case ImageEditorStringId.DrawDialogTitle: return "Draw"; - case ImageEditorStringId.DrawDialogBrushSize: return "Brush Size"; - case ImageEditorStringId.DrawDialogBrushColor: return "Brush Color"; - case ImageEditorStringId.DrawShapeDialogTitle: return "Draw Shape"; - case ImageEditorStringId.DrawShapeDialogShape: return "Shape"; - case ImageEditorStringId.DrawShapeDialogShapeFill: return "Shape Fill"; - case ImageEditorStringId.DrawShapeDialogBorderThickness: return "Border Thickness"; - case ImageEditorStringId.DrawShapeDialogBorderColor: return "Border Color"; - case ImageEditorStringId.ShapeTypeRectangle: return "Rectangle"; - case ImageEditorStringId.ShapeTypeSquare: return "Square"; - case ImageEditorStringId.ShapeTypeEllipse: return "Ellipse"; - case ImageEditorStringId.ShapeTypeCircle: return "Circle"; - case ImageEditorStringId.ShapeTypeLine: return "Line"; - case ImageEditorStringId.ShapeTypeFreeflow: return "Freeflow"; - case ImageEditorStringId.HueDialogTitle: return "Hue"; - case ImageEditorStringId.HueDialogHueShift: return "Hue Shift"; - case ImageEditorStringId.HueDialogReset: return "Reset"; - case ImageEditorStringId.SaturationDialogTitle: return "Saturation"; - case ImageEditorStringId.SaturationDialogSaturation: return "Saturation"; - case ImageEditorStringId.SaturationDialogReset: return "Reset"; - case ImageEditorStringId.ContrastAndBrightnessDialogTitle: return "Contrast & Brightness"; - case ImageEditorStringId.ContrastAndBrightnessDialogBrightness: return "Brightness"; - case ImageEditorStringId.ContrastAndBrightnessDialogContrast: return "Contrast"; - case ImageEditorStringId.ContrastAndBrightnessDialogReset: return "Reset"; - case ImageEditorStringId.SharpenDialogTitle: return "Sharpen"; - case ImageEditorStringId.SharpenDialogAmount: return "Amount"; - case ImageEditorStringId.SharpenDialogReset: return "Reset"; - case ImageEditorStringId.BlurDialogTitle: return "Blur"; - case ImageEditorStringId.BlurDialogAmount: return "Amount"; - case ImageEditorStringId.BlurDialogReset: return "Reset"; - case ImageEditorStringId.ZoomFactorAuto: return "Auto"; - case ImageEditorStringId.CommandsTransform: return "Transform"; - case ImageEditorStringId.CommandsResize: return "Resize"; - case ImageEditorStringId.CommandsCanvasResize: return "Canvas Resize"; - case ImageEditorStringId.CommandsRotate90: return "Rotate 90"; - case ImageEditorStringId.CommandsRotate180: return "Rotate 180"; - case ImageEditorStringId.CommandsRotate270: return "Rotate 270"; - case ImageEditorStringId.CommandsRoundCorners: return "Round Corners"; - case ImageEditorStringId.CommandsFlipHorizontal: return "Flip Horizontal"; - case ImageEditorStringId.CommandsFlipVertical: return "Flip Vertical"; - case ImageEditorStringId.CommandsCrop: return "Crop"; - case ImageEditorStringId.CommandsDrawText: return "Draw Text"; - case ImageEditorStringId.CommandsDraw: return "Draw"; - case ImageEditorStringId.CommandsDrawShape: return "Draw Shape"; - case ImageEditorStringId.CommandsPan: return "Pan"; - case ImageEditorStringId.CommandsAdjust: return "Adjust"; - case ImageEditorStringId.CommandsHue: return "Hue"; - case ImageEditorStringId.CommandsSaturation: return "Saturation"; - case ImageEditorStringId.CommandsContrast: return "Contrast"; - case ImageEditorStringId.CommandsInvertColors: return "InvertColors"; - case ImageEditorStringId.CommandsEffects: return "Effects"; - case ImageEditorStringId.CommandsSharpen: return "Sharpen"; - case ImageEditorStringId.CommandsBlur: return "Blur"; - default: return base.GetLocalizedString(id); - } - } -} - -```` -````VB.NET -Public Class MyImageEditorLocalizationProvider - Inherits ImageEditorLocalizationProvider - Public Overrides Function GetLocalizedString(ByVal id As String) As String - Select Case id - Case ImageEditorStringId.OpenCommandTooltip - Return "Open Image" - Case ImageEditorStringId.SaveCommandTooltip - Return "Save Image" - Case ImageEditorStringId.UndoCommandTooltip - Return "Undo" - Case ImageEditorStringId.RedoCommandTooltip - Return "Redo" - Case ImageEditorStringId.ResizeDialogTitle - Return "Resize" - Case ImageEditorStringId.ResizeDialogImageSize - Return "Image Size (px)" - Case ImageEditorStringId.ResizeDialogWidth - Return "Width" - Case ImageEditorStringId.ResizeDialogHeight - Return "Height" - Case ImageEditorStringId.ResizeDialogRelativeSize - Return "Relative Size (%)" - Case ImageEditorStringId.ResizeDialogRelativeWidth - Return "Width" - Case ImageEditorStringId.ResizeDialogRelativeHeight - Return "Height" - Case ImageEditorStringId.ResizeDialogPreserveAspectRatio - Return "Preserve Aspect Ratio" - Case ImageEditorStringId.ResizeDialogReset - Return "Reset" - Case ImageEditorStringId.CanvasResizeDialogTitle - Return "Resize Canvas" - Case ImageEditorStringId.CanvasResizeDialogCanvasSize - Return "Canvas Size" - Case ImageEditorStringId.CanvasResizeDialogWidth - Return "Width" - Case ImageEditorStringId.CanvasResizeDialogHeight - Return "Height" - Case ImageEditorStringId.CanvasResizeDialogImageAlignment - Return "Image Alignment" - Case ImageEditorStringId.CanvasResizeDialogBackground - Return "Background" - Case ImageEditorStringId.CanvasResizeDialogReset - Return "Reset" - Case ImageEditorStringId.RoundCornersDialogTitle - Return "Round Corners" - Case ImageEditorStringId.RoundCornersDialogRadius - Return "Radius" - Case ImageEditorStringId.RoundCornersDialogBackground - Return "Background" - Case ImageEditorStringId.RoundCornersDialogBorderThickness - Return "Border Thickness" - Case ImageEditorStringId.RoundCornersDialogBorderColor - Return "Border Color" - Case ImageEditorStringId.RoundCornersDialogReset - Return "Reset" - Case ImageEditorStringId.CropAccept - Return "Accept" - Case ImageEditorStringId.CropCancel - Return "Cancel" - Case ImageEditorStringId.DrawTextDialogTitle - Return "Draw Text" - Case ImageEditorStringId.DrawTextDialogText - Return "Text" - Case ImageEditorStringId.DrawTextDialogYourTextHere - Return "Your Text Here..." - Case ImageEditorStringId.DrawTextDialogFontSize - Return "Font Size" - Case ImageEditorStringId.DrawTextDialogTextColort - Return "Text Colort" - Case ImageEditorStringId.DrawTextDialogHorizontalPosition - Return "Horizontal Position" - Case ImageEditorStringId.DrawTextDialogVerticalPosition - Return "Vertical Position" - Case ImageEditorStringId.DrawTextDialogRotation - Return "Rotation" - Case ImageEditorStringId.DrawTextDialogReset - Return "Reset" - Case ImageEditorStringId.DrawDialogTitle - Return "Draw" - Case ImageEditorStringId.DrawDialogBrushSize - Return "Brush Size" - Case ImageEditorStringId.DrawDialogBrushColor - Return "Brush Color" - Case ImageEditorStringId.DrawShapeDialogTitle - Return "Draw Shape" - Case ImageEditorStringId.DrawShapeDialogShape - Return "Shape" - Case ImageEditorStringId.DrawShapeDialogShapeFill - Return "Shape Fill" - Case ImageEditorStringId.DrawShapeDialogBorderThickness - Return "Border Thickness" - Case ImageEditorStringId.DrawShapeDialogBorderColor - Return "Border Color" - Case ImageEditorStringId.ShapeTypeRectangle - Return "Rectangle" - Case ImageEditorStringId.ShapeTypeSquare - Return "Square" - Case ImageEditorStringId.ShapeTypeEllipse - Return "Ellipse" - Case ImageEditorStringId.ShapeTypeCircle - Return "Circle" - Case ImageEditorStringId.ShapeTypeLine - Return "Line" - Case ImageEditorStringId.ShapeTypeFreeflow - Return "Freeflow" - Case ImageEditorStringId.HueDialogTitle - Return "Hue" - Case ImageEditorStringId.HueDialogHueShift - Return "Hue Shift" - Case ImageEditorStringId.HueDialogReset - Return "Reset" - Case ImageEditorStringId.SaturationDialogTitle - Return "Saturation" - Case ImageEditorStringId.SaturationDialogSaturation - Return "Saturation" - Case ImageEditorStringId.SaturationDialogReset - Return "Reset" - Case ImageEditorStringId.ContrastAndBrightnessDialogTitle - Return "Contrast & Brightness" - Case ImageEditorStringId.ContrastAndBrightnessDialogBrightness - Return "Brightness" - Case ImageEditorStringId.ContrastAndBrightnessDialogContrast - Return "Contrast" - Case ImageEditorStringId.ContrastAndBrightnessDialogReset - Return "Reset" - Case ImageEditorStringId.SharpenDialogTitle - Return "Sharpen" - Case ImageEditorStringId.SharpenDialogAmount - Return "Amount" - Case ImageEditorStringId.SharpenDialogReset - Return "Reset" - Case ImageEditorStringId.BlurDialogTitle - Return "Blur" - Case ImageEditorStringId.BlurDialogAmount - Return "Amount" - Case ImageEditorStringId.BlurDialogReset - Return "Reset" - Case ImageEditorStringId.ZoomFactorAuto - Return "Auto" - Case ImageEditorStringId.CommandsTransform - Return "Transform" - Case ImageEditorStringId.CommandsResize - Return "Resize" - Case ImageEditorStringId.CommandsCanvasResize - Return "Canvas Resize" - Case ImageEditorStringId.CommandsRotate90 - Return "Rotate 90" - Case ImageEditorStringId.CommandsRotate180 - Return "Rotate 180" - Case ImageEditorStringId.CommandsRotate270 - Return "Rotate 270" - Case ImageEditorStringId.CommandsRoundCorners - Return "Round Corners" - Case ImageEditorStringId.CommandsFlipHorizontal - Return "Flip Horizontal" - Case ImageEditorStringId.CommandsFlipVertical - Return "Flip Vertical" - Case ImageEditorStringId.CommandsCrop - Return "Crop" - Case ImageEditorStringId.CommandsDrawText - Return "Draw Text" - Case ImageEditorStringId.CommandsDraw - Return "Draw" - Case ImageEditorStringId.CommandsDrawShape - Return "Draw Shape" - Case ImageEditorStringId.CommandsPan - Return "Pan" - Case ImageEditorStringId.CommandsAdjust - Return "Adjust" - Case ImageEditorStringId.CommandsHue - Return "Hue" - Case ImageEditorStringId.CommandsSaturation - Return "Saturation" - Case ImageEditorStringId.CommandsContrast - Return "Contrast" - Case ImageEditorStringId.CommandsInvertColors - Return "InvertColors" - Case ImageEditorStringId.CommandsEffects - Return "Effects" - Case ImageEditorStringId.CommandsSharpen - Return "Sharpen" - Case ImageEditorStringId.CommandsBlur - Return "Blur" - Case Else - Return MyBase.GetLocalizedString(id) - End Select - End Function -End Class - -```` - - -{{endregion}} - + + + + + #### Assigning the Current Localization Provider -{{source=..\SamplesCS\ImageEditor\ImageEditorLocalization.cs region=SetProvider}} -{{source=..\SamplesVB\ImageEditor\ImageEditorLocalization.vb region=SetProvider}} -````C# -ImageEditorLocalizationProvider.CurrentProvider = new MyImageEditorLocalizationProvider(); - -```` -````VB.NET -ImageEditorLocalizationProvider.CurrentProvider = New MyImageEditorLocalizationProvider() - -```` - -{{endregion}} - - + + + + + # See Also * [Structure]({%slug radimageeditor-structure%}) diff --git a/controls/layoutcontrol/customizing-appearance.md b/controls/layoutcontrol/customizing-appearance.md index 25893e2c9..806679bf1 100644 --- a/controls/layoutcontrol/customizing-appearance.md +++ b/controls/layoutcontrol/customizing-appearance.md @@ -19,21 +19,10 @@ You can use the __PreviewRectangleFill__ and __PreviewRectangleStroke__ propert #### Setting Fill and Stroke -{{source=..\SamplesCS\LayoutControl\CustomizeLayoutControl.cs region=FillStroke}} -{{source=..\SamplesVB\LayoutControl\CustomizeLayoutControl.vb region=FillStroke}} + + -````C# -radLayoutControl1.ContainerElement.PreviewRectangleFill = ColorTranslator.FromHtml("#008de7"); -radLayoutControl1.ContainerElement.PreviewRectangleStroke = ColorTranslator.FromHtml("#e83737"); -```` -````VB.NET -radLayoutControl1.ContainerElement.PreviewRectangleFill = ColorTranslator.FromHtml("#008de7") -radLayoutControl1.ContainerElement.PreviewRectangleStroke = ColorTranslator.FromHtml("#e83737") - -```` - -{{endregion}} >caption Figure 1:Changed Fill and Stroke ![WinForms RadLayoutControl Changed Fill and Stroke](images/layoutcontrol-customize-appearance001.gif) @@ -44,125 +33,46 @@ radLayoutControl1.ContainerElement.PreviewRectangleStroke = ColorTranslator.From #### Change BackColor and Font -{{source=..\SamplesCS\LayoutControl\CustomizeLayoutControl.cs region=LabelItem}} -{{source=..\SamplesVB\LayoutControl\CustomizeLayoutControl.vb region=LabelItem}} - -````C# -layoutControlLabelItem5.BackColor = ColorTranslator.FromHtml("#008de7"); -layoutControlLabelItem5.GradientStyle = Telerik.WinControls.GradientStyles.Solid; -layoutControlLabelItem5.DrawFill = true; -layoutControlLabelItem5.Font = new Font("Segoe Script", 16, FontStyle.Regular); + + -```` -````VB.NET -layoutControlLabelItem5.BackColor = ColorTranslator.FromHtml("#008de7") -layoutControlLabelItem5.GradientStyle = Telerik.WinControls.GradientStyles.Solid -layoutControlLabelItem5.DrawFill = True -layoutControlLabelItem5.Font = New Font("Segoe Script", 16, FontStyle.Regular) -```` - -{{endregion}} * __LayoutControlSeparatorItem:__ By default this item shows only a single line, however you can customize its __Thickness__ and __BackColor__. #### Customize Separator Item -{{source=..\SamplesCS\LayoutControl\CustomizeLayoutControl.cs region=Separator}} -{{source=..\SamplesVB\LayoutControl\CustomizeLayoutControl.vb region=Separator}} - -````C# -layoutControlSeparatorItem1.Thickness = 10; -layoutControlSeparatorItem1.DrawFill = true; -layoutControlSeparatorItem1.BackColor = ColorTranslator.FromHtml("#008de7"); -layoutControlSeparatorItem1.GradientStyle = Telerik.WinControls.GradientStyles.Solid; - -```` -````VB.NET -layoutControlSeparatorItem1.Thickness = 10 -layoutControlSeparatorItem1.DrawFill = True -layoutControlSeparatorItem1.BackColor = ColorTranslator.FromHtml("#008de7") -layoutControlSeparatorItem1.GradientStyle = Telerik.WinControls.GradientStyles.Solid + + -```` -{{endregion}} * __LayoutControlSplitterItem:__ By default this element does not draw its fill. The following snippet shows how you can change its __BackColor__ and __Thickness__. #### Customize Splitter Item -{{source=..\SamplesCS\LayoutControl\CustomizeLayoutControl.cs region=Splitter}} -{{source=..\SamplesVB\LayoutControl\CustomizeLayoutControl.vb region=Splitter}} + + -````C# -layoutControlSplitterItem1.Thickness = 10; -layoutControlSplitterItem1.DrawFill = true; -layoutControlSplitterItem1.BackColor = ColorTranslator.FromHtml("#e83737"); -layoutControlSplitterItem1.GradientStyle = Telerik.WinControls.GradientStyles.Solid; -```` -````VB.NET -layoutControlSplitterItem1.Thickness = 10 -layoutControlSplitterItem1.DrawFill = True -layoutControlSplitterItem1.BackColor = ColorTranslator.FromHtml("#e83737") -layoutControlSplitterItem1.GradientStyle = Telerik.WinControls.GradientStyles.Solid - -```` - -{{endregion}} * __LayoutControlGroupItem:__ The following code shows how you can access and customize the group item header. #### Customize Group Header -{{source=..\SamplesCS\LayoutControl\CustomizeLayoutControl.cs region=Group}} -{{source=..\SamplesVB\LayoutControl\CustomizeLayoutControl.vb region=Group}} - -````C# -this.layoutControlGroupItem1.HeaderElement.Font = new Font("Segoe Script", 14, FontStyle.Regular); -this.layoutControlGroupItem1.HeaderElement.BackColor = ColorTranslator.FromHtml("#008de7"); -this.layoutControlGroupItem1.HeaderElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid; -this.layoutControlGroupItem1.HeaderElement.HeaderButtonElement.DrawFill = false; -this.layoutControlGroupItem1.HeaderElement.HeaderButtonElement.DrawBorder = false; -this.layoutControlGroupItem1.ShowHeaderLine = false; + + -```` -````VB.NET -Me.layoutControlGroupItem1.HeaderElement.Font = New Font("Segoe Script", 14, FontStyle.Regular) -Me.layoutControlGroupItem1.HeaderElement.BackColor = ColorTranslator.FromHtml("#008de7") -Me.layoutControlGroupItem1.HeaderElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid -Me.layoutControlGroupItem1.HeaderElement.HeaderButtonElement.DrawFill = False -Me.layoutControlGroupItem1.HeaderElement.HeaderButtonElement.DrawBorder = False -Me.layoutControlGroupItem1.ShowHeaderLine = False -```` - -{{endregion}} * __LayoutControlTabbedGroup:__ This item gives you access to the underlying TabStrip, this way you can customize its appearance. #### Customize Tabs -{{source=..\SamplesCS\LayoutControl\CustomizeLayoutControl.cs region=Tab}} -{{source=..\SamplesVB\LayoutControl\CustomizeLayoutControl.vb region=Tab}} - -````C# -this.layoutControlTabbedGroup1.TabStrip.Font = new Font("Segoe Script", 14, FontStyle.Regular); -this.layoutControlTabbedGroup1.TabStrip.ItemFitMode = StripViewItemFitMode.Fill; -this.layoutControlTabbedGroup1.TabStrip.Items[0].ForeColor = ColorTranslator.FromHtml("#e83737"); -this.layoutControlTabbedGroup1.TabStrip.Items[1].ForeColor = ColorTranslator.FromHtml("#008de7"); - -```` -````VB.NET -Me.layoutControlTabbedGroup1.TabStrip.Font = New Font("Segoe Script", 14, FontStyle.Regular) -Me.layoutControlTabbedGroup1.TabStrip.ItemFitMode = StripViewItemFitMode.Fill -Me.layoutControlTabbedGroup1.TabStrip.Items(0).ForeColor = ColorTranslator.FromHtml("#e83737") -Me.layoutControlTabbedGroup1.TabStrip.Items(1).ForeColor = ColorTranslator.FromHtml("#008de7") + + -```` -{{endregion}} # See Also diff --git a/controls/layoutcontrol/getting-started.md b/controls/layoutcontrol/getting-started.md index 908f1ad95..5c71c49a0 100644 --- a/controls/layoutcontrol/getting-started.md +++ b/controls/layoutcontrol/getting-started.md @@ -50,135 +50,10 @@ The example below shows how you can create a layout that will fill the entire fo 3\. Let’s add some functionality to our new form. The following snippet shows how you can bind the two controls and close the form when the button is clicked. Additionally you can show text above the __RadDataEntry__ and __RadListView__. For this purpose you can just use the items text. Detailed information about the used properties is available in the [Items]({%slug winforms/layoutcontrol/items%}) article. Figure 3 shows the final layout. If you now try to resize the form, you will see that the controls in __RadLayoutControl__ grow and shrink proportionally. -{{source=..\SamplesCS\LayoutControl\GettingStartedForm.cs region=FormCode}} -{{source=..\SamplesVB\LayoutControl\GettingStartedForm.vb region=FormCode}} - -````C# - -public partial class GettingStartedForm : Telerik.WinControls.UI.RadForm -{ - public GettingStartedForm() - { - InitializeComponent(); - - List employees = new List(); - employees.Add(new Employee() - { - FirstName = "Sarah", - LastName = "Blake", - Occupation = "Supplied Manager", - StartingDate = new DateTime(2005, 04, 12), - IsMarried = true - }); - employees.Add(new Employee() - { - FirstName = "Jane", - LastName = "Simpson", - Occupation = "Security", - StartingDate = new DateTime(2008, 12, 03), - IsMarried = true - }); - employees.Add(new Employee() - { - FirstName = "John", - LastName = "Peterson", - Occupation = "Consultant", - StartingDate = new DateTime(2005, 04, 12), - IsMarried = false - }); - employees.Add(new Employee() - { - FirstName = "Peter", - LastName = "Bush", - Occupation = "Cashier", - StartingDate = new DateTime(2005, 04, 12), - IsMarried = true - }); - - BindingSource bindingSource1 = new BindingSource(); - bindingSource1.DataSource = employees; - - radDataEntry1.DataSource = bindingSource1; - radListView1.DataSource = bindingSource1; - radListView1.DisplayMember = "FirstName"; - radListView1.AllowEdit = false; - - this.radButton1.Click += radButton1_Click; - layoutControlItem1.DrawText = true; - layoutControlItem2.DrawText = true; - layoutControlItem1.TextProportionalSize = 0.05f; - layoutControlItem2.TextProportionalSize = 0.05f; - layoutControlItem1.TextPosition = LayoutItemTextPosition.Top; - layoutControlItem2.TextPosition = LayoutItemTextPosition.Top; - layoutControlItem1.TextAlignment = ContentAlignment.BottomLeft; - layoutControlItem2.TextAlignment = ContentAlignment.BottomLeft; - layoutControlItem1.Text = "Select Item"; - layoutControlItem2.Text = "Change Item Properties"; - } - - void radButton1_Click(object sender, EventArgs e) - { - this.Close(); - } -} - -public class Employee -{ - public string FirstName { get; set; } - - public string LastName { get; set; } - - public string Occupation { get; set; } - - public DateTime StartingDate { get; set; } - - public bool IsMarried { get; set; } -} - -```` -````VB.NET -Partial Public Class GettingStartedForm1 - Inherits Telerik.WinControls.UI.RadForm - Public Sub New() - InitializeComponent() - Dim employees As New List(Of EmployeeData)() - employees.Add(New EmployeeData() With {.FirstName = "Sarah", .LastName = "Blake", .Occupation = "Supplied Manager", .StartingDate = New Date(2005, 4, 12), .IsMarried = True}) - employees.Add(New EmployeeData() With {.FirstName = "Jane", .LastName = "Simpson", .Occupation = "Security", .StartingDate = New Date(2008, 12, 3), .IsMarried = True}) - employees.Add(New EmployeeData() With {.FirstName = "John", .LastName = "Peterson", .Occupation = "Consultant", .StartingDate = New Date(2005, 4, 12), .IsMarried = False}) - employees.Add(New EmployeeData() With {.FirstName = "Peter", .LastName = "Bush", .Occupation = "Cashier", .StartingDate = New Date(2005, 4, 12), .IsMarried = True}) - Dim bindingSource1 As New BindingSource() - bindingSource1.DataSource = employees - radDataEntry1.DataSource = bindingSource1 - radListView1.DataSource = bindingSource1 - radListView1.DisplayMember = "FirstName" - radListView1.AllowEdit = False - AddHandler Me.radButton1.Click, AddressOf radButton1_Click - layoutControlItem1.DrawText = True - layoutControlItem2.DrawText = True - layoutControlItem1.TextProportionalSize = 0.05F - layoutControlItem2.TextProportionalSize = 0.05F - layoutControlItem1.TextPosition = LayoutItemTextPosition.Top - layoutControlItem2.TextPosition = LayoutItemTextPosition.Top - layoutControlItem1.TextAlignment = ContentAlignment.BottomLeft - layoutControlItem2.TextAlignment = ContentAlignment.BottomLeft - layoutControlItem1.Text = "Select Item" - layoutControlItem2.Text = "Change Item Properties" - End Sub - Private Sub radButton1_Click(ByVal sender As Object, ByVal e As EventArgs) - Me.Close() - End Sub -End Class -Public Class EmployeeData - Public Property FirstName() As String - Public Property LastName() As String - Public Property Occupation() As String - Public Property StartingDate() As Date - Public Property IsMarried() As Boolean -End Class - -```` - -{{endregion}} + + + + >caption Figure 3: Final Layout ![WinForms RadLayoutControl Final Layout](images/layoutcontrol-getting-started003.png) diff --git a/controls/layoutcontrol/load-layout.md b/controls/layoutcontrol/load-layout.md index 4ee8dada8..f724a9225 100644 --- a/controls/layoutcontrol/load-layout.md +++ b/controls/layoutcontrol/load-layout.md @@ -15,77 +15,17 @@ __RadLayoutControl__ allows layout changes at runtime. To preserve the changed l #### Save Layout -{{source=..\SamplesCS\LayoutControl\LoadSaveLayout.cs region=SaveLayout}} -{{source=..\SamplesVB\LayoutControl\LoadSaveLayout.vb region=SaveLayout}} + + -````C# - -private void SaveButton_Click(object sender, EventArgs e) -{ - string s = "default.xml"; - SaveFileDialog dialog = new SaveFileDialog(); - dialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*"; - dialog.Title = "Select a xml file"; - if (dialog.ShowDialog() == DialogResult.OK) - { - s = dialog.FileName; - } - this.radLayoutControl1.SaveLayout(s); -} -```` -````VB.NET -Private Sub SaveButton_Click(ByVal sender As Object, ByVal e As EventArgs) - Dim s As String = "default.xml" - Dim dialog As New SaveFileDialog() - dialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*" - dialog.Title = "Select a xml file" - If dialog.ShowDialog() = DialogResult.OK Then - s = dialog.FileName - End If - Me.radLayoutControl1.SaveLayout(s) -End Sub - -```` - -{{endregion}} #### Load Layout -{{source=..\SamplesCS\LayoutControl\LoadSaveLayout.cs region=LoadLayout}} -{{source=..\SamplesVB\LayoutControl\LoadSaveLayout.vb region=LoadLayout}} - -````C# - -private void LoadButton_Click(object sender, EventArgs e) -{ - string s = "default.xml"; - OpenFileDialog dialog = new OpenFileDialog(); - dialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*"; - dialog.Title = "Select a xml file"; - if (dialog.ShowDialog() == DialogResult.OK) - { - s = dialog.FileName; - } - this.radLayoutControl1.LoadLayout(s); -} - -```` -````VB.NET -Private Sub LoadButton_Click(ByVal sender As Object, ByVal e As EventArgs) - Dim s As String = "default.xml" - Dim dialog As New OpenFileDialog() - dialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*" - dialog.Title = "Select a xml file" - If dialog.ShowDialog() = DialogResult.OK Then - s = dialog.FileName - End If - Me.radLayoutControl1.LoadLayout(s) -End Sub + + -```` -{{endregion}} The layout can be saved/loaded with the [customize dialog]({%slug winforms/layoutcontrol/customize-layout-mode%}) as well. diff --git a/controls/layoutcontrol/localization.md b/controls/layoutcontrol/localization.md index f4d6646b8..2c8ba65eb 100644 --- a/controls/layoutcontrol/localization.md +++ b/controls/layoutcontrol/localization.md @@ -21,171 +21,19 @@ Below is a sample implementation of an English localization provider: #### Localizing RadLayoutControl Strings. -{{source=..\SamplesCS\LayoutControl\LayoutControlLocalization.cs region=Localization}} -{{source=..\SamplesVB\LayoutControl\LayoutControlLocalization.vb region=Localization}} - -````C# - -class MyEnglishLayoutControlLocalizationProvider : LayoutControlLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case LayoutControlStringId.CustomizeDialogHiddenItems: - return "Hidden Items ({0})"; - case LayoutControlStringId.CustomizeDialogNewItems: - return "New Items ({0})"; - - case LayoutControlStringId.CustomizeDialogPageItems: - return "Items"; - case LayoutControlStringId.CustomizeDialogPageStructure: - return "Structure"; - - case LayoutControlStringId.CustomizeDialogRootItem: - return "Root"; - case LayoutControlStringId.CustomizeDialogLayoutItem: - return "Layout Item"; - case LayoutControlStringId.CustomizeDialogLabelItem: - return "Label Item"; - case LayoutControlStringId.CustomizeDialogSplitterItem: - return "Splitter Item"; - case LayoutControlStringId.CustomizeDialogSeparatorItem: - return "Separator Item"; - case LayoutControlStringId.CustomizeDialogGroupItem: - return "Group Item"; - case LayoutControlStringId.CustomizeDialogTabbedGroup: - return "Tabbed Group"; - - case LayoutControlStringId.CustomizeDialogSaveLayout: - return "Save Layout"; - case LayoutControlStringId.CustomizeDialogLoadLayout: - return "Load Layout"; - - case LayoutControlStringId.NewGroupDefaultText: - return "Item Group"; - case LayoutControlStringId.NewLabelDefaultText: - return "Label Item"; - - case LayoutControlStringId.CustomizeDialogNewItemsEmptySpace: - return "Empty Space"; - case LayoutControlStringId.CustomizeDialogNewItemsLabel: - return "Label"; - case LayoutControlStringId.CustomizeDialogNewItemsSeparator: - return "Separator"; - case LayoutControlStringId.CustomizeDialogNewItemsSplitter: - return "Splitter"; - case LayoutControlStringId.CustomizeDialogNewItemsGroup: - return "Group"; - case LayoutControlStringId.CustomizeDialogNewItemsTabbedGroup: - return "Tabbed Group"; - - case LayoutControlStringId.ContextMenuCustomize: - return "Customize"; - case LayoutControlStringId.ContextMenuHideItem: - return "Hide"; - case LayoutControlStringId.CustomizeDialogTitle: - return "Customize"; - - case LayoutControlStringId.ErrorBoxTitle: - return "Error!"; - case LayoutControlStringId.ErrorFileNotFoundMessage: - return "File not found!"; - case LayoutControlStringId.ErrorLoadingLayoutMessage: - return "Error loading layout!"; - } - - return base.GetLocalizedString(id); - } -} - -```` -````VB.NET -Friend Class DataLayoutEnglishLayoutControlLocalizationProvider - Inherits LayoutControlLocalizationProvider - Public Overrides Function GetLocalizedString(ByVal id As String) As String - Select Case id - Case LayoutControlStringId.CustomizeDialogHiddenItems - Return "Hidden Items ({0})" - Case LayoutControlStringId.CustomizeDialogNewItems - Return "New Items ({0})" - Case LayoutControlStringId.CustomizeDialogPageItems - Return "Items" - Case LayoutControlStringId.CustomizeDialogPageStructure - Return "Structure" - Case LayoutControlStringId.CustomizeDialogRootItem - Return "Root" - Case LayoutControlStringId.CustomizeDialogLayoutItem - Return "Layout Item" - Case LayoutControlStringId.CustomizeDialogLabelItem - Return "Label Item" - Case LayoutControlStringId.CustomizeDialogSplitterItem - Return "Splitter Item" - Case LayoutControlStringId.CustomizeDialogSeparatorItem - Return "Separator Item" - Case LayoutControlStringId.CustomizeDialogGroupItem - Return "Group Item" - Case LayoutControlStringId.CustomizeDialogTabbedGroup - Return "Tabbed Group" - Case LayoutControlStringId.CustomizeDialogSaveLayout - Return "Save Layout" - Case LayoutControlStringId.CustomizeDialogLoadLayout - Return "Load Layout" - Case LayoutControlStringId.NewGroupDefaultText - Return "Item Group" - Case LayoutControlStringId.NewLabelDefaultText - Return "Label Item" - Case LayoutControlStringId.CustomizeDialogNewItemsEmptySpace - Return "Empty Space" - Case LayoutControlStringId.CustomizeDialogNewItemsLabel - Return "Label" - Case LayoutControlStringId.CustomizeDialogNewItemsSeparator - Return "Separator" - Case LayoutControlStringId.CustomizeDialogNewItemsSplitter - Return "Splitter" - Case LayoutControlStringId.CustomizeDialogNewItemsGroup - Return "Group" - Case LayoutControlStringId.CustomizeDialogNewItemsTabbedGroup - Return "Tabbed Group" - Case LayoutControlStringId.ContextMenuCustomize - Return "Customize" - Case LayoutControlStringId.ContextMenuHideItem - Return "Hide" - Case LayoutControlStringId.CustomizeDialogTitle - Return "Customize" - Case LayoutControlStringId.ErrorBoxTitle - Return "Error!" - Case LayoutControlStringId.ErrorFileNotFoundMessage - Return "File not found!" - Case LayoutControlStringId.ErrorLoadingLayoutMessage - Return "Error loading layout!" - End Select - Return MyBase.GetLocalizedString(id) - End Function -End Class - -```` - -{{endregion}} + + -To apply the custom localization provider, instantiate and assign it to the current localization provider: -#### Assigning the Current Localization Provider -{{source=..\SamplesCS\LayoutControl\LayoutControlLocalization.cs region=SetProvider}} -{{source=..\SamplesVB\LayoutControl\LayoutControlLocalization.vb region=SetProvider}} +To apply the custom localization provider, instantiate and assign it to the current localization provider: -````C# - -LayoutControlLocalizationProvider.CurrentProvider = new MyEnglishLayoutControlLocalizationProvider(); +#### Assigning the Current Localization Provider -```` -````VB.NET -LayoutControlLocalizationProvider.CurrentProvider = New DataLayoutEnglishLayoutControlLocalizationProvider() + + -```` -{{endregion}} # See Also diff --git a/controls/listview/custom-items.md b/controls/listview/custom-items.md index 2dcc61e1a..fbec03d2f 100644 --- a/controls/listview/custom-items.md +++ b/controls/listview/custom-items.md @@ -26,141 +26,19 @@ First let's create a custom visual item by inheriting from the __SimpleListViewV #### Creating custom item -{{source=..\SamplesCS\ListView\ListViewCustomItems.cs region=CustomItem}} -{{source=..\SamplesVB\ListView\ListViewCustomItems.vb region=CustomItem}} - -````C# - -public class MyCustomVisualItem : SimpleListViewVisualItem -{ - private RadButtonElement buttonElement1; - private RadButtonElement buttonElement2; - private LightVisualElement contentElement; - private StackLayoutPanel stackLayout; - - protected override void CreateChildElements() - { - base.CreateChildElements(); - - this.stackLayout = new StackLayoutPanel(); - this.stackLayout.Orientation = Orientation.Horizontal; - this.stackLayout.EqualChildrenWidth = true; - this.stackLayout.ShouldHandleMouseInput = false; - this.stackLayout.NotifyParentOnMouseInput = true; - - this.contentElement = new LightVisualElement(); - this.contentElement.StretchHorizontally = true; - this.contentElement.MinSize = new Size(120, 0); - this.contentElement.ShouldHandleMouseInput = false; - this.contentElement.NotifyParentOnMouseInput = true; - this.stackLayout.Children.Add(this.contentElement); - - this.buttonElement1 = new RadButtonElement(); - this.buttonElement1.Text = "Button1"; - this.stackLayout.Children.Add(this.buttonElement1); - - this.buttonElement2 = new RadButtonElement(); - this.buttonElement2.Text = "Button2"; - this.stackLayout.Children.Add(this.buttonElement2); - - this.Children.Add(this.stackLayout); - } - - protected override void SynchronizeProperties() - { - base.SynchronizeProperties(); - - this.Text = ""; - this.contentElement.Text = Convert.ToString(this.Data["Name"]); - this.buttonElement1.Text = "Call " + Convert.ToString(this.Data["Phone"]); - this.buttonElement2.Text = "Fax " + Convert.ToString(this.Data["Fax"]); - } - - protected override Type ThemeEffectiveType - { - get - { - return typeof(SimpleListViewVisualItem); - } - } -} - -```` -````VB.NET - -Public Class MyCustomVisualItem -Inherits SimpleListViewVisualItem - Private buttonElement1 As RadButtonElement - Private buttonElement2 As RadButtonElement - Private contentElement As LightVisualElement - Private stackLayout As StackLayoutPanel - Protected Overrides Sub CreateChildElements() - MyBase.CreateChildElements() - Me.stackLayout = New StackLayoutPanel() - Me.stackLayout.Orientation = Orientation.Horizontal - Me.stackLayout.EqualChildrenWidth = True - Me.stackLayout.ShouldHandleMouseInput = False - Me.stackLayout.NotifyParentOnMouseInput = True - Me.contentElement = New LightVisualElement() - Me.contentElement.StretchHorizontally = True - Me.contentElement.MinSize = New Size(120, 0) - Me.contentElement.ShouldHandleMouseInput = False - Me.contentElement.NotifyParentOnMouseInput = True - Me.stackLayout.Children.Add(Me.contentElement) - Me.buttonElement1 = New RadButtonElement() - Me.buttonElement1.Text = "Button1" - Me.stackLayout.Children.Add(Me.buttonElement1) - Me.buttonElement2 = New RadButtonElement() - Me.buttonElement2.Text = "Button2" - Me.stackLayout.Children.Add(Me.buttonElement2) - Me.Children.Add(Me.stackLayout) - End Sub - Protected Overrides Sub SynchronizeProperties() - MyBase.SynchronizeProperties() - Me.Text = "" - Me.contentElement.Text = Convert.ToString(Me.Data("Name")) - Me.buttonElement1.Text = "Call " + Convert.ToString(Me.Data("Phone")) - Me.buttonElement2.Text = "Fax " + Convert.ToString(Me.Data("Fax")) - End Sub - Protected Overrides ReadOnly Property ThemeEffectiveType() As Type - Get - Return GetType(SimpleListViewVisualItem) - End Get - End Property -End Class - -```` - -{{endregion}} + + -To use the newly created items, you should handle the __VisualItemCreating__ event as shown below: -#### Use the Custom Item -{{source=..\SamplesCS\ListView\ListViewCustomItems.cs region=UseCustomItem}} -{{source=..\SamplesVB\ListView\ListViewCustomItems.vb region=UseCustomItem}} +To use the newly created items, you should handle the __VisualItemCreating__ event as shown below: -````C# - -void radListView1_VisualItemCreating(object sender, ListViewVisualItemCreatingEventArgs e) -{ - if (this.radListView1.ViewType == ListViewType.ListView) - { - e.VisualItem = new MyCustomVisualItem(); - } -} +#### Use the Custom Item -```` -````VB.NET -Private Sub radListView1_VisualItemCreating(ByVal sender As Object, ByVal e As ListViewVisualItemCreatingEventArgs) - If Me.RadListView1.ViewType = ListViewType.ListView Then - e.VisualItem = New MyCustomVisualItem() - End If -End Sub + + -```` -{{endregion}} ## Custom items in IconsView ViewType @@ -172,109 +50,17 @@ We should create a custom visual item inheriting the __IconListViewVisualItem__. #### Creating custom item -{{source=..\SamplesCS\ListView\ListViewCustomItems.cs region=CustomIconListViewVisualItem}} -{{source=..\SamplesVB\ListView\ListViewCustomItems.vb region=CustomIconListViewVisualItem}} - -````C# - -public class MyCustomIconListViewVisualItem :IconListViewVisualItem -{ - protected override Type ThemeEffectiveType - { - get - { - return typeof(IconListViewVisualItem); - } - } - - LightVisualElement imageElement = new LightVisualElement(); - RadButtonElement buttonElement = new RadButtonElement(); - StackLayoutElement stack = new StackLayoutElement(); - - protected override void CreateChildElements() - { - base.CreateChildElements(); - - stack.Orientation = Orientation.Vertical; - imageElement.Image = Image.FromFile(@"..\..\Resources\email.png"); - buttonElement.Image = Image.FromFile(@"..\..\Resources\file.png"); - buttonElement.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText; - - stack.Children.Add(imageElement); - stack.Children.Add(buttonElement); - this.Children.Add(stack); - } - - protected override void SynchronizeProperties() - { - base.SynchronizeProperties(); - this.Text = string.Empty; - this.buttonElement.Text = this.Data.Text; - } -} - -```` -````VB.NET -Public Class MyCustomIconListViewVisualItem -Inherits IconListViewVisualItem - Protected Overrides ReadOnly Property ThemeEffectiveType() As Type - Get - Return GetType(IconListViewVisualItem) - End Get - End Property - Private imageElement As LightVisualElement - Private buttonElement As RadButtonElement - Private stack As StackLayoutElement - Protected Overrides Sub CreateChildElements() - MyBase.CreateChildElements() - stack = New StackLayoutElement() - imageElement = New LightVisualElement() - buttonElement = New RadButtonElement() - stack.Orientation = Orientation.Vertical - imageElement.Image = Image.FromFile("..\..\Resources\email.png") - buttonElement.Image = Image.FromFile("..\..\Resources\file.png") - buttonElement.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText - stack.Children.Add(imageElement) - stack.Children.Add(buttonElement) - Me.Children.Add(stack) - End Sub - Protected Overrides Sub SynchronizeProperties() - MyBase.SynchronizeProperties() - Me.Text = String.Empty - Me.buttonElement.Text = Me.Data.Text - End Sub -End Class - -```` - -{{endregion}} + + -To use the newly created item, you should subscribe to the __VisualItemCreating__ event and replace the default item with your custom one: -{{source=..\SamplesCS\ListView\ListViewCustomItems.cs region=UseCustomIconItem}} -{{source=..\SamplesVB\ListView\ListViewCustomItems.vb region=UseCustomIconItem}} -````C# - -void VisualItemCreating(object sender, ListViewVisualItemCreatingEventArgs e) -{ - if (this.radListView1.ViewType == ListViewType.IconsView) - { - e.VisualItem = new MyCustomIconListViewVisualItem(); - } -} +To use the newly created item, you should subscribe to the __VisualItemCreating__ event and replace the default item with your custom one: -```` -````VB.NET -Private Sub VisualItemCreating(sender As Object, e As ListViewVisualItemCreatingEventArgs) - If Me.RadListView1.ViewType = ListViewType.IconsView Then - e.VisualItem = New MyCustomIconListViewVisualItem() - End If -End Sub + + -```` -{{endregion}} ## Custom Items in DetailsView ViewType @@ -286,218 +72,29 @@ Since the *DetailsView* provides a grid-like interface, it displays a cell for e First let's populate __RadListView__ with items and set its __ViewType__ property to *DetailsView*: -{{source=..\SamplesCS\ListView\ListViewCustomItems.cs region=FillData}} -{{source=..\SamplesVB\ListView\ListViewCustomItems.vb region=FillData}} - -````C# -radListView1.ViewType = ListViewType.DetailsView; -DataTable dt = new DataTable(); -dt.Columns.Add("Id", typeof(int)); -dt.Columns.Add("Name", typeof(string)); -for (int i = 0; i < 50; i++) -{ - dt.Rows.Add(i, "Item " + i); -} -this.radListView1.DataSource = dt; - -```` -````VB.NET -RadListView1.ViewType = ListViewType.DetailsView -Dim dt As New DataTable() -dt.Columns.Add("Id", GetType(Integer)) -dt.Columns.Add("Name", GetType(String)) -For i As Integer = 0 To 49 - dt.Rows.Add(i, "Item " & i.ToString()) -Next -Me.RadListView1.DataSource = dt - -```` - -{{endregion}} - -Now let`s create our custom cell element containing a __RadButtonElement__. Additionally, we should inherit the __DetailListViewDataCellElement__ class: + + -{{source=..\SamplesCS\ListView\ListViewCustomItems.cs region=CustomCell}} -{{source=..\SamplesVB\ListView\ListViewCustomItems.vb region=CustomCell}} - -````C# - -public class CustomDetailListViewDataCellElement : DetailListViewDataCellElement -{ - private RadButtonElement button; - - public CustomDetailListViewDataCellElement(DetailListViewVisualItem owner, - ListViewDetailColumn column) : base(owner, column) - { - } - - protected override void CreateChildElements() - { - base.CreateChildElements(); - - this.button = new RadButtonElement(); - this.Children.Add(this.button); - } - - protected override Type ThemeEffectiveType - { - get - { - return typeof(DetailListViewHeaderCellElement); - } - } - - public override void Synchronize() - { - base.Synchronize(); - this.Text = ""; - DataRowView rowView = this.Row.DataBoundItem as DataRowView; - this.button.Text = rowView.Row["Name"].ToString(); - } - - public override bool IsCompatible(ListViewDetailColumn data, object context) - { - if (data.Name != "Name") - { - return false; - } - return base.IsCompatible(data, context); - } -} - -```` -````VB.NET - -Public Class CustomDetailListViewDataCellElement -Inherits DetailListViewDataCellElement - Private button As RadButtonElement - Public Sub New(owner As DetailListViewVisualItem, column As ListViewDetailColumn) - MyBase.New(owner, column) - End Sub - Protected Overrides Sub CreateChildElements() - MyBase.CreateChildElements() - Me.button = New RadButtonElement() - Me.Children.Add(Me.button) - End Sub - Protected Overrides ReadOnly Property ThemeEffectiveType() As Type - Get - Return GetType(DetailListViewHeaderCellElement) - End Get - End Property - Public Overrides Sub Synchronize() - MyBase.Synchronize() - Me.Text = "" - Dim rowView As DataRowView = TryCast(Me.Row.DataBoundItem, DataRowView) - Me.button.Text = rowView.Row("Name").ToString() - End Sub - Public Overrides Function IsCompatible(data As ListViewDetailColumn, context As Object) As Boolean - If data.Name <> "Name" Then - Return False - End If - Return MyBase.IsCompatible(data, context) - End Function -End Class - -```` - -{{endregion}} -Due to the virtualization mechanism of the RadListView control, the default cell of the control is compatible with all columns. When the control is scrolled, the default cell could override the custom one. To apply the custom cell when the control is scrolled is necessary to create another __DetailListViewDataCellElement__ which is not compatible with your custom item. -{{source=..\SamplesCS\ListView\ListViewCustomItems.cs region=DefaultCell}} -{{source=..\SamplesVB\ListView\ListViewCustomItems.vb region=DefaultCell}} - -````C# - -public class DefaultCell : DetailListViewDataCellElement -{ - public DefaultCell(DetailListViewVisualItem owner, ListViewDetailColumn column) : base(owner, column) - { - } - protected override Type ThemeEffectiveType - { - get - { - return typeof(DetailListViewHeaderCellElement); - } - } - public override bool IsCompatible(ListViewDetailColumn data, object context) - { - if (data.Name != "Name") - { - return true; - } - return false; - } -} - - -```` -````VB.NET - -Public Class DefaultCell - Inherits DetailListViewDataCellElement - - Public Sub New(ByVal owner As DetailListViewVisualItem, ByVal column As ListViewDetailColumn) - MyBase.New(owner, column) - End Sub +Now let`s create our custom cell element containing a __RadButtonElement__. Additionally, we should inherit the __DetailListViewDataCellElement__ class: - Protected Overrides ReadOnly Property ThemeEffectiveType As Type - Get - Return GetType(DetailListViewHeaderCellElement) - End Get - End Property + + - Public Overrides Function IsCompatible(ByVal data As ListViewDetailColumn, ByVal context As Object) As Boolean - If data.Name <> "Name" Then - Return True - End If - Return False - End Function -End Class +Due to the virtualization mechanism of the RadListView control, the default cell of the control is compatible with all columns. When the control is scrolled, the default cell could override the custom one. To apply the custom cell when the control is scrolled is necessary to create another __DetailListViewDataCellElement__ which is not compatible with your custom item. -```` + + -{{endregion}} Finally, we should handle the __CellCreating__ event and substitute the default cell element with our own or return the default cell for the other columns: -{{source=..\SamplesCS\ListView\ListViewCustomItems.cs region=ReplaceCell}} -{{source=..\SamplesVB\ListView\ListViewCustomItems.vb region=ReplaceCell}} - -````C# - -private void radListView1_CellCreating(object sender, ListViewCellElementCreatingEventArgs e) -{ - DetailListViewDataCellElement cell = e.CellElement as DetailListViewDataCellElement; - if (cell != null && cell.Data.Name == "Name") - { - e.CellElement = new CustomDetailListViewDataCellElement(cell.RowElement, e.CellElement.Data); - } - else if (cell != null && cell.Data.Name != "Name") - { - e.CellElement = new DefaultCell(cell.RowElement, e.CellElement.Data); - } -} - -```` -````VB.NET -Private Sub radListView1_CellCreating(ByVal sender As Object, ByVal e As ListViewCellElementCreatingEventArgs) - Dim cell As DetailListViewDataCellElement = TryCast(e.CellElement, DetailListViewDataCellElement) - - If cell IsNot Nothing AndAlso cell.Data.Name = "Name" Then - e.CellElement = New CustomDetailListViewDataCellElement(cell.RowElement, e.CellElement.Data) - ElseIf cell IsNot Nothing AndAlso cell.Data.Name <> "Name" Then - e.CellElement = New DefaultCell(cell.RowElement, e.CellElement.Data) - End If -End Sub - -```` - -{{endregion}} + + diff --git a/controls/listview/customizing-appearance/accessing-and-customizing-elements.md b/controls/listview/customizing-appearance/accessing-and-customizing-elements.md index da9dafcdc..4537b42df 100644 --- a/controls/listview/customizing-appearance/accessing-and-customizing-elements.md +++ b/controls/listview/customizing-appearance/accessing-and-customizing-elements.md @@ -31,22 +31,11 @@ You can customize the nested elements at run time as well: #### Customize Elements -{{source=..\SamplesCS\ListView\ListViewFormattingItems.cs region=CustomizeElements}} -{{source=..\SamplesVB\ListView\ListViewFormattingItems.vb region=CustomizeElements}} + + -````C# -this.radListView1.ListViewElement.BackColor = Color.Yellow; -this.radListView1.ListViewElement.ViewElement.HScrollBar.ThumbElement.ThumbFill.BackColor = Color.Red; -```` -````VB.NET -Me.RadListView1.ListViewElement.BackColor = Color.Yellow -Me.RadListView1.ListViewElement.ViewElement.HScrollBar.ThumbElement.ThumbFill.BackColor = Color.Red -```` - -{{endregion}} - # See Also * [Formatting Items]({%slug winforms/listview/formatting-items%}) diff --git a/controls/listview/customizing-appearance/formatting-items.md b/controls/listview/customizing-appearance/formatting-items.md index 0878de08f..f92a47457 100644 --- a/controls/listview/customizing-appearance/formatting-items.md +++ b/controls/listview/customizing-appearance/formatting-items.md @@ -25,53 +25,10 @@ Items appearance in __RadListView__ can be customized by making use of the __Vis #### Customizing items when using the VisualItemFormatting event -{{source=..\SamplesCS\ListView\ListViewFormattingItems.cs region=VisualItemFormatting}} -{{source=..\SamplesVB\ListView\ListViewFormattingItems.vb region=VisualItemFormatting}} - -````C# -Font font = new Font("Consolas", 14, FontStyle.Bold); -void radListView1_VisualItemFormatting(object sender, Telerik.WinControls.UI.ListViewVisualItemEventArgs e) -{ - if (e.VisualItem.Selected) - { - e.VisualItem.NumberOfColors = 1; - e.VisualItem.BackColor = Color.LightGreen; - e.VisualItem.ForeColor = Color.Red; - e.VisualItem.BorderColor = Color.Blue; - e.VisualItem.Font = font; - } - else - { - e.VisualItem.ResetValue(LightVisualElement.NumberOfColorsProperty, Telerik.WinControls.ValueResetFlags.Local); - e.VisualItem.ResetValue(LightVisualElement.BackColorProperty, Telerik.WinControls.ValueResetFlags.Local); - e.VisualItem.ResetValue(LightVisualElement.ForeColorProperty, Telerik.WinControls.ValueResetFlags.Local); - e.VisualItem.ResetValue(LightVisualElement.BorderColorProperty, Telerik.WinControls.ValueResetFlags.Local); - e.VisualItem.ResetValue(LightVisualElement.FontProperty, Telerik.WinControls.ValueResetFlags.Local); - } -} - -```` -````VB.NET -Private font As New Font("Consolas", 14, FontStyle.Bold) -Private Sub radListView1_VisualItemFormatting(sender As Object, e As Telerik.WinControls.UI.ListViewVisualItemEventArgs) - If e.VisualItem.Selected Then - e.VisualItem.NumberOfColors = 1 - e.VisualItem.BackColor = Color.LightGreen - e.VisualItem.ForeColor = Color.Red - e.VisualItem.BorderColor = Color.Blue - e.VisualItem.Font = font - Else - e.VisualItem.ResetValue(LightVisualElement.NumberOfColorsProperty, Telerik.WinControls.ValueResetFlags.Local) - e.VisualItem.ResetValue(LightVisualElement.BackColorProperty, Telerik.WinControls.ValueResetFlags.Local) - e.VisualItem.ResetValue(LightVisualElement.ForeColorProperty, Telerik.WinControls.ValueResetFlags.Local) - e.VisualItem.ResetValue(LightVisualElement.BorderColorProperty, Telerik.WinControls.ValueResetFlags.Local) - e.VisualItem.ResetValue(LightVisualElement.FontProperty, Telerik.WinControls.ValueResetFlags.Local) - End If -End Sub - -```` - -{{endregion}} + + + + ## Formatting cells in DetailsView mode @@ -87,109 +44,18 @@ Let’s assume that the __RadListView__ is bound to the *Products* table from th #### Customizing cells when using the CellFormatting event -{{source=..\SamplesCS\ListView\ListViewFormattingItems.cs region=CellFormatting}} -{{source=..\SamplesVB\ListView\ListViewFormattingItems.vb region=CellFormatting}} - -````C# -private void ListViewFormattingItems_Load(object sender, EventArgs e) -{ - this.productsTableAdapter.Fill(this.nwindDataSet.Products); - this.radListView1.DataSource = this.productsBindingSource; - this.radListView1.DisplayMember = "ProductName"; - this.radListView1.ValueMember = "ProductID"; - this.radListView1.ViewType = ListViewType.DetailsView; - this.radListView1.CellFormatting += radListView1_CellFormatting; -} -Font newFont = new Font("Arial", 12f, FontStyle.Bold); -private void radListView1_CellFormatting(object sender, ListViewCellFormattingEventArgs e) -{ - DetailListViewDataCellElement cell = e.CellElement as DetailListViewDataCellElement; - if (cell != null) - { - DataRowView productRowView = cell.Row.DataBoundItem as DataRowView; - if (productRowView != null && (bool)productRowView.Row["Discontinued"] == true) - { - e.CellElement.BackColor = Color.Yellow; - e.CellElement.ForeColor = Color.Red; - e.CellElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid; - e.CellElement.Font = newFont; - } - else - { - e.CellElement.ResetValue(LightVisualElement.BackColorProperty, Telerik.WinControls.ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.ForeColorProperty, Telerik.WinControls.ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.GradientStyleProperty, Telerik.WinControls.ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.FontProperty, Telerik.WinControls.ValueResetFlags.Local); - } - } -} - -```` -````VB.NET -Private Sub FormattingItems_Load(sender As Object, e As EventArgs) Handles MyBase.Load - Me.ProductsTableAdapter.Fill(Me.NwindDataSet.Products) - Me.RadListView1.DataSource = Me.ProductsBindingSource - Me.RadListView1.DisplayMember = "ProductName" - Me.RadListView1.ValueMember = "ProductID" - Me.RadListView1.ViewType = ListViewType.DetailsView - AddHandler Me.RadListView1.CellFormatting, AddressOf radListView1_CellFormatting -End Sub -Private newFont As New Font("Arial", 12.0F, FontStyle.Bold) -Private Sub radListView1_CellFormatting(sender As Object, e As ListViewCellFormattingEventArgs) - Dim cell As DetailListViewDataCellElement = TryCast(e.CellElement, DetailListViewDataCellElement) - If cell IsNot Nothing Then - Dim productRowView As DataRowView = TryCast(cell.Row.DataBoundItem, DataRowView) - If productRowView IsNot Nothing AndAlso CBool(productRowView.Row("Discontinued")) = True Then - e.CellElement.BackColor = Color.Yellow - e.CellElement.ForeColor = Color.Red - e.CellElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid - e.CellElement.Font = newFont - Else - e.CellElement.ResetValue(LightVisualElement.BackColorProperty, Telerik.WinControls.ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.ForeColorProperty, Telerik.WinControls.ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.GradientStyleProperty, Telerik.WinControls.ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.FontProperty, Telerik.WinControls.ValueResetFlags.Local) - End If - End If -End Sub - -```` - -{{endregion}} + + + + >note In order to customize the header cells, the __e.CellElement__ property should be cast to the **DetailListViewHeaderCellElement** type. -{{source=..\SamplesCS\ListView\ListViewFormattingItems.cs region=HeaderFormatting}} -{{source=..\SamplesVB\ListView\ListViewFormattingItems.vb region=HeaderFormatting}} - -````C# -private void radListView1_CellFormatting(object sender, ListViewCellFormattingEventArgs e) -{ - if (e.CellElement is DetailListViewHeaderCellElement) - { - e.CellElement.TextAlignment = ContentAlignment.MiddleLeft; - } - else - { - e.CellElement.ResetValue(LightVisualElement.TextAlignmentProperty, Telerik.WinControls.ValueResetFlags.Local); - } -} - -```` -````VB.NET -Private Sub radListView1_CellFormatting1(ByVal sender As Object, ByVal e As ListViewCellFormattingEventArgs) - If TypeOf e.CellElement Is DetailListViewHeaderCellElement Then - e.CellElement.TextAlignment = ContentAlignment.MiddleLeft - Else - e.CellElement.ResetValue(LightVisualElement.TextAlignmentProperty, Telerik.WinControls.ValueResetFlags.Local) - End If -End Sub - -```` - -{{endregion}} - - + + + + + # See Also * [Accessing and Customizing Elements]({%slug winforms/listview/customizing-appearance/accessing-and-customizing-elements%}) diff --git a/controls/listview/drag-and-drop/combining-raddragdropservice-and-ole-drag-and-drop.md b/controls/listview/drag-and-drop/combining-raddragdropservice-and-ole-drag-and-drop.md index b306dfcaa..27536e2c9 100644 --- a/controls/listview/drag-and-drop/combining-raddragdropservice-and-ole-drag-and-drop.md +++ b/controls/listview/drag-and-drop/combining-raddragdropservice-and-ole-drag-and-drop.md @@ -17,40 +17,9 @@ Let’s assume that our __RadListView__ is in bound mode and its __ViewType__ pr #### Populating with data -{{source=..\SamplesCS\ListView\DragDrop\DragDropListViewListControl.cs region=PopulateWithData}} -{{source=..\SamplesVB\ListView\DragDrop\DragDropListViewListControl.vb region=PopulateWithData}} - -````C# - -BindingList items = new BindingList(); -for (int i = 0; i < 10; i++) -{ - items.Add("Item" + i); - this.radListControl1.Items.Add("ListControlItem" + i); -} - -this.radListView1.DataSource = items; -this.radListView1.AllowDragDrop = true; -this.radListView1.AllowDrop = true; -this.radListControl1.AllowDrop = true; -this.radListView1.ViewType = Telerik.WinControls.UI.ListViewType.IconsView; - -```` -````VB.NET -Dim items As New BindingList(Of String)() -For i As Integer = 0 To 9 - items.Add("Item" & i) - Me.RadListControl1.Items.Add("ListControlItem" & i) -Next -Me.RadListView1.DataSource = items -Me.RadListView1.AllowDragDrop = True -Me.RadListView1.AllowDrop = True -Me.RadListControl1.AllowDrop = True -Me.RadListView1.ViewType = Telerik.WinControls.UI.ListViewType.IconsView - -```` - -{{endregion}} + + + ## Drag and drop from RadListView to RadListControl using RadDragDropService @@ -63,71 +32,10 @@ To implement drag and drop functionality for this scenario, we will use the List #### Handling the RadDragDropService's events -{{source=..\SamplesCS\ListView\DragDrop\DragDropListViewListControl.cs region=ListViewToListControl}} -{{source=..\SamplesVB\ListView\DragDrop\DragDropListViewListControl.vb region=ListViewToListControl}} - -````C# - -private void DragDropService_PreviewDragOver(object sender, Telerik.WinControls.RadDragOverEventArgs e) -{ - e.CanDrop = e.HitTarget is RadListElement; -} - -private void DragDropService_PreviewDragDrop(object sender, Telerik.WinControls.RadDropEventArgs e) -{ - BaseListViewVisualItem draggedItem = e.DragInstance as BaseListViewVisualItem; - RadListElement listElement = e.HitTarget as RadListElement; - - if (listElement == null) - { - return; - } - e.Handled = true; - RadListControl listControl = listElement.ElementTree.Control as RadListControl; - RadListVisualItem targetItem = listControl.ElementTree.GetElementAtPoint(e.DropLocation) as RadListVisualItem; - int indexToInsert; - if (targetItem != null) - { - indexToInsert = targetItem.Data.RowIndex; - } - else - { - indexToInsert = listControl.Items.Count; - } - RadListDataItem newItem = new RadListDataItem(draggedItem.Data.Text); - listControl.Items.Insert(indexToInsert, newItem); - - draggedItem.Data.ListView.Items.Remove(draggedItem.Data); -} - -```` -````VB.NET -Private Sub DragDropService_PreviewDragOver(sender As Object, e As Telerik.WinControls.RadDragOverEventArgs) - e.CanDrop = TypeOf e.HitTarget Is RadListElement -End Sub -Private Sub DragDropService_PreviewDragDrop(sender As Object, e As Telerik.WinControls.RadDropEventArgs) - Dim draggedItem As BaseListViewVisualItem = TryCast(e.DragInstance, BaseListViewVisualItem) - Dim listElement As RadListElement = TryCast(e.HitTarget, RadListElement) - If listElement Is Nothing Then - Return - End If - e.Handled = True - Dim listControl As RadListControl = TryCast(listElement.ElementTree.Control, RadListControl) - Dim targetItem As RadListVisualItem = TryCast(listControl.ElementTree.GetElementAtPoint(e.DropLocation), RadListVisualItem) - Dim indexToInsert As Integer - If targetItem IsNot Nothing Then - indexToInsert = targetItem.Data.RowIndex - Else - indexToInsert = listControl.Items.Count - End If - Dim newItem As New RadListDataItem(draggedItem.Data.Text) - listControl.Items.Insert(indexToInsert, newItem) - draggedItem.Data.ListView.Items.Remove(draggedItem.Data) -End Sub - -```` - -{{endregion}} + + + + ## Drag and drop from RadListControl to RadListView using the OLE drag-and-drop @@ -139,170 +47,19 @@ End Sub #### Starting the drag and drop operation -{{source=..\SamplesCS\ListView\DragDrop\DragDropListViewListControl.cs region=ListControlToListViewStart}} -{{source=..\SamplesVB\ListView\DragDrop\DragDropListViewListControl.vb region=ListControlToListViewStart}} - -````C# - -private Point mouseDownPosition; -private bool isDragging; -private void radListControl1_MouseDown(object sender, MouseEventArgs e) -{ - this.mouseDownPosition = e.Location; -} -private void radListControl1_MouseMove(object sender, MouseEventArgs e) -{ - if (e.Button != MouseButtons.Left) - { - this.isDragging = false; - return; - } - if (this.isDragging) - { - return; - } - if (this.ShouldBeginDrag(this.mouseDownPosition, e.Location)) - { - RadListVisualItem draggedItem = this.radListControl1.ElementTree.GetElementAtPoint(this.mouseDownPosition) as RadListVisualItem; - if (draggedItem != null) - { - this.isDragging = true; - //start the drag and drop operation - (sender as RadListControl).DoDragDrop(draggedItem.Data, DragDropEffects.Copy); - } - } -} - -private bool ShouldBeginDrag(Point current, Point capture) -{ - Size dragSize = SystemInformation.DragSize; - Rectangle dragRect = new Rectangle(capture.X - dragSize.Width / 2, - capture.Y - dragSize.Height / 2, dragSize.Width, dragSize.Height); - return !dragRect.Contains(current); -} - -private void radListView1_DragEnter(object sender, DragEventArgs e) -{ - e.Effect = DragDropEffects.Copy; -} - -```` -````VB.NET -Private mouseDownPosition As Point -Private isDragging As Boolean -Private Sub radListControl1_MouseDown(sender As Object, e As MouseEventArgs) - Me.mouseDownPosition = e.Location -End Sub -Private Sub radListControl1_MouseMove(sender As Object, e As MouseEventArgs) - If e.Button <> MouseButtons.Left Then - Me.isDragging = False - Return - End If - If Me.isDragging Then - Return - End If - If Me.ShouldBeginDrag(Me.mouseDownPosition, e.Location) Then - Dim draggedItem As RadListVisualItem = TryCast(Me.RadListControl1.ElementTree.GetElementAtPoint(Me.mouseDownPosition), RadListVisualItem) - If draggedItem IsNot Nothing Then - Me.isDragging = True - 'start the drag and drop operation - TryCast(sender, RadListControl).DoDragDrop(draggedItem.Data, DragDropEffects.Copy) - End If - End If -End Sub -Private Function ShouldBeginDrag(current As Point, capture As Point) As Boolean - Dim dragSize As Size = SystemInformation.DragSize - Dim dragRect As New Rectangle(capture.X - dragSize.Width / 2, capture.Y - dragSize.Height / 2, dragSize.Width, dragSize.Height) - Return Not dragRect.Contains(current) -End Function -Private Sub radListView1_DragEnter(sender As Object, e As DragEventArgs) - e.Effect = DragDropEffects.Copy -End Sub - -```` - -{{endregion}} + + + + 2\. In the RadListView.__DragDrop__ event you need to get the location of the mouse and convert it to a point that the __RadListView__ can use to get the element underneath the mouse. Afterwards, insert the dragged item on the specific position. We should reset the stored mouse down location as well: #### Handle the drop operation -{{source=..\SamplesCS\ListView\DragDrop\DragDropListViewListControl.cs region=ListControlToListViewDragDrop}} -{{source=..\SamplesVB\ListView\DragDrop\DragDropListViewListControl.vb region=ListControlToListViewDragDrop}} - -````C# - -private void radListView1_DragDrop(object sender, DragEventArgs e) -{ - RadListView listView = sender as RadListView; - Point point = listView.PointToClient(new Point(e.X, e.Y)); - BaseListViewVisualItem targetItem = listView.ElementTree.GetElementAtPoint(point) as BaseListViewVisualItem; - RadListDataItem draggedItem = e.Data.GetData(typeof(RadListDataItem)) as RadListDataItem; - - BindingList targetDataSource = listView.DataSource as BindingList; - if (targetDataSource != null) - { - //you are dropping over an item - if (targetItem != null) - { - int targetIndex = listView.Items.IndexOf(targetItem.Data); - - targetDataSource.Insert(targetIndex, draggedItem.Text); - } - else // you are dropping over the ListViewElement - { - targetDataSource.Add(draggedItem.Text); - } - } - - int indexToRemove = this.radListControl1.Items.IndexOf(draggedItem); - if (indexToRemove > -1) - { - this.radListControl1.Items.RemoveAt(indexToRemove); - } - this.mouseDownPosition = Point.Empty; - this.isDragging = false; -} - -private void radListControl1_MouseUp(object sender, MouseEventArgs e) -{ - this.mouseDownPosition = Point.Empty; - this.isDragging = false; -} - -```` -````VB.NET -Private Sub radListView1_DragDrop(sender As Object, e As DragEventArgs) - Dim listView As RadListView = TryCast(sender, RadListView) - Dim point__1 As Point = listView.PointToClient(New Point(e.X, e.Y)) - Dim targetItem As BaseListViewVisualItem = TryCast(listView.ElementTree.GetElementAtPoint(point__1), BaseListViewVisualItem) - Dim draggedItem As RadListDataItem = TryCast(e.Data.GetData(GetType(RadListDataItem)), RadListDataItem) - Dim targetDataSource As BindingList(Of String) = TryCast(listView.DataSource, BindingList(Of String)) - If targetDataSource IsNot Nothing Then - 'you are dropping over an item - If targetItem IsNot Nothing Then - Dim targetIndex As Integer = listView.Items.IndexOf(targetItem.Data) - targetDataSource.Insert(targetIndex, draggedItem.Text) - Else - ' you are dropping over the ListViewElement - targetDataSource.Add(draggedItem.Text) - End If - End If - Dim indexToRemove As Integer = Me.RadListControl1.Items.IndexOf(draggedItem) - If indexToRemove > -1 Then - Me.RadListControl1.Items.RemoveAt(indexToRemove) - End If - Me.mouseDownPosition = Point.Empty - Me.isDragging = False -End Sub -Private Sub radListControl1_MouseUp(sender As Object, e As MouseEventArgs) - Me.mouseDownPosition = Point.Empty - Me.isDragging = False -End Sub - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/listview/drag-and-drop/drag-and-drop-from-another-control.md b/controls/listview/drag-and-drop/drag-and-drop-from-another-control.md index 5c9f226a2..e63f5eada 100644 --- a/controls/listview/drag-and-drop/drag-and-drop-from-another-control.md +++ b/controls/listview/drag-and-drop/drag-and-drop-from-another-control.md @@ -23,163 +23,19 @@ __RadListView__ supports drag and drop functionality from another control, such #### Starting a drag and drop operation -{{source=..\SamplesCS\ListView\DragDrop\DragDropFromAnotherControl.cs region=ListBoxToListViewStart}} -{{source=..\SamplesVB\ListView\DragDrop\DragDropFromAnotherControl.vb region=ListBoxToListViewStart}} - -````C# -private bool isDragging; -private Point mouseDownPosition; - -private void listBox1_MouseDown(object sender, MouseEventArgs e) -{ - this.mouseDownPosition = e.Location; -} - -private void listBox1_MouseMove(object sender, MouseEventArgs e) -{ - if (e.Button != MouseButtons.Left) - { - return; - } - if (this.isDragging) - { - return; - } - if (this.ShouldBeginDrag(this.mouseDownPosition, e.Location)) - { - int index = this.listBox1.IndexFromPoint(e.X, e.Y); - if (index > -1 && index < this.listBox1.Items.Count) - { - string itemText = this.listBox1.Items[index].ToString(); - if (itemText != string.Empty) - { - this.isDragging = true; - //start the drag and drop operation - (sender as ListBox).DoDragDrop(itemText, DragDropEffects.Copy); - } - } - } -} -private bool ShouldBeginDrag(Point current, Point capture) -{ - Size dragSize = SystemInformation.DragSize; - Rectangle dragRect = new Rectangle(capture.X - dragSize.Width / 2, - capture.Y - dragSize.Height / 2, dragSize.Width, dragSize.Height); - return !dragRect.Contains(current); -} -private void radListView1_DragEnter(object sender, DragEventArgs e) -{ - e.Effect = DragDropEffects.Copy; -} - -```` -````VB.NET -Private isDragging As Boolean -Private mouseDownPosition As Point -Private Sub listBox1_MouseDown(sender As Object, e As MouseEventArgs) - Me.mouseDownPosition = e.Location -End Sub -Private Sub listBox1_MouseMove(sender As Object, e As MouseEventArgs) - If e.Button <> MouseButtons.Left Then - Return - End If - If Me.isDragging Then - Return - End If - If Me.ShouldBeginDrag(Me.mouseDownPosition, e.Location) Then - Dim index As Integer = Me.ListBox1.IndexFromPoint(e.X, e.Y) - If index > -1 AndAlso index < Me.ListBox1.Items.Count Then - Dim itemText As String = Me.ListBox1.Items(index).ToString() - If itemText <> String.Empty Then - Me.isDragging = True - 'start the drag and drop operation - TryCast(sender, ListBox).DoDragDrop(itemText, DragDropEffects.Copy) - End If - End If - End If -End Sub -Private Function ShouldBeginDrag(current As Point, capture As Point) As Boolean - Dim dragSize As Size = SystemInformation.DragSize - Dim dragRect As New Rectangle(capture.X - dragSize.Width / 2, capture.Y - dragSize.Height / 2, dragSize.Width, dragSize.Height) - Return Not dragRect.Contains(current) -End Function -Private Sub radListView1_DragEnter(sender As Object, e As DragEventArgs) - e.Effect = DragDropEffects.Copy -End Sub - -```` - -{{endregion}} + + + + 2\. In the RadListView.__DragDrop__ event handler you need to get the location of the mouse and convert it to a point that __RadListView__ can use to get the target item underneath the mouse. Afterwards, insert the dragged item at the specific position in the RadListView.__Items__ collection and remove it from the ListBox. We should reset the stored mouse down location as well. #### Handling drop operation -{{source=..\SamplesCS\ListView\DragDrop\DragDropFromAnotherControl.cs region=ListBoxToListViewDragDrop}} -{{source=..\SamplesVB\ListView\DragDrop\DragDropFromAnotherControl.vb region=ListBoxToListViewDragDrop}} - -````C# - -private void radListView1_DragDrop(object sender, DragEventArgs e) -{ - Point point = this.radListView1.PointToClient(new Point(e.X, e.Y)); - BaseListViewVisualItem targetItem = this.radListView1.ElementTree.GetElementAtPoint(point) as BaseListViewVisualItem; - string draggedText = e.Data.GetData(typeof(string)).ToString(); - - //you are dropping over an item - if (targetItem != null) - { - int targetIndex = this.radListView1.Items.IndexOf(targetItem.Data); - this.radListView1.Items.Insert(targetIndex, new ListViewDataItem(draggedText)); - } - else // you are dropping over the ListViewElement - { - this.radListView1.Items.Add(new ListViewDataItem(draggedText)); - } - int indexToRemove = this.listBox1.Items.IndexOf(draggedText); - if (indexToRemove > -1) - { - this.listBox1.Items.RemoveAt(indexToRemove); - } - this.mouseDownPosition = Point.Empty; - this.isDragging = false; -} - -private void listBox1_MouseUp(object sender, MouseEventArgs e) -{ - this.mouseDownPosition = Point.Empty; - this.isDragging = false; -} - -```` -````VB.NET -Private Sub radListView1_DragDrop(sender As Object, e As DragEventArgs) - Dim point As Point = Me.RadListView1.PointToClient(New Point(e.X, e.Y)) - Dim targetItem As BaseListViewVisualItem = TryCast(Me.RadListView1.ElementTree.GetElementAtPoint(point), BaseListViewVisualItem) - Dim draggedText As String = e.Data.GetData(GetType(String)).ToString() - 'you are dropping over an item - If targetItem IsNot Nothing Then - Dim targetIndex As Integer = Me.RadListView1.Items.IndexOf(targetItem.Data) - Me.RadListView1.Items.Insert(targetIndex, New ListViewDataItem(draggedText)) - Else - ' you are dropping over the ListViewElement - Me.RadListView1.Items.Add(New ListViewDataItem(draggedText)) - End If - Dim indexToRemove As Integer = Me.ListBox1.Items.IndexOf(draggedText) - If indexToRemove > -1 Then - Me.ListBox1.Items.RemoveAt(indexToRemove) - End If - Me.mouseDownPosition = point.Empty - Me.isDragging = False -End Sub -Private Sub listBox1_MouseUp(sender As Object, e As MouseEventArgs) - Me.mouseDownPosition = Point.Empty - Me.isDragging = False -End Sub - -```` - -{{endregion}} + + + + ## Drag and drop from RadListView to ListBox @@ -191,136 +47,19 @@ End Sub #### Starting a drag and drop operation -{{source=..\SamplesCS\ListView\DragDrop\DragDropFromAnotherControl.cs region=ListViewToListBoxStart}} -{{source=..\SamplesVB\ListView\DragDrop\DragDropFromAnotherControl.vb region=ListViewToListBoxStart}} - -````C# -private Point lastMouseDownLocation; -private void radListView1_MouseDown(object sender, MouseEventArgs e) -{ - this.lastMouseDownLocation = e.Location; -} - -private void radListView1_MouseMove(object sender, MouseEventArgs e) -{ - if (e.Button != MouseButtons.Left) - { - return; - } - BaseListViewVisualItem draggedItem = radListView1.ElementTree.GetElementAtPoint(e.Location) as BaseListViewVisualItem; - if (draggedItem != null && - IsRealDrag(this.lastMouseDownLocation, e.Location)) - { - radListView1.Capture = false; - radListView1.DoDragDrop(draggedItem.Data, DragDropEffects.Move); - } -} -private bool IsRealDrag(Point current, Point capture) -{ - Size dragSize = SystemInformation.DragSize; - Rectangle dragRect = new Rectangle(capture.X - dragSize.Width / 2, - capture.Y - dragSize.Height / 2, dragSize.Width, dragSize.Height); - return !dragRect.Contains(current); -} - -private void listBox1_DragEnter(object sender, DragEventArgs e) -{ - e.Effect = DragDropEffects.Move; -} - -```` -````VB.NET -Private lastMouseDownLocation As Point -Private Sub radListView1_MouseDown(sender As Object, e As MouseEventArgs) - Me.lastMouseDownLocation = e.Location -End Sub -Private Sub radListView1_MouseMove(sender As Object, e As MouseEventArgs) - If e.Button <> MouseButtons.Left Then - Return - End If - Dim draggedItem As BaseListViewVisualItem = TryCast(RadListView1.ElementTree.GetElementAtPoint(e.Location), BaseListViewVisualItem) - If draggedItem IsNot Nothing AndAlso _ - IsRealDrag(Me.lastMouseDownLocation, e.Location) Then - RadListView1.Capture = False - RadListView1.DoDragDrop(draggedItem.Data, DragDropEffects.Move) - End If -End Sub -Private Function IsRealDrag(current As Point, capture As Point) As Boolean - Dim dragSize As Size = SystemInformation.DragSize - Dim dragRect As New Rectangle(capture.X - dragSize.Width / 2, _ - capture.Y - dragSize.Height / 2, dragSize.Width, dragSize.Height) - Return Not dragRect.Contains(current) -End Function -Private Sub listBox1_DragEnter(sender As Object, e As DragEventArgs) - e.Effect = DragDropEffects.Move -End Sub - -```` - -{{endregion}} + + + + 2\. Finally, perform the exact drag and drop operation via inserting a new item in the **ListBox** in the __DragDrop__ event. We should reset the stored mouse down location as well: #### Handling the drop operation -{{source=..\SamplesCS\ListView\DragDrop\DragDropFromAnotherControl.cs region=ListViewToListBoxDrop}} -{{source=..\SamplesVB\ListView\DragDrop\DragDropFromAnotherControl.vb region=ListViewToListBoxDrop}} - -````C# -private void listBox1_DragDrop(object sender, DragEventArgs e) -{ - ListViewDataItem draggedItem = e.Data.GetData(typeof(ListViewDataItem)) as ListViewDataItem; - if (draggedItem != null) - { - Point point = this.listBox1.PointToClient(new Point(e.X, e.Y)); - int targetIndex = this.listBox1.IndexFromPoint(point); - if (targetIndex > -1) - { - this.listBox1.Items.Insert(targetIndex, draggedItem.Text); - } - else - { - this.listBox1.Items.Add(draggedItem.Text); - } - int sourceIndex = this.radListView1.Items.IndexOf(draggedItem); - if (sourceIndex > -1) - { - this.radListView1.Items.RemoveAt(sourceIndex); - } - } - this.lastMouseDownLocation = Point.Empty; -} -private void radListView1_MouseUp(object sender, MouseEventArgs e) -{ - this.lastMouseDownLocation = Point.Empty; -} - -```` -````VB.NET -Private Sub listBox1_DragDrop(sender As Object, e As DragEventArgs) - Dim draggedItem As ListViewDataItem = TryCast(e.Data.GetData(GetType(ListViewDataItem)), ListViewDataItem) - If draggedItem IsNot Nothing Then - Dim point As Point = Me.ListBox1.PointToClient(New Point(e.X, e.Y)) - Dim targetIndex As Integer = Me.ListBox1.IndexFromPoint(point) - If targetIndex > -1 Then - Me.ListBox1.Items.Insert(targetIndex, draggedItem.Text) - Else - Me.ListBox1.Items.Add(draggedItem.Text) - End If - Dim sourceIndex As Integer = Me.RadListView1.Items.IndexOf(draggedItem) - If sourceIndex > -1 Then - Me.RadListView1.Items.RemoveAt(sourceIndex) - End If - End If - Me.lastMouseDownLocation = Point.Empty -End Sub -Private Sub radListView1_MouseUp(sender As Object, e As MouseEventArgs) - Me.lastMouseDownLocation = Point.Empty -End Sub - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/listview/drag-and-drop/drag-and-drop-in-bound-mode.md b/controls/listview/drag-and-drop/drag-and-drop-in-bound-mode.md index 12d9f5b75..dba28da3b 100644 --- a/controls/listview/drag-and-drop/drag-and-drop-in-bound-mode.md +++ b/controls/listview/drag-and-drop/drag-and-drop-in-bound-mode.md @@ -19,253 +19,31 @@ When __RadListView__ is in bound mode, it does not support drag and drop functio 1\. Let’s start with populating the __RadListView__ with data. For this purpose we will create a class **Item** and fill a **BindingList** with items: -{{source=..\SamplesCS\ListView\DragDrop\DragDropInBoundMode.cs region=CreateItem}} -{{source=..\SamplesVB\ListView\DragDrop\DragDropInBoundMode.vb region=CreateItem}} + + -````C# - -public class Item -{ - public string UniqueId { get; set; } - - public string Title { get; set; } - - public bool IsActive { get; set; } - - public DateTime CreatedOn { get; set; } - - public Item(string uniqueId, string title, bool isActive, DateTime createdOn) - { - this.UniqueId = uniqueId; - this.Title = title; - this.IsActive = isActive; - this.CreatedOn = createdOn; - } -} - -public DragDropInBoundMode() -{ - InitializeComponent(); - - BindingList items = new BindingList(); - for (int i = 0; i < 30; i++) - { - items.Add(new Item(Guid.NewGuid().ToString(), - "Item" + i,i % 2 == 0,DateTime.Now.AddDays(i))); - } - - this.radListView1.DataSource = items; - this.radListView1.DisplayMember = "Title"; -} -```` -````VB.NET -Public Class Item - Public Property UniqueId() As String - Get - Return m_UniqueId - End Get - Set(value As String) - m_UniqueId = value - End Set - End Property - Private m_UniqueId As String - Public Property Title() As String - Get - Return m_Title - End Get - Set(value As String) - m_Title = value - End Set - End Property - Private m_Title As String - Public Property IsActive() As Boolean - Get - Return m_IsActive - End Get - Set(value As Boolean) - m_IsActive = value - End Set - End Property - Private m_IsActive As Boolean - Public Property CreatedOn() As DateTime - Get - Return m_CreatedOn - End Get - Set(value As DateTime) - m_CreatedOn = value - End Set - End Property - Private m_CreatedOn As DateTime - Public Sub New(uniqueId As String, title As String, isActive As Boolean, createdOn As DateTime) - Me.UniqueId = uniqueId - Me.Title = title - Me.IsActive = isActive - Me.CreatedOn = createdOn - End Sub -End Class -Public Sub New() - InitializeComponent() - Dim items As New BindingList(Of Item)() - For i As Integer = 0 To 9 - items.Add(New Item(Guid.NewGuid().ToString(), "Item" & i, i Mod 2 = 0, DateTime.Now.AddDays(i))) - Next - Me.RadListView1.DataSource = items - Me.RadListView1.DisplayMember = "Title" -End Sub - -```` - -{{endregion}} 2\. In order to enable the drag and drop functionality, set the RadListView.__AllowDragDrop__ property to *true*: -{{source=..\SamplesCS\ListView\DragDrop\DragDropInBoundMode.cs region=EnableDragDrop}} -{{source=..\SamplesVB\ListView\DragDrop\DragDropInBoundMode.vb region=EnableDragDrop}} - -````C# - -this.radListView1.AllowDragDrop = true; - -```` -````VB.NET -Me.RadListView1.AllowDragDrop = True + + -```` -{{endregion}} 3\. Use the ListViewElement.DragDropService.__PreviewDragStart__ event to get the dragged item. Subscribe to the ListViewElement.DragDropService.__PreviewDragOver__ event, which allows you to control on what targets the item, being dragged, can be dropped on: -{{source=..\SamplesCS\ListView\DragDrop\DragDropInBoundMode.cs region=DragStartOver}} -{{source=..\SamplesVB\ListView\DragDrop\DragDropInBoundMode.vb region=DragStartOver}} + + -````C# - -Item sourceBoundItem; - -private void DragDropService_PreviewDragStart(object sender, PreviewDragStartEventArgs e) -{ - SimpleListViewVisualItem sourceItem = e.DragInstance as SimpleListViewVisualItem; - if (sourceItem != null) - { - sourceBoundItem = sourceItem.Data.DataBoundItem as Item; - } -} - -private void DragDropService_PreviewDragOver(object sender, RadDragOverEventArgs e) -{ - if (e.DragInstance is SimpleListViewVisualItem) - { - e.CanDrop = e.HitTarget is SimpleListViewVisualItem || - e.HitTarget is SimpleListViewElement ; - } -} -```` -````VB.NET -Private sourceBoundItem As Item -Private Sub DragDropService_PreviewDragStart(sender As Object, e As PreviewDragStartEventArgs) - Dim sourceItem As SimpleListViewVisualItem = TryCast(e.DragInstance, SimpleListViewVisualItem) - If sourceItem IsNot Nothing Then - sourceBoundItem = TryCast(sourceItem.Data.DataBoundItem, Item) - End If -End Sub -Private Sub DragDropService_PreviewDragOver(sender As Object, e As RadDragOverEventArgs) - If TypeOf e.DragInstance Is SimpleListViewVisualItem Then - e.CanDrop = TypeOf e.HitTarget Is SimpleListViewVisualItem OrElse TypeOf e.HitTarget Is SimpleListViewElement - End If -End Sub - -```` - -{{endregion}} 4\. The last event we need to handle in our implementation is the ListViewElement.DragDropService.__PreviewDragDrop__ event. This is where we will initiate the actual physical move of the item from one position to another. Implement the handler as follows: -{{source=..\SamplesCS\ListView\DragDrop\DragDropInBoundMode.cs region=DragDrop}} -{{source=..\SamplesVB\ListView\DragDrop\DragDropInBoundMode.vb region=DragDrop}} - -````C# - -private void DragDropService_PreviewDragDrop(object sender, RadDropEventArgs e) -{ - e.Handled = true; - - SimpleListViewVisualItem targetItem = e.HitTarget as SimpleListViewVisualItem; - SimpleListViewVisualItem sourceItem = e.DragInstance as SimpleListViewVisualItem; - SimpleListViewElement viewElement = e.HitTarget as SimpleListViewElement; - if ((targetItem == null || sourceItem == null) && viewElement == null) - { - return; - } - BindingList dataSource = sourceItem.Data.ListView.DataSource as BindingList ; - if (dataSource != null) - { - if (sourceBoundItem != null) - { - int sourceIndex = dataSource.IndexOf(sourceBoundItem); - if (viewElement != null) - { - //add the dragged item at last position - dataSource.RemoveAt(sourceIndex); - dataSource.Add(sourceBoundItem); - } - else - { - viewElement = sourceItem.Data.ListView.ListViewElement.ViewElement as SimpleListViewElement; - //reorder the items in the BindingList - Item targetBoundItem = targetItem.Data.DataBoundItem as Item; - - dataSource.RemoveAt(sourceIndex); - int targetIndex = dataSource.IndexOf(targetBoundItem); - - if (viewElement.ShouldDropAfter(targetItem, e.DropLocation)) - { - targetIndex++; - } - dataSource.Insert(targetIndex, sourceBoundItem); - } - } - } -} - -```` -````VB.NET -Private Sub DragDropService_PreviewDragDrop(sender As Object, e As RadDropEventArgs) - e.Handled = True - Dim targetItem As SimpleListViewVisualItem = TryCast(e.HitTarget, SimpleListViewVisualItem) - Dim sourceItem As SimpleListViewVisualItem = TryCast(e.DragInstance, SimpleListViewVisualItem) - Dim viewElement As SimpleListViewElement = TryCast(e.HitTarget, SimpleListViewElement) - If (targetItem Is Nothing OrElse sourceItem Is Nothing) AndAlso viewElement Is Nothing Then - Return - End If - Dim dataSource As BindingList(Of Item) = TryCast(sourceItem.Data.ListView.DataSource, BindingList(Of Item)) - If dataSource IsNot Nothing Then - If sourceBoundItem IsNot Nothing Then - Dim sourceIndex As Integer = dataSource.IndexOf(sourceBoundItem) - If viewElement IsNot Nothing Then - 'add the dragged item at last position - dataSource.RemoveAt(sourceIndex) - dataSource.Add(sourceBoundItem) - Else - viewElement = TryCast(sourceItem.Data.ListView.ListViewElement.ViewElement, SimpleListViewElement) - 'reorder the items in the BindingList - Dim targetBoundItem As Item = TryCast(targetItem.Data.DataBoundItem, Item) - dataSource.RemoveAt(sourceIndex) - Dim targetIndex As Integer = dataSource.IndexOf(targetBoundItem) - If viewElement.ShouldDropAfter(targetItem, e.DropLocation) Then - targetIndex += 1 - End If - dataSource.Insert(targetIndex, sourceBoundItem) - End If - End If - End If -End Sub + + -```` -{{endregion}} # See Also diff --git a/controls/listview/drag-and-drop/drag-and-drop-using-raddragdropservice.md b/controls/listview/drag-and-drop/drag-and-drop-using-raddragdropservice.md index 19e7960da..67c1bb8eb 100644 --- a/controls/listview/drag-and-drop/drag-and-drop-using-raddragdropservice.md +++ b/controls/listview/drag-and-drop/drag-and-drop-using-raddragdropservice.md @@ -15,78 +15,11 @@ This article will guide you through the process of achieving drag and drop funct #### Populating with data -{{source=..\SamplesCS\ListView\DragDrop\DragDropRadDragDropService.cs region=PopulateWithData}} -{{source=..\SamplesVB\ListView\DragDrop\DragDropRadDragDropService.vb region=PopulateWithData}} - -````C# - -DataTable gridViewDataTable = new DataTable(); - -public DragDropRadDragDropService() -{ - InitializeComponent(); - - this.radListView1.Columns.Add("Id"); - this.radListView1.Columns.Add("Title"); - this.radListView1.ViewType = Telerik.WinControls.UI.ListViewType.DetailsView; - - List products = new List() - { - "Telerik UI for WinForms", - "Telerik UI for Silverlight", - "Telerik UI for WPF", - "Telerik UI for ASP.NET AJAX" - }; - for (int i = 0; i < products.Count; i++) - { - ListViewDataItem item = new ListViewDataItem(); - this.radListView1.Items.Add(item); - item["Id"] = Guid.NewGuid().ToString(); - item["Title"] = products[i]; - } - - gridViewDataTable.Columns.Add("Id", typeof(string)); - gridViewDataTable.Columns.Add("Title", typeof(string)); - gridViewDataTable.Rows.Add(Guid.NewGuid().ToString(), "Kendo UI"); - gridViewDataTable.Rows.Add(Guid.NewGuid().ToString(), "Telerik UI for iOS"); - gridViewDataTable.Rows.Add(Guid.NewGuid().ToString(), "Telerik UI for Android"); - gridViewDataTable.Rows.Add(Guid.NewGuid().ToString(), "Telerik UI for Windows Phone"); - this.radGridView1.DataSource = gridViewDataTable; -} - -```` -````VB.NET -Private gridViewDataTable As New DataTable() -Sub New() - InitializeComponent() - Me.RadListView1.Columns.Add("Id") - Me.RadListView1.Columns.Add("Title") - Me.RadListView1.ViewType = Telerik.WinControls.UI.ListViewType.DetailsView - Dim products As New List(Of String)() From { _ - "Telerik UI for WinForms", _ - "Telerik UI for Silverlight", _ - "Telerik UI for WPF", _ - "Telerik UI for ASP.NET AJAX" _ - } - For i As Integer = 0 To products.Count - 1 - Dim item As New ListViewDataItem() - Me.RadListView1.Items.Add(item) - item("Id") = Guid.NewGuid().ToString() - item("Title") = products(i) - Next - gridViewDataTable.Columns.Add("Id", GetType(String)) - gridViewDataTable.Columns.Add("Title", GetType(String)) - gridViewDataTable.Rows.Add(Guid.NewGuid().ToString(), "Kendo UI") - gridViewDataTable.Rows.Add(Guid.NewGuid().ToString(), "Telerik UI for iOS") - gridViewDataTable.Rows.Add(Guid.NewGuid().ToString(), "Telerik UI for Android") - gridViewDataTable.Rows.Add(Guid.NewGuid().ToString(), "Telerik UI for Windows Phone") - Me.RadGridView1.DataSource = gridViewDataTable -End Sub - -```` - -{{endregion}} - + + + + + ## Drag and Drop from RadGridView to RadListView >caption Figure 1: Drag and Drop from RadGridView to RadListView @@ -97,162 +30,28 @@ End Sub #### Starting a drag and drop operation -{{source=..\SamplesCS\ListView\DragDrop\DragDropRadDragDropService.cs region=RowBehavior}} -{{source=..\SamplesVB\ListView\DragDrop\DragDropRadDragDropService.vb region=RowBehavior}} - -````C# - -//initiates drag and drop service for clicked rows -public class CustomRowGridBehavior : GridDataRowBehavior -{ - protected override bool OnMouseDownLeft(MouseEventArgs e) - { - GridDataRowElement row = this.GetRowAtPoint(e.Location) as GridDataRowElement; - if (row != null) - { - RadGridViewDragDropService svc = this.GridViewElement.GetService(); - svc.Start(row); - } - return base.OnMouseDownLeft(e); - } -} - -```` -````VB.NET -'initiates drag and drop service for clicked rows -Public Class CustomRowGridBehavior - Inherits GridDataRowBehavior - Protected Overrides Function OnMouseDownLeft(e As MouseEventArgs) As Boolean - Dim row As GridDataRowElement = TryCast(Me.GetRowAtPoint(e.Location), GridDataRowElement) - If row IsNot Nothing Then - Dim svc As RadGridViewDragDropService = Me.GridViewElement.GetService(Of RadGridViewDragDropService)() - svc.Start(row) - End If - Return MyBase.OnMouseDownLeft(e) - End Function -End Class - -```` - -{{endregion}} + + -2\. Next, we should register this behavior in our grid: -#### Register the custom row behavior -{{source=..\SamplesCS\ListView\DragDrop\DragDropRadDragDropService.cs region=RegisterRowBehavior}} -{{source=..\SamplesVB\ListView\DragDrop\DragDropRadDragDropService.vb region=RegisterRowBehavior}} +2\. Next, we should register this behavior in our grid: -````C# - -//register the custom row behavior -BaseGridBehavior gridBehavior = this.radGridView1.GridBehavior as BaseGridBehavior; -gridBehavior.UnregisterBehavior(typeof(GridViewDataRowInfo)); -gridBehavior.RegisterBehavior(typeof(GridViewDataRowInfo), new CustomRowGridBehavior()); +#### Register the custom row behavior -```` -````VB.NET -'register the custom row behavior -Dim gridBehavior As BaseGridBehavior = TryCast(Me.RadGridView1.GridBehavior, BaseGridBehavior) -gridBehavior.UnregisterBehavior(GetType(GridViewDataRowInfo)) -gridBehavior.RegisterBehavior(GetType(GridViewDataRowInfo), New CustomRowGridBehavior()) + + -```` -{{endregion}} 3\. It is necessary to subscribe to the __PreviewDragStart__, __PreviewDragOver__ and __PreviewDragDrop__ events of the grid’s __RadDragDropService__. The __PreviewDragStart__ event is fired once the drag and drop service on the grid is started. We should notify the service that the drag and drop operation can move forward. In the __PreviewDragOver__ event you can control on what targets to allow dropping the dragged row. The __PreviewDragDrop__ event performs the actual move of the row from the __RadGridView__ to the __RadListView__. #### Handling the RadDragDropService's events -{{source=..\SamplesCS\ListView\DragDrop\DragDropRadDragDropService.cs region=GridViewToListView}} -{{source=..\SamplesVB\ListView\DragDrop\DragDropRadDragDropService.vb region=GridViewToListView}} - -````C# - -private void svc_PreviewDragStart(object sender, PreviewDragStartEventArgs e) -{ - e.CanStart = true; -} - -private void svc_PreviewDragOver(object sender, RadDragOverEventArgs e) -{ - if (e.DragInstance is GridDataRowElement) - { - e.CanDrop = e.HitTarget is DetailListViewDataCellElement || - e.HitTarget is DetailListViewElement; - } -} - -private void svc_PreviewDragDrop(object sender, RadDropEventArgs e) -{ - DetailListViewDataCellElement targetCell = e.HitTarget as DetailListViewDataCellElement; - DetailListViewElement targetElement = e.HitTarget as DetailListViewElement; - GridDataRowElement draggedRow = e.DragInstance as GridDataRowElement; - - if (draggedRow == null) - { - return; - } - ListViewDataItem item = new ListViewDataItem(); - DataRow draggedDataBoundItem = ((DataRowView)draggedRow.RowInfo.DataBoundItem).Row; - if (targetElement != null) - { - ((RadListViewElement)targetElement.Parent).Items.Add(item) ; - } - if (targetCell != null) - { - BaseListViewVisualItem targetVisualItem = targetCell.RowElement; - - int insertIndex = targetCell.Row.ListView.Items.IndexOf(targetVisualItem.Data); - if (insertIndex > -1) - { - targetCell.Row.ListView.Items.Insert(insertIndex, item); - } - } - item["Id"] = draggedDataBoundItem["Id"]; - item["Title"] = draggedDataBoundItem["Title"]; - - gridViewDataTable.Rows.Remove(draggedDataBoundItem); -} - -```` -````VB.NET -Private Sub svc_PreviewDragStart(sender As Object, e As PreviewDragStartEventArgs) - e.CanStart = True -End Sub -Private Sub svc_PreviewDragOver(sender As Object, e As RadDragOverEventArgs) - If TypeOf e.DragInstance Is GridDataRowElement Then - e.CanDrop = TypeOf e.HitTarget Is DetailListViewDataCellElement OrElse TypeOf e.HitTarget Is DetailListViewElement - End If -End Sub -Private Sub svc_PreviewDragDrop(sender As Object, e As RadDropEventArgs) - Dim targetCell As DetailListViewDataCellElement = TryCast(e.HitTarget, DetailListViewDataCellElement) - Dim targetElement As DetailListViewElement = TryCast(e.HitTarget, DetailListViewElement) - Dim draggedRow As GridDataRowElement = TryCast(e.DragInstance, GridDataRowElement) - If draggedRow Is Nothing Then - Return - End If - Dim item As New ListViewDataItem() - Dim draggedDataBoundItem As DataRow = DirectCast(draggedRow.RowInfo.DataBoundItem, DataRowView).Row - If targetElement IsNot Nothing Then - DirectCast(targetElement.Parent, RadListViewElement).Items.Add(item) - End If - If targetCell IsNot Nothing Then - Dim targetVisualItem As BaseListViewVisualItem = targetCell.RowElement - Dim insertIndex As Integer = targetCell.Row.ListView.Items.IndexOf(targetVisualItem.Data) - If insertIndex > -1 Then - targetCell.Row.ListView.Items.Insert(insertIndex, item) - End If - End If - item("Id") = draggedDataBoundItem("Id") - item("Title") = draggedDataBoundItem("Title") - gridViewDataTable.Rows.Remove(draggedDataBoundItem) -End Sub - -```` - -{{endregion}} + + + + ## Drag and Drop from RadListView to RadGridView @@ -264,103 +63,18 @@ End Sub #### Subscribing to the RadDragDropService's events -{{source=..\SamplesCS\ListView\DragDrop\DragDropRadDragDropService.cs region=WireListViewServiceEvents}} -{{source=..\SamplesVB\ListView\DragDrop\DragDropRadDragDropService.vb region=WireListViewServiceEvents}} -````C# - -this.radListView1.ListViewElement.DragDropService.PreviewDragOver += DragDropService_PreviewDragOver; -this.radListView1.ListViewElement.DragDropService.PreviewDragDrop += DragDropService_PreviewDragDrop; - -```` -````VB.NET -AddHandler Me.RadListView1.ListViewElement.DragDropService.PreviewDragOver, AddressOf DragDropService_PreviewDragOver -AddHandler Me.RadListView1.ListViewElement.DragDropService.PreviewDragDrop, AddressOf DragDropService_PreviewDragDrop + + -```` - -{{endregion}} - 2\. To implement drag and drop functionality for this scenario, we will use the ListViewElement.__DragDropService__, which is a derivative of the __RadDragDropService__ . Subscribe to its __PreviewDragOver__ and __PreviewDragDrop__ events. In the __PreviewDragOver__ event allow dropping over a row element or over the table element. The __PreviewDragDrop__ event performs the actual inserting of the dragged item into the __RadGridView__’s data source: #### Handling the RadDragDropService's events -{{source=..\SamplesCS\ListView\DragDrop\DragDropRadDragDropService.cs region=ListViewToGridView}} -{{source=..\SamplesVB\ListView\DragDrop\DragDropRadDragDropService.vb region=ListViewToGridView}} - -````C# - -private void DragDropService_PreviewDragOver(object sender, RadDragOverEventArgs e) -{ - e.CanDrop = e.HitTarget is GridTableElement || - e.HitTarget is GridDataRowElement; -} - -private void DragDropService_PreviewDragDrop(object sender, RadDropEventArgs e) -{ - BaseListViewVisualItem draggedItem = e.DragInstance as BaseListViewVisualItem; - GridDataRowElement rowElement = e.HitTarget as GridDataRowElement; - GridTableElement tableElement = e.HitTarget as GridTableElement; - - if (rowElement == null && tableElement == null) - { - return; - } - e.Handled = true; - DataRow newRow = gridViewDataTable.NewRow(); - if (tableElement != null) - { - gridViewDataTable.Rows.Add(newRow); - } - if (rowElement != null) - { - GridViewRowInfo targetRow = rowElement.RowInfo; - - int insertIndex = this.radGridView1.Rows.IndexOf(targetRow); - if (insertIndex > -1) - { - gridViewDataTable.Rows.InsertAt(newRow, insertIndex); - } - } - newRow["Id"] = draggedItem.Data["Id"]; - newRow["Title"] = draggedItem.Data["Title"]; - - this.radListView1.Items.Remove(draggedItem.Data); -} - -```` -````VB.NET -Private Sub DragDropService_PreviewDragOver(sender As Object, e As RadDragOverEventArgs) - e.CanDrop = TypeOf e.HitTarget Is GridTableElement OrElse TypeOf e.HitTarget Is GridDataRowElement -End Sub -Private Sub DragDropService_PreviewDragDrop(sender As Object, e As RadDropEventArgs) - Dim draggedItem As BaseListViewVisualItem = TryCast(e.DragInstance, BaseListViewVisualItem) - Dim rowElement As GridDataRowElement = TryCast(e.HitTarget, GridDataRowElement) - Dim tableElement As GridTableElement = TryCast(e.HitTarget, GridTableElement) - If rowElement Is Nothing AndAlso tableElement Is Nothing Then - Return - End If - e.Handled = True - Dim newRow As DataRow = gridViewDataTable.NewRow() - If tableElement IsNot Nothing Then - gridViewDataTable.Rows.Add(newRow) - End If - If rowElement IsNot Nothing Then - Dim targetRow As GridViewRowInfo = rowElement.RowInfo - Dim insertIndex As Integer = Me.RadGridView1.Rows.IndexOf(targetRow) - If insertIndex > -1 Then - gridViewDataTable.Rows.InsertAt(newRow, insertIndex) - End If - End If - newRow("Id") = draggedItem.Data("Id") - newRow("Title") = draggedItem.Data("Title") - Me.RadListView1.Items.Remove(draggedItem.Data) -End Sub - -```` - -{{endregion}} + + + # See Also diff --git a/controls/listview/editors/custom-editors.md b/controls/listview/editors/custom-editors.md index af0582e39..8e3efdc80 100644 --- a/controls/listview/editors/custom-editors.md +++ b/controls/listview/editors/custom-editors.md @@ -18,139 +18,19 @@ This article demonstrates a sample approach how to create and replace the defaul #### Custom editor -{{source=..\SamplesCS\ListView\ListViewCheckboxesAndEditors.cs region=MyEditor}} -{{source=..\SamplesVB\ListView\ListViewCheckboxesAndEditors.vb region=MyEditor}} - -````C# - -public class MyTrackBarEditor : BaseInputEditor -{ - public override object Value - { - get - { - RadTrackBarElement editor = (RadTrackBarElement)this.EditorElement; - return editor.Value; - } - set - { - RadTrackBarElement editor = (RadTrackBarElement)this.EditorElement; - if (value != null && value != DBNull.Value) - { - editor.Value = Convert.ToInt32(value); - } - else - { - editor.Value = 0; - } - } - } - - public override void BeginEdit() - { - base.BeginEdit(); - this.EditorElement.Focus(); - ((RadTrackBarElement)this.EditorElement).ValueChanged += new EventHandler(TrackBarEditor_ValueChanged); - } - - void TrackBarEditor_ValueChanged(object sender, EventArgs e) - { - this.OnValueChanged(); - } - - public override bool EndEdit() - { - ((RadTrackBarElement)this.EditorElement).ValueChanged -= TrackBarEditor_ValueChanged; - return base.EndEdit(); - } - - protected override RadElement CreateEditorElement() - { - return new RadTrackBarElement(); - } - - public override Type DataType - { - get - { - return typeof(int); - } - } -} - -```` -````VB.NET -Public Class MyTrackBarEditor - Inherits BaseInputEditor - Public Overrides Property Value() As Object - Get - Dim editor As RadTrackBarElement = DirectCast(Me.EditorElement, RadTrackBarElement) - Return editor.Value - End Get - Set(value As Object) - Dim editor As RadTrackBarElement = DirectCast(Me.EditorElement, RadTrackBarElement) - If value IsNot Nothing AndAlso value <> DBNull.Value Then - editor.Value = Convert.ToInt32(value) - Else - editor.Value = 0 - End If - End Set - End Property - Public Overrides Sub BeginEdit() - MyBase.BeginEdit() - Me.EditorElement.Focus() - AddHandler DirectCast(Me.EditorElement, RadTrackBarElement).ValueChanged, AddressOf TrackBarEditor_ValueChanged - End Sub - Private Sub TrackBarEditor_ValueChanged(sender As Object, e As EventArgs) - Me.OnValueChanged() - End Sub - Public Overrides Function EndEdit() As Boolean - RemoveHandler DirectCast(Me.EditorElement, RadTrackBarElement).ValueChanged, AddressOf TrackBarEditor_ValueChanged - Return MyBase.EndEdit() - End Function - Protected Overrides Function CreateEditorElement() As RadElement - Return New RadTrackBarElement() - End Function - Public Overrides ReadOnly Property DataType() As Type - Get - Return GetType(Integer) - End Get - End Property -End Class - -```` - -{{endregion}} + + + + Here is the sample code snippet how to replace the default editor with the custom one handling the **EditorRequired** event: #### Replace default editor -{{source=..\SamplesCS\ListView\ListViewCheckboxesAndEditors.cs region=ReplaceEditor}} -{{source=..\SamplesVB\ListView\ListViewCheckboxesAndEditors.vb region=ReplaceEditor}} - -````C# -private void RadListView_EditorRequired(object sender, ListViewItemEditorRequiredEventArgs e) -{ - //if you use DetailsView and the current column is a specific one, replace the editor - if (this.radListView1.CurrentColumn.Name == "Quantity") - { - e.EditorType=typeof(MyTrackBarEditor); - } -} - -```` -````VB.NET -Private Sub RadListView_EditorRequired(sender As Object, e As ListViewItemEditorRequiredEventArgs) - 'if you use DetailsView and the current column is a specific one, replace the editor - If Me.RadListView1.CurrentColumn.Name = "Quantity" Then - e.EditorType = GetType(MyTrackBarEditor) - End If -End Sub - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/listview/editors/default-editors.md b/controls/listview/editors/default-editors.md index 0aa04b84b..5742027ec 100644 --- a/controls/listview/editors/default-editors.md +++ b/controls/listview/editors/default-editors.md @@ -24,57 +24,10 @@ The following example shows how you can use the predefined editors: #### Start editing -{{source=..\SamplesCS\ListView\ListViewCheckboxesAndEditors.cs region=usePredefinedEditors}} -{{source=..\SamplesVB\ListView\ListViewCheckboxesAndEditors.vb region=usePredefinedEditors}} + + -````C# - -void radListView1_EditorRequired(object sender, Telerik.WinControls.UI.ListViewItemEditorRequiredEventArgs e) -{ - if (e.ListViewElement.CurrentColumn.FieldName == "CustomerName") - { - e.EditorType = typeof(ListViewTextBoxEditor); - } - else if (e.ListViewElement.CurrentColumn.FieldName == "ProductName") - { - ListViewDropDownListEditor editor = new ListViewDropDownListEditor(); - (editor.EditorElement as BaseDropDownListEditorElement).Items.Add("Product1"); - (editor.EditorElement as BaseDropDownListEditorElement).Items.Add("Product2"); - (editor.EditorElement as BaseDropDownListEditorElement).Items.Add("Product3"); - - e.Editor = editor; - } - else if (e.ListViewElement.CurrentColumn.FieldName == "Quantity") - { - e.EditorType = typeof(ListViewSpinEditor); - } - else if (e.ListViewElement.CurrentColumn.FieldName == "OrderDate") - { - e.EditorType = typeof(ListViewDateTimeEditor); - } -} -```` -````VB.NET -Private Sub radListView1_EditorRequired(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.ListViewItemEditorRequiredEventArgs) - If e.ListViewElement.CurrentColumn.FieldName = "CustomerName" Then - e.EditorType = GetType(ListViewTextBoxEditor) - ElseIf e.ListViewElement.CurrentColumn.FieldName = "ProductName" Then - Dim editor As New ListViewDropDownListEditor() - TryCast(editor.EditorElement, BaseDropDownListEditorElement).Items.Add("Product1") - TryCast(editor.EditorElement, BaseDropDownListEditorElement).Items.Add("Product2") - TryCast(editor.EditorElement, BaseDropDownListEditorElement).Items.Add("Product3") - e.Editor = editor - ElseIf e.ListViewElement.CurrentColumn.FieldName = "Quantity" Then - e.EditorType = GetType(ListViewSpinEditor) - ElseIf e.ListViewElement.CurrentColumn.FieldName = "OrderDate" Then - e.EditorType = GetType(ListViewDateTimeEditor) - End If -End Sub - -```` - -{{endregion}} # See Also diff --git a/controls/listview/editors/editors.md b/controls/listview/editors/editors.md index d55597a6c..63c9871e5 100644 --- a/controls/listview/editors/editors.md +++ b/controls/listview/editors/editors.md @@ -25,32 +25,10 @@ The sample code below shows how to start editing using the API: #### Start editing -{{source=..\SamplesCS\ListView\ListViewCheckboxesAndEditors.cs region=startEdit}} -{{source=..\SamplesVB\ListView\ListViewCheckboxesAndEditors.vb region=startEdit}} - -````C# - -radListView1.AllowEdit = true; -// set the SelectedItem - this item will be edited -// in DetailsView you might also want to set the CurrentColumn property – the value of the selected item in this column will be edited in DetailsView -radListView1.SelectedItem = radListView1.Items[0]; -radListView1.CurrentColumn = radListView1.Columns[0]; -// this will start edit on selected item -radListView1.BeginEdit(); - -```` -````VB.NET -RadListView1.AllowEdit = True -' set the SelectedItem - this node will be edited -' in DetailsView you might also want to set the CurrentColumn property – the value of the selected item in this column will be edited in DetailsView -RadListView1.SelectedItem = RadListView1.Items(0) -RadListView1.CurrentColumn = RadListView1.Columns(0) -' this will start edit on selected item -RadListView1.BeginEdit() - -```` - -{{endregion}} + + + + ## Editing lifecycle @@ -80,46 +58,10 @@ The following example demonstrates the usage of __ItemValidating__ event to edit #### Validation -{{source=..\SamplesCS\ListView\ListViewCheckboxesAndEditors.cs region=ItemValidating}} -{{source=..\SamplesVB\ListView\ListViewCheckboxesAndEditors.vb region=ItemValidating}} - -````C# - -void radListView1_ItemValidating(object sender, ListViewItemValidatingEventArgs e) -{ - int newInt = 0; - if (int.TryParse(Convert.ToString(e.NewValue), out newInt)) - { - e.NewValue = newInt; - } - else - { - e.Cancel = true; - } -} - -void radListView1_ValidationError(object sender, EventArgs e) -{ - MessageBox.Show("Invalid Value"); -} - -```` -````VB.NET -Private Sub radListView1_ItemValidating(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.ListViewItemValidatingEventArgs) Handles RadListView1.ItemValidating - Dim newInt As Integer = 0 - If Integer.TryParse(Convert.ToString(e.NewValue), newInt) Then - e.NewValue = newInt - Else - e.Cancel = True - End If -End Sub -Private Sub radListView1_ValidationError(ByVal sender As Object, ByVal e As EventArgs) Handles RadListView1.ValidationError - MessageBox.Show("Invalid Value") -End Sub - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/listview/export-data/spread-export.md b/controls/listview/export-data/spread-export.md index 804473a3f..671412d19 100644 --- a/controls/listview/export-data/spread-export.md +++ b/controls/listview/export-data/spread-export.md @@ -48,61 +48,19 @@ To use the spread export functionality, an instance of the __ListViewSpreadExpor You should pass an instance of a [SpreadExportRenderer]({%slug winforms/telerik-presentation-framework/export-renderers/spreadexportrenderer%}) to the export method as well. -{{source=..\SamplesCS\ListView\SpreadExportCode.cs region=Export}} -{{source=..\SamplesVB\ListView\SpreadExportCode.vb region=Export}} + + -````C# -ListViewSpreadExport exporter = new ListViewSpreadExport(this.radListView1); -SpreadExportRenderer renderer = new SpreadExportRenderer(); -exporter.RunExport(@"C:\ExportedFile.xlsx", renderer); -```` -````VB.NET -Dim exporter As New ListViewSpreadExport(Me.radListView1) -Dim renderer As New SpreadExportRenderer() -exporter.RunExport("C:\ExportedFile.xlsx", renderer) - -```` - -{{endregion}} The __RunExport__ method has several overloads allowing the user to export using a stream as well: #### Running export synchronously using a stream -{{source=..\SamplesCS\ListView\SpreadExportCode.cs region=StreamRunExport}} -{{source=..\SamplesVB\ListView\SpreadExportCode.vb region=StreamRunExport}} - -````C# - -string exportFile = @"..\..\exportedData.xlsx"; -using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) -{ - Telerik.WinControls.Export.ListViewSpreadExport spreadExporter = new Telerik.WinControls.Export.ListViewSpreadExport(radListView1); - Telerik.WinControls.Export.SpreadExportRenderer spreadRenderer = new Telerik.WinControls.Export.SpreadExportRenderer(); - spreadExporter.RunExport(ms, spreadRenderer); - - using (System.IO.FileStream fileStream = new System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write)) - { - ms.WriteTo(fileStream); - } -} - -```` -````VB.NET -Dim exportFile As String = "..\..\exportedData.xlsx" -Using ms As New System.IO.MemoryStream() - Dim spreadExporter As New Telerik.WinControls.Export.ListViewSpreadExport(Me.radListView1) - Dim spreadRenderer As New Telerik.WinControls.Export.SpreadExportRenderer() - spreadExporter.RunExport(ms, spreadRenderer) - Using fileStream As New System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write) - ms.WriteTo(fileStream) - End Using -End Using - -```` - -{{endregion}} + + + + ## Properties @@ -140,26 +98,10 @@ End Using * __RowIndex__: The index of the currently exported row. Here is an example of formatting the exported list view: -{{source=..\SamplesCS\ListView\SpreadExportCode.cs region=Formatting}} -{{source=..\SamplesVB\ListView\SpreadExportCode.vb region=Formatting}} + + -````C# -void exporter_CellFormatting(object sender, ListViewSpreadExportCellFormattingEventArgs e) -{ - e.ExportCell.BackColor = ColorTranslator.FromHtml("#F4FFEC"); - e.ExportCell.Font = new Font("Consolas", 10, FontStyle.Underline); -} -```` -````VB.NET -Private Sub exporter_CellFormatting(ByVal sender As Object, ByVal e As ListViewSpreadExportCellFormattingEventArgs) - e.ExportCell.BackColor = ColorTranslator.FromHtml("#F4FFEC") - e.ExportCell.Font = New Font("Consolas", 10, FontStyle.Underline) -End Sub - -```` - -{{endregion}} >caption Figure 2: Export using formatting @@ -182,115 +124,26 @@ The following example will demonstrate how the async spread export feature can b 1\. The following code shows how you can subscribe to the notification events and start the async export operation. -{{source=..\SamplesCS\ListView\SpreadExportCode.cs region=AsyncExport}} -{{source=..\SamplesVB\ListView\SpreadExportCode.vb region=AsyncExport}} - -````C# -private void btnExportAsync_Click(object sender, EventArgs e) -{ - ListViewSpreadExport spreadExporter = new ListViewSpreadExport(this.radListView1); - spreadExporter.AsyncExportProgressChanged += spreadExporter_AsyncExportProgressChanged; - spreadExporter.AsyncExportCompleted += spreadExporter_AsyncExportCompleted; - SpreadExportRenderer exportRenderer = new SpreadExportRenderer(); - spreadExporter.RunExportAsync(@"..\..\exportedFile.xlsx", exportRenderer); -} - -```` -````VB.NET -Private Sub btnExportAsync_Click(ByVal sender As Object, ByVal e As EventArgs) - Dim spreadExporter As New ListViewSpreadExport(Me.radListView1) - AddHandler spreadExporter.AsyncExportProgressChanged, AddressOf spreadExporter_AsyncExportProgressChanged - AddHandler spreadExporter.AsyncExportCompleted, AddressOf spreadExporter_AsyncExportCompleted - Dim exportRenderer As New SpreadExportRenderer() - spreadExporter.RunExportAsync("..\..\exportedFile.xlsx", exportRenderer) -End Sub - -```` - -{{endregion}} + + + + 2\. Handle the notification events and report progress. -{{source=..\SamplesCS\ListView\SpreadExportCode.cs region=ReportProgress}} -{{source=..\SamplesVB\ListView\SpreadExportCode.vb region=ReportProgress}} - -````C# -private void spreadExporter_AsyncExportProgressChanged(object sender, ProgressChangedEventArgs e) -{ - this.radProgressBar1.Value1 = e.ProgressPercentage; -} -private void spreadExporter_AsyncExportCompleted(object sender, AsyncCompletedEventArgs e) -{ - RadMessageBox.Show("Async Spread Export Completed!"); - this.radProgressBar1.Value1 = 0; -} - -```` -````VB.NET -Private Sub spreadExporter_AsyncExportProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) - Me.radProgressBar1.Value1 = e.ProgressPercentage -End Sub -Private Sub spreadExporter_AsyncExportCompleted(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs) - RadMessageBox.Show("Async Spread Export Completed!") - Me.radProgressBar1.Value1 = 0 -End Sub - -```` - -{{endregion}} + + + + The __RunExportAsync__ method has several overloads allowing the user to export using a stream as well: #### Running export asynchronously using a stream -{{source=..\SamplesCS\ListView\SpreadExportCode.cs region=StreamRunExportAsync}} -{{source=..\SamplesVB\ListView\SpreadExportCode.vb region=StreamRunExportAsync}} + + + -````C# - -private void buttonRunExportAsync_Click(object sender, EventArgs e) -{ - System.IO.MemoryStream ms = new System.IO.MemoryStream(); - Telerik.WinControls.Export.ListViewSpreadExport spreadExporter = new Telerik.WinControls.Export.ListViewSpreadExport(this.radListView1); - Telerik.WinControls.Export.SpreadExportRenderer spreadRenderer = new Telerik.WinControls.Export.SpreadExportRenderer(); - spreadExporter.AsyncExportCompleted += exporter_AsyncExportCompleted; - spreadExporter.RunExportAsync(ms, spreadRenderer); -} - -private void exporter_AsyncExportCompleted(object sender, AsyncCompletedEventArgs e) -{ - RunWorkerCompletedEventArgs args = e as RunWorkerCompletedEventArgs; - string exportFile = @"..\..\exportedAsyncData.xlsx"; - using (System.IO.FileStream fileStream = new System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write)) - { - MemoryStream ms = args.Result as MemoryStream; - ms.WriteTo(fileStream); - ms.Close(); - } -} - -```` -````VB.NET -Private Sub buttonRunExportAsync_Click(sender As Object, e As EventArgs) - Dim ms As New System.IO.MemoryStream() - Dim spreadExporter As New Telerik.WinControls.Export.ListViewSpreadExport(Me.radListView1) - Dim spreadRenderer As New Telerik.WinControls.Export.SpreadExportRenderer() - AddHandler spreadExporter.AsyncExportCompleted, AddressOf exporter_AsyncExportCompleted - spreadExporter.RunExportAsync(ms, spreadRenderer) -End Sub -Private Sub exporter_AsyncExportCompleted(sender As Object, e As AsyncCompletedEventArgs) - Dim args As RunWorkerCompletedEventArgs = TryCast(e, RunWorkerCompletedEventArgs) - Dim exportFile As String = "..\..\exportedAsyncData.xlsx" - Using fileStream As New System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write) - Dim ms As MemoryStream = TryCast(args.Result, MemoryStream) - ms.WriteTo(fileStream) - ms.Close() - End Using -End Sub - -```` - -{{endregion}} ## Async Export Methods and Events diff --git a/controls/listview/features/filtering.md b/controls/listview/features/filtering.md index 3c7a54965..5bf5ad50e 100644 --- a/controls/listview/features/filtering.md +++ b/controls/listview/features/filtering.md @@ -15,39 +15,19 @@ __RadListView__ allows filtering operations in all views. To enable filtering op #### Enable Filtering -{{source=..\SamplesCS\ListView\Features\ListViewFiltering.cs region=EnableFiltering}} -{{source=..\SamplesVB\ListView\Features\ListViewFiltering.vb region=EnableFiltering}} + + -````C# -radListView1.EnableFiltering = true; -```` -````VB.NET -RadListView1.EnableFiltering = True - -```` - -{{endregion}} Once the filtering is enabled, we have to create a new __FilterDescriptor__ and assign its __PropertyName__, __FilterOperator__ and __SearchCriteria__. First, let’s filter the items by their value and look for items starting with *“Local”*. #### Filter by Value -{{source=..\SamplesCS\ListView\Features\ListViewFiltering.cs region=FilterDescriptor}} -{{source=..\SamplesVB\ListView\Features\ListViewFiltering.vb region=FilterDescriptor}} - -````C# -FilterDescriptor valueFilter = new FilterDescriptor("Value", FilterOperator.StartsWith, "Local"); -radListView1.FilterDescriptors.Add(valueFilter); + + -```` -````VB.NET -Dim valueFilter As New FilterDescriptor("Value", FilterOperator.StartsWith, "Local") -RadListView1.FilterDescriptors.Add(valueFilter) -```` - -{{endregion}} |Before Filtering|After Filtering| |----|----| @@ -57,21 +37,10 @@ When a column name is specified as __PropertyName__ of the filter descriptor, ** #### Filter by type -{{source=..\SamplesCS\ListView\Features\ListViewFiltering.cs region=FilterDescriptor1}} -{{source=..\SamplesVB\ListView\Features\ListViewFiltering.vb region=FilterDescriptor1}} - -````C# -FilterDescriptor typeFilter = new FilterDescriptor("Type", FilterOperator.Contains, "Disk"); -radListView1.FilterDescriptors.Add(typeFilter); + + -```` -````VB.NET -Dim typeFilter As New FilterDescriptor("Type", FilterOperator.Contains, "Disk") -RadListView1.FilterDescriptors.Add(typeFilter) -```` - -{{endregion}} |Before|After| |----|----| @@ -83,47 +52,17 @@ RadListView1.FilterDescriptors.Add(typeFilter) #### Custom FilterPredicate -{{source=..\SamplesCS\ListView\Features\ListViewFiltering.cs region=CustomFilterPredicate}} -{{source=..\SamplesVB\ListView\Features\ListViewFiltering.vb region=CustomFilterPredicate}} - -````C# -private bool MyFilter(ListViewDataItem item) -{ - if (item.Value.ToString().Contains("C")) - { - return true; - } - return false; -} - -```` -````VB.NET -Private Function MyFilter(item As ListViewDataItem) As Boolean - If item.Value.ToString().Contains("C") Then - Return True - End If - Return False -End Function + + -```` -{{endregion}} #### Apply the custom FilterPredicate -{{source=..\SamplesCS\ListView\Features\ListViewFiltering.cs region=ApplyCustomFilterPredicate}} -{{source=..\SamplesVB\ListView\Features\ListViewFiltering.vb region=ApplyCustomFilterPredicate}} - -````C# -this.radListView1.ListViewElement.DataView.Filter = MyFilter; - -```` -````VB.NET -Me.RadListView1.ListViewElement.DataView.Filter = AddressOf MyFilter + + -```` -{{endregion}} >caption Figure 3: Custom Filtering diff --git a/controls/listview/features/grouping.md b/controls/listview/features/grouping.md index 2efc0407b..9d0754b78 100644 --- a/controls/listview/features/grouping.md +++ b/controls/listview/features/grouping.md @@ -19,25 +19,10 @@ The basic grouping is achievable by enabling the __EnableGrouping__ and __ShowGr #### Group by value -{{source=..\SamplesCS\ListView\Features\ListViewGrouping.cs region=groupByValue}} -{{source=..\SamplesVB\ListView\Features\ListViewGrouping.vb region=groupByValue}} + + -````C# -radListView1.EnableGrouping = true; -radListView1.ShowGroups = true; -GroupDescriptor groupByValue = new GroupDescriptor(new SortDescriptor[] { new SortDescriptor("Value", ListSortDirection.Descending) }); -radListView1.GroupDescriptors.Add(groupByValue); -```` -````VB.NET -RadListView1.EnableGrouping = True -RadListView1.ShowGroups = True -Dim groupByValue As New GroupDescriptor(New SortDescriptor() {New SortDescriptor("Value", ListSortDirection.Descending)}) -RadListView1.GroupDescriptors.Add(groupByValue) - -```` - -{{endregion}} |Before Grouping|After Grouping| |----|----| @@ -47,28 +32,10 @@ And here is how you can group by a certain column when __DetailsView__ is used: #### Group by column "Type" -{{source=..\SamplesCS\ListView\Features\ListViewGrouping.cs region=groupByColumn}} -{{source=..\SamplesVB\ListView\Features\ListViewGrouping.vb region=groupByColumn}} - -````C# -radListView1.EnableGrouping = true; -radListView1.ShowGroups = true; -GroupDescriptor groupByType = new GroupDescriptor(new SortDescriptor[] -{ - new SortDescriptor("Type", ListSortDirection.Descending), -}); -radListView1.GroupDescriptors.Add(groupByType); - -```` -````VB.NET -RadListView1.EnableGrouping = True -RadListView1.ShowGroups = True -Dim groupByType As New GroupDescriptor(New SortDescriptor() {New SortDescriptor("Type", ListSortDirection.Descending)}) -RadListView1.GroupDescriptors.Add(groupByType) + + -```` -{{endregion}} |Before Grouping|After Grouping| |----|----| @@ -80,47 +47,10 @@ To take advantage of the custom grouping feature of **RadListView**, just enable #### Custom Grouping -{{source=..\SamplesCS\ListView\Features\ListViewGrouping.cs region=customGrouping}} -{{source=..\SamplesVB\ListView\Features\ListViewGrouping.vb region=customGrouping}} - -````C# -radListView1.EnableCustomGrouping = true; -radListView1.ShowGroups = true; -ListViewDataItemGroup docGroup = new ListViewDataItemGroup("Documents"); -ListViewDataItemGroup diskGroup = new ListViewDataItemGroup("Disks"); -radListView1.Groups.Add(docGroup); -radListView1.Groups.Add(diskGroup); -foreach (ListViewDataItem item in radListView1.Items) -{ - if (item.Value.ToString() == "Shared Documents" || item.Value.ToString() == "Administrator's Documents") - { - item.Group = docGroup; - } - else - { - item.Group = diskGroup; - } -} - -```` -````VB.NET -RadListView1.EnableCustomGrouping = True -RadListView1.ShowGroups = True -Dim docGroup As New ListViewDataItemGroup("Documents") -Dim diskGroup As New ListViewDataItemGroup("Disks") -RadListView1.Groups.Add(docGroup) -RadListView1.Groups.Add(diskGroup) -For Each item As ListViewDataItem In RadListView1.Items - If item.Value = "Shared Documents" OrElse item.Value = "Administrator's Documents" Then - item.Group = docGroup - Else - item.Group = diskGroup - End If -Next - -```` - -{{endregion}} + + + + >important Items in a certain group are sorted in the order of setting the **Group** property of each **ListViewDataItem**. @@ -134,23 +64,11 @@ When grouping is enabled you have the option to quickly expand or collapse all g #### Expand and Collapse All Groups -{{source=..\SamplesCS\ListView\Features\ListViewGrouping.cs region=ExpandCollapseAll}} -{{source=..\SamplesVB\ListView\Features\ListViewGrouping.vb region=ExpandCollapseAll}} - -````C# -this.radListView1.ExpandAll(); -this.radListView1.CollapseAll(); - -```` -````VB.NET -Me.RadListView1.ExpandAll() -Me.RadListView1.CollapseAll() + + -```` -{{endregion}} - # See Also * [Filtering]({%slug winforms/listview/features/filtering%}) diff --git a/controls/listview/features/item-sizing.md b/controls/listview/features/item-sizing.md index 92e326cbc..45ca652aa 100644 --- a/controls/listview/features/item-sizing.md +++ b/controls/listview/features/item-sizing.md @@ -16,25 +16,10 @@ In *DetailsView* the **ItemSize** property sets only the **Height** of the item, #### Item's height in DetailsView -{{source=..\SamplesCS\ListView\Features\ListViewWorkingWithItems.cs region=itemSizing}} -{{source=..\SamplesVB\ListView\Features\ListViewWorkingWithItems.vb region=itemSizing}} + + -````C# -radListView1.ItemSize = new Size(0, 50); -radListView1.Columns[0].Width = 50; -radListView1.Columns[1].Width = 75; -radListView1.Columns[2].Width = 100; -```` -````VB.NET -RadListView1.ItemSize = New Drawing.Size(0, 50) -RadListView1.Columns(0).Width = 50 -RadListView1.Columns(1).Width = 75 -RadListView1.Columns(2).Width = 100 - -```` - -{{endregion}} >caption Figure 1: Item sizing in DetailsView @@ -44,21 +29,10 @@ In ViewType.*ListView*, when the __FullRowSelect__ property is set to *false*, t #### Item sizing in ListView -{{source=..\SamplesCS\ListView\Features\ListViewWorkingWithItems.cs region=fullRowSelect}} -{{source=..\SamplesVB\ListView\Features\ListViewWorkingWithItems.vb region=fullRowSelect}} - -````C# -radListView1.FullRowSelect = false; -radListView1.ItemSize = new Size(180, 35); + + -```` -````VB.NET -RadListView1.FullRowSelect = False -RadListView1.ItemSize = New Drawing.Size(180, 35) -```` - -{{endregion}} >caption Figure 2: Item sizing in ListView @@ -68,23 +42,10 @@ There are two more properties that provide additional customization options for #### Item sizing when arbitrary height/width is disabled -{{source=..\SamplesCS\ListView\Features\ListViewWorkingWithItems.cs region=arbitrarySizes}} -{{source=..\SamplesVB\ListView\Features\ListViewWorkingWithItems.vb region=arbitrarySizes}} - -````C# -radListView1.ItemSize = new Size(160, 80); -radListView1.AllowArbitraryItemHeight = false; -radListView1.AllowArbitraryItemWidth = false; - -```` -````VB.NET -RadListView1.ItemSize = New Drawing.Size(160, 80) -RadListView1.AllowArbitraryItemHeight = False -RadListView1.AllowArbitraryItemWidth = False + + -```` -{{endregion}} >caption Figure 3: Item sizing when arbitrary height/width is disabled diff --git a/controls/listview/features/selection.md b/controls/listview/features/selection.md index c79904c05..673dcdfac 100644 --- a/controls/listview/features/selection.md +++ b/controls/listview/features/selection.md @@ -16,29 +16,10 @@ Multiple items can be selected in code as well. This can be achieved by using th #### Programmatically Select Items -{{source=..\SamplesCS\ListView\Features\ListViewWorkingWithItems.cs region=itemSelect}} -{{source=..\SamplesVB\ListView\Features\ListViewWorkingWithItems.vb region=itemSelect}} - -````C# -radListView1.MultiSelect = true; -ListViewDataItem[] itemsToSlelct = new ListViewDataItem[3]; -itemsToSlelct[0] = radListView1.Items[1]; -itemsToSlelct[1] = radListView1.Items[3]; -itemsToSlelct[2] = radListView1.Items[4]; -radListView1.Select(itemsToSlelct); - -```` -````VB.NET -RadListView1.MultiSelect = True -Dim itemsToSlelct(2) As ListViewDataItem -itemsToSlelct(0) = RadListView1.Items(1) -itemsToSlelct(1) = RadListView1.Items(3) -itemsToSlelct(2) = RadListView1.Items(4) -RadListView1.Select(itemsToSlelct) - -```` - -{{endregion}} + + + + The **FullRowSelect** property controls whether the full row should be selected or not. diff --git a/controls/listview/features/sorting.md b/controls/listview/features/sorting.md index 1193c44ef..9bc033d5e 100644 --- a/controls/listview/features/sorting.md +++ b/controls/listview/features/sorting.md @@ -17,43 +17,19 @@ Enabling sorting on header click is done by setting both __EnableSorting__ and _ #### Enable column sorting -{{source=..\SamplesCS\ListView\Features\ListViewSorting.cs region=EnableColumnSort}} -{{source=..\SamplesVB\ListView\Features\ListViewSorting.vb region=EnableColumnSort}} + + -````C# -radListView1.EnableSorting = true; -radListView1.EnableColumnSort = true; -```` -````VB.NET -RadListView1.EnableColumnSort = True -RadListView1.EnableSorting = True - -```` - -{{endregion}} The following code snippet demonstrates how to add a __SortDescriptor__ to **RadListView**: #### Adding SortDescriptors -{{source=..\SamplesCS\ListView\Features\ListViewSorting.cs region=SortDescriptor}} -{{source=..\SamplesVB\ListView\Features\ListViewSorting.vb region=SortDescriptor}} - -````C# -radListView1.EnableSorting = true; -SortDescriptor sort = new SortDescriptor("Free Space", ListSortDirection.Ascending); -radListView1.SortDescriptors.Add(sort); - -```` -````VB.NET -RadListView1.EnableSorting = True -Dim sort = New SortDescriptor("Free Space", ListSortDirection.Ascending) -RadListView1.SortDescriptors.Add(sort) + + -```` -{{endregion}} Here is the sorted data: @@ -67,97 +43,10 @@ Here is the sorted data: #### Custom sorting -{{source=..\SamplesCS\ListView\Features\ListViewSorting.cs region=CustomSorting}} -{{source=..\SamplesVB\ListView\Features\ListViewSorting.vb region=CustomSorting}} + + + -````C# - -private void Form_Load(object sender, EventArgs e) -{ - this.radListView1.ViewType = ListViewType.DetailsView; - this.radListView1.Columns.Add("Number"); - this.radListView1.Columns.Add("Freight"); - Random rand = new Random(); - for (int i = 0; i < 10; i++) - { - ListViewDataItem item = new ListViewDataItem(); - this.radListView1.Items.Add(item); - item[0] = i; - item[1] = (decimal)(rand.NextDouble() * Int32.MaxValue); - } - - this.radListView1.SortDescriptors.Add(new Telerik.WinControls.Data.SortDescriptor("Number", ListSortDirection.Ascending)); - this.radListView1.ListViewElement.DataView.Comparer = new ListViewCustomComparer(this.radListView1.ListViewElement); - this.radListView1.EnableSorting = true; -} - -public class ListViewCustomComparer : IComparer -{ - RadListViewElement listViewElement; - - public ListViewCustomComparer(RadListViewElement listViewElement) - { - this.listViewElement = listViewElement; - } - - public int Compare(ListViewDataItem x, ListViewDataItem y) - { - decimal row1Freight = (decimal)x["Freight"]; - decimal row2Freight = (decimal)y["Freight"]; - if (row1Freight > row2Freight) - { - return 1; - } - else if (row1Freight < row2Freight) - { - return -1; - } - else - { - return 0; - } - } -} - -```` -````VB.NET -Private Sub Form_Load(sender As Object, e As EventArgs) - Me.RadListView1.ViewType = ListViewType.DetailsView - Me.RadListView1.Columns.Add("Number") - Me.RadListView1.Columns.Add("Freight") - Dim rand As New Random() - For i As Integer = 0 To 9 - Dim item As New ListViewDataItem() - Me.RadListView1.Items.Add(item) - item(0) = i - item(1) = CDec(rand.NextDouble() * Int32.MaxValue) - Next - Me.RadListView1.SortDescriptors.Add(New Telerik.WinControls.Data.SortDescriptor("Number", ListSortDirection.Ascending)) - Me.RadListView1.ListViewElement.DataView.Comparer = New ListViewCustomComparer(Me.RadListView1.ListViewElement) - Me.RadListView1.EnableSorting = True -End Sub -Public Class ListViewCustomComparer -Implements IComparer(Of ListViewDataItem) - Private listViewElement As RadListViewElement - Public Sub New(listViewElement As RadListViewElement) - Me.listViewElement = listViewElement - End Sub - Public Function [Compare](x As ListViewDataItem, y As ListViewDataItem) As Integer Implements IComparer(Of ListViewDataItem).[Compare] - Dim row1Freight As Decimal = CDec(x("Freight")) - Dim row2Freight As Decimal = CDec(y("Freight")) - If row1Freight > row2Freight Then - Return 1 - ElseIf row1Freight < row2Freight Then - Return -1 - Else - Return 0 - End If - End Function -End Class - -```` - -{{endregion}} |Basic Sorting|Custom Sorting| |----|----| diff --git a/controls/listview/getting-started.md b/controls/listview/getting-started.md index 9cf03e051..f83ac3615 100644 --- a/controls/listview/getting-started.md +++ b/controls/listview/getting-started.md @@ -70,185 +70,46 @@ At this point the form should like something similar to this: #### Initial settings -{{source=..\SamplesCS\ListView\ListViewGettingStarted.cs region=initialSettings}} -{{source=..\SamplesVB\ListView\ListViewGettingStarted.vb region=initialSettings}} - -````C# -this.radListView1.ItemDataBound += new Telerik.WinControls.UI.ListViewItemEventHandler(radListView1_ItemDataBound); -this.radListView1.VisualItemFormatting += new Telerik.WinControls.UI.ListViewVisualItemEventHandler(radListView1_VisualItemFormatting); -this.radListView1.CellFormatting += new Telerik.WinControls.UI.ListViewCellFormattingEventHandler(radListView1_CellFormatting); -this.radListView1.ColumnCreating += new ListViewColumnCreatingEventHandler(radListView1_ColumnCreating); -this.radListView1.ViewTypeChanged += new EventHandler(radListView1_ViewTypeChanged); -this.radListView1.AllowEdit = false; -this.radListView1.AllowRemove = false; -this.radListView1.DataSource = this.songsDataTableBindingSource; -this.radListView1.DisplayMember = "SongName"; -this.radListView1.ValueMember = "SongID"; -this.radListView1.ViewType = ListViewType.IconsView; - -```` -````VB.NET -AddHandler Me.RadListView1.ItemDataBound, AddressOf radListView1_ItemDataBound -AddHandler Me.RadListView1.VisualItemFormatting, AddressOf radListView1_VisualItemFormatting -AddHandler Me.RadListView1.ViewTypeChanged, AddressOf radListView1_ViewTypeChanged -AddHandler Me.RadListView1.CellFormatting, AddressOf radListView1_CellFormatting -AddHandler Me.RadListView1.ColumnCreating, AddressOf radListView1_ColumnCreating -Me.RadListView1.AllowEdit = False -Me.RadListView1.AllowRemove = False -Me.RadListView1.DataSource = Me.SongsDataTableBindingSource -Me.RadListView1.DisplayMember = "SongName" -Me.RadListView1.ValueMember = "SongID" - -```` - -{{endregion}} + + -3\. Now, lets handle those events. In the event handler for the __ItemDataBound__ event, we will take the corresponding item image from the data source and we will assign it to the **ListViewDataItem**. -#### Set the item image to the data item -{{source=..\SamplesCS\ListView\ListViewGettingStarted.cs region=ItemDataBound}} -{{source=..\SamplesVB\ListView\ListViewGettingStarted.vb region=ItemDataBound}} +3\. Now, lets handle those events. In the event handler for the __ItemDataBound__ event, we will take the corresponding item image from the data source and we will assign it to the **ListViewDataItem**. -````C# -void radListView1_ItemDataBound(object sender, Telerik.WinControls.UI.ListViewItemEventArgs e) -{ - DataRowView row = e.Item.DataBoundItem as DataRowView; - MusicCollectionDataSet.SongsDataTableRow songRow = row.Row as MusicCollectionDataSet.SongsDataTableRow; - e.Item.Image = Image.FromStream(new MemoryStream(songRow.Image), false, false); -} +#### Set the item image to the data item -```` -````VB.NET -Private Sub radListView1_ItemDataBound(sender As Object, e As Telerik.WinControls.UI.ListViewItemEventArgs) - Dim row As DataRowView = TryCast(e.Item.DataBoundItem, DataRowView) - Dim songRow As MusicCollectionDataSet.SongsDataTableRow = TryCast(row.Row, MusicCollectionDataSet.SongsDataTableRow) - e.Item.Image = Image.FromStream(New MemoryStream(songRow.Image), False, False) -End Sub + + -```` -{{endregion}} 4\. Next, lets handle the __VisualItemFormatting__ event, where we will set the visual item image. Additionally, for *IconsView* we will set the visual item text to a html-like combination of the *AlbumName*, *ArtistName* and *SongName*. #### Customize visual item -{{source=..\SamplesCS\ListView\ListViewGettingStarted.cs region=VisualItemFormatting}} -{{source=..\SamplesVB\ListView\ListViewGettingStarted.vb region=VisualItemFormatting}} - -````C# -void radListView1_VisualItemFormatting(object sender, Telerik.WinControls.UI.ListViewVisualItemEventArgs e) -{ - if (e.VisualItem.Data.Image != null) - { - e.VisualItem.Image = e.VisualItem.Data.Image.GetThumbnailImage(32, 32, null, IntPtr.Zero); - e.VisualItem.Layout.RightPart.Margin = new Padding(2, 0, 0, 0); - } - if (this.radListView1.ViewType == Telerik.WinControls.UI.ListViewType.IconsView && e.VisualItem.Data.DataBoundItem != null) - { - string albumName = ((MusicCollectionDataSet.SongsDataTableRow)(((System.Data.DataRowView)(e.VisualItem.Data.DataBoundItem)).Row)).AlbumName; - string artisName = ((MusicCollectionDataSet.SongsDataTableRow)(((System.Data.DataRowView)(e.VisualItem.Data.DataBoundItem)).Row)).ArtistName; - string songName = ((MusicCollectionDataSet.SongsDataTableRow)(((System.Data.DataRowView)(e.VisualItem.Data.DataBoundItem)).Row)).SongName; - e.VisualItem.Text = " " + songName + "
" + artisName + "
" + albumName + "
"; - } -} - -```` -````VB.NET -Private Sub radListView1_VisualItemFormatting(sender As Object, e As Telerik.WinControls.UI.ListViewVisualItemEventArgs) - If e.VisualItem.Data.Image IsNot Nothing Then - e.VisualItem.Image = e.VisualItem.Data.Image.GetThumbnailImage(32, 32, Nothing, IntPtr.Zero) - e.VisualItem.Layout.RightPart.Margin = New Windows.Forms.Padding(2, 0, 0, 0) - End If - If Me.RadListView1.ViewType = Telerik.WinControls.UI.ListViewType.IconsView AndAlso e.VisualItem.Data.DataBoundItem IsNot Nothing Then - Dim albumName As String = DirectCast(DirectCast(e.VisualItem.Data.DataBoundItem, System.Data.DataRowView).Row, MusicCollectionDataSet.SongsDataTableRow).AlbumName - Dim artisName As String = DirectCast(DirectCast(e.VisualItem.Data.DataBoundItem, System.Data.DataRowView).Row, MusicCollectionDataSet.SongsDataTableRow).ArtistName - Dim songName As String = DirectCast(DirectCast(e.VisualItem.Data.DataBoundItem, System.Data.DataRowView).Row, MusicCollectionDataSet.SongsDataTableRow).SongName - e.VisualItem.Text = " " + songName + "
" + artisName + "
" + albumName + "
" - End If -End Sub - -```` - -{{endregion}} + + -The __CellFormatting__ event is handled in order to customize the appearance of the cells, when **RadListView** is in __DetailsView__. Here we will set the cell image. -#### Set the cell image -{{source=..\SamplesCS\ListView\ListViewGettingStarted.cs region=CellFormatting}} -{{source=..\SamplesVB\ListView\ListViewGettingStarted.vb region=CellFormatting}} +The __CellFormatting__ event is handled in order to customize the appearance of the cells, when **RadListView** is in __DetailsView__. Here we will set the cell image. -````C# -void radListView1_CellFormatting(object sender, ListViewCellFormattingEventArgs e) -{ - if (e.CellElement.Image != null) - { - e.CellElement.Image = e.CellElement.Image.GetThumbnailImage(32, 32, null, IntPtr.Zero); - } -} +#### Set the cell image -```` -````VB.NET -Private Sub radListView1_CellFormatting(sender As Object, e As ListViewCellFormattingEventArgs) - If e.CellElement.Image IsNot Nothing Then - e.CellElement.Image = e.CellElement.Image.GetThumbnailImage(32, 32, Nothing, IntPtr.Zero) - End If -End Sub + + -```` -{{endregion}} The __ColumnCreating__ event is fired when a column is being created. This is convenient event to hide unwanted columns. Additionally, we will use this event to set some more user friendly column headers. #### Customize columns -{{source=..\SamplesCS\ListView\ListViewGettingStarted.cs region=ColumnCreating}} -{{source=..\SamplesVB\ListView\ListViewGettingStarted.vb region=ColumnCreating}} - -````C# -void radListView1_ColumnCreating(object sender, ListViewColumnCreatingEventArgs e) -{ - if (e.Column.FieldName == "SongID" || e.Column.FieldName == "Image") - { - e.Column.Visible = false; - } - if (e.Column.FieldName == "SongName") - { - e.Column.HeaderText = "Song Title"; - } - if (e.Column.FieldName == "ArtistName") - { - e.Column.HeaderText = "Artist"; - } - if (e.Column.FieldName == "AlbumName") - { - e.Column.HeaderText = "Album"; - } -} - -```` -````VB.NET -Private Sub radListView1_ColumnCreating(sender As Object, e As ListViewColumnCreatingEventArgs) - If e.Column.FieldName = "SongID" OrElse e.Column.FieldName = "Image" Then - e.Column.Visible = False - End If - If e.Column.FieldName = "SongName" Then - e.Column.HeaderText = "Song Title" - End If - If e.Column.FieldName = "ArtistName" Then - e.Column.HeaderText = "Artist" - End If - If e.Column.FieldName = "AlbumName" Then - e.Column.HeaderText = "Album" - End If -End Sub - -```` - -{{endregion}} + + + + 5\. The last event of **RadListView**, which we are going to handle is the **ViewTypeChanged** event - fired when the **ViewType** of the control is changed. This event is convenient to set view specific settings. To handle the event, we will create three helper methods: @@ -262,312 +123,46 @@ In the **ViewTypeChanged** event handler, we will simply check which is the new #### Handling view type changes -{{source=..\SamplesCS\ListView\ListViewGettingStarted.cs region=ViewTypeChanged}} -{{source=..\SamplesVB\ListView\ListViewGettingStarted.vb region=ViewTypeChanged}} - -````C# -private void SetupDetailsView() -{ - this.radListView1.AllowArbitraryItemHeight = true; -} -private void SetupIconsView() -{ - this.radListView1.ItemSize = new Size(200, 64); - this.radListView1.ItemSpacing = 5; - this.radListView1.AllowArbitraryItemHeight = true; -} -private void SetupSimpleListView() -{ - this.radListView1.AllowArbitraryItemHeight = true; -} -void radListView1_ViewTypeChanged(object sender, EventArgs e) -{ - switch (radListView1.ViewType) - { - case ListViewType.ListView: - SetupSimpleListView(); - break; - case ListViewType.IconsView: - SetupIconsView(); - break; - case ListViewType.DetailsView: - SetupDetailsView(); - break; - } -} - -```` -````VB.NET -Private Sub SetupDetailsView() - Me.RadListView1.AllowArbitraryItemHeight = True -End Sub -Private Sub SetupIconsView() - Me.RadListView1.ItemSize = New Size(200, 64) - Me.RadListView1.ItemSpacing = 5 - Me.RadListView1.AllowArbitraryItemHeight = True -End Sub -Private Sub SetupSimpleListView() - Me.RadListView1.AllowArbitraryItemHeight = True -End Sub -Private Sub radListView1_ViewTypeChanged(sender As Object, e As EventArgs) - Select Case RadListView1.ViewType - Case ListViewType.ListView - SetupSimpleListView() - Exit Select - Case ListViewType.IconsView - SetupIconsView() - Exit Select - Case ListViewType.DetailsView - SetupDetailsView() - Exit Select - End Select -End Sub - -```` - -{{endregion}} - + + + + + 6\. Now, we only need to fill up the __RadCommandBar__ elements functionality. First, we are going to handle the view changing buttons. For this purpose, subscribe for the __ToggleStateChanged__ and __ToggleStateChanging__ events of all the __CommandBarToggleButtons__ that we have added earlier. In the **ToggleStateChanged** event handler, check which is the clicked button, and set the rest of the buttons to *Off*. Additionally, set the RadListView.**ViewType** according to the pressed button. #### Handle the toggle buttons -{{source=..\SamplesCS\ListView\ListViewGettingStarted.cs region=toggleButtons}} -{{source=..\SamplesVB\ListView\ListViewGettingStarted.vb region=toggleButtons}} - -````C# -private bool updatingToggleState = false; -private void ViewToggleButton_ToggleStateChanged(object sender, StateChangedEventArgs args) -{ - if (updatingToggleState) - { - return; - } - this.updatingToggleState = true; - if (this.commandBarToggleButtonDetails != sender) - { - this.commandBarToggleButtonDetails.ToggleState = ToggleState.Off; - } - if (this.commandBarToggleButtonList != sender) - { - this.commandBarToggleButtonList.ToggleState = ToggleState.Off; - } - if (this.commandBarToggleButtonTiles != sender) - { - this.commandBarToggleButtonTiles.ToggleState = ToggleState.Off; - } - this.updatingToggleState = false; - if (this.commandBarToggleButtonDetails.ToggleState == ToggleState.On) - { - this.radListView1.ViewType = ListViewType.DetailsView; - } - if (this.commandBarToggleButtonList.ToggleState == ToggleState.On) - { - this.radListView1.ViewType = ListViewType.ListView; - } - if (this.commandBarToggleButtonTiles.ToggleState == ToggleState.On) - { - this.radListView1.ViewType = ListViewType.IconsView; - } - } -private void ViewToggleButton_ToggleStateChanging(object sender, StateChangingEventArgs args) -{ - if (!updatingToggleState && args.OldValue == ToggleState.On) - { - args.Cancel = true; - } -} - -```` -````VB.NET -Private updatingToggleState As Boolean = False -Private Sub ViewToggleButton_ToggleStateChanged(sender As Object, args As StateChangedEventArgs) Handles commandBarToggleButtonTiles.ToggleStateChanged, commandBarToggleButtonList.ToggleStateChanged, commandBarToggleButtonDetails.ToggleStateChanged - If updatingToggleState Then - Return - End If - Me.updatingToggleState = True - If Me.commandBarToggleButtonDetails IsNot sender Then - Me.commandBarToggleButtonDetails.ToggleState = ToggleState.Off - End If - If Me.commandBarToggleButtonList IsNot sender Then - Me.commandBarToggleButtonList.ToggleState = ToggleState.Off - End If - If Me.commandBarToggleButtonTiles IsNot sender Then - Me.commandBarToggleButtonTiles.ToggleState = ToggleState.Off - End If - Me.updatingToggleState = False - If Me.commandBarToggleButtonDetails.ToggleState = ToggleState.[On] Then - Me.RadListView1.ViewType = ListViewType.DetailsView - End If - If Me.commandBarToggleButtonList.ToggleState = ToggleState.[On] Then - Me.RadListView1.ViewType = ListViewType.ListView - End If - If Me.commandBarToggleButtonTiles.ToggleState = ToggleState.[On] Then - Me.RadListView1.ViewType = ListViewType.IconsView - End If -End Sub -Private Sub ViewToggleButton_ToggleStateChanging(sender As Object, args As StateChangingEventArgs) Handles commandBarToggleButtonTiles.ToggleStateChanging, commandBarToggleButtonList.ToggleStateChanging, commandBarToggleButtonDetails.ToggleStateChanging - If Not updatingToggleState AndAlso args.OldValue = ToggleState.[On] Then - args.Cancel = True - End If -End Sub - -```` - -{{endregion}} + + + + 7\. Next, subscribe to the __SelectedIndexChanged__ event of *commandBarDropDownSort*__CommandBarDropDownList__. In the event handler, we are going to add the desired __SortDescriptors__, according to the selected item in the drop down. #### Handle sorting functionality -{{source=..\SamplesCS\ListView\ListViewGettingStarted.cs region=sort}} -{{source=..\SamplesVB\ListView\ListViewGettingStarted.vb region=sort}} - -````C# -private void commandBarDropDownSort_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e) -{ - this.radListView1.SortDescriptors.Clear(); - switch (this.commandBarDropDownSort.Text) - { - case "Song Name": - this.radListView1.SortDescriptors.Add(new SortDescriptor("SongName", ListSortDirection.Ascending)); - this.radListView1.EnableSorting = true; - break; - case "Album": - this.radListView1.SortDescriptors.Add(new SortDescriptor("AlbumName", ListSortDirection.Ascending)); - this.radListView1.EnableSorting = true; - break; - case "Artist": - this.radListView1.SortDescriptors.Add(new SortDescriptor("ArtistName", ListSortDirection.Ascending)); - this.radListView1.EnableSorting = true; - break; - } -} - -```` -````VB.NET -Private Sub commandBarDropDownSort_SelectedIndexChanged(sender As Object, e As Telerik.WinControls.UI.Data.PositionChangedEventArgs) Handles commandBarDropDownSort.SelectedIndexChanged - Me.RadListView1.SortDescriptors.Clear() - Select Case Me.commandBarDropDownSort.Text - Case "Song Name" - Me.RadListView1.SortDescriptors.Add(New SortDescriptor("SongName", ListSortDirection.Ascending)) - Me.RadListView1.EnableSorting = True - Exit Select - Case "Album" - Me.RadListView1.SortDescriptors.Add(New SortDescriptor("AlbumName", ListSortDirection.Ascending)) - Me.RadListView1.EnableSorting = True - Exit Select - Case "Artist" - Me.RadListView1.SortDescriptors.Add(New SortDescriptor("ArtistName", ListSortDirection.Ascending)) - Me.RadListView1.EnableSorting = True - Exit Select - End Select -End Sub - -```` - -{{endregion}} + + + + To add the grouping functionality, subscribe to the __SelectedIndexChanged__ event of *commandBarDropDownGroup*, __CommandBarDropDownList__. Similar to the sorting functionality, add the desired __GroupDescriptors__ according to the selected item. #### Handle grouping functionality -{{source=..\SamplesCS\ListView\ListViewGettingStarted.cs region=group}} -{{source=..\SamplesVB\ListView\ListViewGettingStarted.vb region=group}} - -````C# -private void commandBarDropDownGroup_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e) -{ - this.radListView1.GroupDescriptors.Clear(); - switch (this.commandBarDropDownGroup.Text) - { - case "None": - this.radListView1.EnableGrouping = false; - this.radListView1.ShowGroups = false; - break; - case "Album": - this.radListView1.GroupDescriptors.Add(new GroupDescriptor( - new SortDescriptor[] { new SortDescriptor("AlbumName", ListSortDirection.Ascending) })); - this.radListView1.EnableGrouping = true; - this.radListView1.ShowGroups = true; - break; - case "Artist": - this.radListView1.GroupDescriptors.Add(new GroupDescriptor( - new SortDescriptor[] { new SortDescriptor("ArtistName", ListSortDirection.Ascending) })); - this.radListView1.EnableGrouping = true; - this.radListView1.ShowGroups = true; - break; - } -} - -```` -````VB.NET -Private Sub commandBarDropDownGroup_SelectedIndexChanged(sender As Object, e As Telerik.WinControls.UI.Data.PositionChangedEventArgs) Handles commandBarDropDownGroup.SelectedIndexChanged - Me.RadListView1.GroupDescriptors.Clear() - Select Case Me.commandBarDropDownGroup.Text - Case "None" - Me.RadListView1.EnableGrouping = False - Me.RadListView1.ShowGroups = False - Exit Select - Case "Album" - Me.RadListView1.GroupDescriptors.Add(New GroupDescriptor(New SortDescriptor() {New SortDescriptor("AlbumName", ListSortDirection.Ascending)})) - Me.RadListView1.EnableGrouping = True - Me.RadListView1.ShowGroups = True - Exit Select - Case "Artist" - Me.RadListView1.GroupDescriptors.Add(New GroupDescriptor(New SortDescriptor() {New SortDescriptor("ArtistName", ListSortDirection.Ascending)})) - Me.RadListView1.EnableGrouping = True - Me.RadListView1.ShowGroups = True - Exit Select - End Select -End Sub - -```` - -{{endregion}} - + + + + + 8\. Lastly, lets subscribe ot the __TextChanged__ event of *commandBarTextBoxFilter*__CommandBarTextBox__. Here we will add __FilterDescriptor__ according to the text entered in the text box: #### Handle filtering functionality -{{source=..\SamplesCS\ListView\ListViewGettingStarted.cs region=filter}} -{{source=..\SamplesVB\ListView\ListViewGettingStarted.vb region=filter}} - -````C# -private void commandBarTextBoxFilter_TextChanged(object sender, EventArgs e) -{ - this.radListView1.FilterDescriptors.Clear(); - if (String.IsNullOrEmpty(this.commandBarTextBoxFilter.Text)) - { - this.radListView1.EnableFiltering = false; - } - else - { - this.radListView1.FilterDescriptors.LogicalOperator = FilterLogicalOperator.Or; - this.radListView1.FilterDescriptors.Add("SongName", FilterOperator.Contains, this.commandBarTextBoxFilter.Text); - this.radListView1.FilterDescriptors.Add("AlbumName", FilterOperator.Contains, this.commandBarTextBoxFilter.Text); - this.radListView1.FilterDescriptors.Add("ArtistName", FilterOperator.Contains, this.commandBarTextBoxFilter.Text); - this.radListView1.EnableFiltering = true; - } -} - -```` -````VB.NET -Private Sub commandBarTextBoxFilter_TextChanged(sender As Object, e As EventArgs) Handles commandBarTextBoxFilter.TextChanged - Me.RadListView1.FilterDescriptors.Clear() - If [String].IsNullOrEmpty(Me.commandBarTextBoxFilter.Text) Then - Me.RadListView1.EnableFiltering = False - Else - Me.RadListView1.FilterDescriptors.LogicalOperator = FilterLogicalOperator.[Or] - Me.RadListView1.FilterDescriptors.Add("SongName", FilterOperator.Contains, Me.commandBarTextBoxFilter.Text) - Me.RadListView1.FilterDescriptors.Add("AlbumName", FilterOperator.Contains, Me.commandBarTextBoxFilter.Text) - Me.RadListView1.FilterDescriptors.Add("ArtistName", FilterOperator.Contains, Me.commandBarTextBoxFilter.Text) - Me.RadListView1.EnableFiltering = True - End If -End Sub - -```` - -{{endregion}} + + + + 9\. Run the application and try the different functionalities: diff --git a/controls/listview/keyboard-navigation-.md b/controls/listview/keyboard-navigation-.md index e1b81a31e..f7c0ca94c 100644 --- a/controls/listview/keyboard-navigation-.md +++ b/controls/listview/keyboard-navigation-.md @@ -22,19 +22,10 @@ To enable this functionality a single property setting is needed: #### Enable Keyboard Navigation -{{source=..\SamplesCS\ListView\ListViewKeyboardNavigation.cs region=KeyboardSearchEnabled}} -{{source=..\SamplesVB\ListView\ListViewKeyboardNavigation.vb region=KeyboardSearchEnabled}} + + -````C# -radListView1.KeyboardSearchEnabled = true; -```` -````VB.NET -RadListView1.KeyboardSearchEnabled = True - -```` - -{{endregion}} >note Considering the **Text** of each data item, the search behavior is performed. So if you populate **RadListView** with data by using data binding, don't miss to set the **DisplayMember** property which will fill the **Text** for each item. @@ -42,19 +33,8 @@ Another property of interest is the __KeyboardSearchResetInterval__ property. It #### Specify the KeyboardSearchResetInterval -{{source=..\SamplesCS\ListView\ListViewKeyboardNavigation.cs region=KeyboardSearchResetInterval}} -{{source=..\SamplesVB\ListView\ListViewKeyboardNavigation.vb region=KeyboardSearchResetInterval}} - -````C# -radListView1.KeyboardSearchResetInterval = 200; - -```` -````VB.NET -RadListView1.KeyboardSearchResetInterval = 200 - -```` - -{{endregion}} + + diff --git a/controls/listview/populating-with-data/data-binding.md b/controls/listview/populating-with-data/data-binding.md index ff6d5be93..8fa640dc3 100644 --- a/controls/listview/populating-with-data/data-binding.md +++ b/controls/listview/populating-with-data/data-binding.md @@ -51,43 +51,10 @@ By handling the __ColumnCreating__ event you can manipulate the size, the visibi #### Columns creating -{{source=..\SamplesCS\ListView\ListViewDataBinding.cs region=ColumnCreating}} -{{source=..\SamplesVB\ListView\ListViewDataBinding.vb region=ColumnCreating}} - -````C# -void radListView1_ColumnCreating(object sender, Telerik.WinControls.UI.ListViewColumnCreatingEventArgs e) -{ - if (e.Column.FieldName == "CustomerID" || e.Column.FieldName == "ParentID") - { - e.Column.Visible = false; - } - if (e.Column.FieldName == "CompanyName") - { - e.Column.HeaderText = "Company"; - } - if (e.Column.FieldName == "ContactName") - { - e.Column.HeaderText = "Contact"; - } -} - -```` -````VB.NET -Private Sub RadListView1_ColumnCreating(ByVal sender As Object, ByVal e As ListViewColumnCreatingEventArgs) Handles RadListView1.ColumnCreating - If e.Column.FieldName = "CustomerID" OrElse e.Column.FieldName = "ParentID" Then - e.Column.Visible = False - End If - If e.Column.FieldName = "CompanyName" Then - e.Column.HeaderText = "Company" - End If - If e.Column.FieldName = "ContactName" Then - e.Column.HeaderText = "Contact" - End If -End Sub - -```` - -{{endregion}} + + + + ## Data Binding at Run Time @@ -97,239 +64,28 @@ The following tutorial will demonstrate how to bind a **RadListView** to a list #### Person Class -{{source=..\SamplesCS\ListView\ListViewDataBinding.cs region=person}} -{{source=..\SamplesVB\ListView\ListViewDataBinding.vb region=person}} - -````C# -public class Person : INotifyPropertyChanged -{ - private int _id; - private string _name; - private string _address; - private DateTime _dateOfBirth; - private Image _picture; - public event PropertyChangedEventHandler PropertyChanged; - public Person(int Id, string Name, string Address, DateTime DateOfBirth, Image Picture) - { - this._id = Id; - this._name = Name; - this._address = Address; - this._dateOfBirth = DateOfBirth; - this._picture = Picture; - } - public int ID - { - get - { - return this._id; - } - set - { - if (this._id != value) - { - this._id = value; - OnPropertyChanged("ID"); - } - } - } - public string Name - { - get - { - return this._name; - } - set - { - if (this._name != value) - { - this._name = value; - OnPropertyChanged("Name"); - } - } - } - public string Address - { - get - { - return this._address; - } - set - { - if (this._address != value) - { - this._address = value; - OnPropertyChanged("Address"); - } - } - } - public DateTime DateOfBirth - { - get - { - return this._dateOfBirth; - } - set - { - if (this._dateOfBirth != value) - { - this._dateOfBirth = value; - OnPropertyChanged("DateOfBirth"); - } - } - } - public Image Picture - { - get - { - return this._picture; - } - set - { - if (this._picture != value) - { - this._picture = value; - OnPropertyChanged("Picture"); - } - } - } - protected virtual void OnPropertyChanged(string propertyName) - { - if (PropertyChanged != null) - { - PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); - } - } -} - -```` -````VB.NET -Public Class Person - Private _id As Integer - Private _name As String - Private _address As String - Private _dateOfBirth As DateTime - Private _picture As Image - Public Event PropertyChanged As PropertyChangedEventHandler - Public Sub New(Id As Integer, Name As String, Address As String, DateOfBirth As DateTime, Picture As Image) - Me._id = Id - Me._name = Name - Me._address = Address - Me._dateOfBirth = DateOfBirth - Me._picture = Picture - End Sub - Public Property ID() As Integer - Get - Return Me._id - End Get - Set(value As Integer) - If Me._id <> value Then - Me._id = value - OnPropertyChanged("ID") - End If - End Set - End Property - Public Property Name() As String - Get - Return Me._name - End Get - Set(value As String) - If Me._name <> value Then - Me._name = value - OnPropertyChanged("Name") - End If - End Set - End Property - Public Property Address() As String - Get - Return Me._address - End Get - Set(value As String) - If Me._address <> value Then - Me._address = value - OnPropertyChanged("Address") - End If - End Set - End Property - Public Property DateOfBirth() As DateTime - Get - Return Me._dateOfBirth - End Get - Set(value As DateTime) - If Me._dateOfBirth <> value Then - Me._dateOfBirth = value - OnPropertyChanged("DateOfBirth") - End If - End Set - End Property - Public Property Picture() As Image - Get - Return Me._picture - End Get - Set(value As Image) - If Me._picture IsNot value Then - Me._picture = value - OnPropertyChanged("Picture") - End If - End Set - End Property - Protected Overridable Sub OnPropertyChanged(propertyName As String) - RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName)) - End Sub -End Class - -```` - -{{endregion}} + + -2\. Then, create a collection of our objects. The collection should implement **IBindingList** to support notifications. This, together with the **INotifyPropertyChanged** establishes a two way connection between the control and the object. In this case, we can use **BindingList** since it implements the **IBindingList** interface internally: -#### Create a collection or person objects -{{source=..\SamplesCS\ListView\ListViewDataBinding.cs region=fillDataSource}} -{{source=..\SamplesVB\ListView\ListViewDataBinding.vb region=fillDataSource}} +2\. Then, create a collection of our objects. The collection should implement **IBindingList** to support notifications. This, together with the **INotifyPropertyChanged** establishes a two way connection between the control and the object. In this case, we can use **BindingList** since it implements the **IBindingList** interface internally: -````C# -BindingList dataSource = new BindingList() -{ - new Person(1, "Nancy Davolio","507 - 20th Ave. E.Apt. 2A", DateTime.Parse("12/8/1948"), Resources.nancy), - new Person(2, "Andrew Fuller","908 W. Capital Way", DateTime.Parse("2/19/1952"), Resources.Andrew), - new Person(3, "Janet Leverling","722 Moss Bay Blvd.", DateTime.Parse("8/30/1963"), Resources.Janet), - new Person(4, "Margaret Peacock","110 Old Redmond Rd.", DateTime.Parse("9/19/1937"), Resources.Margaret) -}; +#### Create a collection or person objects -```` -````VB.NET -Dim dataSource As New BindingList(Of Person)() -dataSource.Add(New Person(1, "Nancy Davolio", "507 - 20th Ave. E.Apt. 2A", DateTime.Parse("12/8/1948"), My.Resources.nancy)) -dataSource.Add(New Person(2, "Andrew Fuller", "908 W. Capital Way", DateTime.Parse("2/19/1952"), My.Resources.Andrew)) -dataSource.Add(New Person(3, "Janet Leverling", "722 Moss Bay Blvd.", DateTime.Parse("8/30/1963"), My.Resources.Janet)) -dataSource.Add(New Person(4, "Margaret Peacock", "110 Old Redmond Rd.", DateTime.Parse("9/19/1937"), My.Resources.Margaret)) + + -```` -{{endregion}} 3\. To bind our **RadListView** to this collection, simply set its __DataSource__, __DisplayMember__ and __ValueMember__ properties: #### Bind to the collection of custom objects -{{source=..\SamplesCS\ListView\ListViewDataBinding.cs region=binding}} -{{source=..\SamplesVB\ListView\ListViewDataBinding.vb region=binding}} - -````C# -this.radListView1.DataSource = dataSource; -this.radListView1.DisplayMember = "Name"; -this.radListView1.ValueMember = "ID"; - -```` -````VB.NET -Me.RadListView1.DataSource = dataSource -Me.RadListView1.DisplayMember = "Name" -Me.RadListView1.ValueMember = "ID" + + -```` -{{endregion}} As a result you will get the **RadListView** populated with items that display the value __Name__ property of the business objects and have the __ID__ property of the business object returned as value. Opening an item for editing will display the id. @@ -339,29 +95,10 @@ As a result you will get the **RadListView** populated with items that display t #### Assign an image to the item -{{source=..\SamplesCS\ListView\ListViewDataBinding.cs region=ItemDataBound}} -{{source=..\SamplesVB\ListView\ListViewDataBinding.vb region=ItemDataBound}} - -````C# -void radListView1_ItemDataBound(object sender, Telerik.WinControls.UI.ListViewItemEventArgs e) -{ - { - if (radListView1.ViewType == Telerik.WinControls.UI.ListViewType.ListView) - { - e.Item.Image = ((Person)e.Item.DataBoundItem).Picture; - } - } -} - -```` -````VB.NET -Private Sub RadListView1_ItemDataBound(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.ListViewItemEventArgs) - e.Item.Image = DirectCast(e.Item.DataBoundItem, Person).Picture -End Sub - -```` - -{{endregion}} + + + + >caption Figure 4: Displying images ![WinForms RadListView Displying images](images/listview-databinding006.png) diff --git a/controls/listview/populating-with-data/unbound-mode.md b/controls/listview/populating-with-data/unbound-mode.md index 908e683a8..6589aab4d 100644 --- a/controls/listview/populating-with-data/unbound-mode.md +++ b/controls/listview/populating-with-data/unbound-mode.md @@ -23,21 +23,10 @@ The items in **RadListView** are stored in a collection that is accessible throu #### Adding items -{{source=..\SamplesCS\ListView\ListViewProgramaticallyPopulatingWithData.cs region=addItems}} -{{source=..\SamplesVB\ListView\ListViewProgramaticallyPopulatingWithData.vb region=addItems}} + + -````C# -this.radListView1.Items.Add(new ListViewDataItem("Item 1")); -this.radListView1.Items.Add("Item 2"); -```` -````VB.NET -Me.RadListView1.Items.Add(New ListViewDataItem("Item 1")) -Me.RadListView1.Items.Add("Item 2") - -```` - -{{endregion}} ## Adding Columns @@ -45,52 +34,19 @@ When in [DetailsView]({%slug winforms/listview/views%}), **RadListView** display #### Adding columns -{{source=..\SamplesCS\ListView\ListViewProgramaticallyPopulatingWithData.cs region=addColumns}} -{{source=..\SamplesVB\ListView\ListViewProgramaticallyPopulatingWithData.vb region=addColumns}} - -````C# -this.radListView1.Columns.Add("Column1"); -this.radListView1.Columns.Add("Column2", "Column2Header"); -this.radListView1.Columns.Add(new ListViewDetailColumn("Column3", "Column3Header")); + + -```` -````VB.NET -Me.RadListView1.Columns.Add("Column1") -Me.RadListView1.Columns.Add("Column2", "Column2Header") -Me.RadListView1.Columns.Add(New ListViewDetailColumn("Column3", "Column3Header")) -```` - -{{endregion}} You can set cell values to the items of **RadListView** using their indexers. The keys can be either the index of the column, the name of the column, or the column itself. #### Populating cells -{{source=..\SamplesCS\ListView\ListViewProgramaticallyPopulatingWithData.cs region=populateCells}} -{{source=..\SamplesVB\ListView\ListViewProgramaticallyPopulatingWithData.vb region=populateCells}} - -````C# -ListViewDataItem item = new ListViewDataItem(); -//it is important that you add the item to the control prior assigning its cell's values, so it will have its cells schema -radListView1.Items.Add(item); - -item[0] = "CellValue1"; -item["Column2"] = "CellValue2"; -item[radListView1.Columns[2]] = "CellValue3"; + + -```` -````VB.NET -Dim item As ListViewDataItem = New ListViewDataItem() -'it is important that you add the item to the control prior assigning its cell's values, so it will have its cells schema -RadListView1.Items.Add(item) -item(0) = "CellValue1" -item("Column2") = "CellValue2" -item(RadListView1.Columns(2)) = "CellValue3" -```` - -{{endregion}} >important To use these indexers, the item must have a valid owner e.g. it first has to be added to the __Items__ collection of **RadListView**. @@ -102,45 +58,19 @@ Aside from using __GroupDescriptors__, custom groups can also be added to **RadL #### Adding groups -{{source=..\SamplesCS\ListView\ListViewProgramaticallyPopulatingWithData.cs region=addGroups}} -{{source=..\SamplesVB\ListView\ListViewProgramaticallyPopulatingWithData.vb region=addGroups}} - -````C# -this.radListView1.Groups.Add(new ListViewDataItemGroup("First Group")); -this.radListView1.Groups.Add(new ListViewDataItemGroup("Second Group")); - -```` -````VB.NET -Me.RadListView1.Groups.Add(New ListViewDataItemGroup("First Group")) -Me.RadListView1.Groups.Add(New ListViewDataItemGroup("Second Group")) + + -```` -{{endregion}} In order to assign an item to a group, you should set the item’s __Group__ property: #### Assign item to a group -{{source=..\SamplesCS\ListView\ListViewProgramaticallyPopulatingWithData.cs region=assignItemToAGroup}} -{{source=..\SamplesVB\ListView\ListViewProgramaticallyPopulatingWithData.vb region=assignItemToAGroup}} - -````C# -this.radListView1.Items[0].Group = this.radListView1.Groups[0]; -this.radListView1.Items[1].Group = this.radListView1.Groups[0]; -this.radListView1.Items[2].Group = this.radListView1.Groups[1]; -this.radListView1.Items[3].Group = this.radListView1.Groups[1]; - -```` -````VB.NET -Me.RadListView1.Items(0).Group = Me.RadListView1.Groups(0) -Me.RadListView1.Items(1).Group = Me.RadListView1.Groups(0) -Me.RadListView1.Items(2).Group = Me.RadListView1.Groups(1) -Me.RadListView1.Items(3).Group = Me.RadListView1.Groups(1) + + -```` -{{endregion}} In order to enable this kind of grouping the __EnableCustomGrouping__ property needs to be set to *true*. In order to display the groups, the __ShowGroups__ property needs to be set to *true*. diff --git a/controls/listview/using-checkboxes.md b/controls/listview/using-checkboxes.md index 77f06f296..bee4f0cbf 100644 --- a/controls/listview/using-checkboxes.md +++ b/controls/listview/using-checkboxes.md @@ -14,20 +14,10 @@ position: 9 #### Enable Checkboxes -{{source=..\SamplesCS\ListView\ListViewCheckboxesAndEditors.cs region=EnableCheckBoxes}} -{{source=..\SamplesVB\ListView\ListViewCheckboxesAndEditors.vb region=EnableCheckBoxes}} + + -````C# - -this.radListView1.ShowCheckBoxes = true; -```` -````VB.NET -Me.RadListView1.ShowCheckBoxes = True - -```` - -{{endregion}} When checkboxes are enabled, you have several options to handle the checked items: @@ -41,30 +31,10 @@ When checkboxes are enabled, you have several options to handle the checked item #### Toggle an item programmatically -{{source=..\SamplesCS\ListView\ListViewCheckboxesAndEditors.cs region=ToggleItem}} -{{source=..\SamplesVB\ListView\ListViewCheckboxesAndEditors.vb region=ToggleItem}} - -````C# -ListViewDataItem checkedItem = new ListViewDataItem("Checked item"); -checkedItem.CheckState = Telerik.WinControls.Enumerations.ToggleState.On; -this.radListView1.Items.Add(checkedItem); - -ListViewDataItem uncheckedItem = new ListViewDataItem("Unchecked item"); -uncheckedItem.CheckState = Telerik.WinControls.Enumerations.ToggleState.Off; -this.radListView1.Items.Add(uncheckedItem); - -```` -````VB.NET -Dim checkedItem As New ListViewDataItem("Checked item") -checkedItem.CheckState = Telerik.WinControls.Enumerations.ToggleState.[On] -Me.RadListView1.Items.Add(checkedItem) -Dim uncheckedItem As New ListViewDataItem("Unchecked item") -uncheckedItem.CheckState = Telerik.WinControls.Enumerations.ToggleState.Off -Me.RadListView1.Items.Add(uncheckedItem) - -```` - -{{endregion}} + + + + >caption Figure 2: Toggle items programmatically diff --git a/controls/map/drag-and-drop/ole-drag-and-drop.md b/controls/map/drag-and-drop/ole-drag-and-drop.md index 44ed1de2e..9f114370a 100644 --- a/controls/map/drag-and-drop/ole-drag-and-drop.md +++ b/controls/map/drag-and-drop/ole-drag-and-drop.md @@ -24,45 +24,10 @@ In order to achieve the desired result the MouseMove, MouseUp, and DragEnter eve #### Subscribe to Events -{{source=..\SamplesCS\Map\DragAndDropRadMapForm.cs region=SubscribeEvents}} -{{source=..\SamplesVB\Map\DragAndDropRadMapForm.vb region=SubscribeEvents}} -````C# -public DragAndDropRadMapForm() -{ - InitializeComponent(); - this.SetupProviders(); - this.SetupLayer(); - this.SetupLegend(); - this.SetupData(); - this.radMap1.AllowDrop = true; - this.radListView1.AllowDrop = true; - this.radMap1.MouseMove += RadMap1_MouseMove; - this.radMap1.DragEnter += RadMap1_DragEnter; - this.radListView1.DragEnter += RadListView1_DragEnter; - this.radListView1.DragDrop += RadListView1_DragDrop; -} - -```` -````VB.NET -Public Sub New() - InitializeComponent() - Me.SetupProviders() - Me.SetupLayer() - Me.SetupLegend() - Me.SetupData() - Me.radMap1.AllowDrop = True - Me.radListView1.AllowDrop = True - AddHandler Me.radMap1.MouseMove, AddressOf RadMap1_MouseMove - AddHandler Me.radMap1.DragEnter, AddressOf RadMap1_DragEnter - AddHandler Me.radListView1.DragEnter, AddressOf RadListView1_DragEnter - AddHandler Me.radListView1.DragDrop, AddressOf RadListView1_DragDrop -End Sub - -```` - - - -{{endregion}} + + + + ## Handling Events @@ -70,81 +35,10 @@ The RadMapElement.**EnablePanning** property will be set in the MouseMove event #### Drag and Drop Events -{{source=..\SamplesCS\Map\DragAndDropRadMapForm.cs region=HandleEvents}} -{{source=..\SamplesVB\Map\DragAndDropRadMapForm.vb region=HandleEvents}} -````C# -private void RadMap1_MouseMove(object sender, MouseEventArgs e) -{ - if (!(e.Button == MouseButtons.Left)) - { - return; - } - - PointL point = new PointL(e.X - this.radMap1.MapElement.PanOffset.Width, e.Y - this.radMap1.MapElement.PanOffset.Height); - MapPin pin = this.radMap1.Layers.HitTest(point) as MapPin; - if (pin != null) - { - this.radMap1.InputBehavior.OnMouseUp(e); - ((RadMap)sender).DoDragDrop(pin, DragDropEffects.Move); - } -} -private void RadMap1_DragEnter(object sender, DragEventArgs e) -{ - MapPin pin = e.Data.GetData(typeof(MapPin)) as MapPin; - e.Effect = pin == null ? DragDropEffects.None : DragDropEffects.Move; -} - -private void RadListView1_DragEnter(object sender, DragEventArgs e) -{ - MapPin pin = e.Data.GetData(typeof(MapPin)) as MapPin; - e.Effect = pin == null ? DragDropEffects.None : DragDropEffects.Move; -} -private void RadListView1_DragDrop(object sender, DragEventArgs e) -{ - MapPin pin = e.Data.GetData(typeof(MapPin)) as MapPin; - this.radMap1.Layers["Pins"].Remove(pin); - this.radListView1.Items.Add(pin.Text); - this.radMap1.Refresh(); -} - -```` -````VB.NET -Private Sub RadMap1_MouseMove(ByVal sender As Object, ByVal e As MouseEventArgs) - If Not (e.Button = MouseButtons.Left) Then - Return - End If - - Dim point As PointL = New PointL(e.X - Me.radMap1.MapElement.PanOffset.Width, e.Y - Me.radMap1.MapElement.PanOffset.Height) - Dim pin As MapPin = TryCast(Me.radMap1.Layers.HitTest(point), MapPin) - - If pin IsNot Nothing Then - Me.radMap1.InputBehavior.OnMouseUp(e) - (CType(sender, RadMap)).DoDragDrop(pin, DragDropEffects.Move) - End If -End Sub - -Private Sub RadMap1_DragEnter(ByVal sender As Object, ByVal e As DragEventArgs) - Dim pin As MapPin = TryCast(e.Data.GetData(GetType(MapPin)), MapPin) - e.Effect = If(pin Is Nothing, DragDropEffects.None, DragDropEffects.Move) -End Sub - -Private Sub RadListView1_DragEnter(ByVal sender As Object, ByVal e As DragEventArgs) - Dim pin As MapPin = TryCast(e.Data.GetData(GetType(MapPin)), MapPin) - e.Effect = If(pin Is Nothing, DragDropEffects.None, DragDropEffects.Move) -End Sub - -Private Sub RadListView1_DragDrop(ByVal sender As Object, ByVal e As DragEventArgs) - Dim pin As MapPin = TryCast(e.Data.GetData(GetType(MapPin)), MapPin) - Me.radMap1.Layers("Pins").Remove(pin) - Me.radListView1.Items.Add(pin.Text) - Me.radMap1.Refresh() -End Sub - -```` - - - -{{endregion}} + + + + # See Also diff --git a/controls/map/features/layers/clusterization.md b/controls/map/features/layers/clusterization.md index 15a4f2fce..36cc3a45e 100644 --- a/controls/map/features/layers/clusterization.md +++ b/controls/map/features/layers/clusterization.md @@ -28,65 +28,10 @@ The example below creates a layer with four __MapPin__ elements and defines clus #### Add Layer and Data -{{source=..\SamplesCS\Map\ClusterizationForm.cs region=SetupLayersAndData}} -{{source=..\SamplesVB\Map\ClusterizationForm.vb region=SetupLayersAndData}} -````C# -private void SetupLayers() -{ - MapLayer easternLayer = new MapLayer("CitiesLayer"); - this.radMap1.Layers.Add(easternLayer); -} - -private void SetupData() -{ - MapPin element = new MapPin(new PointG(40.4467648, -80.01576030)); - element.Text = "Pittsburgh"; - element.BackColor = Color.Red; - this.radMap1.Layers["CitiesLayer"].Add(element); - element = new MapPin(new PointG(40.8130697, -74.07439790)); - element.Text = "New York"; - element.BackColor = Color.Green; - this.radMap1.Layers["CitiesLayer"].Add(element); - element = new MapPin(new PointG(42.3665137, -71.06160420)); - element.Text = "Boston"; - element.BackColor = Color.Blue; - this.radMap1.Layers["CitiesLayer"].Add(element); - element = new MapPin(new PointG(43.6434661, -79.37909890)); - element.Text = "Toronto"; - element.BackColor = Color.Yellow; - this.radMap1.Layers["CitiesLayer"].Add(element); -} - -```` -````VB.NET -Private Sub SetupLayers() - Dim easternLayer As New MapLayer("CitiesLayer") - Me.RadMap1.Layers.Add(easternLayer) -End Sub -Private Sub SetupData() - Dim element As New MapPin(New PointG(40.4467648, -80.0157603)) - element.Text = "Pittsburgh" - element.BackColor = Color.Red - Me.RadMap1.Layers("CitiesLayer").Add(element) - element = New MapPin(New PointG(40.8130697, -74.0743979)) - element.Text = "New York" - element.BackColor = Color.Green - Me.RadMap1.Layers("CitiesLayer").Add(element) - element = New MapPin(New PointG(42.3665137, -71.0616042)) - element.Text = "Boston" - element.BackColor = Color.Blue - Me.RadMap1.Layers("CitiesLayer").Add(element) - element = New MapPin(New PointG(43.6434661, -79.3790989)) - element.Text = "Toronto" - element.BackColor = Color.Yellow - Me.RadMap1.Layers("CitiesLayer").Add(element) -End Sub - -```` - - - -{{endregion}} + + + + >caption Figure 2: Initial Result @@ -94,55 +39,21 @@ End Sub #### ElementClusterStrategy -{{source=..\SamplesCS\Map\ClusterizationForm.cs region=ElementClusterStrategy}} -{{source=..\SamplesVB\Map\ClusterizationForm.vb region=ElementClusterStrategy}} -````C# -private void SetElementCluster() -{ - this.radMap1.Layers[0].ClusterStrategy = new ElementClusterStrategy(); - this.radMap1.Layers["CitiesLayer"].ClusterDistance = 200; -} - -```` -````VB.NET -Private Sub SetElementCluster() - Me.RadMap1.Layers(0).ClusterStrategy = New ElementClusterStrategy() - Me.RadMap1.Layers("CitiesLayer").ClusterDistance = 200 -End Sub - -```` + + -{{endregion}} - >caption Figure 3: ElementClusterStrategy ![WinForms RadMap ElementClusterStrategy](images/map-features-layers-clusterization003.png) #### DistanceClusterStrategy -{{source=..\SamplesCS\Map\ClusterizationForm.cs region=DistanceClusterStrategy}} -{{source=..\SamplesVB\Map\ClusterizationForm.vb region=DistanceClusterStrategy}} -````C# -private void DistanceElementCluster() -{ - this.radMap1.Layers[0].ClusterStrategy = new DistanceClusterStrategy(); - this.radMap1.Layers["CitiesLayer"].ClusterDistance = 200; -} - -```` -````VB.NET -Private Sub SetDistanceCluster() - Me.RadMap1.Layers(0).ClusterStrategy = New DistanceClusterStrategy() - Me.RadMap1.Layers("CitiesLayer").ClusterDistance = 200 -End Sub - -```` - + + -{{endregion}} >caption Figure 4: DistanceClusterStrategy diff --git a/controls/map/features/layers/colorization.md b/controls/map/features/layers/colorization.md index c3f88544f..dab9ed262 100644 --- a/controls/map/features/layers/colorization.md +++ b/controls/map/features/layers/colorization.md @@ -28,41 +28,10 @@ The __GraphColorizationStrategy__ internally arranges the predefined colors so t #### Setting up GraphColorizationStrategy -{{source=..\SamplesCS\Map\MapColorizers.cs region=SetupGraphColorizationStrategy}} -{{source=..\SamplesVB\Map\MapColorizers.vb region=SetupGraphColorizationStrategy}} -````C# -private void SetupGraphColorizationStrategy() -{ - GraphColorizationStrategy colorizer = new GraphColorizationStrategy(); - colorizer.Colors = new List() { - Color.LightBlue, - Color.LightCoral, - Color.Coral, - Color.LightGray, - Color.LightGreen - }; - this.radMap1.MapElement.Layers["World Layout"].ColorizationStrategy = colorizer; -} - -```` -````VB.NET -Private Sub SetupGraphColorizationStrategy() - Dim colorizer As New GraphColorizationStrategy() - colorizer.Colors = New List(Of Color)() From { - Color.LightBlue, - Color.LightCoral, - Color.Coral, - Color.LightGray, - Color.LightGreen - } - Me.RadMap1.MapElement.Layers("World Layout").ColorizationStrategy = colorizer -End Sub - -```` - - - -{{endregion}} + + + + ## Choropleth Colorization @@ -74,71 +43,10 @@ The __ChoroplethColorizationStrategy__ arranges the predefined colors according #### Setting up ChoroplethColorizationStrategy -{{source=..\SamplesCS\Map\MapColorizers.cs region=SetupChoroplethColorizationStrategy}} -{{source=..\SamplesVB\Map\MapColorizers.vb region=SetupChoroplethColorizationStrategy}} -````C# -private void SetupChoroplethColorizationStrategy() -{ - ChoroplethColorizationStrategy colorizer = new ChoroplethColorizationStrategy(); - colorizer.Colors = new List() { - Color.Red, - Color.Blue, - Color.Green, - Color.Yellow, - Color.Brown, - Color.Gray, - Color.LightBlue, - Color.LightCoral, - Color.Coral, - Color.LightGray, - Color.LightGreen - }; - colorizer.ValueProvider = new MapGeometryPropertyValueProvider("POP_CNTRY"); - colorizer.ColorStops = new List() { 0, 1000000, 5000000, 10000000, 15000000, 20000000, 30000000, 40000000, 50000000, 100000000, 200000000 }; - this.radMap1.MapElement.Layers["World Layout"].ColorizationStrategy = colorizer; - this.radMap1.MapElement.LegendElement.LegendInfoProvider = colorizer; -} - -```` -````VB.NET -Private Sub SetupChoroplethColorizationStrategy() - Dim colorizer As New ChoroplethColorizationStrategy() - colorizer.Colors = New List(Of Color)() From { - Color.Red, - Color.Blue, - Color.Green, - Color.Yellow, - Color.Brown, - Color.Gray, - Color.LightBlue, - Color.LightCoral, - Color.Coral, - Color.LightGray, - Color.LightGreen - } - colorizer.ValueProvider = New MapGeometryPropertyValueProvider("POP_CNTRY") - colorizer.ColorStops = New List(Of Double)() From { - 0, - 1000000, - 5000000, - 10000000, - 15000000, - 20000000, - 30000000, - 40000000, - 50000000, - 100000000, - 200000000 - } - Me.RadMap1.MapElement.Layers("World Layout").ColorizationStrategy = colorizer - Me.RadMap1.MapElement.LegendElement.LegendInfoProvider = colorizer -End Sub - -```` - - - -{{endregion}} + + + + ## Property Colorization @@ -150,166 +58,33 @@ The __PropertyColorizationStrategy__ evaluates the values of a certain property #### Setting up PropertyColorizationStrategy -{{source=..\SamplesCS\Map\MapColorizers.cs region=SetupPropertyColorizationStrategy}} -{{source=..\SamplesVB\Map\MapColorizers.vb region=SetupPropertyColorizationStrategy}} -````C# -private void SetupPropertyColorizationStrategy() -{ - PropertyColorizationStrategy colorizer = new PropertyColorizationStrategy(); - colorizer.Colors = new List() { - Color.LightBlue, - Color.Coral - }; - colorizer.PropertyValues.Add(new PropertyColorizerItem("N", "NOT LANDLOCKED")); - colorizer.PropertyValues.Add(new PropertyColorizerItem("Y", "LANDLOCKED")); - colorizer.ValueProvider = new MapGeometryPropertyValueProvider("LANDLOCKED"); - this.radMap1.MapElement.Layers["World Layout"].ColorizationStrategy = colorizer; - this.radMap1.MapElement.LegendElement.LegendInfoProvider = colorizer; -} - -```` -````VB.NET -Private Sub SetupPropertyColorizationStrategy() - Dim colorizer As New PropertyColorizationStrategy() - colorizer.Colors = New List(Of Color)() From { - Color.LightBlue, - Color.Coral - } - colorizer.PropertyValues.Add(New PropertyColorizerItem("N", "NOT LANDLOCKED")) - colorizer.PropertyValues.Add(New PropertyColorizerItem("Y", "LANDLOCKED")) - colorizer.ValueProvider = New MapGeometryPropertyValueProvider("LANDLOCKED") - Me.RadMap1.MapElement.Layers("World Layout").ColorizationStrategy = colorizer - Me.RadMap1.MapElement.LegendElement.LegendInfoProvider = colorizer -End Sub - -```` - - - -{{endregion}} + + + + Here is the required code to setup the provider and read the [sample shape file](http://www.telerik.com/docs/default-source/ui-for-winforms/world_data.zip?sfvrsn=2) used in the examples above. #### Setting up EmptyMapProvider -{{source=..\SamplesCS\Map\MapColorizers.cs region=SetupProvider}} -{{source=..\SamplesVB\Map\MapColorizers.vb region=SetupProvider}} -````C# -private void SetupProvider() -{ - EmptyMapProvider emptyProvider = new EmptyMapProvider(); - emptyProvider.InitializationComplete += emptyProvider_InitializationComplete; - this.radMap1.Providers.Add(emptyProvider); -} -private void emptyProvider_InitializationComplete(object sender, EventArgs e) -{ - List locations = new List(); - foreach (MapVisualElement el in this.radMap1.Layers["World Layout"].Overlays) - { - locations.Add(el.Location); - } - this.radMap1.BringIntoView(RectangleG.GetBoundingRectangle(locations)); -} - -```` -````VB.NET -Private Sub SetupProvider() - Dim emptyProvider As New EmptyMapProvider() - AddHandler emptyProvider.InitializationComplete, AddressOf emptyProvider_InitializationComplete - Me.RadMap1.Providers.Add(emptyProvider) -End Sub -Private Sub emptyProvider_InitializationComplete(sender As Object, e As EventArgs) - Dim locations As New List(Of PointG)() - For Each el As MapVisualElement In Me.RadMap1.Layers("World Layout").Overlays - locations.Add(el.Location) - Next - Me.RadMap1.BringIntoView(RectangleG.GetBoundingRectangle(locations)) -End Sub - -```` - - - -{{endregion}} + + -#### Setting up Layer - -{{source=..\SamplesCS\Map\MapColorizers.cs region=SetupLayer}} -{{source=..\SamplesVB\Map\MapColorizers.vb region=SetupLayer}} -````C# -private void SetupLayer() -{ - MapLayer worldLayer = new MapLayer("World Layout"); - this.radMap1.Layers.Add(worldLayer); -} -```` -````VB.NET -Private Sub SetupLayer() - Dim worldLayer As New MapLayer("World Layout") - Me.RadMap1.Layers.Add(worldLayer) -End Sub -```` +#### Setting up Layer + + -{{endregion}} #### Setting up Data -{{source=..\SamplesCS\Map\MapColorizers.cs region=SetupData}} -{{source=..\SamplesVB\Map\MapColorizers.vb region=SetupData}} -````C# -private void SetupData() -{ - using (MemoryStream worldStream = new MemoryStream(Properties.Resources.world)) - using (MemoryStream worlDataStream = new MemoryStream(Properties.Resources.world_data)) - { - ShapeFileReaderParameters parameters = new ShapeFileReaderParameters(); - parameters.ShapeStream = worldStream; - parameters.DbfStream = worlDataStream; - ShapeFileReader reader = new ShapeFileReader(); - List elements = reader.Read(parameters); - Font elementFont = new Font("Arial", 7f, FontStyle.Bold); - foreach (MapGeometry element in elements) - { - element.Font = elementFont; - element.ForeColor = Color.Black; - element.Text = (string)element.ExtendedData.GetValue("CNTRY_NAME"); - element.BorderWidth = 1; - } - this.radMap1.Layers["World Layout"].AddRange(elements); - } -} - -```` -````VB.NET -Private Sub SetupData() - Using worldStream As New MemoryStream(My.Resources.world) - Using worlDataStream As New MemoryStream(My.Resources.world_data) - Dim parameters As New ShapeFileReaderParameters() - parameters.ShapeStream = worldStream - parameters.DbfStream = worlDataStream - Dim reader As New ShapeFileReader() - Dim elements As List(Of MapVisualElement) = reader.Read(parameters) - Dim elementFont As New Font("Arial", 7.0F, FontStyle.Bold) - For Each element As MapGeometry In elements - element.Font = elementFont - element.ForeColor = Color.Black - element.Text = DirectCast(element.ExtendedData.GetValue("CNTRY_NAME"), String) - element.BorderWidth = 1 - Next - Me.RadMap1.Layers("World Layout").AddRange(elements) - End Using - End Using -End Sub - -```` - - - -{{endregion}} + + + + # See Also diff --git a/controls/map/features/layers/overview.md b/controls/map/features/layers/overview.md index 115907f46..2e7a83018 100644 --- a/controls/map/features/layers/overview.md +++ b/controls/map/features/layers/overview.md @@ -21,117 +21,17 @@ The example below uses the [BingRestMapProvider]({%slug winforms/map/providers/ #### Setup Layers -{{source=..\SamplesCS\Map\MapLayers.cs region=SetupLayers}} -{{source=..\SamplesVB\Map\MapLayers.vb region=SetupLayers}} -````C# -private void SetupLayers() -{ - MapLayer easternLayer = new MapLayer("Eastern"); - this.radMap1.Layers.Add(easternLayer); - MapLayer westernLayer = new MapLayer("Western"); - this.radMap1.Layers.Add(westernLayer); -} + + -```` -````VB.NET -Private Sub SetupLayers() - Dim easternLayer As New MapLayer("Eastern") - Me.RadMap1.Layers.Add(easternLayer) - Dim westernLayer As New MapLayer("Western") - Me.RadMap1.Layers.Add(westernLayer) -End Sub - -```` +#### Setup Data -{{endregion}} + + -#### Setup Data -{{source=..\SamplesCS\Map\MapLayers.cs region=SetupData}} -{{source=..\SamplesVB\Map\MapLayers.vb region=SetupData}} -````C# -private void SetupData() -{ - MapPin element = new MapPin(new PointG(34.0140562, -118.2880489)); - element.Text = "Los Angeles"; - element.BackColor = Color.Red; - this.radMap1.Layers["Western"].Add(element); - element = new MapPin(new PointG(47.5951518, -122.3316280)); - element.Text = "Seattle"; - element.BackColor = Color.Red; - this.radMap1.Layers["Western"].Add(element); - element = new MapPin(new PointG(29.4270198, -98.43744520)); - element.Text = "San Antonio"; - element.BackColor = Color.Red; - this.radMap1.Layers["Western"].Add(element); - element = new MapPin(new PointG(41.8806908, -87.67416460)); - element.Text = "Chicago"; - element.BackColor = Color.Blue; - this.radMap1.Layers["Eastern"].Add(element); - element = new MapPin(new PointG(40.8296426, -73.92636320)); - element.Text = "New York"; - element.BackColor = Color.Blue; - this.radMap1.Layers["Eastern"].Add(element); - element = new MapPin(new PointG(42.3665137, -71.06160420)); - element.Text = "Boston"; - element.BackColor = Color.Blue; - this.radMap1.Layers["Eastern"].Add(element); - MapLabel westernLabel = new MapLabel(new PointG(36.251282d, -111.593335d), "Western") - { - BackColor = Color.FromArgb(122, 255, 0, 0) - }; - MapLabel easternLabel = new MapLabel(new PointG(38.790412d, -81.000594d), "Eastern") - { - BackColor = Color.FromArgb(122, 0, 0, 255) - }; - this.radMap1.Layers["Western"].Add(westernLabel); - this.radMap1.Layers["Eastern"].Add(easternLabel); -} - -```` -````VB.NET -Private Sub SetupData() - Dim element As New MapPin(New PointG(34.0140562, -118.2880489)) - element.Text = "Los Angeles" - element.BackColor = Color.Red - Me.RadMap1.Layers("Western").Add(element) - element = New MapPin(New PointG(47.5951518, -122.331628)) - element.Text = "Seattle" - element.BackColor = Color.Red - Me.RadMap1.Layers("Western").Add(element) - element = New MapPin(New PointG(29.4270198, -98.4374452)) - element.Text = "San Antonio" - element.BackColor = Color.Red - Me.RadMap1.Layers("Western").Add(element) - element = New MapPin(New PointG(41.8806908, -87.6741646)) - element.Text = "Chicago" - element.BackColor = Color.Blue - Me.RadMap1.Layers("Eastern").Add(element) - element = New MapPin(New PointG(40.8296426, -73.9263632)) - element.Text = "New York" - element.BackColor = Color.Blue - Me.RadMap1.Layers("Eastern").Add(element) - element = New MapPin(New PointG(42.3665137, -71.0616042)) - element.Text = "Boston" - element.BackColor = Color.Blue - Me.RadMap1.Layers("Eastern").Add(element) - Dim westernLabel As New MapLabel(New PointG(36.251282, -111.593335), "Western") With { - .BackColor = Color.FromArgb(122, 255, 0, 0) - } - Dim easternLabel As New MapLabel(New PointG(38.790412, -81.000594), "Eastern") With { - .BackColor = Color.FromArgb(122, 0, 0, 255) - } - Me.RadMap1.Layers("Western").Add(westernLabel) - Me.RadMap1.Layers("Eastern").Add(easternLabel) -End Sub - -```` - - - -{{endregion}} # See Also diff --git a/controls/map/features/legend.md b/controls/map/features/legend.md index bc2b44c5b..9c05b643f 100644 --- a/controls/map/features/legend.md +++ b/controls/map/features/legend.md @@ -26,28 +26,10 @@ Legend items can be added by accessing the __Children__ collection of the legend #### Customizing Appearance -{{source=..\SamplesCS\Map\MapLayers.cs region=SetLegends}} -{{source=..\SamplesVB\Map\MapLayers.vb region=SetLegends}} -````C# -this.radMap1.MapElement.LegendElement.TitleElement.Text = "NBA"; -this.radMap1.MapElement.LegendElement.SubtitleElement.Text = "Conferences"; -this.radMap1.MapElement.LegendElement.Orientation = Orientation.Horizontal; -this.radMap1.MapElement.LegendElement.ItemStackElement.Children.Add(new MapLegendItemElement("Western", Color.Red)); -this.radMap1.MapElement.LegendElement.ItemStackElement.Children.Add(new MapLegendItemElement("Eastern", Color.Blue)); + + -```` -````VB.NET -Me.RadMap1.MapElement.LegendElement.TitleElement.Text = "NBA" -Me.RadMap1.MapElement.LegendElement.SubtitleElement.Text = "Conferences" -Me.RadMap1.MapElement.LegendElement.Orientation = Orientation.Horizontal -Me.RadMap1.MapElement.LegendElement.ItemStackElement.Children.Add(New MapLegendItemElement("Western", Color.Red)) -Me.RadMap1.MapElement.LegendElement.ItemStackElement.Children.Add(New MapLegendItemElement("Eastern", Color.Blue)) -```` - - - -{{endregion}} # See Also diff --git a/controls/map/features/minimap.md b/controls/map/features/minimap.md index 83db8dbae..f23b199ee 100644 --- a/controls/map/features/minimap.md +++ b/controls/map/features/minimap.md @@ -20,50 +20,18 @@ The RadMap.__ShowMiniMap__ property is responsible for showing or hiding the min #### Hide Mini Map -{{source=..\SamplesCS\Map\MapLayers.cs region=HideMiniMap}} -{{source=..\SamplesVB\Map\MapLayers.vb region=HideMiniMap}} -````C# -this.radMap1.ShowMiniMap = false; + + -```` -````VB.NET -Me.RadMap1.ShowMiniMap = False -```` - - - -{{endregion}} The mini map can be also programmatically expanded or collapsed via its __IsCollapsed__ property or the __Expand__ and __Collapse__ methods. #### Expand/Collapse -{{source=..\SamplesCS\Map\MapLayers.cs region=ExpandCollapse}} -{{source=..\SamplesVB\Map\MapLayers.vb region=ExpandCollapse}} -````C# -if (this.radMap1.MapElement.MiniMapElement.IsCollapsed) -{ - this.radMap1.MapElement.MiniMapElement.Expand(); -} -else -{ - this.radMap1.MapElement.MiniMapElement.Collapse(); -} - -```` -````VB.NET -If Me.RadMap1.MapElement.MiniMapElement.IsCollapsed Then - Me.RadMap1.MapElement.MiniMapElement.Expand() -Else - Me.RadMap1.MapElement.MiniMapElement.Collapse() -End If - -```` - - + + -{{endregion}} ## Mini Map Modes diff --git a/controls/map/features/navigation-controls.md b/controls/map/features/navigation-controls.md index 28385d264..a7620642a 100644 --- a/controls/map/features/navigation-controls.md +++ b/controls/map/features/navigation-controls.md @@ -20,19 +20,10 @@ The __RadMap.ShowNavigationBar__ property is responsible for showing or hiding t #### Hide Navigation Bar -{{source=..\SamplesCS\Map\MapLayers.cs region=HideNavigationBar}} -{{source=..\SamplesVB\Map\MapLayers.vb region=HideNavigationBar}} -````C# -this.radMap1.ShowNavigationBar = false; + + -```` -````VB.NET -Me.RadMap1.ShowNavigationBar = False -```` - - -{{endregion}} # Navigation Bar Location diff --git a/controls/map/features/pan-and-zoom.md b/controls/map/features/pan-and-zoom.md index 12a7ab734..bfe02c5fd 100644 --- a/controls/map/features/pan-and-zoom.md +++ b/controls/map/features/pan-and-zoom.md @@ -26,22 +26,10 @@ The control exposes an API for panning and zooming programmatically. The respons ## Customizing Appearance -{{source=..\SamplesCS\Map\MapLayers.cs region=ZoomAndPan}} -{{source=..\SamplesVB\Map\MapLayers.vb region=ZoomAndPan}} -````C# -this.radMap1.Zoom(8, true); -this.radMap1.Pan(new SizeL(200, 200)); + + -```` -````VB.NET -Me.RadMap1.Zoom(8, True) -Me.RadMap1.Pan(New SizeL(200, 200)) -```` - - - -{{endregion}} ## ViewportChanged Event diff --git a/controls/map/features/scale-indicators.md b/controls/map/features/scale-indicators.md index 6c456d91d..74d70abba 100644 --- a/controls/map/features/scale-indicators.md +++ b/controls/map/features/scale-indicators.md @@ -30,32 +30,10 @@ The scaling indicators expose several properties allowing modification of the wa #### Customizing Appearance -{{source=..\SamplesCS\Map\MapLayers.cs region=CustomizeScalingIndicators}} -{{source=..\SamplesVB\Map\MapLayers.vb region=CustomizeScalingIndicators}} -````C# -this.radMap1.MapElement.ScaleIndicatorElement.ImperialBarColor = Color.Red; -this.radMap1.MapElement.ScaleIndicatorElement.MetricBarColor = Color.Blue; -this.radMap1.MapElement.ScaleIndicatorElement.BarHeight = 4; -this.radMap1.MapElement.ScaleIndicatorElement.KilometersText = " км"; -this.radMap1.MapElement.ScaleIndicatorElement.MetersText = " м"; -this.radMap1.MapElement.ScaleIndicatorElement.MilesText = " ми"; -this.radMap1.MapElement.ScaleIndicatorElement.FeetText = " фт"; - -```` -````VB.NET -Me.RadMap1.MapElement.ScaleIndicatorElement.ImperialBarColor = Color.Red -Me.RadMap1.MapElement.ScaleIndicatorElement.MetricBarColor = Color.Blue -Me.RadMap1.MapElement.ScaleIndicatorElement.BarHeight = 4 -Me.RadMap1.MapElement.ScaleIndicatorElement.KilometersText = " км" -Me.RadMap1.MapElement.ScaleIndicatorElement.MetersText = " м" -Me.RadMap1.MapElement.ScaleIndicatorElement.MilesText = " ми" -Me.RadMap1.MapElement.ScaleIndicatorElement.FeetText = " фт" - -```` - - - -{{endregion}} + + + + # See Also diff --git a/controls/map/file-readers/esri-shapefile-reader.md b/controls/map/file-readers/esri-shapefile-reader.md index 27d2e4225..4635b9b8e 100644 --- a/controls/map/file-readers/esri-shapefile-reader.md +++ b/controls/map/file-readers/esri-shapefile-reader.md @@ -22,117 +22,10 @@ You can find the shape file for this example in our [demo application](https://t #### Using ShapeFileReader -{{source=..\SamplesCS\Map\MapFileReaders.cs region=SetupESRIShapeReader}} -{{source=..\SamplesVB\Map\MapFileReaders.vb region=SetupESRIShapeReader}} + + -````C# - -private Font seatsFont = new Font("Arial", 7f, FontStyle.Bold); - -public void SetupESRIShapeReader() -{ - MapLayer pinsLayer = new MapLayer("Hall Layout"); - this.radMap1.Layers.Add(pinsLayer); - EmptyMapProvider emptyProvider = new EmptyMapProvider(); - emptyProvider.MinZoomLevel = 15; - emptyProvider.MaxZoomLevel = 16; - emptyProvider.InitializationComplete += emptyProvider_ESRIInitializationComplete; - - radMap1.Providers.Add(emptyProvider); - using (MemoryStream seatsStream = new MemoryStream(Properties.Resources.theatre_seats_pol)) - { - using (MemoryStream seatsDataStream = new MemoryStream(Properties.Resources.theatre_seats_pol_data)) - { - using (MemoryStream aisleStream = new MemoryStream(Properties.Resources.theatre_aisle_labels)) - { - ShapeFileReaderParameters parameters = new ShapeFileReaderParameters(); - parameters.ShapeStream = seatsStream; - parameters.DbfStream = seatsDataStream; - ShapeFileReader reader = new ShapeFileReader(); - List elements = reader.Read(parameters); - - foreach (MapGeometry element in elements) - { - element.Font = this.seatsFont; - element.ForeColor = Color.White; - element.Text = "$[CAPTION]"; - element.BackColor = Color.FromArgb( - Convert.ToInt32(element.ExtendedData.GetValue("RGB0")), - Convert.ToInt32(element.ExtendedData.GetValue("RGB1")), - Convert.ToInt32(element.ExtendedData.GetValue("RGB2"))); - element.BorderWidth = 0; - } - - this.radMap1.Layers["Hall Layout"].AddRange(elements); - - parameters = new ShapeFileReaderParameters(); - parameters.ShapeStream = aisleStream; - elements = reader.Read(parameters); - this.radMap1.Layers["Hall Layout"].AddRange(elements); - } - } - } -} - -private void emptyProvider_ESRIInitializationComplete(object sender, EventArgs e) -{ - List locations = new List(); - - foreach (MapVisualElement el in this.radMap1.Layers["Hall Layout"].Overlays) - { - locations.Add(el.Location); - } - - this.radMap1.BringIntoView(Telerik.WinControls.UI.Map.RectangleG.GetBoundingRectangle(locations)); -} -```` -````VB.NET -Private seatsFont As New Font("Arial", 7.0F, FontStyle.Bold) -Public Sub SetupESRIShapeReader() - Dim pinsLayer As New MapLayer("Hall Layout") - Me.radMap1.Layers.Add(pinsLayer) - Dim emptyProvider As New EmptyMapProvider() - emptyProvider.MinZoomLevel = 15 - emptyProvider.MaxZoomLevel = 16 - AddHandler emptyProvider.InitializationComplete, AddressOf emptyProvider_ESRIInitializationComplete - radMap1.Providers.Add(emptyProvider) - Using seatsStream As New MemoryStream(My.Resources.theatre_seats_pol) - Using seatsDataStream As New MemoryStream(My.Resources.theatre_seats_pol_data) - Using aisleStream As New MemoryStream(My.Resources.theatre_aisle_labels) - Dim parameters As New ShapeFileReaderParameters() - parameters.ShapeStream = seatsStream - parameters.DbfStream = seatsDataStream - Dim reader As New ShapeFileReader() - Dim elements As List(Of MapVisualElement) = reader.Read(parameters) - For Each element As MapGeometry In elements - element.Font = Me.seatsFont - element.ForeColor = Color.White - element.Text = "$[CAPTION]" - element.BackColor = Color.FromArgb(Convert.ToInt32(element.ExtendedData.GetValue("RGB0")), _ - Convert.ToInt32(element.ExtendedData.GetValue("RGB1")), Convert.ToInt32(element.ExtendedData.GetValue("RGB2"))) - element.BorderWidth = 0 - Next - Me.radMap1.Layers("Hall Layout").AddRange(elements) - parameters = New ShapeFileReaderParameters() - parameters.ShapeStream = aisleStream - elements = reader.Read(parameters) - Me.radMap1.Layers("Hall Layout").AddRange(elements) - End Using - End Using - End Using -End Sub -Private Sub emptyProvider_ESRIInitializationComplete(sender As Object, e As EventArgs) - Dim locations As New List(Of Telerik.WinControls.UI.Map.PointG)() - For Each el As MapVisualElement In Me.radMap1.Layers("Hall Layout").Overlays - locations.Add(el.Location) - Next - Me.radMap1.BringIntoView(Telerik.WinControls.UI.Map.RectangleG.GetBoundingRectangle(locations)) -End Sub - -```` - -{{endregion}} # See Also * [Shapefile](https://en.wikipedia.org/wiki/Shapefile) diff --git a/controls/map/file-readers/kml-reader.md b/controls/map/file-readers/kml-reader.md index d5c9027a8..47e8d6f12 100644 --- a/controls/map/file-readers/kml-reader.md +++ b/controls/map/file-readers/kml-reader.md @@ -20,44 +20,9 @@ To read your data you have to use a __KmlReader__. #### Using KmlReader -{{source=..\SamplesCS\Map\MapFileReaders.cs region=SetupKMLReader}} -{{source=..\SamplesVB\Map\MapFileReaders.vb region=SetupKMLReader}} - -````C# - -OpenStreetMapProvider osmProvider = new OpenStreetMapProvider(); -this.radMap1.MapElement.Providers.Add(osmProvider); -this.radMap1.Layers.Clear(); -this.radMap1.Layers.Add(new MapLayer("Capitals")); -using (FileStream seatsStream = new FileStream(@"..\..\Resources\cb_2015_us_county_5m.kml", FileMode.Open, FileAccess.Read)) -{ -List elements = KmlReader.Read(seatsStream); -foreach (MapVisualElement item in elements) -{ -item.BorderWidth = 1; -item.BorderColor = Color.Red; -} - this.radMap1.Layers["Capitals"].AddRange(elements); -} - -```` -````VB.NET -Dim osmProvider As New OpenStreetMapProvider() -Me.radMap1.MapElement.Providers.Add(osmProvider) -Me.radMap1.Layers.Clear() -Me.radMap1.Layers.Add(New MapLayer("Capitals")) -Using seatsStream As New FileStream("..\..\Resources\cb_2015_us_county_5m.kml", FileMode.Open, FileAccess.Read) - Dim elements As List(Of MapVisualElement) = KmlReader.Read(seatsStream) - For Each item As MapVisualElement In elements - item.BorderWidth = 1 - item.BorderColor = Color.Red - Next - Me.radMap1.Layers("Capitals").AddRange(elements) -End Using - -```` - -{{endregion}} + + + # Using local images diff --git a/controls/map/file-readers/sql-geospatial-reader.md b/controls/map/file-readers/sql-geospatial-reader.md index f2320d644..b8a6d391c 100644 --- a/controls/map/file-readers/sql-geospatial-reader.md +++ b/controls/map/file-readers/sql-geospatial-reader.md @@ -19,51 +19,10 @@ __SqlGeospatialDataReader__ allows generating map shapes from any IEnumerable in #### Using SqlGeospatialDataReader -{{source=..\SamplesCS\Map\MapFileReaders.cs region=SetupSQLGeospatialReader}} -{{source=..\SamplesVB\Map\MapFileReaders.vb region=SetupSQLGeospatialReader}} + + -````C# - -OpenStreetMapProvider osmProvider = new OpenStreetMapProvider(); -this.radMap1.Providers.Add(osmProvider); -MapLayer layer = new MapLayer("Capitals"); -this.radMap1.Layers.Add(layer); - -BindingSource source = new BindingSource(); -source.DataSource = dt; - -SqlGeospatialDataReader datareader = new SqlGeospatialDataReader(); -datareader.Source = source; -datareader.GeospatialPropertyName = "Geometry"; - -List elements = datareader.Read(source, "Geometry", true, null); -foreach (var item in elements) -{ - item.BorderColor = Color.YellowGreen; -} - -this.radMap1.Layers["Capitals"].AddRange(elements); -```` -````VB.NET -Dim osmProvider As New OpenStreetMapProvider() -Me.radMap1.Providers.Add(osmProvider) -Dim layer As New MapLayer("Capitals") -Me.radMap1.Layers.Add(layer) -Dim source As New BindingSource() -source.DataSource = dt -Dim datareader As New SqlGeospatialDataReader() -datareader.Source = source -datareader.GeospatialPropertyName = "Geometry" -Dim elements As List(Of MapVisualElement) = datareader.Read(source, "Geometry", True, Nothing) -For Each item As MapVisualElement In elements - item.BorderColor = Color.YellowGreen -Next -Me.radMap1.Layers("Capitals").AddRange(elements) - -```` - -{{endregion}} >caption Figure 2: Sample Data Table diff --git a/controls/map/getting-started.md b/controls/map/getting-started.md index 64b870129..761dfe785 100644 --- a/controls/map/getting-started.md +++ b/controls/map/getting-started.md @@ -52,31 +52,10 @@ If you want to use data caching, you should set an __IMapCacheProvider__ instanc #### Using BingRestMapProvider -{{source=..\SamplesCS\Map\MapGettingStarted.cs region=GettingStarted}} -{{source=..\SamplesVB\Map\MapGettingStarted.vb region=GettingStarted}} - -````C# -string cacheFolder = @"..\..\cache"; -BingRestMapProvider bingProvider = new Telerik.WinControls.UI.BingRestMapProvider(); -bingProvider.UseSession = true; -bingProvider.BingKey = bingKey; -LocalFileCacheProvider cache = new LocalFileCacheProvider(cacheFolder); -bingProvider.CacheProvider = cache; -this.radMap1.Providers.Add(bingProvider); - -```` -````VB.NET -Dim cacheFolder As String = "..\..\cache" -Dim bingProvider As BingRestMapProvider = New Telerik.WinControls.UI.BingRestMapProvider() -bingProvider.UseSession = True -bingProvider.BingKey = bingKey -Dim cache As New LocalFileCacheProvider(cacheFolder) -bingProvider.CacheProvider = cache -Me.radMap1.Providers.Add(bingProvider) - -```` - -{{endregion}} + + + + >caption Figure 1: RadMap diff --git a/controls/map/how-to/adding-pins-and-drawing-regions.md b/controls/map/how-to/adding-pins-and-drawing-regions.md index f8241805d..291681085 100644 --- a/controls/map/how-to/adding-pins-and-drawing-regions.md +++ b/controls/map/how-to/adding-pins-and-drawing-regions.md @@ -24,143 +24,19 @@ A common requirement for applications utilizing a map control is to allow the en #### Setup Provider -{{source=..\SamplesCS\Map\DrawRegionsForm.cs region=SetupProvider}} -{{source=..\SamplesVB\Map\DrawRegionsForm.vb region=SetupProvider}} -````C# -BingRestMapProvider bingProvider = new BingRestMapProvider(); -bingProvider.ImagerySet = ImagerySet.Road; -bingProvider.UseSession = true; -bingProvider.BingKey = this.bingKey; -bingProvider.InitializationComplete += delegate (object sender, EventArgs e) -{ - this.radMap1.BringIntoView(new PointG(40d, -99d), 4); -}; -LocalFileCacheProvider cache = new LocalFileCacheProvider(Path.Combine(Path.GetTempPath(), "cache")); -bingProvider.CacheProvider = cache; -this.radMap1.MapElement.Providers.Add(bingProvider); -MapLayer pinsLayer = new MapLayer("Pins"); -this.radMap1.Layers.Add(pinsLayer); -this.radMap1.InputBehavior = new CustomMapInputBehavior(); - -```` -````VB.NET -Dim bingProvider As New BingRestMapProvider() -bingProvider.ImagerySet = ImagerySet.Road -bingProvider.UseSession = True -bingProvider.BingKey = Me.bingKey -AddHandler bingProvider.InitializationComplete, Sub(sender As Object, e As EventArgs) Me.radMap1.BringIntoView(New PointG(40.0, -99.0), 4) -Dim cache As New LocalFileCacheProvider(Path.Combine(Path.GetTempPath(), "cache")) -bingProvider.CacheProvider = cache -Me.radMap1.MapElement.Providers.Add(bingProvider) -Dim pinsLayer As New MapLayer("Pins") -Me.radMap1.Layers.Add(pinsLayer) -Me.radMap1.InputBehavior = New CustomMapInputBehavior() - -```` - - - -{{endregion}} + + + + In our custom implementation, we will add pins as long as their count is less than three, from then on each double click on the map while holding the *Ctrl* key will result in drawing a region enclosing all of the added points. #### CustomMapInputBehavior Implementation -{{source=..\SamplesCS\Map\DrawRegionsForm.cs region=CustomMapInputBehaviorImplementation}} -{{source=..\SamplesVB\Map\DrawRegionsForm.vb region=CustomMapInputBehaviorImplementation}} -````C# -public class CustomMapInputBehavior : MapInputBehavior -{ - public override void OnDoubleClick(EventArgs e) - { - MouseEventArgs args = e as MouseEventArgs; - if (args.Button == MouseButtons.Left && Control.ModifierKeys == Keys.Control) - { - PointL point = new PointL(args.X - this.MapElement.PanOffset.Width, args.Y - this.MapElement.PanOffset.Height); - PointG location = MapTileSystemHelper.PixelXYToLatLong(point.X, point.Y, this.MapElement.ZoomLevel); - while (location.Longitude > 180) - { - location.Longitude -= 360; - } - if (this.MapElement.Layers[0].Overlays.Count > 1 || (this.MapElement.Layers[0].Overlays.Count > 0 && this.MapElement.Layers[0].Overlays[0] is MapPolygon)) - { - List points = new List(); - foreach (MapVisualElement element in this.MapElement.Layers[0].Overlays) - { - MapPin pin = element as MapPin; - if (pin != null) - { - points.Add(element.Location); - } - MapPolygon pol = element as MapPolygon; - if (pol != null) - { - points.AddRange(pol.OuterBoundary); - } - } - points.Add(location); - this.MapElement.Layers[0].Clear(); - MapPolygon polygon = new MapPolygon(points); - polygon.BackColor = Color.FromArgb(125, Color.LightGreen); - this.MapElement.Layers[0].Add(polygon); - } - else - { - MapPin pin = new MapPin(location); - this.MapElement.Layers[0].Add(pin); - } - } - else - { - base.OnDoubleClick(e); - } - } -} - -```` -````VB.NET -Public Class CustomMapInputBehavior - Inherits MapInputBehavior - Public Overrides Sub OnDoubleClick(e As EventArgs) - Dim args As MouseEventArgs = TryCast(e, MouseEventArgs) - If args.Button = MouseButtons.Left AndAlso Control.ModifierKeys = Keys.Control Then - Dim point As New PointL(args.X - Me.MapElement.PanOffset.Width, args.Y - Me.MapElement.PanOffset.Height) - Dim location As PointG = MapTileSystemHelper.PixelXYToLatLong(point.X, point.Y, Me.MapElement.ZoomLevel) - While location.Longitude > 180 - location.Longitude -= 360 - End While - If Me.MapElement.Layers(0).Overlays.Count > 1 OrElse (Me.MapElement.Layers(0).Overlays.Count > 0 AndAlso TypeOf Me.MapElement.Layers(0).Overlays(0) Is MapPolygon) Then - Dim points As New List(Of PointG)() - For Each element As MapVisualElement In Me.MapElement.Layers(0).Overlays - Dim pin As MapPin = TryCast(element, MapPin) - If pin IsNot Nothing Then - points.Add(element.Location) - End If - Dim pol As MapPolygon = TryCast(element, MapPolygon) - If pol IsNot Nothing Then - points.AddRange(pol.OuterBoundary) - End If - Next - points.Add(location) - Me.MapElement.Layers(0).Clear() - Dim polygon As New MapPolygon(points) - polygon.BackColor = Color.FromArgb(125, Color.LightGreen) - Me.MapElement.Layers(0).Add(polygon) - Else - Dim pin As New MapPin(location) - Me.MapElement.Layers(0).Add(pin) - End If - Else - MyBase.OnDoubleClick(e) - End If - End Sub -End Class - -```` - - - -{{endregion}} + + + + # See Also diff --git a/controls/map/localization.md b/controls/map/localization.md index 52bd44f2f..aeaa3d9d5 100644 --- a/controls/map/localization.md +++ b/controls/map/localization.md @@ -20,93 +20,17 @@ Below is a sample implementation of an English localization provider: #### Localizing RadMap's Strings -{{source=..\SamplesCS\Map\MapLocalization.cs region=LocalizeText}} -{{source=..\SamplesVB\Map\MapLocalization.vb region=LocalizeText}} + + -````C# - -public class EnglishMapLocalizationProvider : Telerik.WinControls.UI.Localization.RadMapLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case RadMapStringId.SearchBarNullText: - return "Search"; - case RadMapStringId.ScaleIndicatorMiles: - return "mi"; - case RadMapStringId.ScaleIndicatorKilometers: - return "km"; - case RadMapStringId.ScaleIndicatorFeet: - return "ft"; - case RadMapStringId.ScaleIndicatorMeters: - return "m"; - case RadMapStringId.BingMapsAerialView: - return "Aerial"; - case RadMapStringId.BingMapsRoadView: - return "Road"; - case RadMapStringId.NavigationBarShowViewLabels: - return "Show labels"; - } - - return string.Empty; - } -} -```` -````VB.NET -Public Class EnglishMapLocalizationProvider - Inherits Telerik.WinControls.UI.Localization.RadMapLocalizationProvider - Public Overrides Function GetLocalizedString(id As String) As String - Select Case id - Case RadMapStringId.SearchBarNullText - Return "Search" - Case RadMapStringId.ScaleIndicatorMiles - Return "mi" - Case RadMapStringId.ScaleIndicatorKilometers - Return "km" - Case RadMapStringId.ScaleIndicatorFeet - Return "ft" - Case RadMapStringId.ScaleIndicatorMeters - Return "m" - Case RadMapStringId.BingMapsAerialView - Return "Aerial" - Case RadMapStringId.BingMapsRoadView - Return "Road" - Case RadMapStringId.NavigationBarShowViewLabels - Return "Show labels" - End Select - Return String.Empty - End Function -End Class - -```` - -{{endregion}} To apply the custom localization provider, instantiate and assign it to the current localization provider: #### Assigning the Current Localization Provider -{{source=..\SamplesCS\Map\MapLocalization.cs region=SetMapLocalization}} -{{source=..\SamplesVB\Map\MapLocalization.vb region=SetMapLocalization}} - -````C# - -public MapLocalization() -{ - Telerik.WinControls.UI.Localization.RadMapLocalizationProvider.CurrentProvider = new EnglishMapLocalizationProvider(); - InitializeComponent(); -} + + -```` -````VB.NET -Public Sub New() - Telerik.WinControls.UI.Localization.RadMapLocalizationProvider.CurrentProvider = New EnglishMapLocalizationProvider() - InitializeComponent() -End Sub -```` -{{endregion}} - diff --git a/controls/map/map-factory.md b/controls/map/map-factory.md index 0213a700d..f7650b34a 100644 --- a/controls/map/map-factory.md +++ b/controls/map/map-factory.md @@ -14,115 +14,9 @@ position: 2 If you need to customize any of these elements you can use the **MapVisualElementFactory** class. It allows you to replace the default elements with custom ones. This can be achieved by creating a **MapVisualElementFactory** descendant class and overriding one of the following methods according to the element you want to replace. Then, set the static RadMapElement.**VisualElementFactory** property before starting the usage of **RadMap**. -{{source=..\SamplesCS\Map\CustomMapFactory.cs region=MyMapProvider}} -{{source=..\SamplesVB\Map\CustomMapFactory.vb region=MyMapProvider}} + + -````C# - -public partial class CustomMapFactory : Form -{ - public CustomMapFactory() - { - InitializeComponent(); - - //Specify the map factory - RadMapElement.VisualElementFactory = new MyMapVisualElementFactory(); - - //Specify the map provider - string cacheFolder = @"C:\cache"; - OpenStreetMapProvider osmProvider = new OpenStreetMapProvider(); - LocalFileCacheProvider cache = new LocalFileCacheProvider(cacheFolder); - osmProvider.CacheProvider = cache; - this.radMap1.MapElement.Providers.Add(osmProvider); - } -} - -public class MyMapVisualElementFactory : MapVisualElementFactory -{ - public override MapVisualElement CreatePoint(Telerik.WinControls.UI.Map.PointG location) - { - return base.CreatePoint(location); - } - - public override MapVisualElement CreatePolyline(System.Collections.ObjectModel.Collection points) - { - MapPolyline polyline = new MapPolyline(points); - - return polyline; - } - - public override MapVisualElement CreatePolygon(System.Collections.ObjectModel.Collection points) - { - MapPolygon polygon = new MapPolygon(points); - - return polygon; - } - - public override MapVisualElement CreatePath(System.Collections.ObjectModel.Collection> points) - { - MapPath path = new MapPath(points); - - return path; - } - - public override MapCluster CreateCluster() - { - MapCluster cluster = new MapCluster(); - - return cluster; - } - - public override MapTile CreateTile(Image image, Rectangle rectangle) - { - MapTile tile = new MapTile(image, rectangle); - - return tile; - } -} - -```` -````VB.NET -Sub New() - InitializeComponent() - 'Specify the map factory - RadMapElement.VisualElementFactory = New MyMapVisualElementFactory() - 'Specify the map provider - Dim cacheFolder As String = "C:\cache" - Dim osmProvider As OpenStreetMapProvider = New OpenStreetMapProvider() - Dim cache As LocalFileCacheProvider = New LocalFileCacheProvider(cacheFolder) - osmProvider.CacheProvider = cache - Me.RadMap1.MapElement.Providers.Add(osmProvider) -End Sub -Public Class MyMapVisualElementFactory - Inherits MapVisualElementFactory - Public Overrides Function CreatePoint(ByVal location As Telerik.WinControls.UI.Map.PointG) As MapVisualElement - Return MyBase.CreatePoint(location) - End Function - Public Overrides Function CreatePolyline(ByVal points As System.Collections.ObjectModel.Collection(Of Telerik.WinControls.UI.Map.PointG)) As MapVisualElement - Dim polyline As MapPolyline = New MapPolyline(points) - Return polyline - End Function - Public Overrides Function CreatePolygon(ByVal points As System.Collections.ObjectModel.Collection(Of Telerik.WinControls.UI.Map.PointG)) As MapVisualElement - Dim polygon As MapPolygon = New MapPolygon(points) - Return polygon - End Function - Public Overrides Function CreatePath(ByVal points As System.Collections.ObjectModel.Collection(Of System.Collections.ObjectModel.Collection(Of Telerik.WinControls.UI.Map.PointG))) As MapVisualElement - Dim path As MapPath = New MapPath(points) - Return path - End Function - Public Overrides Function CreateCluster() As MapCluster - Dim cluster As MapCluster = New MapCluster() - Return cluster - End Function - Public Overrides Function CreateTile(ByVal image As Image, ByVal rectangle As Rectangle) As MapTile - Dim tile As MapTile = New MapTile(image, rectangle) - Return tile - End Function -End Class - -```` - -{{endregion}} # See Also diff --git a/controls/map/providers/azure-map/azuremapprovider.md b/controls/map/providers/azure-map/azuremapprovider.md index 82a962b58..4ddaf89f3 100644 --- a/controls/map/providers/azure-map/azuremapprovider.md +++ b/controls/map/providers/azure-map/azuremapprovider.md @@ -44,10 +44,6 @@ provider.CacheProvider = cache Me.radMap1.Providers.Add(provider) ```` - -{{endregion}} - - ## Language The Azure Maps services provide a culture parameter in its URL address and the AzureMapProvider allows you to utilize it. To do so, set the `LanguageCulture` property to the desired culture string. diff --git a/controls/map/providers/bingmaps/bingrestmapprovider.md b/controls/map/providers/bingmaps/bingrestmapprovider.md index 2227dd57f..33bcfb416 100644 --- a/controls/map/providers/bingmaps/bingrestmapprovider.md +++ b/controls/map/providers/bingmaps/bingrestmapprovider.md @@ -25,33 +25,10 @@ __RadMap__ can visualize tile data from the [Bing Maps](https://www.bingmapsport #### Using BingRestMapProvider -{{source=..\SamplesCS\Map\MapGettingStarted.cs region=GettingStarted}} -{{source=..\SamplesVB\Map\MapGettingStarted.vb region=GettingStarted}} + + -````C# -string cacheFolder = @"..\..\cache"; -BingRestMapProvider bingProvider = new Telerik.WinControls.UI.BingRestMapProvider(); -bingProvider.UseSession = true; -bingProvider.BingKey = bingKey; -LocalFileCacheProvider cache = new LocalFileCacheProvider(cacheFolder); -bingProvider.CacheProvider = cache; -this.radMap1.Providers.Add(bingProvider); - -```` -````VB.NET - -Dim cacheFolder As String = "..\..\cache" -Dim bingProvider As BingRestMapProvider = New Telerik.WinControls.UI.BingRestMapProvider() -bingProvider.UseSession = True -bingProvider.BingKey = bingKey -Dim cache As New LocalFileCacheProvider(cacheFolder) -bingProvider.CacheProvider = cache -Me.radMap1.Providers.Add(bingProvider) - -```` - -{{endregion}} >note If you use __RadMap__ with .Net Framework 2.0 and you don't have an installation of the Telerik UI for WinForms suite on the current machine, it is necessary to add a reference to the Newtonsoft.Json assembly which can be found in the \Bin folder of the *Telerik_UI_For_WinForms_[version]_Dev_dlls.zip*. If you are using .Net Framework 4.0 this is not required. diff --git a/controls/map/providers/bingmaps/elevation/bounds.md b/controls/map/providers/bingmaps/elevation/bounds.md index 3cdf7541f..c8ea29ecc 100644 --- a/controls/map/providers/bingmaps/elevation/bounds.md +++ b/controls/map/providers/bingmaps/elevation/bounds.md @@ -20,180 +20,10 @@ ElevationType.*Bounds* __ElevationRequest__ gets elevations at equally-spaced lo #### Bounds ElevationType request -{{source=..\SamplesCS\Map\BingProvider.cs region=BoundsElevationRequest}} -{{source=..\SamplesVB\Map\BingProvider.vb region=BoundsElevationRequest}} + + -````C# -ElevationRequest boundsRequest = new ElevationRequest(); - -public void SetupElevationRequest() -{ - //add pins to the map - Telerik.WinControls.UI.Map.PointG point1 = new Telerik.WinControls.UI.Map.PointG(36.114647, -115.172813); - Telerik.WinControls.UI.Map.PointG point2 = new Telerik.WinControls.UI.Map.PointG(34.05223, -118.24368); - Telerik.WinControls.UI.Map.PointG point3 = new Telerik.WinControls.UI.Map.PointG(37.77493, -122.41942); - MapPin pin1 = new MapPin(point1); - MapPin pin2 = new MapPin(point2); - MapPin pin3 = new MapPin(point3); - - MapLayer pinsLayer = new MapLayer("Pins"); - this.radMap1.Layers.Add(pinsLayer); - - MapLayer calloutsLayer = new MapLayer("Callouts"); - this.radMap1.Layers.Add(calloutsLayer); - this.radMap1.Layers["Pins"].Add(pin1); - this.radMap1.Layers["Pins"].Add(pin2); - this.radMap1.Layers["Pins"].Add(pin3); - - boundsRequest.ElevationType = ElevationType.Bounds; - boundsRequest.Bounds = Telerik.WinControls.UI.Map.RectangleG.GetBoundingRectangle(new List() - { - point1, - point2, - point3 - }); - boundsRequest.Rows = 2; - boundsRequest.Columns = 3; - - BingRestMapProvider bingProvider = this.radMap1.Providers[0] as BingRestMapProvider; - bingProvider.CalculateElevationCompleted += BingProviderBounds_CalculateBoundsElevationCompleted; - bingProvider.CalculateElevationAsync(boundsRequest); -} - -private void BingProviderBounds_CalculateBoundsElevationCompleted(object sender, ElevationCompletedEventArgs e) -{ - List points = new List(); - - for (int i = 0; i < this.radMap1.Layers["Pins"].Overlays.Count; i++) - { - MapPin pin = this.radMap1.Layers["Pins"].Overlays[i] as MapPin; - - if (pin != null) - { - points.Add(pin.Location); - } - } - this.radMap1.Layers["Pins"].Clear(); - - Telerik.WinControls.UI.Map.RectangleG rect = Telerik.WinControls.UI.Map.RectangleG.GetBoundingRectangle(points); - Telerik.WinControls.UI.Map.PointG[,] p = this.CalculateEquidistantPointsInRectangle(rect, this.radMap1.MapElement.ZoomLevel, - boundsRequest.Rows, boundsRequest.Columns); - - int rows = p.GetLength(0); - int flatIndex = 0; - - for (int i = p.GetLength(0) - 1; i >= 0; i--) - { - for (int j = 0; j < p.GetLength(1); j++) - { - MapPoint point = new MapPoint(p[i, j]); - this.radMap1.Layers["Callouts"].Add(point); - - MapCallout callout = new MapCallout(point); - callout.MaxWidth = 50; - callout.Text = e.Elevations[0].Elevations[flatIndex++].ToString() + "m"; - this.radMap1.Layers["Callouts"].Add(callout); - } - } -} - -private Telerik.WinControls.UI.Map.PointG[,] CalculateEquidistantPointsInRectangle(Telerik.WinControls.UI.Map.RectangleG rect, int zoomLevel, int rows, int columns) -{ - Telerik.WinControls.UI.Map.PointL topLeft = MapTileSystemHelper.LatLongToPixelXY(rect.North, rect.West, zoomLevel); - Telerik.WinControls.UI.Map.PointL bottomRight = MapTileSystemHelper.LatLongToPixelXY(rect.South, rect.East, zoomLevel); - Telerik.WinControls.UI.Map.RectangleL rectangle = new Telerik.WinControls.UI.Map.RectangleL(topLeft, - new Telerik.WinControls.UI.Map.SizeL(bottomRight.X - topLeft.X, bottomRight.Y - topLeft.Y)); - - Telerik.WinControls.UI.Map.PointG[,] result = new Telerik.WinControls.UI.Map.PointG[rows, columns]; - double xStep = (double)rectangle.Width / (columns - 1); - double yStep = (double)rectangle.Height / (rows - 1); - - for (int i = 0; i < rows; i++) - { - for (int j = 0; j < columns; j++) - { - Telerik.WinControls.UI.Map.PointL point = new Telerik.WinControls.UI.Map.PointL((long)Math.Round(rectangle.X + j * xStep, MidpointRounding.AwayFromZero), - (long)Math.Round(rectangle.Y + i * yStep, MidpointRounding.AwayFromZero)); - result[i, j] = MapTileSystemHelper.PixelXYToLatLong(point, zoomLevel); - } - } - - return result; -} -```` -````VB.NET -Private boundsRequest As New ElevationRequest() -Public Sub SetupElevationRequest() - 'add pins to the map - Dim point1 As New Telerik.WinControls.UI.Map.PointG(36.114647, -115.172813) - Dim point2 As New Telerik.WinControls.UI.Map.PointG(34.05223, -118.24368) - Dim point3 As New Telerik.WinControls.UI.Map.PointG(37.77493, -122.41942) - Dim pin1 As New MapPin(point1) - Dim pin2 As New MapPin(point2) - Dim pin3 As New MapPin(point3) - Dim pinsLayer As New MapLayer("Pins") - Me.radMap1.Layers.Add(pinsLayer) - Dim calloutsLayer As New MapLayer("Callouts") - Me.radMap1.Layers.Add(calloutsLayer) - Me.radMap1.Layers("Pins").Add(pin1) - Me.radMap1.Layers("Pins").Add(pin2) - Me.radMap1.Layers("Pins").Add(pin3) - boundsRequest.ElevationType = ElevationType.Bounds - boundsRequest.Bounds = Telerik.WinControls.UI.Map.RectangleG.GetBoundingRectangle(New List(Of Telerik.WinControls.UI.Map.PointG)() From { _ - point1, _ - point2, _ - point3 _ - }) - boundsRequest.Rows = 2 - boundsRequest.Columns = 3 - Dim bingProvider As BingRestMapProvider = TryCast(Me.radMap1.Providers(0), BingRestMapProvider) - AddHandler bingProvider.CalculateElevationCompleted, AddressOf BingProviderBounds_CalculateBoundsElevationCompleted - bingProvider.CalculateElevationAsync(boundsRequest) -End Sub -Private Sub BingProviderBounds_CalculateBoundsElevationCompleted(sender As Object, e As ElevationCompletedEventArgs) - Dim points As New List(Of Telerik.WinControls.UI.Map.PointG)() - For i As Integer = 0 To Me.radMap1.Layers("Pins").Overlays.Count - 1 - Dim pin As MapPin = TryCast(Me.radMap1.Layers("Pins").Overlays(i), MapPin) - If pin IsNot Nothing Then - points.Add(pin.Location) - End If - Next - Me.radMap1.Layers("Pins").Clear() - Dim rect As Telerik.WinControls.UI.Map.RectangleG = Telerik.WinControls.UI.Map.RectangleG.GetBoundingRectangle(points) - Dim p As Telerik.WinControls.UI.Map.PointG(,) = Me.CalculateEquidistantPointsInRectangle(rect, Me.radMap1.MapElement.ZoomLevel, boundsRequest.Rows, boundsRequest.Columns) - Dim rows As Integer = p.GetLength(0) - Dim flatIndex As Integer = 0 - For i As Integer = p.GetLength(0) - 1 To 0 Step -1 - For j As Integer = 0 To p.GetLength(1) - 1 - Dim point As New MapPoint(p(i, j)) - Me.radMap1.Layers("Callouts").Add(point) - Dim callout As New MapCallout(point) - callout.MaxWidth = 50 - callout.Text = e.Elevations(0).Elevations(System.Math.Max(System.Threading.Interlocked.Increment(flatIndex), flatIndex - 1)).ToString() + "m" - Me.radMap1.Layers("Callouts").Add(callout) - Next - Next -End Sub -Private Function CalculateEquidistantPointsInRectangle(rect As Telerik.WinControls.UI.Map.RectangleG, zoomLevel As Integer, rows As Integer, columns As Integer) As Telerik.WinControls.UI.Map.PointG(,) - Dim topLeft As Telerik.WinControls.UI.Map.PointL = MapTileSystemHelper.LatLongToPixelXY(rect.North, rect.West, zoomLevel) - Dim bottomRight As Telerik.WinControls.UI.Map.PointL = MapTileSystemHelper.LatLongToPixelXY(rect.South, rect.East, zoomLevel) - Dim rectangle As New Telerik.WinControls.UI.Map.RectangleL(topLeft, New Telerik.WinControls.UI.Map.SizeL(bottomRight.X - topLeft.X, bottomRight.Y - topLeft.Y)) - Dim result As Telerik.WinControls.UI.Map.PointG(,) = New Telerik.WinControls.UI.Map.PointG(rows - 1, columns - 1) {} - Dim xStep As Double = CDbl(rectangle.Width) / (columns - 1) - Dim yStep As Double = CDbl(rectangle.Height) / (rows - 1) - For i As Integer = 0 To rows - 1 - For j As Integer = 0 To columns - 1 - Dim point As New Telerik.WinControls.UI.Map.PointL(CLng(Math.Round(rectangle.X + j * xStep, MidpointRounding.AwayFromZero)), CLng(Math.Round(rectangle.Y + i * yStep, MidpointRounding.AwayFromZero))) - result(i, j) = MapTileSystemHelper.PixelXYToLatLong(point, zoomLevel) - Next - Next - Return result -End Function - -```` - -{{endregion}} # See Also * [Bing Elevation](https://msdn.microsoft.com/en-us/library/jj158961.aspx) diff --git a/controls/map/providers/bingmaps/elevation/list.md b/controls/map/providers/bingmaps/elevation/list.md index 7d00d8525..5b7e9b6a5 100644 --- a/controls/map/providers/bingmaps/elevation/list.md +++ b/controls/map/providers/bingmaps/elevation/list.md @@ -20,101 +20,10 @@ ElevationType.*List* __ElevationRequest__ gets elevations for latitude and longi #### List ElevationType request -{{source=..\SamplesCS\Map\BingProvider.cs region=ListElevationRequest}} -{{source=..\SamplesVB\Map\BingProvider.vb region=ListElevationRequest}} + + -````C# - -public void SetupListElevationRequest() -{ - //add pins to the map - Telerik.WinControls.UI.Map.PointG point1 = new Telerik.WinControls.UI.Map.PointG(36.114647, -115.172813); - Telerik.WinControls.UI.Map.PointG point2 = new Telerik.WinControls.UI.Map.PointG(34.05223, -118.24368); - Telerik.WinControls.UI.Map.PointG point3 = new Telerik.WinControls.UI.Map.PointG(37.77493, -122.41942); - MapPin pin1 = new MapPin(point1); - MapPin pin2 = new MapPin(point2); - MapPin pin3 = new MapPin(point3); - - MapLayer pinsLayer = new MapLayer("Pins"); - this.radMap1.Layers.Add(pinsLayer); - - MapLayer calloutsLayer = new MapLayer("Callouts"); - this.radMap1.Layers.Add(calloutsLayer); - this.radMap1.Layers["Pins"].Add(pin1); - this.radMap1.Layers["Pins"].Add(pin2); - this.radMap1.Layers["Pins"].Add(pin3); - - ElevationRequest request = new ElevationRequest(); - request.ElevationType = ElevationType.List; - request.Points = new List() - { - point1, - point2, - point3 - }; - BingRestMapProvider bingProvider = this.radMap1.Providers[0] as BingRestMapProvider; - bingProvider.CalculateElevationCompleted += BingProvider_CalculateElevationCompleted; - bingProvider.CalculateElevationAsync(request); -} - -private void BingProvider_CalculateElevationCompleted(object sender, ElevationCompletedEventArgs e) -{ - for (int i = 0; i < this.radMap1.Layers["Pins"].Overlays.Count; i++) - { - MapPin pin = this.radMap1.Layers["Pins"].Overlays[i] as MapPin; - if (pin != null) - { - MapCallout callout = new MapCallout(pin); - callout.MaxWidth = 50; - callout.Text = e.Elevations[0].Elevations[i].ToString() + "m"; - this.radMap1.Layers["Callouts"].Add(callout); - } - } -} -```` -````VB.NET -Public Sub SetupListElevationRequest() - 'add pins to the map - Dim point1 As New Telerik.WinControls.UI.Map.PointG(36.114647, -115.172813) - Dim point2 As New Telerik.WinControls.UI.Map.PointG(34.05223, -118.24368) - Dim point3 As New Telerik.WinControls.UI.Map.PointG(37.77493, -122.41942) - Dim pin1 As New MapPin(point1) - Dim pin2 As New MapPin(point2) - Dim pin3 As New MapPin(point3) - Dim pinsLayer As New MapLayer("Pins") - Me.radMap1.Layers.Add(pinsLayer) - Dim calloutsLayer As New MapLayer("Callouts") - Me.radMap1.Layers.Add(calloutsLayer) - Me.radMap1.Layers("Pins").Add(pin1) - Me.radMap1.Layers("Pins").Add(pin2) - Me.radMap1.Layers("Pins").Add(pin3) - Dim request As New ElevationRequest() - request.ElevationType = ElevationType.List - request.Points = New List(Of Telerik.WinControls.UI.Map.PointG)() From { _ - point1, _ - point2, _ - point3 _ - } - Dim bingProvider As BingRestMapProvider = TryCast(Me.radMap1.Providers(0), BingRestMapProvider) - AddHandler bingProvider.CalculateElevationCompleted, AddressOf BingProvider_CalculateElevationCompleted - bingProvider.CalculateElevationAsync(request) -End Sub -Private Sub BingProvider_CalculateElevationCompleted(sender As Object, e As ElevationCompletedEventArgs) - For i As Integer = 0 To Me.radMap1.Layers("Pins").Overlays.Count - 1 - Dim pin As MapPin = TryCast(Me.radMap1.Layers("Pins").Overlays(i), MapPin) - If pin IsNot Nothing Then - Dim callout As New MapCallout(pin) - callout.MaxWidth = 50 - callout.Text = e.Elevations(0).Elevations(i).ToString() + "m" - Me.radMap1.Layers("Callouts").Add(callout) - End If - Next -End Sub - -```` - -{{endregion}} # See Also * [Bing Elevation](https://msdn.microsoft.com/en-us/library/jj158961.aspx) diff --git a/controls/map/providers/bingmaps/elevation/polyline.md b/controls/map/providers/bingmaps/elevation/polyline.md index e3776654a..b13ce8703 100644 --- a/controls/map/providers/bingmaps/elevation/polyline.md +++ b/controls/map/providers/bingmaps/elevation/polyline.md @@ -20,225 +20,10 @@ ElevationType.*Polyline* __ElevationRequest__ gets elevations at equally-spaced #### Polyline ElevationType request -{{source=..\SamplesCS\Map\BingProvider.cs region=PolylineElevationRequest}} -{{source=..\SamplesVB\Map\BingProvider.vb region=PolylineElevationRequest}} + + -````C# - -public void SetupPolylineElevationRequest() -{ - //add pins to the map - Telerik.WinControls.UI.Map.PointG point1 = new Telerik.WinControls.UI.Map.PointG(36.114647, -115.172813); - Telerik.WinControls.UI.Map.PointG point2 = new Telerik.WinControls.UI.Map.PointG(34.05223, -118.24368); - Telerik.WinControls.UI.Map.PointG point3 = new Telerik.WinControls.UI.Map.PointG(37.77493, -122.41942); - MapPin pin1 = new MapPin(point1); - MapPin pin2 = new MapPin(point2); - MapPin pin3 = new MapPin(point3); - - MapLayer pinsLayer = new MapLayer("Pins"); - this.radMap1.Layers.Add(pinsLayer); - - MapLayer calloutsLayer = new MapLayer("Callouts"); - this.radMap1.Layers.Add(calloutsLayer); - this.radMap1.Layers["Pins"].Add(pin1); - this.radMap1.Layers["Pins"].Add(pin2); - this.radMap1.Layers["Pins"].Add(pin3); - - ElevationRequest request = new ElevationRequest(); - request.ElevationType = ElevationType.Polyline; - request.Samples = 3; - request.Points = new List() - { - point1, - point2, - point3 - }; - BingRestMapProvider bingProvider = this.radMap1.Providers[0] as BingRestMapProvider; - bingProvider.CalculateElevationCompleted += BingProviderPolyline_CalculateElevationCompleted; - bingProvider.CalculateElevationAsync(request); -} - -private void BingProviderPolyline_CalculateElevationCompleted(object sender, ElevationCompletedEventArgs e) -{ - List points = new List(); - - for (int i = 0; i < this.radMap1.Layers["Pins"].Overlays.Count; i++) - { - MapPin pin = this.radMap1.Layers["Pins"].Overlays[i] as MapPin; - - if (pin != null) - { - points.Add(pin.Location); - } - } - this.radMap1.Layers["Pins"].Clear(); - - MapPolyline polyline = new MapPolyline(points); - this.radMap1.Layers["Callouts"].Add(polyline); - - List p = this.CalculateEquidistantPointsAlongPolyline(polyline, - this.radMap1.MapElement.ZoomLevel, e.Elevations[0].Elevations.Length); - - for (int i = 0; i < p.Count; i++) - { - MapPoint point = new MapPoint(p[i]); - this.radMap1.Layers["Callouts"].Add(point); - - MapCallout callout = new MapCallout(point); - callout.MaxWidth = 50; - callout.Text = e.Elevations[0].Elevations[i].ToString() + "m"; - this.radMap1.Layers["Callouts"].Add(callout); - } -} - -private List CalculateEquidistantPointsAlongPolyline(MapPolyline polyline, int zoomLevel, int numberOfPoints) -{ - List points = new List(); - - foreach (Telerik.WinControls.UI.Map.PointG point in polyline.Points) - { - points.Add(MapTileSystemHelper.LatLongToPixelXY(point, zoomLevel)); - } - - int totalDistance = 0; - List distances = new List(); - - for (int i = 0; i < points.Count - 1; i++) - { - totalDistance += (int)Math.Sqrt(Math.Pow(points[i + 1].X - points[i].X, 2) + Math.Pow(points[i + 1].Y - points[i].Y, 2)); - distances.Add(totalDistance); - } - - List equidistantPoints = new List(); - double step = (double)totalDistance / (numberOfPoints - 1); - double currentDistance = 0; - - while (currentDistance < totalDistance - 1) - { - int index = distances.BinarySearch(currentDistance); - - if (index < 0) - { - index = ~index; - } - - Telerik.WinControls.UI.Map.PointL p1 = points[index]; - Telerik.WinControls.UI.Map.PointL p2 = points[index + 1]; - double distance = index == 0 ? distances[index] : distances[index] - distances[index - 1]; - double dt = index == 0 ? currentDistance : currentDistance - distances[index - 1]; - - double t = (double)dt / distance; - double x = ((1d - t) * p1.X + t * p2.X); - double y = ((1d - t) * p1.Y + t * p2.Y); - - equidistantPoints.Add(new Telerik.WinControls.UI.Map.PointL((long)Math.Round(x, MidpointRounding.AwayFromZero), - (long)Math.Round(y, MidpointRounding.AwayFromZero))); - currentDistance += step; - } - equidistantPoints.Add(points[points.Count - 1]); - List result = new List(); - - foreach (Telerik.WinControls.UI.Map.PointL point in equidistantPoints) - { - result.Add(MapTileSystemHelper.PixelXYToLatLong(point, zoomLevel)); - } - - return result; -} -```` -````VB.NET -Public Sub SetupPolylineElevationRequest() - 'add pins to the map - Dim point1 As New Telerik.WinControls.UI.Map.PointG(36.114647, -115.172813) - Dim point2 As New Telerik.WinControls.UI.Map.PointG(34.05223, -118.24368) - Dim point3 As New Telerik.WinControls.UI.Map.PointG(37.77493, -122.41942) - Dim pin1 As New MapPin(point1) - Dim pin2 As New MapPin(point2) - Dim pin3 As New MapPin(point3) - Dim pinsLayer As New MapLayer("Pins") - Me.radMap1.Layers.Add(pinsLayer) - Dim calloutsLayer As New MapLayer("Callouts") - Me.radMap1.Layers.Add(calloutsLayer) - Me.radMap1.Layers("Pins").Add(pin1) - Me.radMap1.Layers("Pins").Add(pin2) - Me.radMap1.Layers("Pins").Add(pin3) - Dim request As New ElevationRequest() - request.ElevationType = ElevationType.Polyline - request.Samples = 3 - request.Points = New List(Of Telerik.WinControls.UI.Map.PointG)() From { _ - point1, _ - point2, _ - point3 _ - } - Dim bingProvider As BingRestMapProvider = TryCast(Me.radMap1.Providers(0), BingRestMapProvider) - AddHandler bingProvider.CalculateElevationCompleted, AddressOf BingProviderPolyline_CalculateElevationCompleted - bingProvider.CalculateElevationAsync(request) -End Sub -Private Sub BingProviderPolyline_CalculateElevationCompleted(sender As Object, e As ElevationCompletedEventArgs) - Dim points As New List(Of Telerik.WinControls.UI.Map.PointG)() - For i As Integer = 0 To Me.radMap1.Layers("Pins").Overlays.Count - 1 - Dim pin As MapPin = TryCast(Me.radMap1.Layers("Pins").Overlays(i), MapPin) - If pin IsNot Nothing Then - points.Add(pin.Location) - End If - Next - Me.radMap1.Layers("Pins").Clear() - Dim polyline As New MapPolyline(points) - Me.radMap1.Layers("Callouts").Add(polyline) - Dim p As List(Of Telerik.WinControls.UI.Map.PointG) = Me.CalculateEquidistantPointsAlongPolyline(polyline, _ - Me.radMap1.MapElement.ZoomLevel, e.Elevations(0).Elevations.Length) - For i As Integer = 0 To p.Count - 1 - Dim point As New MapPoint(p(i)) - Me.radMap1.Layers("Callouts").Add(point) - Dim callout As New MapCallout(point) - callout.MaxWidth = 50 - callout.Text = e.Elevations(0).Elevations(i).ToString() + "m" - Me.radMap1.Layers("Callouts").Add(callout) - Next -End Sub -Private Function CalculateEquidistantPointsAlongPolyline(polyline As MapPolyline, zoomLevel As Integer, _ -numberOfPoints As Integer) As List(Of Telerik.WinControls.UI.Map.PointG) - Dim points As New List(Of Telerik.WinControls.UI.Map.PointL)() - For Each point As Telerik.WinControls.UI.Map.PointG In polyline.Points - points.Add(MapTileSystemHelper.LatLongToPixelXY(point, zoomLevel)) - Next - Dim totalDistance As Integer = 0 - Dim distances As New List(Of Double)() - For i As Integer = 0 To points.Count - 2 - totalDistance += CInt(Math.Sqrt(Math.Pow(points(i + 1).X - points(i).X, 2) + Math.Pow(points(i + 1).Y - points(i).Y, 2))) - distances.Add(totalDistance) - Next - Dim equidistantPoints As New List(Of Telerik.WinControls.UI.Map.PointL)() - Dim [step] As Double = CDbl(totalDistance) / (numberOfPoints - 1) - Dim currentDistance As Double = 0 - While currentDistance < totalDistance - 1 - Dim index As Integer = distances.BinarySearch(currentDistance) - If index < 0 Then - index = Not index - End If - Dim p1 As Telerik.WinControls.UI.Map.PointL = points(index) - Dim p2 As Telerik.WinControls.UI.Map.PointL = points(index + 1) - Dim distance As Double = If(index = 0, distances(index), distances(index) - distances(index - 1)) - Dim dt As Double = If(index = 0, currentDistance, currentDistance - distances(index - 1)) - Dim t As Double = CDbl(dt) / distance - Dim x As Double = ((1.0 - t) * p1.X + t * p2.X) - Dim y As Double = ((1.0 - t) * p1.Y + t * p2.Y) - equidistantPoints.Add(New Telerik.WinControls.UI.Map.PointL(CLng(Math.Round(x, MidpointRounding.AwayFromZero)), _ - CLng(Math.Round(y, MidpointRounding.AwayFromZero)))) - currentDistance += [step] - End While - equidistantPoints.Add(points(points.Count - 1)) - Dim result As New List(Of Telerik.WinControls.UI.Map.PointG)() - For Each point As Telerik.WinControls.UI.Map.PointL In equidistantPoints - result.Add(MapTileSystemHelper.PixelXYToLatLong(point, zoomLevel)) - Next - Return result -End Function - -```` - -{{endregion}} # See Also * [Bing Elevation](https://msdn.microsoft.com/en-us/library/jj158961.aspx) diff --git a/controls/map/providers/bingmaps/elevation/sealevel.md b/controls/map/providers/bingmaps/elevation/sealevel.md index fb8b25def..b30f4aefd 100644 --- a/controls/map/providers/bingmaps/elevation/sealevel.md +++ b/controls/map/providers/bingmaps/elevation/sealevel.md @@ -19,96 +19,10 @@ ElevationType.*SeaLevel* __ElevationRequest__ gets the offset of the geoid sea #### SeaLevel ElevationType request -{{source=..\SamplesCS\Map\BingProvider.cs region=SeaLevelElevationRequest}} -{{source=..\SamplesVB\Map\BingProvider.vb region=SeaLevelElevationRequest}} + + -````C# - -public void SetupSeaLevelElevation() -{ - //add pins to the map - Telerik.WinControls.UI.Map.PointG point1 = new Telerik.WinControls.UI.Map.PointG(36.114647, -115.172813); - Telerik.WinControls.UI.Map.PointG point2 = new Telerik.WinControls.UI.Map.PointG(34.05223, -118.24368); - Telerik.WinControls.UI.Map.PointG point3 = new Telerik.WinControls.UI.Map.PointG(37.77493, -122.41942); - MapPin pin1 = new MapPin(point1); - MapPin pin2 = new MapPin(point2); - MapPin pin3 = new MapPin(point3); - MapLayer pinsLayer = new MapLayer("Pins"); - this.radMap1.Layers.Add(pinsLayer); - - MapLayer calloutsLayer = new MapLayer("Callouts"); - this.radMap1.Layers.Add(calloutsLayer); - this.radMap1.Layers["Pins"].Add(pin1); - this.radMap1.Layers["Pins"].Add(pin2); - this.radMap1.Layers["Pins"].Add(pin3); - ElevationRequest boundsRequest = new ElevationRequest(); - boundsRequest.ElevationType = ElevationType.SeaLevel; - boundsRequest.Points.Add(point1); - boundsRequest.Points.Add(point2); - boundsRequest.Points.Add(point3); - - BingRestMapProvider bingProvider = this.radMap1.Providers[0] as BingRestMapProvider; - bingProvider.CalculateElevationCompleted += BingProviderBounds_CalculateSeaLevelElevationCompleted; - bingProvider.CalculateElevationAsync(boundsRequest); -} - -private void BingProviderBounds_CalculateSeaLevelElevationCompleted(object sender, ElevationCompletedEventArgs e) -{ - for (int i = 0; i < this.radMap1.Layers["Pins"].Overlays.Count; i++) - { - MapPin pin = this.radMap1.Layers["Pins"].Overlays[i] as MapPin; - - if (pin != null) - { - MapCallout callout = new MapCallout(pin); - callout.MaxWidth = 35; - callout.Text = e.SeaLevels[0].Offsets[i].ToString() + "m"; - this.radMap1.Layers["Callouts"].Add(callout); - } - } -} -```` -````VB.NET -Public Sub SetupSeaLevelElevation() - 'add pins to the map - Dim point1 As New Telerik.WinControls.UI.Map.PointG(36.114647, -115.172813) - Dim point2 As New Telerik.WinControls.UI.Map.PointG(34.05223, -118.24368) - Dim point3 As New Telerik.WinControls.UI.Map.PointG(37.77493, -122.41942) - Dim pin1 As New MapPin(point1) - Dim pin2 As New MapPin(point2) - Dim pin3 As New MapPin(point3) - Dim pinsLayer As New MapLayer("Pins") - Me.radMap1.Layers.Add(pinsLayer) - Dim calloutsLayer As New MapLayer("Callouts") - Me.radMap1.Layers.Add(calloutsLayer) - Me.radMap1.Layers("Pins").Add(pin1) - Me.radMap1.Layers("Pins").Add(pin2) - Me.radMap1.Layers("Pins").Add(pin3) - Dim boundsRequest As New ElevationRequest() - boundsRequest.ElevationType = ElevationType.SeaLevel - boundsRequest.Points.Add(point1) - boundsRequest.Points.Add(point2) - boundsRequest.Points.Add(point3) - Dim bingProvider As BingRestMapProvider = TryCast(Me.radMap1.Providers(0), BingRestMapProvider) - AddHandler bingProvider.CalculateElevationCompleted, AddressOf BingProviderBounds_CalculateSeaLevelElevationCompleted - bingProvider.CalculateElevationAsync(boundsRequest) -End Sub -Private Sub BingProviderBounds_CalculateSeaLevelElevationCompleted(sender As Object, e As ElevationCompletedEventArgs) - For i As Integer = 0 To Me.radMap1.Layers("Pins").Overlays.Count - 1 - Dim pin As MapPin = TryCast(Me.radMap1.Layers("Pins").Overlays(i), MapPin) - If pin IsNot Nothing Then - Dim callout As New MapCallout(pin) - callout.MaxWidth = 35 - callout.Text = e.SeaLevels(0).Offsets(i).ToString() + "m" - Me.radMap1.Layers("Callouts").Add(callout) - End If - Next -End Sub - -```` - -{{endregion}} # See Also * [Bing Elevation](https://msdn.microsoft.com/en-us/library/jj158961.aspx) diff --git a/controls/map/providers/bingmaps/route.md b/controls/map/providers/bingmaps/route.md index 41323b6aa..17ee7b684 100644 --- a/controls/map/providers/bingmaps/route.md +++ b/controls/map/providers/bingmaps/route.md @@ -46,148 +46,19 @@ The following code snippet demonstrates how to build a route from Madrid to Pari #### Bing routing -{{source=..\SamplesCS\Map\BingProvider.cs region=BingRouteRequest}} -{{source=..\SamplesVB\Map\BingProvider.vb region=BingRouteRequest}} - -````C# -public void RunRouteRequest() -{ - //add a layer to display the route - this.radMap1.MapElement.Layers.Add(new MapLayer()); - RouteRequest request = new RouteRequest(); - request.DistanceUnit = DistanceUnit.Kilometer; - request.Options.Mode = TravelMode.Driving; - request.Options.Optimization = RouteOptimization.Time; - request.Options.RouteAttributes = RouteAttributes.RoutePath; - request.Options.RouteAvoidance = RouteAvoidance.None; - request.RoutePoints.Add(new Waypoint("Paris, France")); - request.RoutePoints.Add(new Waypoint("Madrid, Spain")); - BingRestMapProvider bingProvider = this.radMap1.Providers[0] as BingRestMapProvider; - bingProvider.CalculateRouteCompleted += BingProvider_RoutingCompleted; - bingProvider.CalculateRouteAsync(request); -} -private void BingProvider_RoutingCompleted(object sender, RoutingCompletedEventArgs e) -{ - List points = new List(); - foreach (var route in e.Routes) - { - foreach (double[] coordinatePair in route.RoutePath.Line.Coordinates) - { - Telerik.WinControls.UI.Map.PointG point = new Telerik.WinControls.UI.Map.PointG(coordinatePair[0], coordinatePair[1]); - points.Add(point); - } - - Telerik.WinControls.UI.Map.RectangleG boundingRectangle = new Telerik.WinControls.UI.Map.RectangleG(route.BBox[2], - route.BBox[1], route.BBox[0], route.BBox[3]); - MapRoute routeElement = new MapRoute(points, boundingRectangle); - routeElement.BorderColor = Color.Blue; - routeElement.BorderWidth = 5; - MapPin start = new MapPin(new Telerik.WinControls.UI.Map.PointG(route.RouteLegs[0].ActualStart.Coordinates[0], - route.RouteLegs[0].ActualStart.Coordinates[1])); - start.BackColor = Color.White; - start.BorderColor = Color.Green; - start.BorderWidth = 2f; - MapPin end = new MapPin(new Telerik.WinControls.UI.Map.PointG(route.RouteLegs[route.RouteLegs.Length - 1].ActualEnd.Coordinates[0], - route.RouteLegs[route.RouteLegs.Length - 1].ActualEnd.Coordinates[1])); - end.BackColor = Color.White; - end.BorderColor = Color.Red; - end.BorderWidth = 2f; - - this.radMap1.MapElement.Layers[0].Add(routeElement); - this.radMap1.MapElement.Layers[0].Add(start); - this.radMap1.MapElement.Layers[0].Add(end); - } -} - -```` -````VB.NET -Public Sub RunRouteRequest() - 'add a layer to display the route - Me.radMap1.MapElement.Layers.Add(New MapLayer()) - Dim request As New RouteRequest() - request.DistanceUnit = DistanceUnit.Kilometer - request.Options.Mode = TravelMode.Driving - request.Options.Optimization = RouteOptimization.Time - request.Options.RouteAttributes = RouteAttributes.RoutePath - request.Options.RouteAvoidance = RouteAvoidance.None - request.RoutePoints.Add(New Waypoint("Paris, France")) - request.RoutePoints.Add(New Waypoint("Madrid, Spain")) - Dim bingProvider As BingRestMapProvider = TryCast(Me.radMap1.Providers(0), BingRestMapProvider) - AddHandler bingProvider.CalculateRouteCompleted, AddressOf BingProvider_RoutingCompleted - bingProvider.CalculateRouteAsync(request) -End Sub -Private Sub BingProvider_TruckRoutingCompleted(ByVal sender As Object, ByVal e As RoutingCompletedEventArgs) - Dim points As List(Of Telerik.WinControls.UI.Map.PointG) = New List(Of PointG)() - For Each route As Route In e.Routes - For Each coordinatePair As Double() In route.RoutePath.Line.Coordinates - Dim point As PointG = New PointG(coordinatePair(0), coordinatePair(1)) - points.Add(point) - Next - - Dim boundingRectangle As RectangleG = New RectangleG(route.BBox(2), route.BBox(1), - route.BBox(0), route.BBox(3)) - Dim routeElement As MapRoute = New MapRoute(points, boundingRectangle) - routeElement.BorderColor = Color.Blue - routeElement.BorderWidth = 5 - Dim start As MapPin = New MapPin(New PointG(route.RouteLegs(0).ActualStart.Coordinates(0), - route.RouteLegs(0).ActualStart.Coordinates(1))) - start.BackColor = Color.White - start.BorderColor = Color.Green - start.BorderWidth = 2.0F - Dim [end] As MapPin = New MapPin(New PointG(route.RouteLegs(route.RouteLegs.Length - 1).ActualEnd.Coordinates(0), - route.RouteLegs(route.RouteLegs.Length - 1).ActualEnd.Coordinates(1))) - [end].BackColor = Color.White - [end].BorderColor = Color.Red - [end].BorderWidth = 2.0F - Me.RadMap1.MapElement.Layers(0).Add(routeElement) - Me.RadMap1.MapElement.Layers(0).Add(start) - Me.RadMap1.MapElement.Layers(0).Add([end]) - Next - -End Sub - -```` - -{{endregion}} + + + + The **RouteRequest** class also supports *ViaWayPoints* objects. These route points allow a particular leg to be divided into separate sub legs. The [Bing REST Serivices documentation](https://msdn.microsoft.com/en-us/library/ff701717.aspx) provides additional information what a *waypoint* and a *viaWayPoint* represents. #### Creating a Route with ViaWayPoints -{{source=..\SamplesCS\Map\BingProvider.cs region=ViaWayPointsExample}} -{{source=..\SamplesVB\Map\BingProvider.vb region=ViaWayPointsExample}} -````C# -RouteRequest viaWayPointsRequest = new RouteRequest(); -viaWayPointsRequest.DistanceUnit = DistanceUnit.Kilometer; -viaWayPointsRequest.Options.Mode = TravelMode.Driving; -viaWayPointsRequest.Options.Optimization = RouteOptimization.Time; -viaWayPointsRequest.Options.RouteAttributes = RouteAttributes.RoutePath; -viaWayPointsRequest.Options.RouteAvoidance = RouteAvoidance.None; -viaWayPointsRequest.RoutePoints.Add(new Waypoint("47.6062, -122.3321")); //Seattle -viaWayPointsRequest.RoutePoints.Add(new ViaWaypoint("40.7306, -73.9352")); //New York -viaWayPointsRequest.RoutePoints.Add(new Waypoint("25.789, -80.2264")); //Miami -BingRestMapProvider bingProvider = this.radMap1.Providers[0] as BingRestMapProvider; -bingProvider.CalculateRouteAsync(viaWayPointsRequest); - -```` -````VB.NET -Dim viaWayPointsRequest As RouteRequest = New RouteRequest() -viaWayPointsRequest.DistanceUnit = DistanceUnit.Kilometer -viaWayPointsRequest.Options.Mode = TravelMode.Driving -viaWayPointsRequest.Options.Optimization = RouteOptimization.Time -viaWayPointsRequest.Options.RouteAttributes = RouteAttributes.RoutePath -viaWayPointsRequest.Options.RouteAvoidance = RouteAvoidance.None -viaWayPointsRequest.RoutePoints.Add(New Waypoint("47.6062, -122.3321")) -viaWayPointsRequest.RoutePoints.Add(New ViaWaypoint("40.7306, -73.9352")) -viaWayPointsRequest.RoutePoints.Add(New Waypoint("25.789, -80.2264")) -Dim bingProvider As BingRestMapProvider = TryCast(Me.radMap1.Providers(0), BingRestMapProvider) -bingProvider.CalculateRouteAsync(viaWayPointsRequest) - -```` - - - -{{endregion}} + + + + # See Also * [BingRestMapProvider]({%slug winforms/map/providers/bingrestmapprovider%}) diff --git a/controls/map/providers/bingmaps/search.md b/controls/map/providers/bingmaps/search.md index 826a39b62..857a51ac6 100644 --- a/controls/map/providers/bingmaps/search.md +++ b/controls/map/providers/bingmaps/search.md @@ -24,107 +24,10 @@ In this example we will use the second approach by setting the MapElement.Searc #### Bing search -{{source=..\SamplesCS\Map\BingProvider.cs region=SearchCompleted}} -{{source=..\SamplesVB\Map\BingProvider.vb region=SearchCompleted}} - -````C# - -private void BingProvider_Load(object sender, EventArgs e) -{ - this.radMap1.ShowSearchBar = true; - BingRestMapProvider bingProvider = this.radMap1.Providers[0] as BingRestMapProvider; - Telerik.WinControls.UI.MapLayer pinsLayer = new MapLayer("Pins"); - this.radMap1.Layers.Add(pinsLayer); - this.radMap1.MapElement.SearchBarElement.SearchProvider = bingProvider; - - this.radMap1.MapElement.SearchBarElement.SearchProvider.SearchCompleted += BingProvider_SearchCompleted; - this.radMap1.MapElement.SearchBarElement.SearchProvider.SearchError += BingProvider_SearchError; -} - -private void BingProvider_SearchError(object sender, SearchErrorEventArgs e) -{ - RadMessageBox.Show(e.Error.Message); -} - -private void BingProvider_SearchCompleted(object sender, SearchCompletedEventArgs e) -{ - Telerik.WinControls.UI.Map.RectangleG allPoints = new Telerik.WinControls.UI.Map.RectangleG(double.MinValue, double.MaxValue, double.MaxValue, double.MinValue); - this.radMap1.Layers["Pins"].Clear(); - foreach (Telerik.WinControls.UI.Map.Bing.Location location in e.Locations) - { - Telerik.WinControls.UI.Map.PointG point = new Telerik.WinControls.UI.Map.PointG(location.Point.Coordinates[0], location.Point.Coordinates[1]); - MapPin pin = new MapPin(point); - pin.Size = new System.Drawing.Size(20, 40); - pin.BackColor = Color.Red; - pin.ToolTipText = location.Address.FormattedAddress; - this.radMap1.MapElement.Layers["Pins"].Add(pin); - allPoints.North = Math.Max(allPoints.North, point.Latitude); - allPoints.South = Math.Min(allPoints.South, point.Latitude); - allPoints.West = Math.Min(allPoints.West, point.Longitude); - allPoints.East = Math.Max(allPoints.East, point.Longitude); - } - if (e.Locations.Length > 0) - { - if (e.Locations.Length == 1) - { - this.radMap1.BringIntoView(new Telerik.WinControls.UI.Map.PointG(e.Locations[0].Point.Coordinates[0], e.Locations[0].Point.Coordinates[1])); - } - else - { - this.radMap1.MapElement.BringIntoView(allPoints); - this.radMap1.Zoom(this.radMap1.MapElement.ZoomLevel - 1); - } - } - else - { - RadMessageBox.Show("No result found for the provided search query!"); - } -} - -```` -````VB.NET -Private Sub BingProvider_Load(sender As Object, e As EventArgs) Handles Me.Load - Me.radMap1.ShowSearchBar = True - Dim bingProvider As BingRestMapProvider = TryCast(Me.radMap1.Providers(0), BingRestMapProvider) - Dim pinsLayer As Telerik.WinControls.UI.MapLayer = New MapLayer("Pins") - Me.radMap1.Layers.Add(pinsLayer) - Me.radMap1.MapElement.SearchBarElement.SearchProvider = bingProvider - AddHandler Me.radMap1.MapElement.SearchBarElement.SearchProvider.SearchCompleted, AddressOf BingProvider_SearchCompleted - AddHandler Me.radMap1.MapElement.SearchBarElement.SearchProvider.SearchError, AddressOf BingProvider_SearchError -End Sub -Private Sub BingProvider_SearchError(sender As Object, e As SearchErrorEventArgs) - RadMessageBox.Show(e.[Error].Message) -End Sub -Private Sub BingProvider_SearchCompleted(sender As Object, e As SearchCompletedEventArgs) - Dim allPoints As New Telerik.WinControls.UI.Map.RectangleG(Double.MinValue, Double.MaxValue, Double.MaxValue, Double.MinValue) - Me.radMap1.Layers("Pins").Clear() - For Each location As Telerik.WinControls.UI.Map.Bing.Location In e.Locations - Dim point As New Telerik.WinControls.UI.Map.PointG(location.Point.Coordinates(0), location.Point.Coordinates(1)) - Dim pin As New MapPin(point) - pin.Size = New System.Drawing.Size(20, 40) - pin.BackColor = Color.Red - pin.ToolTipText = location.Address.FormattedAddress - Me.radMap1.MapElement.Layers("Pins").Add(pin) - allPoints.North = Math.Max(allPoints.North, point.Latitude) - allPoints.South = Math.Min(allPoints.South, point.Latitude) - allPoints.West = Math.Min(allPoints.West, point.Longitude) - allPoints.East = Math.Max(allPoints.East, point.Longitude) - Next - If e.Locations.Length > 0 Then - If e.Locations.Length = 1 Then - Me.radMap1.BringIntoView(New Telerik.WinControls.UI.Map.PointG(e.Locations(0).Point.Coordinates(0), e.Locations(0).Point.Coordinates(1))) - Else - Me.radMap1.MapElement.BringIntoView(allPoints) - Me.radMap1.Zoom(Me.radMap1.MapElement.ZoomLevel - 1) - End If - Else - RadMessageBox.Show("No result found for the provided search query!") - End If -End Sub - -```` - -{{endregion}} + + + + >note Enter some text in the search box and press `Enter` to start searching. @@ -136,30 +39,10 @@ You can perform searching programmatically by using a __SearchRequest__: #### Bing search -{{source=..\SamplesCS\Map\BingProvider.cs region=BingSearchRequest}} -{{source=..\SamplesVB\Map\BingProvider.vb region=BingSearchRequest}} - -````C# - -Telerik.WinControls.UI.Map.Bing.SearchRequest request = new SearchRequest(); -request.Query = "San Marino"; -request.SearchOptions.Count = 10; -request.SearchOptions.QueryParse = true; -BingRestMapProvider bingProvider = this.radMap1.Providers[0] as BingRestMapProvider; -bingProvider.SearchAsync(request); - -```` -````VB.NET -Dim request As Telerik.WinControls.UI.Map.Bing.SearchRequest = New SearchRequest() -request.Query = "San Marino" -request.SearchOptions.Count = 10 -request.SearchOptions.QueryParse = True -Dim bingProvider As BingRestMapProvider = TryCast(Me.radMap1.Providers(0), BingRestMapProvider) -bingProvider.SearchAsync(request) - -```` - -{{endregion}} + + + + >note It is necessary to handle the __SearchProvider__'s __SearchCompleted__ and __SearchError__ events as it is demonstrated above. diff --git a/controls/map/providers/bingmaps/truck-route.md b/controls/map/providers/bingmaps/truck-route.md index b05bab83e..b1c2475a1 100644 --- a/controls/map/providers/bingmaps/truck-route.md +++ b/controls/map/providers/bingmaps/truck-route.md @@ -55,167 +55,10 @@ The following code snippet demonstrates how to calculate a route considering the #### Truck Route -{{source=..\SamplesCS\Map\BingTruckRoute.cs region=BingTruckRouteRequest}} -{{source=..\SamplesVB\Map\BingTruckRoute.vb region=BingTruckRouteRequest}} - -````C# - - public BingTruckRoute() -{ - InitializeComponent(); - - BingRestMapProvider bingProvider = new BingRestMapProvider(); - bingProvider.UseSession = true; - bingProvider.BingKey = bingKey; - - LocalFileCacheProvider cache = new LocalFileCacheProvider(@"..\..\Cache"); - bingProvider.CacheProvider = cache; - - this.radMap1.MapElement.Providers.Add(bingProvider); - this.radMap1.MapElement.Layers.Add(new MapLayer()); - - TruckRouteOptions options = new TruckRouteOptions(); - options.Avoid = TruckRouteAvoidance.BorderCrossing; - options.DateTime = DateTime.Now; - options.OptimizeWaypoints = true; - options.RouteAttributes = TruckRouteAttributes.RoutePath; - - options.VehicleSpec = new VehicleSpec() - { - DimensionUnit = DimensionUnit.Meter, - VehicleLength = 32, - VehicleHeight = 4, - VehicleSemi = true, - VehicleHazardousMaterials = HazardousMaterial.Flammable - }; - - List wp = new List() - { - new TruckWaypoint("590 Crane Ave, Pittsburgh, PA"), - new TruckWaypoint("600 Forbes Ave, Pittsburgh, PA") - }; - - Telerik.WinControls.UI.Map.Bing.TruckRouteRequest request = new TruckRouteRequest(); - request.RoutePoints = wp; - request.Options = options; - - bingProvider.CalculateTruckRouteCompleted += BingProvider_TruckRoutingCompleted; - bingProvider.CalculateTruckRouteError += BingProvider_CalculateRouteError; - bingProvider.CalculateTruckRouteAsync(request); -} - -private void BingProvider_CalculateRouteError(object sender, CalculateRouteErrorEventArgs e) -{ - RadMessageBox.Show(e.Error.Message); -} - -private void BingProvider_TruckRoutingCompleted(object sender, RoutingCompletedEventArgs e) -{ - List points = new List(); - foreach (var route in e.Routes) - { - foreach (double[] coordinatePair in route.RoutePath.Line.Coordinates) - { - PointG point = new PointG(coordinatePair[0], coordinatePair[1]); - points.Add(point); - } - - RectangleG boundingRectangle = new RectangleG(route.BBox[2], route.BBox[1], - route.BBox[0], route.BBox[3]); - MapRoute routeElement = new MapRoute(points, boundingRectangle); - routeElement.BorderColor = Color.Blue; - routeElement.BorderWidth = 5; - MapPin start = new MapPin(new PointG(route.RouteLegs[0].ActualStart.Coordinates[0], - route.RouteLegs[0].ActualStart.Coordinates[1])); - start.BackColor = Color.White; - start.BorderColor = Color.Green; - start.BorderWidth = 2f; - MapPin end = new MapPin(new PointG(route.RouteLegs[route.RouteLegs.Length - 1].ActualEnd.Coordinates[0], - route.RouteLegs[route.RouteLegs.Length - 1].ActualEnd.Coordinates[1])); - end.BackColor = Color.White; - end.BorderColor = Color.Red; - end.BorderWidth = 2f; - - this.radMap1.MapElement.Layers[0].Add(routeElement); - this.radMap1.MapElement.Layers[0].Add(start); - this.radMap1.MapElement.Layers[0].Add(end); - } - -} - - -```` -````VB.NET - - Public Sub New() - InitializeComponent() - Dim bingProvider As BingRestMapProvider = New BingRestMapProvider() - bingProvider.UseSession = True - bingProvider.BingKey = bingKey - Dim cache As LocalFileCacheProvider = New LocalFileCacheProvider("..\..\Cache") - bingProvider.CacheProvider = cache - Me.RadMap1.MapElement.Providers.Add(bingProvider) - Me.RadMap1.MapElement.Layers.Add(New MapLayer()) - Dim options As TruckRouteOptions = New TruckRouteOptions() - options.Avoid = TruckRouteAvoidance.BorderCrossing - options.DateTime = DateTime.Now - options.OptimizeWaypoints = True - options.RouteAttributes = TruckRouteAttributes.RoutePath - options.VehicleSpec = New VehicleSpec() With { - .DimensionUnit = DimensionUnit.Meter, - .VehicleLength = 32, - .VehicleHeight = 4, - .VehicleSemi = True, - .VehicleHazardousMaterials = HazardousMaterial.Flammable - } - Dim wp As List(Of TruckWaypoint) = New List(Of TruckWaypoint)() From { - New TruckWaypoint("590 Crane Ave, Pittsburgh, PA"), - New TruckWaypoint("600 Forbes Ave, Pittsburgh, PA") - } - Dim request As Telerik.WinControls.UI.Map.Bing.TruckRouteRequest = New TruckRouteRequest() - request.RoutePoints = wp - request.Options = options - AddHandler bingProvider.CalculateTruckRouteCompleted, AddressOf BingProvider_TruckRoutingCompleted - AddHandler bingProvider.CalculateTruckRouteError, AddressOf BingProvider_CalculateRouteError - bingProvider.CalculateTruckRouteAsync(request) -End Sub - -Private Sub BingProvider_CalculateRouteError(ByVal sender As Object, ByVal e As CalculateRouteErrorEventArgs) - RadMessageBox.Show(e.[Error].Message) -End Sub - -Private Sub BingProvider_TruckRoutingCompleted(ByVal sender As Object, ByVal e As RoutingCompletedEventArgs) - Dim points As List(Of Telerik.WinControls.UI.Map.PointG) = New List(Of PointG)() - - For Each coordinatePair As Double() In e.Route.RoutePath.Line.Coordinates - Dim point As PointG = New PointG(coordinatePair(0), coordinatePair(1)) - points.Add(point) - Next - - Dim boundingRectangle As RectangleG = New RectangleG(e.Route.BBox(2), e.Route.BBox(1), _ - e.Route.BBox(0), e.Route.BBox(3)) - Dim routeElement As MapRoute = New MapRoute(points, boundingRectangle) - routeElement.BorderColor = Color.Blue - routeElement.BorderWidth = 5 - Dim start As MapPin = New MapPin(New PointG(e.Route.RouteLegs(0).ActualStart.Coordinates(0), _ - e.Route.RouteLegs(0).ActualStart.Coordinates(1))) - start.BackColor = Color.White - start.BorderColor = Color.Green - start.BorderWidth = 2.0F - Dim [end] As MapPin = New MapPin(New PointG(e.Route.RouteLegs(e.Route.RouteLegs.Length - 1).ActualEnd.Coordinates(0), _ - e.Route.RouteLegs(e.Route.RouteLegs.Length - 1).ActualEnd.Coordinates(1))) - [end].BackColor = Color.White - [end].BorderColor = Color.Red - [end].BorderWidth = 2.0F - Me.RadMap1.MapElement.Layers(0).Add(routeElement) - Me.RadMap1.MapElement.Layers(0).Add(start) - Me.RadMap1.MapElement.Layers(0).Add([end]) -End Sub - - -```` - -{{endregion}} + + + + # See Also * [BingRestMapProvider]({%slug winforms/map/providers/bingrestmapprovider%}) diff --git a/controls/map/providers/cacheprovider.md b/controls/map/providers/cacheprovider.md index c161a3b2e..003e34916 100644 --- a/controls/map/providers/cacheprovider.md +++ b/controls/map/providers/cacheprovider.md @@ -24,28 +24,8 @@ You should set the IMapTileProvider.__EnableCaching__ property to *true* to allo #### Using LocalFileCacheProvider with BingRestMapProvider -{{source=..\SamplesCS\Map\MapGettingStarted.cs region=GettingStarted}} -{{source=..\SamplesVB\Map\MapGettingStarted.vb region=GettingStarted}} - -````C# -string cacheFolder = @"..\..\cache"; -BingRestMapProvider bingProvider = new Telerik.WinControls.UI.BingRestMapProvider(); -bingProvider.UseSession = true; -bingProvider.BingKey = bingKey; -LocalFileCacheProvider cache = new LocalFileCacheProvider(cacheFolder); -bingProvider.CacheProvider = cache; -this.radMap1.Providers.Add(bingProvider); - -```` -````VB.NET -Dim cacheFolder As String = "..\..\cache" -Dim bingProvider As BingRestMapProvider = New Telerik.WinControls.UI.BingRestMapProvider() -bingProvider.UseSession = True -bingProvider.BingKey = bingKey -Dim cache As New LocalFileCacheProvider(cacheFolder) -bingProvider.CacheProvider = cache -Me.radMap1.Providers.Add(bingProvider) - -```` - -{{endregion}} + + + + + diff --git a/controls/map/providers/localmapprovider.md b/controls/map/providers/localmapprovider.md index a319b2f04..6dd94257e 100644 --- a/controls/map/providers/localmapprovider.md +++ b/controls/map/providers/localmapprovider.md @@ -18,32 +18,10 @@ __RadMap__ can visualize data from local image files by using a __LocalMapProvid #### Using LocalMapProvider -{{source=..\SamplesCS\Map\MapLocalMapProvider.cs region=SetupLocalMapProvider}} -{{source=..\SamplesVB\Map\MapLocalMapProvider.vb region=SetupLocalMapProvider}} + + -````C# - -string mapFolder = @"..\..\World"; -LocalMapProvider provider = new LocalMapProvider(); -provider.DirectoryPath = mapFolder; -provider.FileFormat = "os_{0}_{1}_{2}.png"; -provider.MinZoomLevel = 1; -provider.MaxZoomLevel = 9; -radMap1.Providers.Add(provider); -```` -````VB.NET -Dim mapFolder As String = "..\..\World" -Dim provider As New LocalMapProvider() -provider.DirectoryPath = mapFolder -provider.FileFormat = "os_{0}_{1}_{2}.png" -provider.MinZoomLevel = 1 -provider.MaxZoomLevel = 9 -radMap1.Providers.Add(provider) - -```` - -{{endregion}} >note The __FileFormat__ property specifies what is the exact format of the image files stored in the local folder. The parameters needed are the tile X *{0}* and Y *{1}* numbers and the Zoom level *{2}*. In the code snippet above, each file image's name is built by using x,y,z values: "os_X_Y_Z.png". diff --git a/controls/map/providers/openstreetmapprovider.md b/controls/map/providers/openstreetmapprovider.md index bb00469b6..ccbb24196 100644 --- a/controls/map/providers/openstreetmapprovider.md +++ b/controls/map/providers/openstreetmapprovider.md @@ -18,83 +18,17 @@ __RadMap__ can visualize data from the [OpenStreetMaps](http://wiki.openstreetma #### Using OpenStreetMapProvider -{{source=..\SamplesCS\Map\OSMProvider.cs region=UseOSMProvider}} -{{source=..\SamplesVB\Map\OSMProvider.vb region=UseOSMProvider}} + + -````C# -string cacheFolder = @"..\..\cache"; -OpenStreetMapProvider osmProvider = new OpenStreetMapProvider(); -LocalFileCacheProvider cache = new LocalFileCacheProvider(cacheFolder); -osmProvider.CacheProvider = cache; -this.radMap1.MapElement.Providers.Add(osmProvider); -```` -````VB.NET -Dim cacheFolder As String = "..\..\cache" -Dim osmProvider As New OpenStreetMapProvider() -Dim cache As New LocalFileCacheProvider(cacheFolder) -osmProvider.CacheProvider = cache -Me.radMap1.MapElement.Providers.Add(osmProvider) - -```` - -{{endregion}} ## Using Encrypted HTTP Version A __TLS 1.2 SecurityProtocol__ will be required when modifying the RadMap URL to use __https:\\__ while using OpenStreetMapProvider. This protocol automatically comes with .NET Framework 4.7. For older .NET Frameworks, or because of some other Windows settings, it may be necessary to explicitly choose TLS 1.2 for your application by setting the __System.Net.ServicePointManager.SecurityProtocol__ property to __SecurityProtocolType.Tls12__. Otherwise the tiles won't be donwload while using __https://__. This is further described in the [Transport Layer Security (TLS) best practices with the .NET Framework](https://learn.microsoft.com/en-us/dotnet/framework/network-programming/tls) MSDN article. -{{source=..\SamplesCS\Map\OSMProvider.cs region=SecurityProtocol}} -{{source=..\SamplesVB\Map\OSMProvider.vb region=SecurityProtocol}} - -````C# -private void RadForm1_Load(object sender, EventArgs e) -{ - System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; - OpenStreetMapProvider osmProvider = new OpenStreetMapProvider(); - osmProvider.TileDownloader = new CustomMapTileDownloader(); - MapTileDownloader tileDownloader = osmProvider.TileDownloader as MapTileDownloader; - tileDownloader.WebHeaders.Add(System.Net.HttpRequestHeader.UserAgent, "your application name"); - osmProvider.EnableCaching = false; - this.radMap1.MapElement.Providers.Add(osmProvider); -} - -public class CustomMapTileDownloader : MapTileDownloader -{ - public override void BeginDownloadTile(Uri uri, TileInfo tileInfo) - { - Uri myUri = new Uri(uri.AbsoluteUri.Replace("http:", "https:")); - base.BeginDownloadTile(myUri, tileInfo); - } -} - -```` -````VB.NET -Private Sub RadForm1_Load(sender As Object, e As EventArgs) Handles MyBase.Load - System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12 - Dim osmProvider As OpenStreetMapProvider = New OpenStreetMapProvider() - osmProvider.TileDownloader = New CustomMapTileDownloader() - Dim tileDownloader As MapTileDownloader = TryCast(osmProvider.TileDownloader, MapTileDownloader) - tileDownloader.WebHeaders.Add(System.Net.HttpRequestHeader.UserAgent, "your application name") - osmProvider.EnableCaching = False - Me.radMap1.MapElement.Providers.Add(osmProvider) -End Sub - -Public Class CustomMapTileDownloader - Inherits MapTileDownloader - - Public Overrides Sub BeginDownloadTile(ByVal uri As Uri, ByVal tileInfo As TileInfo) - Dim myUri As Uri = New Uri(uri.AbsoluteUri.Replace("http:", "https:")) - MyBase.BeginDownloadTile(myUri, tileInfo) - End Sub -End Class - - -```` - - -{{endregion}} - + + diff --git a/controls/map/tooltips.md b/controls/map/tooltips.md index 2c7faf6b9..f886a2655 100644 --- a/controls/map/tooltips.md +++ b/controls/map/tooltips.md @@ -19,21 +19,10 @@ The code snippet below demonstrates how you can assign a tool tip to zoom out bu #### Using the ToolTipText property -{{source=..\SamplesCS\Map\MapGettingStarted.cs region=MapVisualElementToolTip}} -{{source=..\SamplesVB\Map\MapGettingStarted.vb region=MapVisualElementToolTip}} + + -````C# -this.radMap1.ShowItemToolTips = true; -this.radMap1.MapElement.NavigationBarElement.ZoomOutButton.ToolTipText = "Zoom out"; -```` -````VB.NET -Me.radMap1.ShowItemToolTips = True -Me.radMap1.MapElement.NavigationBarElement.ZoomOutButton.ToolTipText = "Zoom out" - -```` - -{{endregion}} >caption Figure 1: Tool tip assigned by using the ToolTipText property @@ -45,31 +34,9 @@ The code snippet below demonstrates how you can use __ToolTipTextNeeded__ event #### Using the ToolTipTextNeeded event -{{source=..\SamplesCS\Map\MapGettingStarted.cs region=ToolTipTextNeeded}} -{{source=..\SamplesVB\Map\MapGettingStarted.vb region=ToolTipTextNeeded}} - -````C# -private void radMap1_ToolTipTextNeeded(object sender, Telerik.WinControls.ToolTipTextNeededEventArgs e) -{ - MapZoomInButton zoomInButton = sender as MapZoomInButton; - if ( zoomInButton!=null) - { - e.ToolTipText = "Zoom in"; - } -} - -```` -````VB.NET -Private Sub radMap1_ToolTipTextNeeded(sender As Object, e As Telerik.WinControls.ToolTipTextNeededEventArgs) - Dim zoomInButton As MapZoomInButton = TryCast(sender, MapZoomInButton) - If zoomInButton IsNot Nothing Then - e.ToolTipText = "Zoom in" - End If -End Sub - -```` - -{{endregion}} + + + >caption Figure 2: Tool tip assigned by using the ToolTipTextNeeded event diff --git a/controls/menus/application-menu/getting-started.md b/controls/menus/application-menu/getting-started.md index 9e53e23c5..d06ac8d1c 100644 --- a/controls/menus/application-menu/getting-started.md +++ b/controls/menus/application-menu/getting-started.md @@ -59,24 +59,10 @@ The following tutorial demonstrates how to populate **RadApplicationMenu** and h #### Handling Click event -{{source=..\SamplesCS\Menus\AppMenu\ApplicationMenu.cs region=ItemClick}} -{{source=..\SamplesVB\Menus\AppMenu\ApplicationMenu.vb region=ItemClick}} - -````C# -private void radMenuItem1_Click(object sender, EventArgs e) -{ - RadMenuItem item = sender as RadMenuItem; - RadMessageBox.Show(item.Text + " is clicked!"); -} - -```` -````VB.NET -Private Sub RadMenuItem1_Click(sender As Object, e As EventArgs) Handles RadMenuItem1.Click - Dim item As RadMenuItem = TryCast(sender, RadMenuItem) - RadMessageBox.Show(item.Text + " is clicked!") -End Sub - -```` + + + + >caption Figure 2: Handling Click event diff --git a/controls/menus/application-menu/populating-with-data.md b/controls/menus/application-menu/populating-with-data.md index ba375e16d..e9dc49e86 100644 --- a/controls/menus/application-menu/populating-with-data.md +++ b/controls/menus/application-menu/populating-with-data.md @@ -41,91 +41,10 @@ Another possibility to open the editor is via the __Items__ collection in the *P #### Add items programmatically -{{source=..\SamplesCS\Menus\AppMenu\ApplicationMenu.cs region=AddItems}} -{{source=..\SamplesVB\Menus\AppMenu\ApplicationMenu.vb region=AddItems}} - -````C# -public ApplicationMenu() -{ - InitializeComponent(); - - RadMenuItem newItem = new RadMenuItem("New"); - newItem.Click += NewItem_Click; - this.radApplicationMenu1.Items.Add(newItem); - - RadMenuItem saveItem = new RadMenuItem("Save"); - saveItem.Click += SaveItem_Click; - this.radApplicationMenu1.Items.Add(saveItem); - - RadMenuItem printItem = new RadMenuItem("Print"); - printItem.Click += PrintItem_Click; - this.radApplicationMenu1.RightColumnItems.Add(printItem); - - RadMenuButtonItem exitItem = new RadMenuButtonItem("Exit"); - exitItem.Click += ExitItem_Click; - this.radApplicationMenu1.ButtonItems.Add(exitItem); -} - -private void ExitItem_Click(object sender, EventArgs e) -{ - this.radApplicationMenu1.DropDownButtonElement.DropDownMenu.ClosePopup(RadPopupCloseReason.Mouse); -} - -private void PrintItem_Click(object sender, EventArgs e) -{ - RadMessageBox.Show("Print item is clicked!"); -} - -private void SaveItem_Click(object sender, EventArgs e) -{ - RadMessageBox.Show("Save item is clicked!"); -} - -private void NewItem_Click(object sender, EventArgs e) -{ - RadMessageBox.Show( "New item is clicked!"); -} - -```` -````VB.NET -Public Sub New() - InitializeComponent() - - Dim newItem As New RadMenuItem("New") - AddHandler newItem.Click, AddressOf NewItem_Click - Me.RadApplicationMenu1.Items.Add(newItem) - - Dim saveItem As New RadMenuItem("Save") - AddHandler saveItem.Click, AddressOf SaveItem_Click - Me.RadApplicationMenu1.Items.Add(saveItem) - - Dim printItem As New RadMenuItem("Print") - AddHandler printItem.Click, AddressOf PrintItem_Click - Me.RadApplicationMenu1.RightColumnItems.Add(printItem) - - Dim exitItem As New RadMenuButtonItem("Exit") - AddHandler exitItem.Click, AddressOf ExitItem_Click - Me.RadApplicationMenu1.ButtonItems.Add(exitItem) -End Sub - -Private Sub ExitItem_Click(sender As Object, e As EventArgs) - Me.RadApplicationMenu1.DropDownButtonElement.DropDownMenu.ClosePopup(RadPopupCloseReason.Mouse) -End Sub - -Private Sub PrintItem_Click(sender As Object, e As EventArgs) - RadMessageBox.Show("Print item is clicked!") -End Sub - -Private Sub SaveItem_Click(sender As Object, e As EventArgs) - RadMessageBox.Show("Save item is clicked!") -End Sub - -Private Sub NewItem_Click(sender As Object, e As EventArgs) - RadMessageBox.Show("New item is clicked!") -End Sub - - -```` + + + + >caption Figure 4: Add Items Programmatically diff --git a/controls/menus/contextmenu/add-context-menu-in-code.md b/controls/menus/contextmenu/add-context-menu-in-code.md index 6de960f0f..18acc6fee 100644 --- a/controls/menus/contextmenu/add-context-menu-in-code.md +++ b/controls/menus/contextmenu/add-context-menu-in-code.md @@ -38,31 +38,26 @@ This article demonstrates how you can add __RadContextMenu__ in the code and att 1\. Adding a __RadContextMenu__ at runtime. To programmatically add a __RadContextMenu__ to a form, create a new instance of a __RadContextMenu__ -{{source=..\SamplesCS\Menus\ContextMenu\ContextMenuCode2.cs region=AddMenu}} -{{source=..\SamplesVB\Menus\ContextMenu\ContextMenuCode2.vb region=AddMenu}} + + -{{endregion}} 2\. Add __RadMenuItems__ to __RadContextMenu__. -{{source=..\SamplesCS\Menus\ContextMenu\ContextMenuCode2.cs region=AddItems}} -{{source=..\SamplesVB\Menus\ContextMenu\ContextMenuCode2.vb region=AddItems}} + + -{{endregion}} - 3\. Subscribe to __МouseClick__ event of the control and call the __RadContextMenu.Show()__ method: -{{source=..\SamplesCS\Menus\ContextMenu\ContextMenuCode2.cs region=AttachToControl}} -{{source=..\SamplesVB\Menus\ContextMenu\ContextMenuCode2.vb region=AttachToControl}} - + + -{{endregion}} 4\. Here is the result: diff --git a/controls/menus/contextmenu/context-menus.md b/controls/menus/contextmenu/context-menus.md index 009320b23..7a28394cf 100644 --- a/controls/menus/contextmenu/context-menus.md +++ b/controls/menus/contextmenu/context-menus.md @@ -28,19 +28,10 @@ There are two ways to attach a context menu to a given control or portion of a c #### Assigning a RadContextMenu -{{source=..\SamplesCS\Menus\ContextMenu\ContextMenu1.cs region=assignToTreeView}} -{{source=..\SamplesVB\Menus\ContextMenu\ContextMenu1.vb region=assignToTreeView}} + + -````C# -radTreeView1.Nodes[0].ContextMenu = radContextMenu1; -```` -````VB.NET -RadTreeView1.Nodes(0).ContextMenu = RadContextMenu1 - -```` - -{{endregion}} >important The __ContextMenuStrip__ property refers to a Windows standard control. This property drop down will not display __RadMenu__ or __RadContextMenu__ components that exist on the form. > @@ -50,31 +41,10 @@ RadTreeView1.Nodes(0).ContextMenu = RadContextMenu1 #### Handling the MouseDown event -{{source=..\SamplesCS\Menus\ContextMenu\ContextMenu1.cs region=mouseDown}} -{{source=..\SamplesVB\Menus\ContextMenu\ContextMenu1.vb region=mouseDown}} - -````C# -void radCalendar1_MouseDown(object sender, MouseEventArgs e) -{ - if (e.Button == MouseButtons.Right) - { - Point p = (sender as Control).PointToScreen(e.Location); - radContextMenu1.Show(p.X, p.Y); - } -} - -```` -````VB.NET -Private Sub radCalendar1_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) - If e.Button = MouseButtons.Right Then - Dim p As Point = (TryCast(sender, Control)).PointToScreen(e.Location) - RadContextMenu1.Show(p.X, p.Y) - End If -End Sub - -```` - -{{endregion}} + + + + ## Telerik UI for WinForms Learning Resources * [Telerik UI for WinForms ContextMenu Homepage](https://www.telerik.com/products/winforms/contextmenu.aspx) diff --git a/controls/menus/menu/getting-started.md b/controls/menus/menu/getting-started.md index 1fad84ed8..e5ff96a71 100644 --- a/controls/menus/menu/getting-started.md +++ b/controls/menus/menu/getting-started.md @@ -119,19 +119,10 @@ The following tutorial demonstrates creating a **RadMenu** with standard **RadMe #### Assigning shortcuts -{{source=..\SamplesCS\Menus\Menu\MenuGettingStarted.cs region=shortcut}} -{{source=..\SamplesVB\Menus\Menu\MenuGettingStarted.vb region=shortcut}} + + -````C# -radMenuItem3.Shortcuts.Add(new Telerik.WinControls.RadShortcut(Keys.Control, Keys.N)); -```` -````VB.NET -RadMenuItem3.Shortcuts.Add(New Telerik.WinControls.RadShortcut(Keys.Control, Keys.N)) - -```` - -{{endregion}} 27\. Go to the Design View of the form and select the **New** menu item. @@ -144,24 +135,10 @@ RadMenuItem3.Shortcuts.Add(New Telerik.WinControls.RadShortcut(Keys.Control, Key 30\. Replace the automatically-generated event handler with this code: -{{source=..\SamplesCS\Menus\Menu\MenuGettingStarted.cs region=clickHandler}} -{{source=..\SamplesVB\Menus\Menu\MenuGettingStarted.vb region=clickHandler}} - -````C# -private void radMenuItem3_Click(object sender, EventArgs e) -{ - MessageBox.Show("New File"); -} - -```` -````VB.NET -Private Sub RadMenuItem3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadMenuItem3.Click - MessageBox.Show("New File") -End Sub + + -```` -{{endregion}} 31\. Return to the Design View of the form. diff --git a/controls/menus/menu/menu-merge/menu-merge.md b/controls/menus/menu/menu-merge/menu-merge.md index 1c978b977..099d921eb 100644 --- a/controls/menus/menu/menu-merge/menu-merge.md +++ b/controls/menus/menu/menu-merge/menu-merge.md @@ -18,19 +18,10 @@ You can merge **RadMenuItems** by using the **MergeMenu** method of **RadMenu* #### Menu Merge -{{source=..\SamplesCS\Menus\Menu\MenuMerge.cs region=Merge}} -{{source=..\SamplesVB\Menus\Menu\MenuMerge.vb region=Merge}} + + -````C# -radMenu1.MergeMenu(srcRadMenu2); -```` -````VB.NET -radMenu1.MergeMenu(srcRadMenu2) - -```` - -{{endregion}} __RadMenuItem__ class has two properties that determines the way the items are merged: __MergeType__ and __MergeOrder__.   diff --git a/controls/menus/menu/styling-and-appearance/animation-effects.md b/controls/menus/menu/styling-and-appearance/animation-effects.md index 97f9cc204..6b0cc08b9 100644 --- a/controls/menus/menu/styling-and-appearance/animation-effects.md +++ b/controls/menus/menu/styling-and-appearance/animation-effects.md @@ -39,32 +39,10 @@ To load the __RadDropDownList__ with members of the __RadEasingType__ enumeratio #### Animation effects -{{source=..\SamplesCS\Menus\Menu\AnimationEffects.cs region=easingTypes}} -{{source=..\SamplesVB\Menus\Menu\AnimationEffects.vb region=easingTypes}} - -````C# -foreach (RadEasingType ret in Enum.GetValues(typeof(RadEasingType))) -{ - RadListDataItem item = new RadListDataItem(); - item.Text = ret.ToString("f"); - item.Value = ret; - ddlAnimation.Items.Add(item); -} -ddlAnimation.SelectedIndex = 0; - -```` -````VB.NET -For Each ret As RadEasingType In System.Enum.GetValues(GetType(RadEasingType)) - Dim item As New RadListDataItem() - item.Text = ret.ToString("f") - item.Value = ret - ddlAnimation.Items.Add(item) -Next ret -ddlAnimation.SelectedIndex = 0 - -```` - -{{endregion}} + + + + The example requires event handlers for: @@ -76,53 +54,10 @@ The example requires event handlers for: When the __RadDropDownList__ selection changes, the __RadEasingType__ enumeration value is assigned to the RadMenu.__DropDownAnimationEasing__ property. The RadCheckBox.__Click__ event handler toggles the __DropDownAnimationEnabled__ property. The RadTrackBar.__ValueChanged__ event handler sets the __DropDownAnimationFrames__ property and displays the current value in the label. -{{source=..\SamplesCS\Menus\Menu\AnimationEffects.cs region=eventHandlers}} -{{source=..\SamplesVB\Menus\Menu\AnimationEffects.vb region=eventHandlers}} - -````C# -void ddlAnimation_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e) -{ - RadDropDownList ddl = sender as RadDropDownList; - if (ddl.SelectedItem==null) - { - return; - } - RadListDataItem item = ddl.SelectedItem as RadListDataItem; - radMenu1.DropDownAnimationEasing = (RadEasingType)item.Value; -} -void cbEnabled_ToggleStateChanged(object sender, StateChangedEventArgs args) -{ - radMenu1.DropDownAnimationEnabled = (sender as RadCheckBox).IsChecked; -} -void tbFrames_ValueChanged(object sender, EventArgs e) -{ - int trackBarValue = (int)(sender as RadTrackBar).Value; - lblFrames.Text = "Frames: " + trackBarValue.ToString(); - radMenu1.DropDownAnimationFrames = trackBarValue; -} - -```` -````VB.NET -Private Sub ddlAnimation_SelectedIndexChanged(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.Data.PositionChangedEventArgs) - Dim ddl As RadDropDownList = TryCast(sender, RadDropDownList) - If ddl.SelectedItem Is Nothing Then - Return - End If - Dim item As RadListDataItem = TryCast((TryCast(sender, RadDropDownListElement)).SelectedItem, RadListDataItem) - RadMenu1.DropDownAnimationEasing = CType(item.Value, RadEasingType) -End Sub -Private Sub cbEnabled_ToggleStateChanged(ByVal sender As Object, ByVal e As StateChangedEventArgs) - RadMenu1.DropDownAnimationEnabled = (TryCast(sender, RadCheckBox)).IsChecked -End Sub -Private Sub tbFrames_ValueChanged(ByVal sender As Object, ByVal e As EventArgs) - Dim trackBarValue As Integer = (TryCast(sender, RadTrackBar)).Value - lblFrames.Text = "Frames: " & trackBarValue.ToString() - RadMenu1.DropDownAnimationFrames = trackBarValue -End Sub - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/menus/menu/styling-and-appearance/menu-orientation.md b/controls/menus/menu/styling-and-appearance/menu-orientation.md index d0a1b5c39..2b2ec64e1 100644 --- a/controls/menus/menu/styling-and-appearance/menu-orientation.md +++ b/controls/menus/menu/styling-and-appearance/menu-orientation.md @@ -21,35 +21,10 @@ The __RadMenu__ default settings are: __Orientation__ = *Horizontal*, __TextOrie ![WinForms RadMenu Default Orientation](images/menus-menu-styling-and-appearance-menu-orientation001.png) -{{source=..\SamplesCS\Menus\Menu\MenuOrientation.cs region=default}} -{{source=..\SamplesVB\Menus\Menu\MenuOrientation.vb region=default}} - -````C# -radMenu1.Orientation = System.Windows.Forms.Orientation.Horizontal; -radMenuItemFile.TextOrientation = System.Windows.Forms.Orientation.Horizontal; -radMenuItemFile.FlipText = false; -radMenuItemEdit.TextOrientation = System.Windows.Forms.Orientation.Horizontal; -radMenuItemEdit.FlipText = false; -radMenuItemView.TextOrientation = System.Windows.Forms.Orientation.Horizontal; -radMenuItemView.FlipText = false; -radMenuItemHelp.TextOrientation = System.Windows.Forms.Orientation.Horizontal; -radMenuItemHelp.FlipText = false; - -```` -````VB.NET -radMenu1.Orientation = System.Windows.Forms.Orientation.Horizontal -radMenuItemFile.TextOrientation = System.Windows.Forms.Orientation.Horizontal -radMenuItemFile.FlipText = False -radMenuItemEdit.TextOrientation = System.Windows.Forms.Orientation.Horizontal -radMenuItemEdit.FlipText = False -radMenuItemView.TextOrientation = System.Windows.Forms.Orientation.Horizontal -radMenuItemView.FlipText = False -radMenuItemHelp.TextOrientation = System.Windows.Forms.Orientation.Horizontal -radMenuItemHelp.FlipText = False - -```` - -{{endregion}} + + + + ## Horizontal Menu with Vertical Items @@ -59,35 +34,10 @@ The menu can be oriented horizontally with menu items arranged vertically: ![WinForms RadMenu Horizontal Menu with Vertical Items](images/menus-menu-styling-and-appearance-menu-orientation002.png) -{{source=..\SamplesCS\Menus\Menu\MenuOrientation.cs region=textVertical}} -{{source=..\SamplesVB\Menus\Menu\MenuOrientation.vb region=textVertical}} - -````C# -radMenu1.Orientation = System.Windows.Forms.Orientation.Horizontal; -radMenuItemFile.TextOrientation = System.Windows.Forms.Orientation.Vertical; -radMenuItemFile.FlipText = false; -radMenuItemEdit.TextOrientation = System.Windows.Forms.Orientation.Vertical; -radMenuItemEdit.FlipText = false; -radMenuItemView.TextOrientation = System.Windows.Forms.Orientation.Vertical; -radMenuItemView.FlipText = false; -radMenuItemHelp.TextOrientation = System.Windows.Forms.Orientation.Vertical; -radMenuItemHelp.FlipText = false; - -```` -````VB.NET -radMenu1.Orientation = System.Windows.Forms.Orientation.Horizontal -radMenuItemFile.TextOrientation = System.Windows.Forms.Orientation.Vertical -radMenuItemFile.FlipText = False -radMenuItemEdit.TextOrientation = System.Windows.Forms.Orientation.Vertical -radMenuItemEdit.FlipText = False -radMenuItemView.TextOrientation = System.Windows.Forms.Orientation.Vertical -radMenuItemView.FlipText = False -radMenuItemHelp.TextOrientation = System.Windows.Forms.Orientation.Vertical -radMenuItemHelp.FlipText = False - -```` - -{{endregion}} + + + + ## Sideways Menu @@ -97,35 +47,10 @@ The menu can be oriented vertically with menu items arranged horizontally to cre #### Vertical Menu With Horizontal Text -{{source=..\SamplesCS\Menus\Menu\MenuOrientation.cs region=menuVertical}} -{{source=..\SamplesVB\Menus\Menu\MenuOrientation.vb region=menuVertical}} - -````C# -radMenu1.Orientation = System.Windows.Forms.Orientation.Vertical; -radMenuItemFile.TextOrientation = System.Windows.Forms.Orientation.Horizontal; -radMenuItemFile.FlipText = false; -radMenuItemEdit.TextOrientation = System.Windows.Forms.Orientation.Horizontal; -radMenuItemEdit.FlipText = false; -radMenuItemView.TextOrientation = System.Windows.Forms.Orientation.Horizontal; -radMenuItemView.FlipText = false; -radMenuItemHelp.TextOrientation = System.Windows.Forms.Orientation.Horizontal; -radMenuItemHelp.FlipText = false; - -```` -````VB.NET -radMenu1.Orientation = System.Windows.Forms.Orientation.Vertical -radMenuItemFile.TextOrientation = System.Windows.Forms.Orientation.Horizontal -radMenuItemFile.FlipText = False -radMenuItemEdit.TextOrientation = System.Windows.Forms.Orientation.Horizontal -radMenuItemEdit.FlipText = False -radMenuItemView.TextOrientation = System.Windows.Forms.Orientation.Horizontal -radMenuItemView.FlipText = False -radMenuItemHelp.TextOrientation = System.Windows.Forms.Orientation.Horizontal -radMenuItemHelp.FlipText = False - -```` - -{{endregion}} + + + + ## Stacked Vertical Menu @@ -133,35 +58,10 @@ radMenuItemHelp.FlipText = False ![WinForms RadMenu Stacked Vertical Menu](images/menus-menu-styling-and-appearance-menu-orientation004.png) -{{source=..\SamplesCS\Menus\Menu\MenuOrientation.cs region=textMenuVertical}} -{{source=..\SamplesVB\Menus\Menu\MenuOrientation.vb region=textMenuVertical}} - -````C# -radMenu1.Orientation = System.Windows.Forms.Orientation.Vertical; -radMenuItemFile.TextOrientation = System.Windows.Forms.Orientation.Vertical; -radMenuItemFile.FlipText = true; -radMenuItemEdit.TextOrientation = System.Windows.Forms.Orientation.Vertical; -radMenuItemEdit.FlipText = true; -radMenuItemView.TextOrientation = System.Windows.Forms.Orientation.Vertical; -radMenuItemView.FlipText = true; -radMenuItemHelp.TextOrientation = System.Windows.Forms.Orientation.Vertical; -radMenuItemHelp.FlipText = true; - -```` -````VB.NET -radMenu1.Orientation = System.Windows.Forms.Orientation.Vertical -radMenuItemFile.TextOrientation = System.Windows.Forms.Orientation.Vertical -radMenuItemFile.FlipText = True -radMenuItemEdit.TextOrientation = System.Windows.Forms.Orientation.Vertical -radMenuItemEdit.FlipText = True -radMenuItemView.TextOrientation = System.Windows.Forms.Orientation.Vertical -radMenuItemView.FlipText = True -radMenuItemHelp.TextOrientation = System.Windows.Forms.Orientation.Vertical -radMenuItemHelp.FlipText = True - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/menus/menu/usability/keyboard-navigation.md b/controls/menus/menu/usability/keyboard-navigation.md index ca4adbdc0..d81d8a7e4 100644 --- a/controls/menus/menu/usability/keyboard-navigation.md +++ b/controls/menus/menu/usability/keyboard-navigation.md @@ -25,19 +25,10 @@ You can assign mnemonics to the menu items. For example, you can use the __N__ k #### Assigning mnemonics -{{source=..\SamplesCS\Menus\Menu\MenuForm.cs region=mnemonics}} -{{source=..\SamplesVB\Menus\Menu\MenuForm.vb region=mnemonics}} + + -````C# -radMenuItem1.Text = "&New"; -```` -````VB.NET -radMenuItem1.Text = "&New" - -```` - -{{endregion}} >note Mnemonics and accelerators are different features. For example, you need the accelerator Alt+F to open the file menu and the mnemonic N to invoke the event handler associated with the *New* menu item. > diff --git a/controls/menus/menu/working-with-radmenu-items/adding-and-removing-items.md b/controls/menus/menu/working-with-radmenu-items/adding-and-removing-items.md index 85a31ee52..fd580fc78 100644 --- a/controls/menus/menu/working-with-radmenu-items/adding-and-removing-items.md +++ b/controls/menus/menu/working-with-radmenu-items/adding-and-removing-items.md @@ -21,31 +21,10 @@ In order to add top level "main" menu items use the RadMenu.__Items__ collection #### Constructing and adding menu items -{{source=..\SamplesCS\Menus\Menu\MenuForm.cs region=menuItems}} -{{source=..\SamplesVB\Menus\Menu\MenuForm.vb region=menuItems}} - -````C# -RadMenuItem cdItem = new RadMenuItem(); -cdItem.Text = "CDs"; -radMenu1.Items.Add(cdItem); -radMenu1.Items.Add(new RadMenuItem("Books")); -int someData = 123; -RadMenuItem dvdItem = new RadMenuItem("DVDs", someData); -radMenu1.Items.Add(dvdItem); - -```` -````VB.NET -Dim cdItem As New RadMenuItem() -cdItem.Text = "CDs" -RadMenu1.Items.Add(cdItem) -RadMenu1.Items.Add(New RadMenuItem("Books")) -Dim someData As Integer = 123 -Dim dvdItem As New RadMenuItem("DVDs", someData) -RadMenu1.Items.Add(dvdItem) - -```` - -{{endregion}} + + + + ## Adding Sub Menu Items @@ -55,45 +34,10 @@ Adding sub menu items plays by the same rules as adding items to the RadMenu.__I ![WinForms RadMenus Adding Sub Menu Items](images/menus-menu-working-with-radmenu-items-adding-and-removing-items002.png) -{{source=..\SamplesCS\Menus\Menu\MenuForm.cs region=subItems}} -{{source=..\SamplesVB\Menus\Menu\MenuForm.vb region=subItems}} - -````C# -void Form1_Load(object sender, EventArgs e) -{ - radMenu1.Items.Add(new RadMenuItem("Books")); - RadMenuItem item = radMenu1.Items[0] as RadMenuItem; - item.Items.Add(new RadMenuItem("Best Sellers")); - item.Items.Add(new RadMenuItem("Reference Books")); - RadMenuItem bargainItem = new RadMenuItem("Bargains"); - bargainItem.Click += new EventHandler(menuItem_Click); - item.Items.Add(bargainItem); -} -void menuItem_Click(object sender, EventArgs e) -{ - RadMenuItem item = (sender as RadMenuItem); - MessageBox.Show(item.Text + " was clicked."); -} - -```` -````VB.NET -Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) - RadMenu1.Items.Add(New RadMenuItem("Books")) - Dim item As RadMenuItem = TryCast(RadMenu1.Items(0), RadMenuItem) - item.Items.Add(New RadMenuItem("Best Sellers")) - item.Items.Add(New RadMenuItem("Reference Books")) - Dim bargainItem As New RadMenuItem("Bargains") - AddHandler bargainItem.Click, AddressOf menuItem_Click - item.Items.Add(bargainItem) -End Sub -Private Sub menuItem_Click(ByVal sender As Object, ByVal e As EventArgs) - Dim item As RadMenuItem = (TryCast(sender, RadMenuItem)) - MessageBox.Show(item.Text & " was clicked.") -End Sub - -```` - -{{endregion}} + + + + ## Adding a RadMenuComboItem @@ -105,31 +49,10 @@ End Sub #### Adding Combo Sub Item -{{source=..\SamplesCS\Menus\Menu\MenuForm.cs region=comboItem}} -{{source=..\SamplesVB\Menus\Menu\MenuForm.vb region=comboItem}} - -````C# -RadMenuItem bargainItem = new RadMenuItem("Bargains"); -RadMenuComboItem comboItem = new RadMenuComboItem(); -comboItem.ComboBoxElement.Items.Add(new RadListDataItem("$5 - $10")); -comboItem.ComboBoxElement.Items.Add(new RadListDataItem("$10 - $20")); -comboItem.ComboBoxElement.Items.Add(new RadListDataItem("$20 - $50")); -bargainItem.Items.Add(comboItem); -radMenu1.Items.Add(bargainItem); + + -```` -````VB.NET -Dim bargainItem As New RadMenuItem("Bargains") -Dim comboItem As New RadMenuComboItem() -comboItem.ComboBoxElement.Items.Add(New RadListDataItem("$5 - $10")) -comboItem.ComboBoxElement.Items.Add(New RadListDataItem("$10 - $20")) -comboItem.ComboBoxElement.Items.Add(New RadListDataItem("$20 - $50")) -bargainItem.Items.Add(comboItem) -RadMenu1.Items.Add(bargainItem) -```` - -{{endregion}} ## Performance @@ -137,23 +60,10 @@ For best performance when performing long running operations, such as loading a #### Suspending the layout -{{source=..\SamplesCS\Menus\Menu\MenuForm.cs region=performance}} -{{source=..\SamplesVB\Menus\Menu\MenuForm.vb region=performance}} - -````C# -radMenu1.BeginInit(); -// ... perform operations -radMenu1.EndInit(); - -```` -````VB.NET -RadMenu1.BeginInit() -' ... perform operations -RadMenu1.EndInit() + + -```` -{{endregion}} ## Removing Menu Items @@ -161,25 +71,10 @@ Remove items from the items collection using __Remove()__ or __RemoveAt()__ meth #### Removing items -{{source=..\SamplesCS\Menus\Menu\MenuForm.cs region=removingItems}} -{{source=..\SamplesVB\Menus\Menu\MenuForm.vb region=removingItems}} - -````C# -// remove second item in collection -radMenu1.Items.RemoveAt(1); -// Remove the zero-ith ite -radMenu1.Items.Remove(radMenu1.Items[0]); - -```` -````VB.NET -' remove second item in collection -RadMenu1.Items.RemoveAt(1) -' Remove the zero-ith ite -RadMenu1.Items.Remove(RadMenu1.Items(0)) + + -```` -{{endregion}} # See Also diff --git a/controls/menus/menu/working-with-radmenu-items/assign-shortcuts-to-menu-items.md b/controls/menus/menu/working-with-radmenu-items/assign-shortcuts-to-menu-items.md index b550d7fd1..fbd251c31 100644 --- a/controls/menus/menu/working-with-radmenu-items/assign-shortcuts-to-menu-items.md +++ b/controls/menus/menu/working-with-radmenu-items/assign-shortcuts-to-menu-items.md @@ -29,51 +29,19 @@ The following tutorial demonstrates how to assign a shortcut to a **RadMenuItem* #### RadMenuItems Click event handlers -{{source=..\SamplesCS\Shortcuts\Form2.cs region=handlingClickEvent}} -{{source=..\SamplesVB\Shortcuts\Form2.vb region=handlingClickEvent}} - -````C# -void radMenuItem1_Click(object sender, EventArgs e) -{ - MessageBox.Show("New"); -} -void radMenuItem2_Click(object sender, EventArgs e) -{ - MessageBox.Show("File"); -} - -```` -````VB.NET -Private Sub radMenuItem1_Click(ByVal sender As Object, ByVal e As EventArgs) - MessageBox.Show("New") -End Sub -Private Sub radMenuItem2_Click(ByVal sender As Object, ByVal e As EventArgs) - MessageBox.Show("File") -End Sub - -```` - -{{endregion}} + + -6\. Now all you have to do is to add the shortcuts to the desired items -#### Adding shortcuts to menu items -{{source=..\SamplesCS\Shortcuts\Form2.cs region=menuShortcuts}} -{{source=..\SamplesVB\Shortcuts\Form2.vb region=menuShortcuts}} +6\. Now all you have to do is to add the shortcuts to the desired items -````C# -this.radMenuItem1.Shortcuts.Add(new RadShortcut(Keys.Control, Keys.N)); -this.radMenuItem2.Shortcuts.Add(new RadShortcut(Keys.Shift, Keys.F, Keys.K)); +#### Adding shortcuts to menu items -```` -````VB.NET -Me.RadMenuItem1.Shortcuts.Add(New RadShortcut(Keys.Control, Keys.N)) -Me.RadMenuItem2.Shortcuts.Add(New RadShortcut(Keys.Shift, Keys.F, Keys.K)) + + -```` -{{endregion}} >note In the constructor of **RadShortcut**, you should first pass the key modifier as a parameter and then an array of the key mappings. > @@ -86,19 +54,10 @@ Interesting functionality to mention is the ability to set your own custom text #### Assigning HintText -{{source=..\SamplesCS\Shortcuts\Form2.cs region=SetHintText}} -{{source=..\SamplesVB\Shortcuts\Form2.vb region=SetHintText}} - -````C# -radMenuItem2.HintText = "Custom Text"; - -```` -````VB.NET -RadMenuItem2.HintText = "Custom Text" + + -```` -{{endregion}} ![WinForms RadMenu ShortCut HintText](images/menu-items-shortcut004.png) diff --git a/controls/menus/menu/working-with-radmenu-items/multi-line-menu-item-text.md b/controls/menus/menu/working-with-radmenu-items/multi-line-menu-item-text.md index a1e42ae7c..773289072 100644 --- a/controls/menus/menu/working-with-radmenu-items/multi-line-menu-item-text.md +++ b/controls/menus/menu/working-with-radmenu-items/multi-line-menu-item-text.md @@ -21,39 +21,19 @@ In the Properties Window for a __RadMenuItem__ use the drop down list to invoke In code use __Environment.NewLine__ to separate strings: -{{source=..\SamplesCS\Menus\Menu\MenuForm.cs region=multiline}} -{{source=..\SamplesVB\Menus\Menu\MenuForm.vb region=multiline}} + + -````C# -radMenuItem1.Text = "Bar Chart - " + - Environment.NewLine + - "Compare multiple series of data"; -```` -````VB.NET -radMenuItem1.Text = "Bar Chart - " & Environment.NewLine & "Compare multiple series of data" - -```` - -{{endregion}} ## Menu Item Height The __AllItemsEqualHeight__ property controls whether the **RadMenu** allows some menu items to be higher than others. By default, menu items with multiple lines of text are higher than menu items with single lines of text. If you set this property to *true*, the height of all items increases to match that of the tallest items. -{{source=..\SamplesCS\Menus\Menu\WorkingWithRadMenuItems\MultilineMenuItemText.cs region=Height}} -{{source=..\SamplesVB\Menus\Menu\WorkingWithRadMenuItems\MultilineMenuItemText.vb region=Height}} - -````C# -radMenu1.AllItemsEqualHeight = true; - -```` -````VB.NET -radMenu1.AllItemsEqualHeight = True + + -```` -{{endregion}} # See Also diff --git a/controls/menus/menu/working-with-radmenu-items/nesting-controls-in-menu-items.md b/controls/menus/menu/working-with-radmenu-items/nesting-controls-in-menu-items.md index e9158f172..b77e1d54a 100644 --- a/controls/menus/menu/working-with-radmenu-items/nesting-controls-in-menu-items.md +++ b/controls/menus/menu/working-with-radmenu-items/nesting-controls-in-menu-items.md @@ -19,54 +19,10 @@ The __RadMenuContentItem__ is a container menu item that allows you to build up #### Adding content items -{{source=..\SamplesCS\Menus\Menu\NestingControls.cs region=nestingControls}} -{{source=..\SamplesVB\Menus\Menu\NestingControls.vb region=nestingControls}} - -````C# -void Form1_Load(object sender, EventArgs e) -{ - RadMenuContentItem textBoxContentItem = new RadMenuContentItem(); - RadTextBoxElement textBox = new RadTextBoxElement(); - textBox.Text = "Enter text here"; - textBox.MinSize = new Size(100, 0); - textBoxContentItem.ContentElement = textBox; - radMenu1.Items.Add(textBoxContentItem); - RadMenuContentItem buttonContentItem = new RadMenuContentItem(); - RadButtonElement button = new RadButtonElement(); - button.Text = "OK"; - button.Click += new EventHandler(button_Click); - buttonContentItem.ContentElement = button; - radMenu1.Items.Add(buttonContentItem); -} -void button_Click(object sender, EventArgs e) -{ - RadTextBoxElement textBox = radMenu1.Items[0] as RadTextBoxElement; - MessageBox.Show("Text is: " + textBox.Text); -} - -```` -````VB.NET -Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) - Dim textBoxContentItem As New RadMenuContentItem() - Dim textBox As New RadTextBoxElement() - textBox.Text = "Enter text here" - textBox.MinSize = New Size(100, 0) - textBoxContentItem.ContentElement = textBox - RadMenu1.Items.Add(textBoxContentItem) - Dim buttonContentItem As New RadMenuContentItem() - Dim button As New RadButtonElement() - button.Text = "OK" - buttonContentItem.ContentElement = button - RadMenu1.Items.Add(buttonContentItem) -End Sub -Private Sub button_Click(ByVal sender As Object, ByVal e As EventArgs) - Dim textBox As RadTextBoxElement = TryCast(RadMenu1.Items(0), RadTextBoxElement) - MessageBox.Show("Text is: " & textBox.Text) -End Sub - -```` - -{{endregion}} + + + + # Nesting RadControls in Menu Items @@ -80,165 +36,24 @@ This tutorial demonstrates adding a **RadPageView** to a **RadMenu**. Each page 2\. Add the necessary items definitions along with a string array for the months and seasons. -{{source=..\SamplesCS\Menus\Menu\NestingControlsTutorial.cs region=data}} -{{source=..\SamplesVB\Menus\Menu\NestingControlsTutorial.vb region=data}} - -````C# -private RadDropDownList seasonDropDownList; -private RadDropDownList monthDropDownList; -private RadPageView pageView; -private string[] months = new string[] -{ -         "January", "February", "March", "April", "May", -         "June", "July", "August", "September", "October", -         "November", "December", "January" -}; -private string[] seasons = new string[] { "Spring", "Summer", "Fall", "Winter" }; - -```` -````VB.NET -Private seasonDropDownList As RadDropDownList -Private monthDropDownList As RadDropDownList -Private pageView As RadPageView -Private months() As String = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", "January"} -Private seasons() As String = {"Spring", "Summer", "Fall", "Winter"} - -```` - -{{endregion}} + + + + 3\. Create a private method that builds and returns a __RadDropDownList__. In addition, you can display the selected item text by using the **SelectedIndexChanged** event. -{{source=..\SamplesCS\Menus\Menu\NestingControlsTutorial.cs region=CreaateDDL}} -{{source=..\SamplesVB\Menus\Menu\NestingControlsTutorial.vb region=CreaateDDL}} - -````C# -private RadDropDownList CreateRadDropDownListElement(string text, string[] captions) -{ - RadDropDownList ddl = new RadDropDownList(); - ddl.Location = new Point(15, 15); - ddl.Size = new Size(150, 19); - ddl.Margin = new Padding(25, 5, 5, 5); - ddl.Text = text; - foreach (string caption in captions) - { - ddl.Items.Add(new RadListDataItem(caption)); - } - ddl.SelectedIndexChanged += ddl_SelectedIndexChanged; - return ddl; -} -void ddl_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e) -{ - RadListDataItem item = - (sender as RadDropDownList).SelectedItem; - MessageBox.Show(item.Text); -} - -```` -````VB.NET -Private Function CreateRadDropDownListElement(ByVal text As String, ByVal captions() As String) As RadDropDownList - Dim ddl As New RadDropDownList() - ddl.Location = New Point(15, 15) - ddl.Size = New Size(150, 19) - ddl.Margin = New Padding(25, 5, 5, 5) - ddl.Text = text - For Each caption As String In captions - ddl.Items.Add(New RadListDataItem(caption)) - Next caption - AddHandler ddl.SelectedIndexChanged, AddressOf ddl_SelectedIndexChanged - Return ddl -End Function -Private Sub ddl_SelectedIndexChanged(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.Data.PositionChangedEventArgs) - Dim item As RadListDataItem = (TryCast(sender, RadDropDownList)).SelectedItem - MessageBox.Show(item.Text) -End Sub - -```` - -{{endregion}} + + + + 4\. Create a form's __Load__ event handler. In addition, you should add the event prevent the drop down from closing when one is working with the page view. The exit item can be used for closing the drop down in this case. -{{source=..\SamplesCS\Menus\Menu\NestingControlsTutorial.cs region=main}} -{{source=..\SamplesVB\Menus\Menu\NestingControlsTutorial.vb region=main}} - -````C# -private void Form1_Load(object sender, EventArgs e) -{ - monthDropDownList = CreateRadDropDownListElement("Select Month", months); - seasonDropDownList = CreateRadDropDownListElement("Select Season", seasons); - RadMenuItem rmiSettings = new RadMenuItem("Calendar"); - rmiSettings.DropDownClosing += rmiSettings_DropDownClosing; - radMenu1.Items.Add(rmiSettings); - rmiSettings.Items.Add(new RadMenuItem("Options")); - RadMenuItem closeItem = new RadMenuItem("Exit"); - closeItem.Click += closeItem_Click; - rmiSettings.Items.Add(closeItem); - this.pageView = new RadPageView(); - this.pageView.Size = new System.Drawing.Size(300, 100); - RadPageViewStripElement stripElement = this.pageView.ViewElement as RadPageViewStripElement; - stripElement.ItemFitMode = StripViewItemFitMode.None; - stripElement.StripButtons = StripViewButtons.None; - RadPageViewPage montsPage = new RadPageViewPage("Month"); - RadPageViewPage seasonsPage = new RadPageViewPage("Season"); - montsPage.Controls.Add(monthDropDownList); - seasonsPage.Controls.Add(seasonDropDownList); - pageView.Pages.Add(montsPage); - pageView.Pages.Add(seasonsPage); - RadMenuHostItem hostItem = new RadMenuHostItem(pageView); - hostItem.MinSize = new System.Drawing.Size(210, 50); - rmiSettings.Items.Insert(1, hostItem); -} -void closeItem_Click(object sender, EventArgs e) -{ - RadMenuItem item = (RadMenuItem)sender; - RadMenuItem parent = item.HierarchyParent as RadMenuItem; - parent.DropDown.ClosePopup(new PopupCloseInfo(RadPopupCloseReason.CloseCalled, this)); -} -void rmiSettings_DropDownClosing(object sender, RadPopupClosingEventArgs args) -{ - args.Cancel = args.CloseReason == RadPopupCloseReason.Mouse; -} - -```` -````VB.NET -Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) - monthDropDownList = CreateRadDropDownListElement("Select Month", months) - seasonDropDownList = CreateRadDropDownListElement("Select Season", seasons) - Dim rmiSettings As New RadMenuItem("Calendar") - AddHandler rmiSettings.DropDownClosing, AddressOf rmiSettings_DropDownClosing - radMenu1.Items.Add(rmiSettings) - rmiSettings.Items.Add(New RadMenuItem("Options")) - Dim closeItem As New RadMenuItem("Exit") - AddHandler closeItem.Click, AddressOf closeItem_Click - rmiSettings.Items.Add(closeItem) - Me.pageView = New RadPageView() - Me.pageView.Size = New System.Drawing.Size(300, 100) - Dim stripElement As RadPageViewStripElement = TryCast(Me.pageView.ViewElement, RadPageViewStripElement) - stripElement.ItemFitMode = StripViewItemFitMode.None - stripElement.StripButtons = StripViewButtons.None - Dim montsPage As New RadPageViewPage("Month") - Dim seasonsPage As New RadPageViewPage("Season") - montsPage.Controls.Add(monthDropDownList) - seasonsPage.Controls.Add(seasonDropDownList) - pageView.Pages.Add(montsPage) - pageView.Pages.Add(seasonsPage) - Dim hostItem As New RadMenuHostItem(pageView) - hostItem.MinSize = New System.Drawing.Size(210, 50) - rmiSettings.Items.Insert(1, hostItem) -End Sub -Private Sub closeItem_Click(ByVal sender As Object, ByVal e As EventArgs) - Dim item As RadMenuItem = DirectCast(sender, RadMenuItem) - Dim parent As RadMenuItem = TryCast(item.HierarchyParent, RadMenuItem) - parent.DropDown.ClosePopup(New PopupCloseInfo(RadPopupCloseReason.CloseCalled, Me)) -End Sub -Private Sub rmiSettings_DropDownClosing(ByVal sender As Object, ByVal args As RadPopupClosingEventArgs) - args.Cancel = args.CloseReason = RadPopupCloseReason.Mouse -End Sub - -```` - -{{endregion}} + + + + This **Load** event handler performs the main work of the application. diff --git a/controls/menus/menu/working-with-radmenu-items/radmenuitem-events.md b/controls/menus/menu/working-with-radmenu-items/radmenuitem-events.md index 78c5994db..df69ee9a4 100644 --- a/controls/menus/menu/working-with-radmenu-items/radmenuitem-events.md +++ b/controls/menus/menu/working-with-radmenu-items/radmenuitem-events.md @@ -21,117 +21,42 @@ The key event for the __RadMenuItem__ object is the __Click__ event, which is fi #### Handling the ToggleStateChanging event -{{source=..\SamplesCS\Menus\Menu\MenuEvents.cs region=toggleStateChanging}} -{{source=..\SamplesVB\Menus\Menu\MenuEvents.vb region=toggleStateChanging}} - -````C# -void radMenuItem2_ToggleStateChanging(object sender, StateChangingEventArgs args) -{ - if (args.NewValue == Telerik.WinControls.Enumerations.ToggleState.Indeterminate) - { - args.Cancel = true; - } -} - -```` -````VB.NET -Private Sub radMenuItem2_ToggleStateChanging(ByVal sender As Object, ByVal args As StateChangingEventArgs) - If args.NewValue = Telerik.WinControls.Enumerations.ToggleState.Indeterminate Then - args.Cancel = True - End If -End Sub - -```` - -{{endregion}} - + + + + + * __ToggleStateChanged__: This event fires when the check-box state changes between one of the __ToggleState__ enumeration values of *On*, *Off* or *Indeterminate*. The __StateChangedEventaArgs__ passed to this event handler contain the __ToggleState__ property. #### Handling the ToggleStateChanged event -{{source=..\SamplesCS\Menus\Menu\MenuEvents.cs region=toggleStateChanged}} -{{source=..\SamplesVB\Menus\Menu\MenuEvents.vb region=toggleStateChanged}} - -````C# -void radMenuItem2_ToggleStateChanged(object sender, StateChangedEventArgs args) -{ - MessageBox.Show(args.ToggleState.ToString()); -} - -```` -````VB.NET -Private Sub radMenuItem2_ToggleStateChanged(ByVal sender As Object, ByVal args As StateChangedEventArgs) - MessageBox.Show(args.ToggleState.ToString()) -End Sub - -```` - -{{endregion}} - + + + + + ## RadMenuComboItem Events For the __RadMenuComboItem__, you will probably want to work with the events of the embedded __ComboBoxElement__ property. The example below uses the ComboBoxElement.__SelectedIndexChanged__ event to get the currently selected combo box value. #### Handling the SelectedIndexChanged event of RadMenuComboItem -{{source=..\SamplesCS\Menus\Menu\MenuEvents.cs region=comboEvent}} -{{source=..\SamplesVB\Menus\Menu\MenuEvents.vb region=comboEvent}} - -````C# -void Form1_Load(object sender, EventArgs e) -{ - radMenuComboItem1.ComboBoxElement.SelectedIndexChanged += new Telerik.WinControls.UI.Data.PositionChangedEventHandler(ComboBoxElement_SelectedIndexChanged); -} -void ComboBoxElement_SelectedIndexChanged(object sender, EventArgs e) -{ - RadListDataItem item = (sender as RadDropDownListElement).SelectedItem as RadListDataItem; - MessageBox.Show(item.Text); -} - -```` -````VB.NET -Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) - AddHandler radMenuComboItem1.ComboBoxElement.SelectedIndexChanged, AddressOf ComboBoxElement_SelectedIndexChanged -End Sub -Private Sub ComboBoxElement_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) - Dim item As RadListDataItem = TryCast((TryCast(sender, RadDropDownListElement)).SelectedItem, RadListDataItem) - MessageBox.Show(item.Text) -End Sub - -```` - -{{endregion}} - + + + + + ## RadMenuContentItem Handle the events for the control assigned to RadMenuContentItem.__ContentElement__, not the content item itself. In the example below an event handler is attached to the __Click__ event of a button. #### Handling events for controls embedded in RadMenuContentItem -{{source=..\SamplesCS\Menus\Menu\MenuEvents.cs region=contentItem}} -{{source=..\SamplesVB\Menus\Menu\MenuEvents.vb region=contentItem}} - -````C# -RadMenuContentItem buttonItem = new RadMenuContentItem(); -RadButtonElement button = new RadButtonElement(); -button.Text = "OK"; -button.Click += new EventHandler(button_Click); -buttonItem.ContentElement = button; -radMenu1.Items.Add(buttonItem); - -```` -````VB.NET -Dim buttonItem As New RadMenuContentItem() -Dim button As New RadButtonElement() -button.Text = "OK" -AddHandler button.Click, AddressOf button_Click -buttonItem.ContentElement = button -RadMenu1.Items.Add(buttonItem) - -```` - -{{endregion}} - + + + + + # See Also * [Adding and Removing Items]({%slug winforms/menus/menu/working-with-radmenu-items/adding-and-removing-items%}) diff --git a/controls/multicolumncombobox/cancel-drop-down-closing.md b/controls/multicolumncombobox/cancel-drop-down-closing.md index d41879a38..d8ac8dd42 100644 --- a/controls/multicolumncombobox/cancel-drop-down-closing.md +++ b/controls/multicolumncombobox/cancel-drop-down-closing.md @@ -12,32 +12,8 @@ position: 8 **RadMultiColumnComboBox** offers the **DropDownClosing** event which is fired just before the pop up gets closed. This is an appropriate place to prevent closing the drop down according to any custom criteria, e.g. a certain row in the pop up grid is selected. -{{source=..\SamplesCS\MultiColumnComboBox\MCCBgettingStarted.cs region=CancelClosing}} -{{source=..\SamplesVB\MultiColumnComboBox\MCCBgettingStarted.vb region=CancelClosing}} + + -````C# -private void RadMultiColumnComboBox1_DropDownClosing(object sender, RadPopupClosingEventArgs args) -{ - if (this.radMultiColumnComboBox1.EditorControl.CurrentRow != null && - this.radMultiColumnComboBox1.EditorControl.CurrentRow.Index == 2) - { - args.Cancel = true; - } -} - -```` -````VB.NET - -Private Sub RadMultiColumnComboBox1_DropDownClosing(ByVal sender As Object, ByVal args As RadPopupClosingEventArgs) - If Me.RadMultiColumnComboBox1.EditorControl.CurrentRow IsNot Nothing AndAlso - Me.RadMultiColumnComboBox1.EditorControl.CurrentRow.Index = 2 Then - args.Cancel = True - End If -End Sub - - -```` - -{{endregion}} diff --git a/controls/multicolumncombobox/drop-down-properties.md b/controls/multicolumncombobox/drop-down-properties.md index e28c63b59..359d755ad 100644 --- a/controls/multicolumncombobox/drop-down-properties.md +++ b/controls/multicolumncombobox/drop-down-properties.md @@ -19,20 +19,10 @@ The **DropDownWidth** property gets or sets the width of the of the drop-down po #### Setting the DropDownWidth property -{{source=..\SamplesCS\MultiColumnComboBox\MultiColumnComboBox1.cs region=dropDownHeight}} -{{source=..\SamplesVB\MultiColumnComboBox\MultiColumnComboBox1.vb region=dropDownHeight}} + + -````C# - -this.radMultiColumnComboBox1.MultiColumnComboBoxElement.DropDownWidth = 500; -```` -````VB.NET -Me.RadMultiColumnComboBox1.MultiColumnComboBoxElement.DropDownWidth = 500 - -```` - -{{endregion}} >caption Figure 1: DropDownWidth @@ -44,20 +34,10 @@ The **DropDownHeight** property gets or sets the height in pixels of the drop-do #### Setting the DropDownHeight property -{{source=..\SamplesCS\MultiColumnComboBox\MultiColumnComboBox1.cs region=dropDownWidth}} -{{source=..\SamplesVB\MultiColumnComboBox\MultiColumnComboBox1.vb region=dropDownWidth}} - -````C# - -this.radMultiColumnComboBox1.MultiColumnComboBoxElement.DropDownHeight = 500; + + -```` -````VB.NET -Me.RadMultiColumnComboBox1.MultiColumnComboBoxElement.DropDownHeight = 500 -```` - -{{endregion}} >caption Figure 2: DropDownHeight @@ -77,20 +57,10 @@ The **AutoSizeDropDownToBestFit** property determines whether the drop-down port #### Autosize the drop down and best-fitting columns -{{source=..\SamplesCS\MultiColumnComboBox\MultiColumnComboBox1.cs region=AutoSizeDropDownToBestFit}} -{{source=..\SamplesVB\MultiColumnComboBox\MultiColumnComboBox1.vb region=AutoSizeDropDownToBestFit}} - -````C# -this.radMultiColumnComboBox1.AutoSizeDropDownToBestFit = true; - -```` -````VB.NET - -Me.RadMultiColumnComboBox1.AutoSizeDropDownToBestFit = True + + -```` -{{endregion}} ## AutoSizeDropDownColumnMode diff --git a/controls/multicolumncombobox/features/auto-complete.md b/controls/multicolumncombobox/features/auto-complete.md index 412ade097..e926e9a7d 100644 --- a/controls/multicolumncombobox/features/auto-complete.md +++ b/controls/multicolumncombobox/features/auto-complete.md @@ -22,19 +22,10 @@ The __AutoCompleteMode__ property controls the auto-complete behavior and can be ![WinForms RadMultiColumnComboBox AutoCompleteModeNone](images/multicolumncombobox-autocomplete001.png) -{{source=..\SamplesCS\MultiColumnComboBox\AutoCompleteMultiColumnComboBox.cs region=AutoCompleteMode.None}} -{{source=..\SamplesVB\MultiColumnComboBox\AutoCompleteMultiColumnComboBox.vb region=AutoCompleteMode.None}} + + -````C# -this.radMultiColumnComboBox1.AutoCompleteMode = AutoCompleteMode.None; -```` -````VB.NET -Me.RadMultiColumnComboBox1.AutoCompleteMode = AutoCompleteMode.None - -```` - -{{endregion}} * __Append__: As the user types, the next item in the list that matches the user input is automatically appended to the characters the user has already typed. The popup is not shown without the user clicking the arrow. @@ -42,18 +33,9 @@ Me.RadMultiColumnComboBox1.AutoCompleteMode = AutoCompleteMode.None ![WinForms RadMultiColumnComboBox AutoCompleteModeAppend](images/multicolumncombobox-autocomplete002.png) -{{source=..\SamplesCS\MultiColumnComboBox\AutoCompleteMultiColumnComboBox.cs region=AutoCompleteMode.Append}} -{{source=..\SamplesVB\MultiColumnComboBox\AutoCompleteMultiColumnComboBox.vb region=AutoCompleteMode.Append}} - -````C# -this.radMultiColumnComboBox1.AutoCompleteMode = AutoCompleteMode.Append; - -```` -````VB.NET -Me.RadMultiColumnComboBox1.AutoCompleteMode = AutoCompleteMode.Append + + -```` -{{endregion}} * __Suggest__: The following article shows how this functionality can be achieved: [Auto Filter]({%slug winforms/multicolumncombobox/filtering%}). diff --git a/controls/multicolumncombobox/features/filtering.md b/controls/multicolumncombobox/features/filtering.md index 297f1f7fe..5bb211cb5 100644 --- a/controls/multicolumncombobox/features/filtering.md +++ b/controls/multicolumncombobox/features/filtering.md @@ -25,30 +25,10 @@ Filtering operation in __RadMultiColumnComboBox__ is controlled by the Boolean #### FilterDescriptor -{{source=..\SamplesCS\MultiColumnComboBox\MultiColumnComboBox1.cs region=filtering}} -{{source=..\SamplesVB\MultiColumnComboBox\MultiColumnComboBox1.vb region=filtering}} - -````C# - -this.radMultiColumnComboBox1.AutoFilter = true; -this.radMultiColumnComboBox1.DisplayMember = "ContactName"; -FilterDescriptor filter = new FilterDescriptor(); -filter.PropertyName = this.radMultiColumnComboBox1.DisplayMember; -filter.Operator = FilterOperator.Contains; -this.radMultiColumnComboBox1.EditorControl.MasterTemplate.FilterDescriptors.Add(filter); - -```` -````VB.NET -Me.RadMultiColumnComboBox1.AutoFilter = True -Me.RadMultiColumnComboBox1.DisplayMember = "ContactName" -Dim filter As New FilterDescriptor() -filter.PropertyName = Me.RadMultiColumnComboBox1.DisplayMember -filter.Operator = FilterOperator.Contains -Me.RadMultiColumnComboBox1.EditorControl.MasterTemplate.FilterDescriptors.Add(filter) - -```` - -{{endregion}} + + + + The code snippet above will result in the following multi-column combobox: @@ -64,33 +44,10 @@ You can filter data records by multiple values. For this purpose you have to use ![WinForms RadMultiColumnComboBox Filtering with CompositeFilterDescriptors](images/multicolumncombobox-filtering002.gif) -{{source=..\SamplesCS\MultiColumnComboBox\MultiColumnComboBox1.cs region=CompositeFilters}} -{{source=..\SamplesVB\MultiColumnComboBox\MultiColumnComboBox1.vb region=CompositeFilters}} - -````C# -this.radMultiColumnComboBox1.AutoFilter = true; -CompositeFilterDescriptor compositeFilter = new CompositeFilterDescriptor(); -FilterDescriptor prodName = new FilterDescriptor("ProductName", FilterOperator.Contains, ""); -FilterDescriptor prodQuantity = new FilterDescriptor("QuantityPerUnit", FilterOperator.Contains, ""); -compositeFilter.FilterDescriptors.Add(prodName); -compositeFilter.FilterDescriptors.Add(prodQuantity); -compositeFilter.LogicalOperator = FilterLogicalOperator.Or; -this.radMultiColumnComboBox1.EditorControl.FilterDescriptors.Add(compositeFilter); - -```` -````VB.NET -Me.radMultiColumnComboBox1.AutoFilter = True -Dim compositeFilter As New CompositeFilterDescriptor() -Dim prodName As New FilterDescriptor("ProductName", FilterOperator.Contains, "") -Dim prodQuantity As New FilterDescriptor("QuantityPerUnit", FilterOperator.Contains, "") -compositeFilter.FilterDescriptors.Add(prodName) -compositeFilter.FilterDescriptors.Add(prodQuantity) -compositeFilter.LogicalOperator = FilterLogicalOperator.[Or] -Me.radMultiColumnComboBox1.EditorControl.FilterDescriptors.Add(compositeFilter) - -```` - -{{endregion}} + + + + >caution The composite filters allow you to create more complex filtering expressions. Note that this feature is supported for text columns only as the __RadMultiColumnComboBox__ has one common text input for the filtering operation and it is not possible to convert input data to different data formats automatically. > diff --git a/controls/multicolumncombobox/getting-started.md b/controls/multicolumncombobox/getting-started.md index fc0533265..6672a71c5 100644 --- a/controls/multicolumncombobox/getting-started.md +++ b/controls/multicolumncombobox/getting-started.md @@ -44,83 +44,10 @@ The following tutorial demonstrates how to setup **RadMultiColumnComboBox** and 3\. Add a **RadImageButtonElement** and a **RadLabelElement** to the **RadStatusStrip**. 4\. In the Visual Studio *Properties* grid, select the **Events** tab and double click the **SelectedIndexChanged** event in order to generate an event handler. -{{source=..\SamplesCS\MultiColumnComboBox\MCCBgettingStarted.cs region=GettingStarted}} -{{source=..\SamplesVB\MultiColumnComboBox\MCCBgettingStarted.vb region=GettingStarted}} - -````C# - -private void radMultiColumnComboBox1_SelectedIndexChanged(object sender, EventArgs e) -{ - if (this.radMultiColumnComboBox1.SelectedIndex > -1) - { - Image img = GetImageFromBytes(this.radMultiColumnComboBox1.EditorControl.CurrentRow.Cells["Photo"].Value as byte[]); - this.radImageButtonElement1.Image = img.GetThumbnailImage(32, 32, null, IntPtr.Zero); - this.radLabelElement1.Text = this.radMultiColumnComboBox1.Text; - } -} - -private Image GetImageFromBytes(byte[] bytes) -{ - Image result = null; - System.IO.MemoryStream stream = null; - try - { - stream = new System.IO.MemoryStream(bytes, 78, bytes.Length - 78); - result = Image.FromStream(stream); - } - catch - { - try - { - stream = new System.IO.MemoryStream(bytes, 0, bytes.Length); - result = Image.FromStream(stream); - } - catch - { - result = null; - } - } - finally - { - if (stream != null) - stream.Close(); - } - return result; -} - -```` -````VB.NET -Private Sub RadMultiColumnComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles RadMultiColumnComboBox1.SelectedIndexChanged - If Me.RadMultiColumnComboBox1.SelectedIndex > -1 Then - Dim img As Image = GetImageFromBytes(TryCast(Me.RadMultiColumnComboBox1.EditorControl.CurrentRow.Cells("Photo").Value, Byte())) - Me.RadImageButtonElement1.Image = img.GetThumbnailImage(32, 32, Nothing, IntPtr.Zero) - Me.RadLabelElement1.Text = Me.RadMultiColumnComboBox1.Text - End If -End Sub -Private Function GetImageFromBytes(bytes As Byte()) As Image - Dim result As Image = Nothing - Dim stream As System.IO.MemoryStream = Nothing - Try - stream = New System.IO.MemoryStream(bytes, 78, bytes.Length - 78) - result = Image.FromStream(stream) - Catch - Try - stream = New System.IO.MemoryStream(bytes, 0, bytes.Length) - result = Image.FromStream(stream) - Catch - result = Nothing - End Try - Finally - If stream IsNot Nothing Then - stream.Close() - End If - End Try - Return result -End Function - -```` - -{{endregion}} + + + + 5\. Open the **Property Builder** by using the **Smart Tag** and uncheck some of the columns in order to control which columns to be visible. 6\. Press `F5` to run the application and change the selection in **RadMultiColumnComboBox**. diff --git a/controls/multicolumncombobox/how-to/multiple-selection.md b/controls/multicolumncombobox/how-to/multiple-selection.md index 2c15dc970..2f53d334a 100644 --- a/controls/multicolumncombobox/how-to/multiple-selection.md +++ b/controls/multicolumncombobox/how-to/multiple-selection.md @@ -22,435 +22,17 @@ However, in some cases, it may be required to allow multiple selection, e.g. sel #### RadMultiColumnComboBox's extender for multiple selection -{{source=..\SamplesCS\MultiColumnComboBox\MultipleSelectionMCCB.cs region=Extender}} -{{source=..\SamplesVB\MultiColumnComboBox\MultipleSelectionMCCB.vb region=Extender}} + + -````C# -[ToolboxItem(false)] -public class RadMultiColumnComboBoxSelectionExtender : System.ComponentModel.Component -{ - private RadAutoCompleteBoxElement autoCompleteBoxElement; - private System.Collections.Generic.Dictionary rows = new System.Collections.Generic.Dictionary(); - private RadMultiColumnComboBox associatedRadMultiColumnComboBox; - private Size originalSize = Size.Empty; - public RadAutoCompleteBoxElement AutoCompleteBoxElement - { - get - { - return this.autoCompleteBoxElement; - } - } - /// - /// Gets the tokenized items. - /// - public RadTokenizedTextItemCollection Items - { - get { return this.autoCompleteBoxElement.Items; } - } - public RadMultiColumnComboBox AssociatedRadMultiColumnComboBox - { - get - { - return this.associatedRadMultiColumnComboBox; - } - set - { - this.SetAssociatedRadMultiColumnComboBox(value); - } - } - private void SetAssociatedRadMultiColumnComboBox(RadMultiColumnComboBox radMultiColumnComboBox) - { - if (radMultiColumnComboBox == null && this.associatedRadMultiColumnComboBox != null) - { - this.SetAssociatedRadMultiColumnComboBoxCoreToNull(); - } - this.SetAssociatedRadMultiColumnComboBoxCore(radMultiColumnComboBox); - } - private void SetAssociatedRadMultiColumnComboBoxCoreToNull() - { - this.associatedRadMultiColumnComboBox.HandleCreated -= associatedRadMultiColumnComboBox_HandleCreated; - this.associatedRadMultiColumnComboBox.DataBindingComplete -= associatedRadMultiColumnComboBox_DataBindingComplete; - this.associatedRadMultiColumnComboBox.EditorControl.ViewCellFormatting -= EditorControl_ViewCellFormatting; - this.associatedRadMultiColumnComboBox.DropDownClosing -= radMultiColumnCombobox1_DropDownClosing; - this.associatedRadMultiColumnComboBox.MultiColumnComboBoxElement.TextBoxElement.Visibility = ElementVisibility.Visible; - this.associatedRadMultiColumnComboBox.MultiColumnComboBoxElement.Children[2].Children.Remove(autoCompleteBoxElement); - this.autoCompleteBoxElement.MaxSize = new Size(0, 0); - this.autoCompleteBoxElement.AutoCompleteDataSource = null; - this.associatedRadMultiColumnComboBox.AutoSize = false; - this.associatedRadMultiColumnComboBox.Size = this.originalSize; - foreach (GridViewRowInfo item in this.associatedRadMultiColumnComboBox.EditorControl.Rows) - { - item.Tag = null; - } - this.autoCompleteBoxElement.Items.CollectionChanged -= Items_CollectionChanged; - this.autoCompleteBoxElement.CreateTextBlock -= autoCompleteBoxElement_CreateTextBlock; - this.autoCompleteBoxElement.TokenValidating -= autoCompleteBoxElement_TokenValidating; - this.autoCompleteBoxElement.Text = this.associatedRadMultiColumnComboBox.Text; - this.autoCompleteBoxElement.KeyDown -= autoCompleteBoxElement_KeyDown; - this.associatedRadMultiColumnComboBox = null; - this.rows.Clear(); - } - private void SetAssociatedRadMultiColumnComboBoxCore(RadMultiColumnComboBox radMultiColumnComboBox) - { - if (radMultiColumnComboBox == null) - { - return; - } - this.originalSize = radMultiColumnComboBox.Size; - this.associatedRadMultiColumnComboBox = radMultiColumnComboBox; - this.associatedRadMultiColumnComboBox.AutoSize = true; - this.associatedRadMultiColumnComboBox.ThemeNameChanged += associatedRadMultiColumnComboBox_ThemeNameChanged; - this.associatedRadMultiColumnComboBox.HandleCreated += associatedRadMultiColumnComboBox_HandleCreated; - this.associatedRadMultiColumnComboBox.DataBindingComplete += associatedRadMultiColumnComboBox_DataBindingComplete; - this.associatedRadMultiColumnComboBox.DropDownStyle = RadDropDownStyle.DropDownList; - this.associatedRadMultiColumnComboBox.EditorControl.ViewCellFormatting += EditorControl_ViewCellFormatting; - this.associatedRadMultiColumnComboBox.DropDownClosing += radMultiColumnCombobox1_DropDownClosing; - this.autoCompleteBoxElement = new RadAutoCompleteBoxElement(); - this.autoCompleteBoxElement.MinSize = new Size(150, 24); - this.autoCompleteBoxElement.Multiline = true; - this.autoCompleteBoxElement.DrawBorder = false; - this.autoCompleteBoxElement.KeyDown += autoCompleteBoxElement_KeyDown; - this.associatedRadMultiColumnComboBox.MultiColumnComboBoxElement.ArrowButton.ZIndex = 1; - this.associatedRadMultiColumnComboBox.MultiColumnComboBoxElement.TextBoxElement.Visibility = ElementVisibility.Hidden; - this.associatedRadMultiColumnComboBox.MultiColumnComboBoxElement.Children[2].Children.Add(this.autoCompleteBoxElement); - this.autoCompleteBoxElement.MaxSize = new Size(this.associatedRadMultiColumnComboBox.Size.Width - this.associatedRadMultiColumnComboBox.MultiColumnComboBoxElement.ArrowButton.Size.Width, 0); - this.autoCompleteBoxElement.AutoCompleteDataSource = new System.Collections.Generic.List(GetAutoCompleteItems()); - this.autoCompleteBoxElement.Margin = new System.Windows.Forms.Padding(0); - this.autoCompleteBoxElement.Items.CollectionChanged += Items_CollectionChanged; - this.autoCompleteBoxElement.CreateTextBlock += autoCompleteBoxElement_CreateTextBlock; - this.autoCompleteBoxElement.TokenValidating += autoCompleteBoxElement_TokenValidating; - } - void associatedRadMultiColumnComboBox_ThemeNameChanged(object source, ThemeNameChangedEventArgs args) - { - this.autoCompleteBoxElement.MaxSize = new Size(this.associatedRadMultiColumnComboBox.Size.Width - this.associatedRadMultiColumnComboBox.MultiColumnComboBoxElement.ArrowButton.Size.Width, 0); - } - - void autoCompleteBoxElement_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) - { - if (e.KeyCode == System.Windows.Forms.Keys.F4) - { - associatedRadMultiColumnComboBox.MultiColumnComboBoxElement.ShowPopup(); - } - if (e.KeyCode == System.Windows.Forms.Keys.Escape) - { - associatedRadMultiColumnComboBox.MultiColumnComboBoxElement.ClosePopup(RadPopupCloseReason.CloseCalled); - } - } - void associatedRadMultiColumnComboBox_DataBindingComplete(object sender, GridViewBindingCompleteEventArgs e) - { - autoCompleteBoxElement.AutoCompleteDataSource = new System.Collections.Generic.List(GetAutoCompleteItems()); - } - void associatedRadMultiColumnComboBox_HandleCreated(object sender, EventArgs e) - { - autoCompleteBoxElement.AutoCompleteDataSource = new System.Collections.Generic.List(GetAutoCompleteItems()); - } - private System.Collections.Generic.IEnumerable GetAutoCompleteItems() - { - foreach (GridViewRowInfo row in this.associatedRadMultiColumnComboBox.EditorControl.Rows) - { - string value = row.Cells[this.associatedRadMultiColumnComboBox.DisplayMember].Value.ToString().Trim(); - if (!rows.ContainsKey(value)) - { - this.rows.Add(value, row); - } - yield return (value); - } - } - void radMultiColumnCombobox1_DropDownClosing(object sender, RadPopupClosingEventArgs args) - { - args.Cancel = (args.CloseReason == RadPopupCloseReason.Mouse && - this.associatedRadMultiColumnComboBox.EditorControl.ElementTree.GetElementAtPoint(this.associatedRadMultiColumnComboBox.EditorControl.PointToClient(System.Windows.Forms.Cursor.Position)) != null); - this.SyncCollection(); - } - void EditorControl_ViewCellFormatting(object sender, Telerik.WinControls.UI.CellFormattingEventArgs e) - { - if (e.ColumnIndex != -1 || e.CellElement.RowIndex == -1) - { - return; - } - if (e.CellElement.Children.Count == 1) - { - RadCheckBoxElement checkBoxElement = new RadCheckBoxElement(); - checkBoxElement.Padding = new System.Windows.Forms.Padding(0, 3, 1, 0); - checkBoxElement.Alignment = ContentAlignment.MiddleCenter; - checkBoxElement.NotifyParentOnMouseInput = false; - e.CellElement.Children.Add(checkBoxElement); - } - RadCheckBoxElement checkBox = e.CellElement.FindDescendant(); - checkBox.CheckStateChanged -= checkBox_CheckStateChanged; - checkBox.IsChecked = e.Row.Tag != null && e.Row.Tag.ToString() == Boolean.TrueString; - checkBox.CheckStateChanged += checkBox_CheckStateChanged; - } - void SyncCollection() - { - this.associatedRadMultiColumnComboBox.MultiColumnComboBoxElement.TextBoxElement.SuspendPropertyNotifications(); - this.associatedRadMultiColumnComboBox.Text = string.Empty; - foreach (GridViewRowInfo item in this.associatedRadMultiColumnComboBox.EditorControl.Rows) - { - if (item.Tag != null && item.Tag.ToString() == Boolean.TrueString) - { - this.associatedRadMultiColumnComboBox.Text += item.Cells[this.associatedRadMultiColumnComboBox.DisplayMember].Value + "; "; - } - } - this.associatedRadMultiColumnComboBox.MultiColumnComboBoxElement.TextBoxElement.ResumePropertyNotifications(); - autoCompleteBoxElement.Items.CollectionChanged -= Items_CollectionChanged; - autoCompleteBoxElement.CreateTextBlock -= autoCompleteBoxElement_CreateTextBlock; - autoCompleteBoxElement.TokenValidating -= autoCompleteBoxElement_TokenValidating; - autoCompleteBoxElement.Text = this.associatedRadMultiColumnComboBox.Text; - autoCompleteBoxElement.TokenValidating += autoCompleteBoxElement_TokenValidating; - autoCompleteBoxElement.CreateTextBlock += autoCompleteBoxElement_CreateTextBlock; - autoCompleteBoxElement.Items.CollectionChanged += Items_CollectionChanged; - } - void autoCompleteBoxElement_TokenValidating(object sender, TokenValidatingEventArgs e) - { - if (this.rows.ContainsKey(e.Text)) - { - if (this.rows[e.Text].Tag + "" == Boolean.TrueString) - { - e.IsValidToken = false; - } - } - else - { - e.IsValidToken = false; - } - } - void autoCompleteBoxElement_CreateTextBlock(object sender, CreateTextBlockEventArgs e) - { - if (this.rows.ContainsKey(e.Text) && e.TextBlock is TokenizedTextBlockElement) - { - this.rows[e.Text].Tag = Boolean.TrueString; - this.rows[e.Text].InvalidateRow(); - } - } - void Items_CollectionChanged(object sender, Telerik.WinControls.Data.NotifyCollectionChangedEventArgs e) - { - if (e.Action == Telerik.WinControls.Data.NotifyCollectionChangedAction.Remove) - { - foreach (RadTokenizedTextItem item in e.NewItems) - { - if (this.rows.ContainsKey(item.Text.Trim())) - { - string itemText = item.Text.Trim(); - this.rows[itemText].Tag = Boolean.FalseString; - this.rows[itemText].InvalidateRow(); - } - } - } - } - void checkBox_CheckStateChanged(object sender, EventArgs e) - { - RadCheckBoxElement checkBox = sender as RadCheckBoxElement; - GridRowElement row = checkBox.FindAncestor(); - row.RowInfo.Tag = checkBox.IsChecked.ToString(); - } -} -```` -````VB.NET - _ -Public Class RadMultiColumnComboBoxSelectionExtender - Inherits System.ComponentModel.Component - Private m_autoCompleteBoxElement As RadAutoCompleteBoxElement - Private rows As New System.Collections.Generic.Dictionary(Of String, GridViewRowInfo)() - Private m_associatedRadMultiColumnComboBox As RadMultiColumnComboBox - Private originalSize As System.Drawing.Size = System.Drawing.Size.Empty - Public ReadOnly Property AutoCompleteBoxElement() As RadAutoCompleteBoxElement - Get - Return Me.m_autoCompleteBoxElement - End Get - End Property - ''' - ''' Gets the tokenized items. - ''' - Public ReadOnly Property Items() As RadTokenizedTextItemCollection - Get - Return Me.m_autoCompleteBoxElement.Items - End Get - End Property - Public Property AssociatedRadMultiColumnComboBox() As RadMultiColumnComboBox - Get - Return Me.m_associatedRadMultiColumnComboBox - End Get - Set(value As RadMultiColumnComboBox) - Me.SetAssociatedRadMultiColumnComboBox(value) - End Set - End Property - Private Sub SetAssociatedRadMultiColumnComboBox(radMultiColumnComboBox As RadMultiColumnComboBox) - If radMultiColumnComboBox Is Nothing AndAlso Me.m_associatedRadMultiColumnComboBox IsNot Nothing Then - Me.SetAssociatedRadMultiColumnComboBoxCoreToNull() - End If - Me.SetAssociatedRadMultiColumnComboBoxCore(radMultiColumnComboBox) - End Sub - Private Sub SetAssociatedRadMultiColumnComboBoxCoreToNull() - RemoveHandler Me.m_associatedRadMultiColumnComboBox.HandleCreated, AddressOf associatedRadMultiColumnComboBox_HandleCreated - RemoveHandler Me.m_associatedRadMultiColumnComboBox.DataBindingComplete, AddressOf associatedRadMultiColumnComboBox_DataBindingComplete - RemoveHandler Me.m_associatedRadMultiColumnComboBox.EditorControl.ViewCellFormatting, AddressOf EditorControl_ViewCellFormatting - RemoveHandler Me.m_associatedRadMultiColumnComboBox.DropDownClosing, AddressOf radMultiColumnCombobox1_DropDownClosing - Me.m_associatedRadMultiColumnComboBox.MultiColumnComboBoxElement.TextBoxElement.Visibility = ElementVisibility.Visible - Me.m_associatedRadMultiColumnComboBox.MultiColumnComboBoxElement.Children(2).Children.Remove(m_autoCompleteBoxElement) - Me.m_autoCompleteBoxElement.MaxSize = New System.Drawing.Size(0, 0) - Me.m_autoCompleteBoxElement.AutoCompleteDataSource = Nothing - Me.m_associatedRadMultiColumnComboBox.AutoSize = False - Me.m_associatedRadMultiColumnComboBox.Size = Me.originalSize - For Each item As GridViewRowInfo In Me.m_associatedRadMultiColumnComboBox.EditorControl.Rows - item.Tag = Nothing - Next - RemoveHandler Me.m_autoCompleteBoxElement.Items.CollectionChanged, AddressOf Items_CollectionChanged - RemoveHandler Me.m_autoCompleteBoxElement.CreateTextBlock, AddressOf autoCompleteBoxElement_CreateTextBlock - RemoveHandler Me.m_autoCompleteBoxElement.TokenValidating, AddressOf autoCompleteBoxElement_TokenValidating - Me.m_autoCompleteBoxElement.Text = Me.m_associatedRadMultiColumnComboBox.Text - RemoveHandler Me.m_autoCompleteBoxElement.KeyDown, AddressOf autoCompleteBoxElement_KeyDown - Me.m_associatedRadMultiColumnComboBox = Nothing - Me.rows.Clear() - End Sub - Private Sub SetAssociatedRadMultiColumnComboBoxCore(radMultiColumnComboBox As RadMultiColumnComboBox) - If radMultiColumnComboBox Is Nothing Then - Return - End If - Me.originalSize = radMultiColumnComboBox.Size - Me.m_associatedRadMultiColumnComboBox = radMultiColumnComboBox - Me.m_associatedRadMultiColumnComboBox.AutoSize = True - AddHandler Me.m_associatedRadMultiColumnComboBox.ThemeNameChanged, AddressOf associatedRadMultiColumnComboBox_ThemeNameChanged - AddHandler Me.m_associatedRadMultiColumnComboBox.HandleCreated, AddressOf associatedRadMultiColumnComboBox_HandleCreated - AddHandler Me.m_associatedRadMultiColumnComboBox.DataBindingComplete, AddressOf associatedRadMultiColumnComboBox_DataBindingComplete - Me.m_associatedRadMultiColumnComboBox.DropDownStyle = RadDropDownStyle.DropDownList - AddHandler Me.m_associatedRadMultiColumnComboBox.EditorControl.ViewCellFormatting, AddressOf EditorControl_ViewCellFormatting - AddHandler Me.m_associatedRadMultiColumnComboBox.DropDownClosing, AddressOf radMultiColumnCombobox1_DropDownClosing - Me.m_autoCompleteBoxElement = New RadAutoCompleteBoxElement() - Me.m_autoCompleteBoxElement.MinSize = New System.Drawing.Size(150, 24) - Me.m_autoCompleteBoxElement.Multiline = True - Me.m_autoCompleteBoxElement.DrawBorder = False - AddHandler Me.m_autoCompleteBoxElement.KeyDown, AddressOf autoCompleteBoxElement_KeyDown - Me.m_associatedRadMultiColumnComboBox.MultiColumnComboBoxElement.ArrowButton.ZIndex = 1 - Me.m_associatedRadMultiColumnComboBox.MultiColumnComboBoxElement.TextBoxElement.Visibility = ElementVisibility.Hidden - Me.m_associatedRadMultiColumnComboBox.MultiColumnComboBoxElement.Children(2).Children.Add(Me.m_autoCompleteBoxElement) - Me.m_autoCompleteBoxElement.MaxSize = New System.Drawing.Size(Me.m_associatedRadMultiColumnComboBox.Size.Width - Me.m_associatedRadMultiColumnComboBox.MultiColumnComboBoxElement.ArrowButton.Size.Width, 0) - Me.m_autoCompleteBoxElement.AutoCompleteDataSource = New System.Collections.Generic.List(Of String)(GetAutoCompleteItems()) - Me.m_autoCompleteBoxElement.Margin = New System.Windows.Forms.Padding(0) - AddHandler Me.m_autoCompleteBoxElement.Items.CollectionChanged, AddressOf Items_CollectionChanged - AddHandler Me.m_autoCompleteBoxElement.CreateTextBlock, AddressOf autoCompleteBoxElement_CreateTextBlock - AddHandler Me.m_autoCompleteBoxElement.TokenValidating, AddressOf autoCompleteBoxElement_TokenValidating - End Sub - Private Sub associatedRadMultiColumnComboBox_ThemeNameChanged(source As Object, args As ThemeNameChangedEventArgs) - Me.m_autoCompleteBoxElement.MaxSize = New System.Drawing.Size(Me.m_associatedRadMultiColumnComboBox.Size.Width - Me.m_associatedRadMultiColumnComboBox.MultiColumnComboBoxElement.ArrowButton.Size.Width, 0) - End Sub - Private Sub autoCompleteBoxElement_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) - If e.KeyCode = System.Windows.Forms.Keys.F4 Then - m_associatedRadMultiColumnComboBox.MultiColumnComboBoxElement.ShowPopup() - End If - If e.KeyCode = System.Windows.Forms.Keys.Escape Then - m_associatedRadMultiColumnComboBox.MultiColumnComboBoxElement.ClosePopup(RadPopupCloseReason.CloseCalled) - End If - End Sub - Private Sub associatedRadMultiColumnComboBox_DataBindingComplete(sender As Object, e As GridViewBindingCompleteEventArgs) - m_autoCompleteBoxElement.AutoCompleteDataSource = New System.Collections.Generic.List(Of String)(GetAutoCompleteItems()) - End Sub - Private Sub associatedRadMultiColumnComboBox_HandleCreated(sender As Object, e As EventArgs) - m_autoCompleteBoxElement.AutoCompleteDataSource = New System.Collections.Generic.List(Of String)(GetAutoCompleteItems()) - End Sub - Private Function GetAutoCompleteItems() As System.Collections.Generic.IEnumerable(Of String) - Dim items As New List(Of String) - For Each row As GridViewRowInfo In Me.m_associatedRadMultiColumnComboBox.EditorControl.Rows - Dim value As String = row.Cells(Me.m_associatedRadMultiColumnComboBox.DisplayMember).Value.ToString().Trim() - If Not rows.ContainsKey(value) Then - Me.rows.Add(value, row) - End If - items.Add(value) - Next - Return items - End Function - Private Sub radMultiColumnCombobox1_DropDownClosing(sender As Object, args As RadPopupClosingEventArgs) - args.Cancel = (args.CloseReason = RadPopupCloseReason.Mouse AndAlso Me.m_associatedRadMultiColumnComboBox.EditorControl.ElementTree.GetElementAtPoint(Of RadCheckBoxElement)(Me.m_associatedRadMultiColumnComboBox.EditorControl.PointToClient(System.Windows.Forms.Cursor.Position)) IsNot Nothing) - Me.SyncCollection() - End Sub - Private Sub EditorControl_ViewCellFormatting(sender As Object, e As Telerik.WinControls.UI.CellFormattingEventArgs) - If e.ColumnIndex <> -1 OrElse e.CellElement.RowIndex = -1 Then - Return - End If - If e.CellElement.Children.Count = 1 Then - Dim checkBoxElement As New RadCheckBoxElement() - checkBoxElement.Padding = New System.Windows.Forms.Padding(0, 3, 1, 0) - checkBoxElement.Alignment = ContentAlignment.MiddleCenter - checkBoxElement.NotifyParentOnMouseInput = False - e.CellElement.Children.Add(checkBoxElement) - End If - Dim checkBox As RadCheckBoxElement = e.CellElement.FindDescendant(Of RadCheckBoxElement)() - RemoveHandler checkBox.CheckStateChanged, AddressOf checkBox_CheckStateChanged - checkBox.IsChecked = e.Row.Tag IsNot Nothing AndAlso e.Row.Tag.ToString() = [Boolean].TrueString - AddHandler checkBox.CheckStateChanged, AddressOf checkBox_CheckStateChanged - End Sub - Private Sub SyncCollection() - Me.m_associatedRadMultiColumnComboBox.MultiColumnComboBoxElement.TextBoxElement.SuspendPropertyNotifications() - Me.m_associatedRadMultiColumnComboBox.Text = String.Empty - For Each item As GridViewRowInfo In Me.m_associatedRadMultiColumnComboBox.EditorControl.Rows - If item.Tag IsNot Nothing AndAlso item.Tag.ToString() = [Boolean].TrueString Then - Me.m_associatedRadMultiColumnComboBox.Text += item.Cells(Me.m_associatedRadMultiColumnComboBox.DisplayMember).Value + "; " - End If - Next - Me.m_associatedRadMultiColumnComboBox.MultiColumnComboBoxElement.TextBoxElement.ResumePropertyNotifications() - RemoveHandler m_autoCompleteBoxElement.Items.CollectionChanged, AddressOf Items_CollectionChanged - RemoveHandler m_autoCompleteBoxElement.CreateTextBlock, AddressOf autoCompleteBoxElement_CreateTextBlock - RemoveHandler m_autoCompleteBoxElement.TokenValidating, AddressOf autoCompleteBoxElement_TokenValidating - m_autoCompleteBoxElement.Text = Me.m_associatedRadMultiColumnComboBox.Text - AddHandler m_autoCompleteBoxElement.TokenValidating, AddressOf autoCompleteBoxElement_TokenValidating - AddHandler m_autoCompleteBoxElement.CreateTextBlock, AddressOf autoCompleteBoxElement_CreateTextBlock - AddHandler m_autoCompleteBoxElement.Items.CollectionChanged, AddressOf Items_CollectionChanged - End Sub - Private Sub autoCompleteBoxElement_TokenValidating(sender As Object, e As TokenValidatingEventArgs) - If Me.rows.ContainsKey(e.Text) Then - If Me.rows(e.Text).Tag + "" = [Boolean].TrueString Then - e.IsValidToken = False - End If - Else - e.IsValidToken = False - End If - End Sub - Private Sub autoCompleteBoxElement_CreateTextBlock(sender As Object, e As CreateTextBlockEventArgs) - If Me.rows.ContainsKey(e.Text) AndAlso TypeOf e.TextBlock Is TokenizedTextBlockElement Then - Me.rows(e.Text).Tag = [Boolean].TrueString - Me.rows(e.Text).InvalidateRow() - End If - End Sub - Private Sub Items_CollectionChanged(sender As Object, e As Telerik.WinControls.Data.NotifyCollectionChangedEventArgs) - If e.Action = Telerik.WinControls.Data.NotifyCollectionChangedAction.Remove Then - For Each item As RadTokenizedTextItem In e.NewItems - If Me.rows.ContainsKey(item.Text.Trim()) Then - Dim itemText As String = item.Text.Trim() - Me.rows(itemText).Tag = [Boolean].FalseString - Me.rows(itemText).InvalidateRow() - End If - Next - End If - End Sub - Private Sub checkBox_CheckStateChanged(sender As Object, e As EventArgs) - Dim checkBox As RadCheckBoxElement = TryCast(sender, RadCheckBoxElement) - Dim row As GridRowElement = checkBox.FindAncestor(Of GridRowElement)() - row.RowInfo.Tag = checkBox.IsChecked.ToString() - End Sub -End Class - -```` - -{{endregion}} 2\. Create an instance of the above implemented extender and set its **AssociatedRadMultiColumnComboBox** property to the available **RadMultiColumnComboBox** after it is populated with data: -{{source=..\SamplesCS\MultiColumnComboBox\MultipleSelectionMCCB.cs region=ApplyMultiSelection}} -{{source=..\SamplesVB\MultiColumnComboBox\MultipleSelectionMCCB.vb region=ApplyMultiSelection}} - -````C# -RadMultiColumnComboBoxSelectionExtender extender = new RadMultiColumnComboBoxSelectionExtender(); -extender.AssociatedRadMultiColumnComboBox = this.radMultiColumnComboBox1; - -```` -````VB.NET -Dim extender As New RadMultiColumnComboBoxSelectionExtender() -extender.AssociatedRadMultiColumnComboBox = Me.RadMultiColumnComboBox1 + + -```` -{{endregion}} >note A fully functional example is available in our *Demo aplication >> MultiColumnComboBox* section. diff --git a/controls/multicolumncombobox/populating-with-data/databinding.md b/controls/multicolumncombobox/populating-with-data/databinding.md index bcdca1446..3d117c23c 100644 --- a/controls/multicolumncombobox/populating-with-data/databinding.md +++ b/controls/multicolumncombobox/populating-with-data/databinding.md @@ -61,62 +61,10 @@ The important point when adding columns manually is to turn off the automatic ge #### Adding columns -{{source=..\SamplesCS\MultiColumnComboBox\MultiColumnComboBox1.cs region=setUp}} -{{source=..\SamplesVB\MultiColumnComboBox\MultiColumnComboBox1.vb region=setUp}} - -````C# - -protected override void OnLoad(EventArgs e) -{ - base.OnLoad(e); - - NwindDataSet nwindDataSet = new NwindDataSet(); - CustomersTableAdapter customersTableAdapter = new CustomersTableAdapter(); - customersTableAdapter.Fill(nwindDataSet.Customers); - this.radMultiColumnComboBox1.DataSource = nwindDataSet.Customers; - foreach (GridViewDataColumn column in - this.radMultiColumnComboBox1.MultiColumnComboBoxElement.Columns) - { - column.BestFit(); - } -} - -void SetUpGrid() -{ - RadGridView gridViewControl = this.radMultiColumnComboBox1.EditorControl; - gridViewControl.MasterTemplate.AutoGenerateColumns = false; - gridViewControl.Columns.Add(new GridViewTextBoxColumn("CustomerID")); - gridViewControl.Columns.Add(new GridViewTextBoxColumn("ContactName")); - gridViewControl.Columns.Add(new GridViewTextBoxColumn("ContactTitle")); - gridViewControl.Columns.Add(new GridViewTextBoxColumn("Country")); - gridViewControl.Columns.Add(new GridViewTextBoxColumn("Phone")); -} - -```` -````VB.NET -Protected Overrides Sub OnLoad(ByVal e As EventArgs) - MyBase.OnLoad(e) - Dim nwindDataSet As New NwindDataSet() - Dim customersTableAdapter As New CustomersTableAdapter() - customersTableAdapter.Fill(nwindDataSet.Customers) - Me.RadMultiColumnComboBox1.DataSource = nwindDataSet.Customers - For Each column As GridViewDataColumn In Me.RadMultiColumnComboBox1.MultiColumnComboBoxElement.Columns - column.BestFit() - Next column -End Sub -Private Sub SetUpGrid() - Dim gridViewControl As RadGridView = Me.RadMultiColumnComboBox1.EditorControl - gridViewControl.MasterTemplate.AutoGenerateColumns = False - gridViewControl.Columns.Add(New GridViewTextBoxColumn("CustomerID")) - gridViewControl.Columns.Add(New GridViewTextBoxColumn("ContactName")) - gridViewControl.Columns.Add(New GridViewTextBoxColumn("ContactTitle")) - gridViewControl.Columns.Add(New GridViewTextBoxColumn("Country")) - gridViewControl.Columns.Add(New GridViewTextBoxColumn("Phone")) -End Sub - -```` - -{{endregion}} + + + + ## Data binding at run time @@ -124,24 +72,10 @@ You can bind **RadMultiColumnComboBox** programmatically. It is necessary to set #### Binding at run time -{{source=..\SamplesCS\MultiColumnComboBox\MCCBgettingStarted.cs region=Binding}} -{{source=..\SamplesVB\MultiColumnComboBox\MCCBgettingStarted.vb region=Binding}} - -````C# - -this.radMultiColumnComboBox1.DisplayMember = "LastName"; -this.radMultiColumnComboBox1.ValueMember = "EmployeeID"; -this.radMultiColumnComboBox1.DataSource = this.employeesBindingSource; - -```` -````VB.NET -Me.RadMultiColumnComboBox1.DisplayMember = "LastName" -Me.RadMultiColumnComboBox1.ValueMember = "EmployeeID" -Me.RadMultiColumnComboBox1.DataSource = Me.EmployeesBindingSource + + -```` -{{endregion}} # See Also diff --git a/controls/multicolumncombobox/populating-with-data/unbound-mode.md b/controls/multicolumncombobox/populating-with-data/unbound-mode.md index fd3bfe201..5b5dd5585 100644 --- a/controls/multicolumncombobox/populating-with-data/unbound-mode.md +++ b/controls/multicolumncombobox/populating-with-data/unbound-mode.md @@ -14,29 +14,10 @@ position: 1 #### Unbound mode -{{source=..\SamplesCS\MultiColumnComboBox\MCCBgettingStarted.cs region=UnboundMode}} -{{source=..\SamplesVB\MultiColumnComboBox\MCCBgettingStarted.vb region=UnboundMode}} - -````C# -this.radMultiColumnComboBox1.MultiColumnComboBoxElement.Columns.Add("Name"); -this.radMultiColumnComboBox1.MultiColumnComboBoxElement.Columns.Add("Id"); - -for (int i = 0; i < 10; i++) -{ - this.radMultiColumnComboBox1.EditorControl.Rows.Add("Item" + i, i); -} - -```` -````VB.NET -Me.radMultiColumnComboBox1.MultiColumnComboBoxElement.Columns.Add("Name") -Me.radMultiColumnComboBox1.MultiColumnComboBoxElement.Columns.Add("Id") -For i As Integer = 0 To 9 - Me.RadMultiColumnComboBox1.EditorControl.Rows.Add("Item" & i, i) -Next - -```` - -{{endregion}} + + + + >caption Figure 1: Unbound mode diff --git a/controls/multicolumncombobox/styling-and-appearance/accessing-and-customizing-elements.md b/controls/multicolumncombobox/styling-and-appearance/accessing-and-customizing-elements.md index 73d1c2ec5..1dec1600a 100644 --- a/controls/multicolumncombobox/styling-and-appearance/accessing-and-customizing-elements.md +++ b/controls/multicolumncombobox/styling-and-appearance/accessing-and-customizing-elements.md @@ -32,21 +32,10 @@ You can customize the nested elements at run time as well: #### Customize elements -{{source=..\SamplesCS\MultiColumnComboBox\MCCBgettingStarted.cs region=CustomizeElements}} -{{source=..\SamplesVB\MultiColumnComboBox\MCCBgettingStarted.vb region=CustomizeElements}} + + -````C# -this.radMultiColumnComboBox1.MultiColumnComboBoxElement.ArrowButton.Fill.BackColor = Color.Aqua; -this.radMultiColumnComboBox1.MultiColumnComboBoxElement.TextBoxElement.ForeColor = Color.Red; -```` -````VB.NET -Me.RadMultiColumnComboBox1.MultiColumnComboBoxElement.ArrowButton.Fill.BackColor = Color.Aqua -Me.RadMultiColumnComboBox1.MultiColumnComboBoxElement.TextBoxElement.ForeColor = Color.Red -```` - -{{endregion}} - In order to style the pop-up cells it is suitable to use the [CellFormatting]({%slug winforms/gridview/cells/formatting-cells%}) event that **RadGridView** offers. diff --git a/controls/navigationview/header-and-footer.md b/controls/navigationview/header-and-footer.md index 8f4507206..66fca6c2c 100644 --- a/controls/navigationview/header-and-footer.md +++ b/controls/navigationview/header-and-footer.md @@ -25,27 +25,10 @@ The following examples demonstrate how to manage the item's position using the h #### Add items to the Header -{{source=..\SamplesCS\PageView\NavigationView.cs region=PinHeaderItems}} -{{source=..\SamplesVB\PageView\NavigationView.vb region=PinHeaderItems}} + + -````C# -(inboxPage.Item as RadPageViewNavigationViewItem).PinPosition = NavigationViewItemPinPosition.Header; -this.radNavigationView1.PinPage(inboxPage, NavigationViewItemPinPosition.Header); -this.radNavigationView1.PinItem(inboxPage.Item, NavigationViewItemPinPosition.Header); -this.radNavigationView1.AddHeaderPage(inboxPage); -this.radNavigationView1.AddHeaderItem(inboxPage.Item); -```` -````VB.NET -TryCast(Me.inboxPage.Item, RadPageViewNavigationViewItem).PinPosition = NavigationViewItemPinPosition.Header -Me.radNavigationView1.PinPage(Me.inboxPage, NavigationViewItemPinPosition.Header) -Me.radNavigationView1.PinItem(Me.inboxPage.Item, NavigationViewItemPinPosition.Header) -Me.radNavigationView1.AddHeaderPage(Me.inboxPage) -Me.radNavigationView1.AddHeaderItem(Me.inboxPage.Item) - -```` - -{{endregion}} ![WinForms RadNavigationView Header/Footer](images/navigationview-header-and-footer001.png) @@ -62,29 +45,10 @@ In order to pin items into the footer area you can use any of the following opti #### Add items to the Footer -{{source=..\SamplesCS\PageView\NavigationView.cs region=PinFooterItems}} -{{source=..\SamplesVB\PageView\NavigationView.vb region=PinFooterItems}} - -````C# -(draftsPage.Item as RadPageViewNavigationViewItem).PinPosition = NavigationViewItemPinPosition.Footer; -this.radNavigationView1.PinPage(draftsPage, NavigationViewItemPinPosition.Footer); -this.radNavigationView1.PinItem(draftsPage.Item, NavigationViewItemPinPosition.Footer); -this.radNavigationView1.AddFooterPage(draftsPage); -this.radNavigationView1.AddFooterItem(draftsPage.Item); -this.radNavigationView1.AddFooterItem(deletedPage.Item); + + -```` -````VB.NET -TryCast(Me.draftsPage.Item, RadPageViewNavigationViewItem).PinPosition = NavigationViewItemPinPosition.Footer -Me.radNavigationView1.PinPage(Me.draftsPage, NavigationViewItemPinPosition.Footer) -Me.radNavigationView1.PinItem(Me.draftsPage.Item, NavigationViewItemPinPosition.Footer) -Me.radNavigationView1.AddFooterPage(Me.draftsPage) -Me.radNavigationView1.AddFooterItem(Me.draftsPage.Item) -Me.radNavigationView1.AddFooterItem(Me.deletedPage.Item) -```` - -{{endregion}} ![WinForms RadNavigationView Header/Footer](images/navigationview-header-and-footer002.png) @@ -99,27 +63,10 @@ In order to unpin items that have already been pinned, you can use again **PinPo #### Unpin Items -{{source=..\SamplesCS\PageView\NavigationView.cs region=UnpinItems}} -{{source=..\SamplesVB\PageView\NavigationView.vb region=UnpinItems}} - -````C# -(this.draftsPage.Item as RadPageViewNavigationViewItem).PinPosition = NavigationViewItemPinPosition.None; -this.radNavigationView1.PinPage(this.draftsPage, NavigationViewItemPinPosition.None); -this.radNavigationView1.PinItem(this.draftsPage.Item, NavigationViewItemPinPosition.None); -this.radNavigationView1.UnpinPage(this.draftsPage); -this.radNavigationView1.UnpinItem(this.draftsPage.Item); - -```` -````VB.NET -TryCast(Me.draftsPage.Item, RadPageViewNavigationViewItem).PinPosition = NavigationViewItemPinPosition.None -Me.radNavigationView1.PinPage(Me.draftsPage, NavigationViewItemPinPosition.None) -Me.radNavigationView1.PinItem(Me.draftsPage.Item, NavigationViewItemPinPosition.None) -Me.radNavigationView1.UnpinPage(Me.draftsPage) -Me.radNavigationView1.UnpinItem(Me.draftsPage.Item) + + -```` -{{endregion}} ![WinForms RadNavigationView Header/Footer](images/navigationview-header-and-footer003.png) diff --git a/controls/navigationview/hierarchy-support.md b/controls/navigationview/hierarchy-support.md index 1ac91d543..2aef37c02 100644 --- a/controls/navigationview/hierarchy-support.md +++ b/controls/navigationview/hierarchy-support.md @@ -20,78 +20,10 @@ Each **RadPageViewPage** element has a **SubPages** collection that can be popul ### Building Hierarchy with Nested Pages Programmatically -{{source=..\SamplesCS\PageView\NavigationView.cs region=Hierarchy}} -{{source=..\SamplesVB\PageView\NavigationView.vb region=Hierarchy}} - -````C# - -RadPageViewPage inboxPage = new RadPageViewPage("Inbox"); -RadPageViewPage radPageViewPage2 = new RadPageViewPage("LinkedIn"); -RadPageViewPage radPageViewPage3 = new RadPageViewPage("Twitter"); -RadPageViewPage radPageViewPage4 = new RadPageViewPage("Pinterest"); -RadPageViewPage radPageViewPage5 = new RadPageViewPage("Subscriptions"); -RadPageViewPage radPageViewPage6 = new RadPageViewPage("Order Updates"); -RadPageViewPage draftsPage = new RadPageViewPage("Drafts"); -RadPageViewPage sentPage = new RadPageViewPage("Sent"); -RadPageViewPage importantPage = new RadPageViewPage("Important"); -RadPageViewPage radPageViewPage10 = new RadPageViewPage("Univeristy"); -RadPageViewPage radPageViewPage11 = new RadPageViewPage("Work"); -RadPageViewPage allMailPage = new RadPageViewPage("All Mail"); -RadPageViewPage spamPage = new RadPageViewPage("Spam"); -RadPageViewPage deletedPage = new RadPageViewPage("Deleted"); - -inboxPage.SubPages.Add(radPageViewPage2); -inboxPage.SubPages.Add(radPageViewPage3); -inboxPage.SubPages.Add(radPageViewPage4); -inboxPage.SubPages.Add(radPageViewPage5); -inboxPage.SubPages.Add(radPageViewPage6); - -importantPage.SubPages.Add(radPageViewPage10); -importantPage.SubPages.Add(radPageViewPage11); - -this.radNavigationView1.Pages.Add(inboxPage); -this.radNavigationView1.Pages.Add(draftsPage); -this.radNavigationView1.Pages.Add(sentPage); -this.radNavigationView1.Pages.Add(importantPage); -this.radNavigationView1.Pages.Add(allMailPage); -this.radNavigationView1.Pages.Add(spamPage); -this.radNavigationView1.Pages.Add(deletedPage); - -```` -````VB.NET - -Dim inboxPage As RadPageViewPage = New RadPageViewPage("Inbox") -Dim radPageViewPage2 As RadPageViewPage = New RadPageViewPage("LinkedIn") -Dim radPageViewPage3 As RadPageViewPage = New RadPageViewPage("Twitter") -Dim radPageViewPage4 As RadPageViewPage = New RadPageViewPage("Pinterest") -Dim radPageViewPage5 As RadPageViewPage = New RadPageViewPage("Subscriptions") -Dim radPageViewPage6 As RadPageViewPage = New RadPageViewPage("Order Updates") -Dim draftsPage As RadPageViewPage = New RadPageViewPage("Drafts") -Dim sentPage As RadPageViewPage = New RadPageViewPage("Sent") -Dim importantPage As RadPageViewPage = New RadPageViewPage("Important") -Dim radPageViewPage10 As RadPageViewPage = New RadPageViewPage("Univeristy") -Dim radPageViewPage11 As RadPageViewPage = New RadPageViewPage("Work") -Dim allMailPage As RadPageViewPage = New RadPageViewPage("All Mail") -Dim spamPage As RadPageViewPage = New RadPageViewPage("Spam") -Dim deletedPage As RadPageViewPage = New RadPageViewPage("Deleted") -inboxPage.SubPages.Add(radPageViewPage2) -inboxPage.SubPages.Add(radPageViewPage3) -inboxPage.SubPages.Add(radPageViewPage4) -inboxPage.SubPages.Add(radPageViewPage5) -inboxPage.SubPages.Add(radPageViewPage6) -importantPage.SubPages.Add(radPageViewPage10) -importantPage.SubPages.Add(radPageViewPage11) -Me.radNavigationView1.Pages.Add(inboxPage) -Me.radNavigationView1.Pages.Add(draftsPage) -Me.radNavigationView1.Pages.Add(sentPage) -Me.radNavigationView1.Pages.Add(importantPage) -Me.radNavigationView1.Pages.Add(allMailPage) -Me.radNavigationView1.Pages.Add(spamPage) -Me.radNavigationView1.Pages.Add(deletedPage) - -```` - -{{endregion}} + + + + ![WinForms RadNavigationView Hierarchy Sample](images/hierarchy-support002.png) diff --git a/controls/navigationview/ui-automation.md b/controls/navigationview/ui-automation.md index ea95ed269..7376c157d 100644 --- a/controls/navigationview/ui-automation.md +++ b/controls/navigationview/ui-automation.md @@ -14,21 +14,10 @@ With the Q3 2024 version of our controls, RadNavigationView supports UI Automati This functionality is enabled by default. To disable it, you can set the __EnableUIAutomation__ property to false. -{{source=..\SamplesCS\GridView\Cells\NavigationView.cs region=enableUIAutomation}} -{{source=..\SamplesVB\GridView\Cells\NavigationView.vb region=enableUIAutomation}} + + -````C# -this.radNavigationView1.EnableUIAutomation = false; - -```` -````VB.NET - -Me.RadNavigationView1.EnableUIAutomation = False - -```` - -{{endregion}} ![navigationview-ui-automation](images/navigationview-ui-automation001.png) @@ -106,160 +95,10 @@ The following section outlines the supported automation patterns for the __RadNa The __RadNavigationView__ control expose CreateUIAutomationProvider() method that can be overriden to replace the default RadNavigationViewUIAutomationProvider class with your own implementation of the __IRawElementProviderFragmentRoot__ interface. -{{source=..\SamplesCS\GridView\Cells\NavigationView.cs region=customUIAutomationProvider}} -{{source=..\SamplesVB\GridView\Cells\NavigationView.vb region=customUIAutomationProvider}} - -````C# - -public class MyRadNavigationView : RadNavigationView -{ - protected override System.Windows.Automation.Provider.IRawElementProviderFragmentRoot CreateUIAutomationProvider() - { - return new MyUIAutomationProvider(); - } - - public override string ThemeClassName - { - get - { - return typeof(RadNavigationView).FullName; - } - } -} - -public class MyUIAutomationProvider : IRawElementProviderFragmentRoot -{ - public System.Windows.Rect BoundingRectangle => throw new NotImplementedException(); - - public IRawElementProviderFragmentRoot FragmentRoot => throw new NotImplementedException(); - - public ProviderOptions ProviderOptions => throw new NotImplementedException(); - - public IRawElementProviderSimple HostRawElementProvider => throw new NotImplementedException(); - - public IRawElementProviderFragment ElementProviderFromPoint(double x, double y) - { - throw new NotImplementedException(); - } - - public IRawElementProviderSimple[] GetEmbeddedFragmentRoots() - { - throw new NotImplementedException(); - } - - public IRawElementProviderFragment GetFocus() - { - throw new NotImplementedException(); - } - - public object GetPatternProvider(int patternId) - { - throw new NotImplementedException(); - } - - public object GetPropertyValue(int propertyId) - { - throw new NotImplementedException(); - } - - public int[] GetRuntimeId() - { - throw new NotImplementedException(); - } - - public IRawElementProviderFragment Navigate(NavigateDirection direction) - { - throw new NotImplementedException(); - } - - public void SetFocus() - { - throw new NotImplementedException(); - } -} - - -```` -````VB.NET - -Public Class MyRadNavigationView - Inherits RadNavigationView - Protected Overrides Function CreateUIAutomationProvider() As IRawElementProviderFragmentRoot - Return MyBase.CreateUIAutomationProvider() - End Function - Public Overrides Property ThemeClassName As String - Get - Return GetType(RadNavigationView).FullName - End Get - Set(value As String) - MyBase.ThemeClassName = value - End Set - End Property -End Class - -Public Class MyUIAutomationProvider - Implements IRawElementProviderFragmentRoot - - Public ReadOnly Property BoundingRectangle As Rect Implements IRawElementProviderFragment.BoundingRectangle - Get - Throw New NotImplementedException() - End Get - End Property - - Public ReadOnly Property FragmentRoot As IRawElementProviderFragmentRoot Implements IRawElementProviderFragment.FragmentRoot - Get - Throw New NotImplementedException() - End Get - End Property - - Public ReadOnly Property ProviderOptions As ProviderOptions Implements IRawElementProviderSimple.ProviderOptions - Get - Throw New NotImplementedException() - End Get - End Property - - Public ReadOnly Property HostRawElementProvider As IRawElementProviderSimple Implements IRawElementProviderSimple.HostRawElementProvider - Get - Throw New NotImplementedException() - End Get - End Property - - Public Sub SetFocus() Implements IRawElementProviderFragment.SetFocus - Throw New NotImplementedException() - End Sub - - Public Function ElementProviderFromPoint(x As Double, y As Double) As IRawElementProviderFragment Implements IRawElementProviderFragmentRoot.ElementProviderFromPoint - Throw New NotImplementedException() - End Function - - Public Function GetFocus() As IRawElementProviderFragment Implements IRawElementProviderFragmentRoot.GetFocus - Throw New NotImplementedException() - End Function - - Public Function Navigate(direction As NavigateDirection) As IRawElementProviderFragment Implements IRawElementProviderFragment.Navigate - Throw New NotImplementedException() - End Function - - Public Function GetRuntimeId() As Integer() Implements IRawElementProviderFragment.GetRuntimeId - Throw New NotImplementedException() - End Function - - Public Function GetEmbeddedFragmentRoots() As IRawElementProviderSimple() Implements IRawElementProviderFragment.GetEmbeddedFragmentRoots - Throw New NotImplementedException() - End Function - - Public Function GetPatternProvider(patternId As Integer) As Object Implements IRawElementProviderSimple.GetPatternProvider - Throw New NotImplementedException() - End Function - - Public Function GetPropertyValue(propertyId As Integer) As Object Implements IRawElementProviderSimple.GetPropertyValue - Throw New NotImplementedException() - End Function -End Class - -```` - -{{endregion}} + + + + ## See Also diff --git a/controls/notifyicon/features/balloon-notifications.md b/controls/notifyicon/features/balloon-notifications.md index c98cbe3d9..127c75532 100644 --- a/controls/notifyicon/features/balloon-notifications.md +++ b/controls/notifyicon/features/balloon-notifications.md @@ -22,38 +22,9 @@ The RadNotifyIcon exposes the following properties for controlling the look of t >tip Use an .ico file with bigger dimensions (Width/Height) as Windows can scale it down, however it will not be scaled up, if it is less than the default size. -{{source=..\SamplesCS\NotifyIcon\Features.cs region=Balloon}} -{{source=..\SamplesVB\NotifyIcon\Features.vb region=Balloon}} -````C# + + -void ShowBallonNotification() -{ - RadNotifyIcon radNotifyIcon = new RadNotifyIcon(); - radNotifyIcon.TrayIcon = new System.Drawing.Icon("../../WinForms128x28.ico"); - radNotifyIcon.BalloonIcon = new System.Drawing.Icon("../../WinForms128x28.ico"); - radNotifyIcon.ShowTrayIcon = true; - radNotifyIcon.BalloonText = "Balloon Text"; - radNotifyIcon.BalloonTitle = "Balloon Title"; - radNotifyIcon.ShowBalloonTip(); -} - -```` -````VB.NET - -Private Sub ShowBallonNotification() - Dim radNotifyIcon As RadNotifyIcon = New RadNotifyIcon() - radNotifyIcon.TrayIcon = New System.Drawing.Icon("../../WinForms128x28.ico") - radNotifyIcon.BalloonIcon = New System.Drawing.Icon("../../WinForms128x28.ico") - radNotifyIcon.ShowTrayIcon = True - radNotifyIcon.BalloonText = "Balloon Text" - radNotifyIcon.BalloonTitle = "Balloon Title" - radNotifyIcon.ShowBalloonTip() -End Sub - - -```` - -{{endregion}} #### __Figure 1: Balloon Notification__ @@ -68,21 +39,10 @@ Here are the overloads exposed by the ShowBallonTip method: * **void ShowBalloonTip(string title, string text, BalloonTipIcon icon, bool doNotPlaySound = false, int timeout = 10)**: This overload allows for passing a title, text and choosing an icon from the set of standardized icons. Optionally you can specify whether sound should be played and the amount of seconds to wait before the balloon auto hides (The system minimum and maximum are 10 and 30 seconds). -{{source=..\SamplesCS\NotifyIcon\Features.cs region=BalloonWarning}} -{{source=..\SamplesVB\NotifyIcon\Features.vb region=BalloonWarning}} -````C# + + -this.radNotifyIcon.ShowBalloonTip("Warning", "Emergency", BalloonTipIcon.Warning, false, 15); -```` -````VB.NET - -Me.radNotifyIcon.ShowBalloonTip("Warning", "Emergency", BalloonTipIcon.Warning, False, 15) - - -```` - -{{endregion}} #### __Figure 2: Warning Notification__ @@ -90,44 +50,17 @@ Me.radNotifyIcon.ShowBalloonTip("Warning", "Emergency", BalloonTipIcon.Warning, * **void ShowBalloonTip(string title, string text, System.Drawing.Icon icon, bool doNotPlaySound = false, int timeout = 10)**: This overload allows for passing a title, text and a __System.Drawing.Icon__ instance. Optionally you can specify whether sound should be played and the amount of seconds to wait before the balloon auto hides (The system minimum and maximum are 10 and 30 seconds). -{{source=..\SamplesCS\NotifyIcon\Features.cs region=BalloonCustomIcon}} -{{source=..\SamplesVB\NotifyIcon\Features.vb region=BalloonCustomIcon}} -````C# - -var icon = new System.Drawing.Icon("../../WinForms128x28.ico"); -this.radNotifyIcon.ShowBalloonTip("Balloon Title", "Balloon Text", icon, false, 15); + + -```` -````VB.NET - -Dim icon = New System.Drawing.Icon("../../WinForms128x28.ico") -Me.radNotifyIcon.ShowBalloonTip("Balloon Title", "Balloon Text", icon, False, 15) - - -```` - -{{endregion}} ## Hide the Notification You can manually hide the notification by invoking the __HideBalloonTip__ method. -{{source=..\SamplesCS\NotifyIcon\Features.cs region=HideBallon}} -{{source=..\SamplesVB\NotifyIcon\Features.vb region=HideBallon}} -````C# - -this.radNotifyIcon.HideBalloonTip(); - -```` -````VB.NET - -Me.radNotifyIcon.HideBalloonTip() - - -```` - -{{endregion}} + + diff --git a/controls/notifyicon/features/contextmenu.md b/controls/notifyicon/features/contextmenu.md index 4096d54f5..7ea9ebd21 100644 --- a/controls/notifyicon/features/contextmenu.md +++ b/controls/notifyicon/features/contextmenu.md @@ -15,44 +15,10 @@ You can display a context menu when the user interacts with the notify icon with The __TrayContextMenu__ property expects a value of type [RadContextMenu]({%slug winforms/menus/contextmenu/context-menus%}). __Example 1__ demonstrates how it can be used. -{{source=..\SamplesCS\NotifyIcon\Features.cs region=TrayContextMenu}} -{{source=..\SamplesVB\NotifyIcon\Features.vb region=TrayContextMenu}} -````C# + + -void SetContextMenu() -{ - RadNotifyIcon radNotifyIcon = new RadNotifyIcon(); - radNotifyIcon.TrayIcon = new System.Drawing.Icon("../../WinForms128x28.ico"); - radNotifyIcon.ContextMenuActivationMouseEvent = MouseActivationEvent.RightClick; - radNotifyIcon.ShowTrayIcon = true; - radNotifyIcon.PopupContent = new UserControl1(); - var contextMenu = new RadContextMenu(); - contextMenu.Items.Add(new RadMenuItem("Item 1")); - contextMenu.Items.Add(new RadMenuItem("Item 2")); - contextMenu.Items.Add(new RadMenuItem("Item 3")); - radNotifyIcon.TrayContextMenu = contextMenu; -} -```` -````VB.NET - -Private Sub SetContextMenu() - Dim radNotifyIcon As RadNotifyIcon = New RadNotifyIcon() - radNotifyIcon.TrayIcon = New System.Drawing.Icon("../../WinForms128x28.ico") - radNotifyIcon.ContextMenuActivationMouseEvent = MouseActivationEvent.RightClick - radNotifyIcon.ShowTrayIcon = True - radNotifyIcon.PopupContent = New UserControl1() - Dim contextMenu = New RadContextMenu() - contextMenu.Items.Add(New RadMenuItem("Item 1")) - contextMenu.Items.Add(New RadMenuItem("Item 2")) - contextMenu.Items.Add(New RadMenuItem("Item 3")) - radNotifyIcon.TrayContextMenu = contextMenu -End Sub - - -```` - -{{endregion}} #### __Figure 1: RadContextMenu displayed over the icon__ @@ -69,19 +35,8 @@ The __ContextMenuActivationMouseEvent__ property determines when the context men * __MiddleDoubleClick__: Triggered on middle mouse double click. * __All__: Triggered on any mouse click action. -{{source=..\SamplesCS\NotifyIcon\Features.cs region=ContextMenuActivationMouseEvent}} -{{source=..\SamplesVB\NotifyIcon\Features.vb region=ContextMenuActivationMouseEvent}} -````C# - -radNotifyIcon.ContextMenuActivationMouseEvent = MouseActivationEvent.MiddleClick; - -```` -````VB.NET - -radNotifyIcon.ContextMenuActivationMouseEvent = MouseActivationEvent.MiddleClick - + + -```` -{{endregion}} diff --git a/controls/notifyicon/features/popup.md b/controls/notifyicon/features/popup.md index 524f3e6cf..0bae22864 100644 --- a/controls/notifyicon/features/popup.md +++ b/controls/notifyicon/features/popup.md @@ -15,32 +15,9 @@ The __RadNotifyIcon__ allows for displaying a popup upon interacting with the ic The __PopupContent__ property allow for setting the popup's content and changing its default look. The **PopupContent** property is of type **Control**. This way you can design your Form, UserControl, etc. and set it as a content of the popup. -{{source=..\SamplesCS\NotifyIcon\Features.cs region=PopupContent}} -{{source=..\SamplesVB\NotifyIcon\Features.vb region=PopupContent}} -````C# + + -void ShowNotifyIconPopup() -{ - RadNotifyIcon radNotifyIcon = new RadNotifyIcon(); - radNotifyIcon.TrayIcon = new System.Drawing.Icon("../../WinForms128x28.ico"); - radNotifyIcon.PopupContent = new UserControl1(); - radNotifyIcon.ShowTrayIcon = true; -} - -```` -````VB.NET - -Private Sub ShowNotifyIconPopup() - Dim radNotifyIcon As RadNotifyIcon = New RadNotifyIcon() - radNotifyIcon.TrayIcon = New System.Drawing.Icon("../../WinForms128x28.ico") - radNotifyIcon.PopupContent = New UserControl1() - radNotifyIcon.ShowTrayIcon = True -End Sub - - -```` - -{{endregion}} #### __Figure 1: RadNotifyIcon with Popup__ (Windows 11 OS) @@ -59,43 +36,19 @@ The __PopupActivationMouseEvent__ property determines when the popup will be sho * __All__: Triggered on any mouse click action. -{{source=..\SamplesCS\NotifyIcon\Features.cs region=PopupActivationMouseEvent}} -{{source=..\SamplesVB\NotifyIcon\Features.vb region=PopupActivationMouseEvent}} -````C# - -radNotifyIcon.PopupActivationMouseEvent = MouseActivationEvent.All; + + -```` -````VB.NET - -radNotifyIcon.PopupActivationMouseEvent = MouseActivationEvent.All - - -```` - -{{endregion}} ## PopupShowDuration The __PopupShowDuration__ specifies the amount of time in __milliseconds__ after which the popup will begin to close automatically. The default value is __5000__ milliseconds (5s). -{{source=..\SamplesCS\NotifyIcon\Features.cs region=PopupShowDuration}} -{{source=..\SamplesVB\NotifyIcon\Features.vb region=PopupShowDuration}} -````C# - -radNotifyIcon.PopupShowDuration = 3000; + + -```` -````VB.NET - -radNotifyIcon.PopupShowDuration = 3000 - - -```` - -{{endregion}} ## PopupCloseMode @@ -112,37 +65,19 @@ The RadNotifyIcon allows for programmatically showing a popup through the __Show * **void ShowPopup()**: Shows the popup on top of the notify icon. * **void ShowPopup(Point location)**: Shows the popup at the provided location. -{{source=..\SamplesCS\NotifyIcon\Features.cs region=ShowPopup}} -{{source=..\SamplesVB\NotifyIcon\Features.vb region=ShowPopup}} -````C# -radNotifyIcon.ShowPopup(); - -```` -````VB.NET -radNotifyIcon.ShowPopup() + + -```` -{{endregion}} ## Programmatically Hiding the Popup You can manually hide the popup with the __HidePopup__ method as shown in __Example 6__. -{{source=..\SamplesCS\NotifyIcon\Features.cs region=HidePopup}} -{{source=..\SamplesVB\NotifyIcon\Features.vb region=HidePopup}} -````C# - -radNotifyIcon.HidePopup(); + + -```` -````VB.NET -radNotifyIcon.HidePopup() - -```` - -{{endregion}} ## Popup Animations @@ -151,22 +86,10 @@ You can control the opening and closing animation with the __PopupShowAnimation_ * **Fade**: A Fade animation is applied. * **Timeout**: A 'Slide' animation is applied. -{{source=..\SamplesCS\NotifyIcon\Features.cs region=PopupAnimation}} -{{source=..\SamplesVB\NotifyIcon\Features.vb region=PopupAnimation}} -````C# - -radNotifyIcon.PopupShowAnimation = NotifyIconAnimationType.Slide; -radNotifyIcon.PopupHideAnimation = NotifyIconAnimationType.Fade; - -```` -````VB.NET - -radNotifyIcon.PopupShowAnimation = NotifyIconAnimationType.Slide -radNotifyIcon.PopupHideAnimation = NotifyIconAnimationType.Fade + + -```` -{{endregion}} #### __Figure 2: Show/Hide Animation__ (Windows 10 OS) diff --git a/controls/notifyicon/features/tooltip.md b/controls/notifyicon/features/tooltip.md index 4b331b483..6ad89510b 100644 --- a/controls/notifyicon/features/tooltip.md +++ b/controls/notifyicon/features/tooltip.md @@ -11,34 +11,11 @@ position: 3 You can configure the tooltip that is displayed when the user hovers over the icon with the **TooltipText** property. The string set to this property will be shown as a content of the tooltip. -{{source=..\SamplesCS\NotifyIcon\Features.cs region=ToolTip}} -{{source=..\SamplesVB\NotifyIcon\Features.vb region=ToolTip}} -````C# + + -void ShowNotifyIcon() -{ - RadNotifyIcon radNotifyIcon = new RadNotifyIcon(); - radNotifyIcon.TrayIcon = new System.Drawing.Icon("../../WinForms128x28.ico"); - radNotifyIcon.TooltipText = "Telerik UI for WinForms"; - radNotifyIcon.ShowTrayIcon = true; -} -```` -````VB.NET - -Private Sub ShowNotifyIcon() - Dim radNotifyIcon As RadNotifyIcon = New RadNotifyIcon() - radNotifyIcon.TrayIcon = New System.Drawing.Icon("../../WinForms128x28.ico") - radNotifyIcon.TooltipText = "Telerik UI for WinForms" - radNotifyIcon.ShowTrayIcon = True -End Sub - - -```` - -{{endregion}} - #### __Figure 1: RadNotifyIcon with Tooltip__ ![RadNotifyIcon with tooltip](images/radnotifyicon-features-tooltip_001.png) diff --git a/controls/notifyicon/getting-started.md b/controls/notifyicon/getting-started.md index 96c61bf5a..c3974c460 100644 --- a/controls/notifyicon/getting-started.md +++ b/controls/notifyicon/getting-started.md @@ -49,37 +49,10 @@ The Telerik UI for WinForms assemblies can be install by using one of the availa 3\. Add a method called __InitializeNotifyIcon__ to initialize the data displayed inside the notify balloon. The __TrayIcon__ indicates what icon will be shown in the taskbar notification area: -{{source=..\SamplesCS\NotifyIcon\Features.cs region=InitializeNotifyInfo}} -{{source=..\SamplesVB\NotifyIcon\Features.vb region=InitializeNotifyInfo}} - -````C# - private void InitializeNotifyIcon() - { - this.radNotifyIcon1.ShowTrayIcon = true; - this.radNotifyIcon1.BalloonText = "Look for the Telerik UI for WinForms icon in the taskbar notification area (can b" + - "e hidden in the overflow tray). \r\nHappy coding 🐱‍💻!"; - this.radNotifyIcon1.TrayIcon = new System.Drawing.Icon("../../WinForms128x28.ico"); - this.radNotifyIcon1.BalloonTitle = "Getting Started with RadNotifyIcon"; - this.radNotifyIcon1.GuidItem = new System.Guid("00000001-0002-0003-0004-000000000567"); - - this.radNotifyIcon1.TooltipText = "Telerik UI for WinForms RadNotifyIcon"; - } - -```` -````VB.NET - - Private Sub InitializeNotifyIcon() - Me.radNotifyIcon1.ShowTrayIcon = True - Me.radNotifyIcon1.BalloonText = "Look for the Telerik UI for WinForms icon in the taskbar notification area (can b" & "e hidden in the overflow tray). " & vbCrLf & "Happy coding 🐱‍💻!" - Me.radNotifyIcon1.TrayIcon = New System.Drawing.Icon("../../WinForms128x28.ico") - Me.radNotifyIcon1.BalloonTitle = "Getting Started with RadNotifyIcon" - Me.radNotifyIcon1.GuidItem = New System.Guid("00000001-0002-0003-0004-000000000567") - Me.radNotifyIcon1.TooltipText = "Telerik UI for WinForms RadNotifyIcon" - End Sub - -```` + + + -{{endregion}} >caution You should replace the placeholder GuidItem with your own Guid. Make sure to create two separate Guids for building in Debug and Release mode and use the same ones for a given application. This will allow Windows to recognize the icon each time you show it in the tray. @@ -90,23 +63,10 @@ The Telerik UI for WinForms assemblies can be install by using one of the availa 4\. Double click the RadButton at design time to generate its Click event handler. Then, add the code for showing the notify icon for the "NotifyIconDemo" application: -{{source=..\SamplesCS\NotifyIcon\Features.cs region=GettingStarted}} -{{source=..\SamplesVB\NotifyIcon\Features.vb region=GettingStarted}} - -````C# - private void radButton1_Click(object sender, EventArgs e) - { - this.radNotifyIcon1.ShowBalloonTip(); - } + + -```` -````VB.NET - Private Sub radButton1_Click(ByVal sender As Object, ByVal e As EventArgs) - Me.radNotifyIcon1.ShowBalloonTip() - End Sub -```` -{{endregion}} By default, the icon will be displayed in the tray area once the application is started. If you want to manually show the icon, you can initially set its __ShowTrayIcon__ property to *False* and then set it to *True* at a later moment when it is necessary. diff --git a/controls/officenavigationbar/context-menu.md b/controls/officenavigationbar/context-menu.md index da9a2d220..d6b0b458e 100644 --- a/controls/officenavigationbar/context-menu.md +++ b/controls/officenavigationbar/context-menu.md @@ -20,43 +20,10 @@ The **OverflowItem** ("**...**") shows a **RadContextMenuDropDown** with the ove #### Disable Notes item in the ContextMenuDropDown.DropDownOpened Event -{{source=..\SamplesCS\OfficeNavigationBar\OfficeNavigationBarGettingStarted.cs region=DisableNotes}} -{{source=..\SamplesVB\OfficeNavigationBar\OfficeNavigationBarGettingStarted.vb region=DisableNotes}} + + -````C# -private void ContextMenuDropDown_DropDownOpened(object sender, EventArgs e) -{ - foreach (RadItem item in this.radOfficeNavigationBar1.ContextMenuDropDown.Items) - { - if (item.Text.Contains("Notes")) - { - item.Enabled = false; - } - else - { - item.Enabled = true; - } - } -} - -```` -````VB.NET - - Private Sub ContextMenuDropDown_DropDownOpened(ByVal sender As Object, ByVal e As EventArgs) - For Each item As RadItem In Me.radOfficeNavigationBar1.ContextMenuDropDown.Items - - If item.Text.Contains("Notes") Then - item.Enabled = False - Else - item.Enabled = True - End If - Next -End Sub - -```` - -{{endregion}} ![WinForms RadOfficeNavigationBar DropDownOpened Event](images/officenavigationbar-context-menu002.png) diff --git a/controls/officenavigationbar/getting-started.md b/controls/officenavigationbar/getting-started.md index 8eae64bfa..c405e7d51 100644 --- a/controls/officenavigationbar/getting-started.md +++ b/controls/officenavigationbar/getting-started.md @@ -44,64 +44,10 @@ The following picture shows the final result produced by the code of this tutori To start using the __RadOfficeNavigationBar__ control, you can just populate its __Pages__ collection with __RadPageViewPage__ objects. -{{source=..\SamplesCS\OfficeNavigationBar\OfficeNavigationBarGettingStarted.cs region=GettingStarted}} -{{source=..\SamplesVB\OfficeNavigationBar\OfficeNavigationBarGettingStarted.vb region=GettingStarted}} - -````C# - - RadOfficeNavigationBar radOfficeNavigationBar = new RadOfficeNavigationBar(); - var page1 = new RadPageViewPage() { Text = "Mail" }; - page1.Controls.Add(new Label() {Text="Mail" }); - var page2 = new RadPageViewPage() { Text = "Calendar" }; - page2.Controls.Add(new Label() { Text = "Calendar" }); - var page3 = new RadPageViewPage() { Text = "People" }; - page3.Controls.Add(new Label() { Text = "People" }); - var page4 = new RadPageViewPage() { Text = "Tasks" }; - page4.Controls.Add(new Label() { Text = "Tasks" }); - radOfficeNavigationBar.Controls.Add(page1); - radOfficeNavigationBar.Controls.Add(page2); - radOfficeNavigationBar.Controls.Add(page3); - radOfficeNavigationBar.Controls.Add(page4); - this.Controls.Add(radOfficeNavigationBar); - -```` -````VB.NET - - Dim radOfficeNavigationBar As RadOfficeNavigationBar = New RadOfficeNavigationBar() - Dim page1 = New RadPageViewPage() With { - .Text = "Mail" - } - page1.Controls.Add(New Label() With { - .Text = "Mail" - }) - Dim page2 = New RadPageViewPage() With { - .Text = "Calendar" - } - page2.Controls.Add(New Label() With { - .Text = "Calendar" - }) - Dim page3 = New RadPageViewPage() With { - .Text = "People" - } - page3.Controls.Add(New Label() With { - .Text = "People" - }) - Dim page4 = New RadPageViewPage() With { - .Text = "Tasks" - } - page4.Controls.Add(New Label() With { - .Text = "Tasks" - }) - radOfficeNavigationBar.Controls.Add(page1) - radOfficeNavigationBar.Controls.Add(page2) - radOfficeNavigationBar.Controls.Add(page3) - radOfficeNavigationBar.Controls.Add(page4) - Me.Controls.Add(radOfficeNavigationBar) - - -```` - -{{endregion}} + + + + ## See Also diff --git a/controls/officenavigationbar/localization.md b/controls/officenavigationbar/localization.md index 0f6568203..a367b6bee 100644 --- a/controls/officenavigationbar/localization.md +++ b/controls/officenavigationbar/localization.md @@ -22,112 +22,19 @@ Below is a sample implementation of a custom localization provider, which return #### Localizing RadOfficeNavigationBar Strings -{{source=..\SamplesCS\OfficeNavigationBar\OfficeNavigationBarGettingStarted.cs region=Localization}} -{{source=..\SamplesVB\OfficeNavigationBar\OfficeNavigationBarGettingStarted.vb region=Localization}} - -````C# - - public class EnglishOfficeNavigationBarLocalizationProvider : RadOfficeNavigationBarLocalizationProvider - { - public override string GetLocalizedString(string id) - { - switch (id) - { - case RadOfficeNavigationBarStringId.NavigationOptionsMenuItemText: - return "NavigationOptionsMenuItemText"; - case RadOfficeNavigationBarStringId.NavigationOptionsDialogTitle: - return "NavigationOptionsDialogTitle"; - case RadOfficeNavigationBarStringId.NavigationOptionsDialogLabelMaxVisibleItems: - return "NavigationOptionsDialogLabelMaxVisibleItems"; - case RadOfficeNavigationBarStringId.NavigationOptionsDialogLabelDisplayStyle: - return "NavigationOptionsDialogLabelDisplayStyle"; - case RadOfficeNavigationBarStringId.NavigationOptionsDialogUseCompactFont: - return "NavigationOptionsDialogUseCompactFont"; - case RadOfficeNavigationBarStringId.NavigationOptionsDialogLabelDisplayInOrder: - return "NavigationOptionsDialogLabelDisplayInOrder"; - case RadOfficeNavigationBarStringId.NavigationOptionsDialogButtonMoveUp: - return "NavigationOptionsDialogButtonMoveUp"; - case RadOfficeNavigationBarStringId.NavigationOptionsDialogButtonMoveDown: - return "NavigationOptionsDialogButtonMoveDown"; - case RadOfficeNavigationBarStringId.NavigationOptionsDialogButtonOK: - return "NavigationOptionsDialogButtonOK"; - case RadOfficeNavigationBarStringId.NavigationOptionsDialogButtonCancel: - return "NavigationOptionsDialogButtonCancel"; - case RadOfficeNavigationBarStringId.NavigationOptionsDialogDropDownDisplayStyleText: - return "NavigationOptionsDialogDropDownDisplayStyleText"; - case RadOfficeNavigationBarStringId.NavigationOptionsDialogDropDownDisplayStyleImage: - return "NavigationOptionsDialogDropDownDisplayStyleImage"; - case RadOfficeNavigationBarStringId.NavigationOptionsDialogDropDownDisplayStyleImageAndText: - return "NavigationOptionsDialogDropDownDisplayStyleImageAndText"; - } - return string.Empty; - } - } - -```` -````VB.NET - -Public Class EnglishOfficeNavigationBarLocalizationProvider - Inherits RadOfficeNavigationBarLocalizationProvider - - Public Overrides Function GetLocalizedString(ByVal id As String) As String - Select Case id - Case RadOfficeNavigationBarStringId.NavigationOptionsMenuItemText - Return "NavigationOptionsMenuItemText" - Case RadOfficeNavigationBarStringId.NavigationOptionsDialogTitle - Return "NavigationOptionsDialogTitle" - Case RadOfficeNavigationBarStringId.NavigationOptionsDialogLabelMaxVisibleItems - Return "NavigationOptionsDialogLabelMaxVisibleItems" - Case RadOfficeNavigationBarStringId.NavigationOptionsDialogLabelDisplayStyle - Return "NavigationOptionsDialogLabelDisplayStyle" - Case RadOfficeNavigationBarStringId.NavigationOptionsDialogUseCompactFont - Return "NavigationOptionsDialogUseCompactFont" - Case RadOfficeNavigationBarStringId.NavigationOptionsDialogLabelDisplayInOrder - Return "NavigationOptionsDialogLabelDisplayInOrder" - Case RadOfficeNavigationBarStringId.NavigationOptionsDialogButtonMoveUp - Return "NavigationOptionsDialogButtonMoveUp" - Case RadOfficeNavigationBarStringId.NavigationOptionsDialogButtonMoveDown - Return "NavigationOptionsDialogButtonMoveDown" - Case RadOfficeNavigationBarStringId.NavigationOptionsDialogButtonOK - Return "NavigationOptionsDialogButtonOK" - Case RadOfficeNavigationBarStringId.NavigationOptionsDialogButtonCancel - Return "NavigationOptionsDialogButtonCancel" - Case RadOfficeNavigationBarStringId.NavigationOptionsDialogDropDownDisplayStyleText - Return "NavigationOptionsDialogDropDownDisplayStyleText" - Case RadOfficeNavigationBarStringId.NavigationOptionsDialogDropDownDisplayStyleImage - Return "NavigationOptionsDialogDropDownDisplayStyleImage" - Case RadOfficeNavigationBarStringId.NavigationOptionsDialogDropDownDisplayStyleImageAndText - Return "NavigationOptionsDialogDropDownDisplayStyleImageAndText" - End Select - - Return String.Empty - End Function -End Class - -```` - -{{endregion}} - - -To apply the custom localization provider, instantiate and assign it to the current localization provider: + + -#### Localizing RadDock Strings -{{source=..\SamplesCS\OfficeNavigationBar\OfficeNavigationBarGettingStarted.cs region=SettingCustomProvider}} -{{source=..\SamplesVB\OfficeNavigationBar\OfficeNavigationBarGettingStarted.vb region=SettingCustomProvider}} -````C# +To apply the custom localization provider, instantiate and assign it to the current localization provider: -RadOfficeNavigationBarLocalizationProvider.CurrentProvider = new EnglishOfficeNavigationBarLocalizationProvider(); +#### Localizing RadDock Strings -```` -````VB.NET -RadOfficeNavigationBarLocalizationProvider.CurrentProvider = New EnglishOfficeNavigationBarLocalizationProvider() + + -```` -{{endregion}} - The code provided above illustrates the approach to be used to localize the __RadOfficeNavigationBar__ and is not intended as a full translation. diff --git a/controls/officenavigationbar/options-dialog.md b/controls/officenavigationbar/options-dialog.md index d428b960d..a007e207f 100644 --- a/controls/officenavigationbar/options-dialog.md +++ b/controls/officenavigationbar/options-dialog.md @@ -24,22 +24,11 @@ The **ShowNavigationOptionsMenuItem** property indicates whether to show the nav #### Hide NavigationOptionsMenuItem -{{source=..\SamplesCS\OfficeNavigationBar\OfficeNavigationBarGettingStarted.cs region=ShowNavigationOptionsMenuItem}} -{{source=..\SamplesVB\OfficeNavigationBar\OfficeNavigationBarGettingStarted.vb region=ShowNavigationOptionsMenuItem}} + + -````C# -this.radOfficeNavigationBar1.ShowNavigationOptionsMenuItem = false; -```` -````VB.NET - -Me.radOfficeNavigationBar1.ShowNavigationOptionsMenuItem = False - -```` - -{{endregion}} - The dialog offers the following settings: * **Maximum number of visible items**: controls the **VisibleItemsCount** property which indicates how many items to be visible on the strip. If this property is not set, it returns the count of items. diff --git a/controls/officenavigationbar/peek-window.md b/controls/officenavigationbar/peek-window.md index e54743d12..dc0df0e49 100644 --- a/controls/officenavigationbar/peek-window.md +++ b/controls/officenavigationbar/peek-window.md @@ -15,56 +15,19 @@ RadOfficeNavigationBar provides popup preview option for its elements when the m ![WinForms RadOfficeNavigationBar Peek Window](images/officenavigationbar-peek-window001.png) -{{source=..\SamplesCS\OfficeNavigationBar\OfficeNavigationBarGettingStarted.cs region=PeekWindow}} -{{source=..\SamplesVB\OfficeNavigationBar\OfficeNavigationBarGettingStarted.vb region=PeekWindow}} + + -````C# -this.radOfficeNavigationBar1.OfficeNavigationBarElement.EnablePeekPopup = true; - -```` -````VB.NET - -Me.radOfficeNavigationBar1.OfficeNavigationBarElement.EnablePeekPopup = True - - -```` - -{{endregion}} To set a content for each peek window, we can use the __PeekPopupOpening__ event. In the event handler, we have access to the current hovered RadPageViewItem and depending on it, we can set the __Page.PeekPopupContent__ property. This property is of type __Control__. >The Peek Window will take the size of its content. This needs to be considered while using UserControl as a content of the Peek Window. -{{source=..\SamplesCS\OfficeNavigationBar\OfficeNavigationBarGettingStarted.cs region=PeekWindowEvent}} -{{source=..\SamplesVB\OfficeNavigationBar\OfficeNavigationBarGettingStarted.vb region=PeekWindowEvent}} - -````C# - -private void OfficeNavigationBarElement_PeekPopupOpening(object sender, Telerik.WinControls.UI.OfficeNavigationBar.RadPageViewPeekPopupEventArgs e) -{ - RadLabel content = new RadLabel(); - content.Text = e.Page.Item.Text; - content.Font = new Font("Segoe UI Semibold", 27f); - content.LoadElementTree(); - e.Page.PeekPopupContent = content; -} - -```` -````VB.NET - -Private Sub OfficeNavigationBarElement_PeekPopupOpening(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.OfficeNavigationBar.RadPageViewPeekPopupEventArgs) - Dim content As RadLabel = New RadLabel() - content.Text = e.Page.Item.Text - content.Font = New Font("Segoe UI Semibold", 27F) - content.LoadElementTree() - e.Page.PeekPopupContent = content -End Sub - + + -```` -{{endregion}} In the following image we can see the Peek Window content when it hosts a custom user control. diff --git a/controls/officenavigationbar/view-modes.md b/controls/officenavigationbar/view-modes.md index a22ad7cc5..9215af126 100644 --- a/controls/officenavigationbar/view-modes.md +++ b/controls/officenavigationbar/view-modes.md @@ -14,45 +14,19 @@ position: 4 ## Compact -{{source=..\SamplesCS\OfficeNavigationBar\OfficeNavigationBarGettingStarted.cs region=CompactMode}} -{{source=..\SamplesVB\OfficeNavigationBar\OfficeNavigationBarGettingStarted.vb region=CompactMode}} + + -````C# - this.radOfficeNavigationBar1.UseCompactFont = true; - this.radOfficeNavigationBar1.ItemsDisplayStyle = DisplayStyle.Image; - -```` -````VB.NET - - Me.radOfficeNavigationBar1.UseCompactFont = True - Me.radOfficeNavigationBar1.ItemsDisplayStyle = DisplayStyle.Image - -```` - -{{endregion}} ![WinForms RadOfficeNavigationBar Item Display Mode Compact](images/officenavigationbar-view-modes001.png) ## Full -{{source=..\SamplesCS\OfficeNavigationBar\OfficeNavigationBarGettingStarted.cs region=FullMode}} -{{source=..\SamplesVB\OfficeNavigationBar\OfficeNavigationBarGettingStarted.vb region=FullMode}} - -````C# - - this.radOfficeNavigationBar1.UseCompactFont = false; - this.radOfficeNavigationBar1.ItemsDisplayStyle = DisplayStyle.ImageAndText; - -```` -````VB.NET - - Me.radOfficeNavigationBar1.UseCompactFont = False - Me.radOfficeNavigationBar1.ItemsDisplayStyle = DisplayStyle.ImageAndText + + -```` -{{endregion}} ![WinForms RadOfficeNavigationBar Item Display Mode Full](images/officenavigationbar-view-modes002.png) diff --git a/controls/pageview/backstageview/customizing-backstage-view.md b/controls/pageview/backstageview/customizing-backstage-view.md index f49bcf415..2f80ad805 100644 --- a/controls/pageview/backstageview/customizing-backstage-view.md +++ b/controls/pageview/backstageview/customizing-backstage-view.md @@ -52,21 +52,10 @@ Another way of customizing the content area is in code. The following code snipp #### Accessing the content area of Backstage View -{{source=..\SamplesCS\PageView\BackstageView.cs region=contentArea}} -{{source=..\SamplesVB\PageView\BackstageView.vb region=contentArea}} + + -````C# -RadPageViewBackstageElement backStageElement = radPageView1.ViewElement as RadPageViewBackstageElement; -backStageElement.ContentArea.BackColor = Color.Yellow; -```` -````VB.NET -Dim backStageElement As RadPageViewBackstageElement = TryCast(RadPageView1.ViewElement, RadPageViewBackstageElement) -backStageElement.ContentArea.BackColor = Color.Yellow - -```` - -{{endregion}} ## Customizing the items (RadPageViewPages) area @@ -78,23 +67,10 @@ Use the following code snippet to access the element in code: #### Accessing the content area of Backstage View -{{source=..\SamplesCS\PageView\BackstageView.cs region=itemsArea}} -{{source=..\SamplesVB\PageView\BackstageView.vb region=itemsArea}} - -````C# -RadPageViewBackstageElement backStageElement = radPageView1.ViewElement as RadPageViewBackstageElement; -StripViewItemLayout itemLayout = backStageElement.ItemContainer.ItemLayout as StripViewItemLayout; -itemLayout.BackColor = Color.Red; - -```` -````VB.NET -Dim backStageElement As RadPageViewBackstageElement = TryCast(RadPageView1.ViewElement, RadPageViewBackstageElement) -Dim itemLayout As StripViewItemLayout = TryCast(backStageElement.ItemContainer.ItemLayout, StripViewItemLayout) -itemLayout.BackColor = Color.Red + + -```` -{{endregion}} ## Customizing the buttons area @@ -108,27 +84,10 @@ The buttons panel can be accessed from the **ItemsContaier** of the **RadPageVie #### Accessing the content area of Backstage View -{{source=..\SamplesCS\PageView\BackstageView.cs region=buttonsArea}} -{{source=..\SamplesVB\PageView\BackstageView.vb region=buttonsArea}} + + -````C# -RadPageViewBackstageElement backStageElement = radPageView1.ViewElement as RadPageViewBackstageElement; -StripViewButtonsPanel buttonsPanel = backStageElement.ItemContainer.ButtonsPanel as StripViewButtonsPanel; -buttonsPanel.Visibility = ElementVisibility.Visible; -buttonsPanel.DrawFill = true; -buttonsPanel.BackColor = Color.Green; -```` -````VB.NET -Dim backStageElement As RadPageViewBackstageElement = TryCast(RadPageView1.ViewElement, RadPageViewBackstageElement) -Dim buttonsPanel As StripViewButtonsPanel = TryCast(backStageElement.ItemContainer.ButtonsPanel, StripViewButtonsPanel) -buttonsPanel.Visibility = ElementVisibility.Visible -buttonsPanel.DrawFill = True -buttonsPanel.BackColor = Color.Green - -```` - -{{endregion}} ## Customizing RadPageViewItems @@ -172,43 +131,9 @@ The following code snippet demonstrates how to access and customize the group it #### Accessing the content area of Backstage View -{{source=..\SamplesCS\PageView\BackstageView.cs region=groupItems}} -{{source=..\SamplesVB\PageView\BackstageView.vb region=groupItems}} - -````C# -RadPageViewBackstageElement backStageElement = radPageView1.ViewElement as RadPageViewBackstageElement; -StripViewItemLayout itemLayout = backStageElement.ItemContainer.ItemLayout as StripViewItemLayout; -foreach (RadPageViewStripItem item in itemLayout.Children) -{ - RadPageViewStripGroupItem groupItem = item as RadPageViewStripGroupItem; - if (groupItem != null) - { - groupItem.BackColor = Color.Yellow; - groupItem.NumberOfColors = 1; - LightVisualElement underlineElement = ((LightVisualElement)groupItem.Children[1]); - underlineElement.BorderBottomColor = Color.Blue; - underlineElement.BorderTopColor = Color.Red; - } -} - -```` -````VB.NET -Dim backStageElement As RadPageViewBackstageElement = TryCast(RadPageView1.ViewElement, RadPageViewBackstageElement) -Dim itemLayout As StripViewItemLayout = TryCast(backStageElement.ItemContainer.ItemLayout, StripViewItemLayout) -For Each item As RadPageViewStripItem In itemLayout.Children - Dim groupItem = TryCast(item, RadPageViewStripGroupItem) - If groupItem IsNot Nothing Then - groupItem.BackColor = Color.Yellow - groupItem.NumberOfColors = 1 - Dim underlineElement = TryCast(groupItem.Children(1), LightVisualElement) - underlineElement.BorderBottomColor = Color.Blue - underlineElement.BorderTopColor = Color.Red - End If -Next - -```` - -{{endregion}} + + + ![WinForms RadPageView Backstage ContentArea](images/pageview-backstageview-customizing-backstageview014.png) diff --git a/controls/pageview/explorerbarview/customizing-the-explorerbarview.md b/controls/pageview/explorerbarview/customizing-the-explorerbarview.md index 3f891fef6..58e4feca6 100644 --- a/controls/pageview/explorerbarview/customizing-the-explorerbarview.md +++ b/controls/pageview/explorerbarview/customizing-the-explorerbarview.md @@ -25,39 +25,19 @@ To define how expanded pages are sized, you should set the __ContentSizeMode__ p #### ExplorerBarContentSizeMode.EqualLength -{{source=..\SamplesCS\PageView\ExplorerBarView.cs region=contentSizeMode}} -{{source=..\SamplesVB\PageView\ExplorerBarView.vb region=contentSizeMode}} + + -````C# -RadPageViewExplorerBarElement explorerBarElement = (this.radPageView1.ViewElement as RadPageViewExplorerBarElement); -explorerBarElement.ContentSizeMode = ExplorerBarContentSizeMode.EqualLength; -```` -````VB.NET -Dim explorerBarElement As RadPageViewExplorerBarElement = (TryCast(Me.radPageView1.ViewElement, RadPageViewExplorerBarElement)) -explorerBarElement.ContentSizeMode = ExplorerBarContentSizeMode.EqualLength - -```` - -{{endregion}} If you choose to use the *FixedLength* size mode and consequently wish to define length to a given page, you can do this the following way: #### PageLength -{{source=..\SamplesCS\PageView\ExplorerBarView.cs region=pageLength}} -{{source=..\SamplesVB\PageView\ExplorerBarView.vb region=pageLength}} - -````C# -this.radPageViewPage1.PageLength = 430; - -```` -````VB.NET -Me.radPageViewPage1.PageLength = 430 + + -```` -{{endregion}} ## Setting Stack Position @@ -73,19 +53,10 @@ To expand or collapse a page, you should simply click on its item. You can also #### Setting the IsContentVisible property -{{source=..\SamplesCS\PageView\ExplorerBarView.cs region=isContentVisible}} -{{source=..\SamplesVB\PageView\ExplorerBarView.vb region=isContentVisible}} + + -````C# -this.radPageViewPage1.IsContentVisible = true; -```` -````VB.NET -Me.radPageViewPage1.IsContentVisible = True - -```` - -{{endregion}} If you wish to have a page initially expanded, you can set the **IsContentVisible** property in the Visual Studio’s Designer as well. @@ -109,21 +80,10 @@ The PageViewMode.*ExplorerBar* also automatically scrolls to an item when it is #### ScrollToItem -{{source=..\SamplesCS\PageView\ExplorerBarView.cs region=scrolling}} -{{source=..\SamplesVB\PageView\ExplorerBarView.vb region=scrolling}} - -````C# -RadPageViewExplorerBarItem item = this.radPageViewPage1.Item as RadPageViewExplorerBarItem; -explorerBarElement.ScrollToItem(item); - -```` -````VB.NET -Dim item As RadPageViewExplorerBarItem = TryCast(Me.radPageViewPage1.Item, RadPageViewExplorerBarItem) -explorerBarElement.ScrollToItem(item) + + -```` -{{endregion}} # See Also diff --git a/controls/pageview/how-to/add-contextMenu-to-radpageviewpage-tabs.md b/controls/pageview/how-to/add-contextMenu-to-radpageviewpage-tabs.md index e8fd497e7..7df7fbac5 100644 --- a/controls/pageview/how-to/add-contextMenu-to-radpageviewpage-tabs.md +++ b/controls/pageview/how-to/add-contextMenu-to-radpageviewpage-tabs.md @@ -19,163 +19,23 @@ This help article will demonstrate you how to add custom __RadContextMenu__ to _ To create your custom __RadContextMenu__, add its' __RadMenuItems__, set their properties and add them to the RadContextMenu.**Items** collection: -{{source=..\SamplesCS\PageView\HowTo.cs region=createContextMenu}} -{{source=..\SamplesVB\PageView\HowTo.vb region=createContextMenu}} - -````C# -private RadContextMenu contextMenu; - -public MyForm() -{ - InitializeComponent(); - - ... - - contextMenu = new RadContextMenu(); - CreateContextMenu(); -} - -private void CreateContextMenu() -{ - RadMenuItem addNewTabMenuItem = new RadMenuItem(); - addNewTabMenuItem.Text = "Add New Tab"; - addNewTabMenuItem.Click += new EventHandler(addNewTabMenuItem_Click); - contextMenu.Items.Add(addNewTabMenuItem); - RadMenuSeparatorItem separator = new RadMenuSeparatorItem(); - contextMenu.Items.Add(separator); - RadMenuItem closeTabMenuItem = new RadMenuItem(); - closeTabMenuItem.Text = "Close Tab"; - closeTabMenuItem.Click += new EventHandler(closeTabMenuItem_Click); - contextMenu.Items.Add(closeTabMenuItem); - RadMenuItem closeAllButThisMenuItem = new RadMenuItem(); - closeAllButThisMenuItem.Text = "Close All But This"; - closeAllButThisMenuItem.Click += new EventHandler(closeAllButThisMenuItem_Click); - contextMenu.Items.Add(closeAllButThisMenuItem); - RadMenuItem closeAllTabsMenuItem = new RadMenuItem(); - closeAllTabsMenuItem.Text = "Close All Tabs"; - closeAllTabsMenuItem.Click += new EventHandler(closeAllTabsMenuItem_Click); - contextMenu.Items.Add(closeAllTabsMenuItem); -} - -```` -````VB.NET -Private contextMenu As RadContextMenu - -Public Sub New() - InitializeComponent() - ... - contextMenu = New RadContextMenu() - CreateContextMenu() -End Sub - -Private Sub CreateContextMenu() - Dim addNewTabMenuItem As New RadMenuItem() - addNewTabMenuItem.Text = "Add New Tab" - AddHandler addNewTabMenuItem.Click, AddressOf addNewTabMenuItem_Click - contextMenu1.Items.Add(addNewTabMenuItem) - Dim separator As New RadMenuSeparatorItem() - contextMenu1.Items.Add(separator) - Dim closeTabMenuItem As New RadMenuItem() - closeTabMenuItem.Text = "Close Tab" - AddHandler closeTabMenuItem.Click, AddressOf closeTabMenuItem_Click - contextMenu1.Items.Add(closeTabMenuItem) - Dim closeAllButThisMenuItem As New RadMenuItem() - closeAllButThisMenuItem.Text = "Close All But This" - AddHandler closeAllButThisMenuItem.Click, AddressOf closeAllButThisMenuItem_Click - contextMenu1.Items.Add(closeAllButThisMenuItem) - Dim closeAllTabsMenuItem As New RadMenuItem() - closeAllTabsMenuItem.Text = "Close All Tabs" - AddHandler closeAllTabsMenuItem.Click, AddressOf closeAllTabsMenuItem_Click - contextMenu1.Items.Add(closeAllTabsMenuItem) -End Sub - -```` - -{{endregion}} + + + + In the following code snippet you can observe, how to add the most common items functionalities: -{{source=..\SamplesCS\PageView\HowTo.cs region=eventHandlerImpl}} -{{source=..\SamplesVB\PageView\HowTo.vb region=eventHandlerImpl}} - -````C# -void addNewTabMenuItem_Click(object sender, EventArgs e) -{ - RadPageViewPage newPage = new RadPageViewPage(); - newPage.Text = "My new tab text"; - radPageView1.Pages.Add(newPage); -} -void closeTabMenuItem_Click(object sender, EventArgs e) -{ - radPageView1.Pages.Remove(radPageView1.SelectedPage); -} -void closeAllButThisMenuItem_Click(object sender, EventArgs e) -{ - for (int i = radPageView1.Pages.Count - 1; i >= 0; i--) - { - if (radPageView1.Pages[i] != radPageView1.SelectedPage) - { - radPageView1.Pages.RemoveAt(i); - } - } -} -void closeAllTabsMenuItem_Click(object sender, EventArgs e) -{ - radPageView1.Pages.Clear(); -} - -```` -````VB.NET -Private Sub addNewTabMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) - Dim newPage As New RadPageViewPage() - newPage.Text = "My new tab text" - radPageView1.Pages.Add(newPage) -End Sub -Private Sub closeTabMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) - radPageView1.Pages.Remove(radPageView1.SelectedPage) -End Sub -Private Sub closeAllButThisMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) - For i As Integer = radPageView1.Pages.Count - 1 To 0 Step -1 - If radPageView1.Pages(i) IsNot radPageView1.SelectedPage Then - radPageView1.Pages.RemoveAt(i) - End If - Next i -End Sub -Private Sub closeAllTabsMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) - radPageView1.Pages.Clear() -End Sub - -```` - -{{endregion}} + + + + After the context menu is created it have to be associated with __RadPageViewPages__ tabs. This can be done by subscribing to the __RadPageView__ instance' __MouseClick__ event: -{{source=..\SamplesCS\PageView\HowTo.cs region=mouseClick}} -{{source=..\SamplesVB\PageView\HowTo.vb region=mouseClick}} - -````C# -void radPageView1_MouseClick(object sender, MouseEventArgs e) -{ - RadPageViewItem hitItem = this.radPageView1.ViewElement.ItemFromPoint(e.Location); - if (e.Button == MouseButtons.Right && hitItem != null) - { - contextMenu.Show(this.radPageView1.PointToScreen(e.Location)); - } -} - -```` -````VB.NET -Private Sub radPageView1_MouseClick(ByVal sender As Object, ByVal e As MouseEventArgs) - Dim hitItem As RadPageViewItem = Me.radPageView1.ViewElement.ItemFromPoint(e.Location) - If e.Button = MouseButtons.Right AndAlso hitItem IsNot Nothing Then - contextMenu1.Show(Me.radPageView1.PointToScreen(e.Location)) - End If -End Sub - -```` - -{{endregion}} + + + # See Also diff --git a/controls/pageview/how-to/editing-page-tabs.md b/controls/pageview/how-to/editing-page-tabs.md index 0563e0868..ca925c14b 100644 --- a/controls/pageview/how-to/editing-page-tabs.md +++ b/controls/pageview/how-to/editing-page-tabs.md @@ -21,27 +21,10 @@ By default, __RadPageView__ does not allow modifying of the current page tab's t The sample code below demonstrates how to start editing: -{{source=..\SamplesCS\PageView\EditingRadPageViewElement\EditingRadPageViewElement.cs region=EnableEditing}} -{{source=..\SamplesVB\PageView\EditingRadPageViewElement\EditingRadPageViewElement.vb region=EnableEditing}} + + -````C# -radPageView1.ViewElement.AllowEdit = true; -// set the SelectedPage - this page tab will be edited -radPageView1.SelectedPage = radPageView1.Pages[1]; -// this will start edit operation on the selected page tab -radPageView1.ViewElement.BeginEdit(); -```` -````VB.NET -RadPageView1.ViewElement.AllowEdit = True -'set the SelectedPage - this page tab will be edited -RadPageView1.SelectedPage = RadPageView1.Pages(1) -'this will start edit operation on the selected page tab -RadPageView1.ViewElement.BeginEdit() - -```` - -{{endregion}} >caption Figure 1: Page Tab's Editing @@ -65,85 +48,15 @@ RadPageView1.ViewElement.BeginEdit() The sample code below demonstrates how to forbid the user to clear the text in the page tab when pressing `Enter`: -{{source=..\SamplesCS\PageView\EditingRadPageViewElement\EditingRadPageViewElement.cs region=Edit}} -{{source=..\SamplesVB\PageView\EditingRadPageViewElement\EditingRadPageViewElement.vb region=Edit}} - -````C# -radPageView1.ViewElement.AllowEdit = true; -radPageView1.ViewElement.EditorInitialized += ViewElement_EditorInitialized; - -```` -````VB.NET -RadPageView1.ViewElement.AllowEdit = True -AddHandler RadPageView1.ViewElement.EditorInitialized, AddressOf ViewElement_EditorInitialized - -```` - -{{endregion}} - -{{source=..\SamplesCS\PageView\EditingRadPageViewElement\EditingRadPageViewElement.cs region=EditContinuation}} -{{source=..\SamplesVB\PageView\EditingRadPageViewElement\EditingRadPageViewElement.vb region=EditContinuation}} - -````C# - -private void ViewElement_EditorInitialized(object sender, RadPageViewEditorEventArgs e) -{ - radPageView1.ViewElement.ActiveEditor.Validating -= ActiveEditor_Validating; - radPageView1.ViewElement.ActiveEditor.Validated -= ActiveEditor_Validated; - radPageView1.ViewElement.ActiveEditor.ValidationError -= ActiveEditor_ValidationError; - - radPageView1.ViewElement.ActiveEditor.Validating += ActiveEditor_Validating; - radPageView1.ViewElement.ActiveEditor.Validated += ActiveEditor_Validated; - radPageView1.ViewElement.ActiveEditor.ValidationError += ActiveEditor_ValidationError; -} - -private void ActiveEditor_Validating(object sender, CancelEventArgs e) -{ - RadPageViewElement.PageViewItemTextEditor editor = - sender as RadPageViewElement.PageViewItemTextEditor; - - if (editor != null && radPageView1.ViewElement.ActiveEditor.Value == string.Empty) - { - e.Cancel = true; - } -} - -private void ActiveEditor_ValidationError(object sender, ValidationErrorEventArgs e) -{ - RadMessageBox.Show("Page label can't be empty!", "Error", MessageBoxButtons.OK, RadMessageIcon.Error); -} - -private void ActiveEditor_Validated(object sender, EventArgs e) -{ - RadMessageBox.Show("Page label has been successfully updated!", "Information", MessageBoxButtons.OK, RadMessageIcon.Info); -} - -```` -````VB.NET -Private Sub ViewElement_EditorInitialized(sender As Object, e As RadPageViewEditorEventArgs) - RemoveHandler radPageView1.ViewElement.ActiveEditor.Validating, AddressOf ActiveEditor_Validating - RemoveHandler radPageView1.ViewElement.ActiveEditor.Validated, AddressOf ActiveEditor_Validated - RemoveHandler radPageView1.ViewElement.ActiveEditor.ValidationError, AddressOf ActiveEditor_ValidationError - AddHandler radPageView1.ViewElement.ActiveEditor.Validating, AddressOf ActiveEditor_Validating - AddHandler radPageView1.ViewElement.ActiveEditor.Validated, AddressOf ActiveEditor_Validated - AddHandler radPageView1.ViewElement.ActiveEditor.ValidationError, AddressOf ActiveEditor_ValidationError -End Sub -Private Sub ActiveEditor_Validating(sender As Object, e As CancelEventArgs) - Dim editor As RadPageViewElement.PageViewItemTextEditor = TryCast(sender, RadPageViewElement.PageViewItemTextEditor) - If editor IsNot Nothing AndAlso radPageView1.ViewElement.ActiveEditor.Value = String.Empty Then - e.Cancel = True - End If -End Sub -Private Sub ActiveEditor_ValidationError(sender As Object, e As ValidationErrorEventArgs) - RadMessageBox.Show("Page label can't be empty!", "Error", MessageBoxButtons.OK, RadMessageIcon.[Error]) -End Sub -Private Sub ActiveEditor_Validated(sender As Object, e As EventArgs) - RadMessageBox.Show("Page label has been successfully updated!", "Information", MessageBoxButtons.OK, RadMessageIcon.Info) -End Sub - -```` - -{{endregion}} + + + + + + + + + >caption Figure 2: Validation Fails diff --git a/controls/pageview/how-to/programatically-adding-pages.md b/controls/pageview/how-to/programatically-adding-pages.md index bc345cf22..208a4e944 100644 --- a/controls/pageview/how-to/programatically-adding-pages.md +++ b/controls/pageview/how-to/programatically-adding-pages.md @@ -19,31 +19,10 @@ Simply all that has to be done is to create an instance of __RadPageViewPage__, #### Adding pages -{{source=..\SamplesCS\PageView\HowTo.cs region=addingPages}} -{{source=..\SamplesVB\PageView\HowTo.vb region=addingPages}} - -````C# - -RadPageViewPage pageOne = new RadPageViewPage(); -pageOne.Text = "First Page"; -radPageView1.Pages.Add(pageOne); - -RadPageViewPage pageTwo = new RadPageViewPage(); -pageTwo.Text = "Second Page"; -radPageView1.Pages.Add(pageTwo); - -```` -````VB.NET -Dim pageOne As New RadPageViewPage() -pageOne.Text = "First Page" -radPageView1.Pages.Add(pageOne) -Dim pageTwo As New RadPageViewPage() -pageTwo.Text = "Second Page" -radPageView1.Pages.Add(pageTwo) - -```` - -{{endregion}} + + + + >note In case you need to add a page at a certain position, feel free to use the Pages.**Insert** method passing the desired position index and the **RadPageViewPage** instance you want to add. @@ -53,24 +32,10 @@ Additionally, adding other controls to a specified __RadPageViewPage__ programm #### Adding controls to a page -{{source=..\SamplesCS\PageView\HowTo.cs region=addingControls}} -{{source=..\SamplesVB\PageView\HowTo.vb region=addingControls}} - -````C# - -RadButton button = new RadButton(); -button.Text = "My Button"; -pageOne.Controls.Add(button); - -```` -````VB.NET -Dim button As New RadButton() -button.Text = "My Button" -pageOne.Controls.Add(button) + + -```` -{{endregion}} # See Also diff --git a/controls/pageview/how-to/subscribing-to-radpageviewpage-events.md b/controls/pageview/how-to/subscribing-to-radpageviewpage-events.md index 0d384e3e3..27e98a1fc 100644 --- a/controls/pageview/how-to/subscribing-to-radpageviewpage-events.md +++ b/controls/pageview/how-to/subscribing-to-radpageviewpage-events.md @@ -13,49 +13,15 @@ previous_url: pageview-how-to-subscribing-to-radpageviewpage-events Subscribing to **RadPageViewPage**'s event is no different then subscribing to any other event. Following is an example code snippet: -{{source=..\SamplesCS\PageView\HowTo.cs region=subscribeToEvents}} -{{source=..\SamplesVB\PageView\HowTo.vb region=subscribeToEvents}} + + -````C# - -radPageViewPage1.MouseClick += new MouseEventHandler(radPageViewPage1_MouseClick); -radPageViewPage1.MouseDoubleClick += new MouseEventHandler(radPageViewPage1_MouseDoubleClick); -```` -````VB.NET -AddHandler radPageViewPage1.MouseClick, AddressOf radPageViewPage1_MouseClick -AddHandler radPageViewPage1.MouseDoubleClick, AddressOf radPageViewPage1_MouseDoubleClick -```` + + -{{endregion}} -{{source=..\SamplesCS\PageView\HowTo.cs region=eventHandlers}} -{{source=..\SamplesVB\PageView\HowTo.vb region=eventHandlers}} - -````C# - -void radPageViewPage1_MouseDoubleClick(object sender, MouseEventArgs e) -{ - //do something -} -void radPageViewPage1_MouseClick(object sender, MouseEventArgs e) -{ - //do something -} - -```` -````VB.NET -Private Sub radPageViewPage1_MouseDoubleClick(ByVal sender As Object, ByVal e As MouseEventArgs) - 'do something -End Sub -Private Sub radPageViewPage1_MouseClick(ByVal sender As Object, ByVal e As MouseEventArgs) - 'do something -End Sub - -```` - -{{endregion}} # See Also diff --git a/controls/pageview/localization/localization.md b/controls/pageview/localization/localization.md index 50a464323..6654f2d6a 100644 --- a/controls/pageview/localization/localization.md +++ b/controls/pageview/localization/localization.md @@ -23,89 +23,19 @@ Below is a sample implementation of a custom localization provider, which return #### Localizing RadPageView strings -{{source=..\SamplesCS\PageView\Localization.cs region=localizationImpl}} -{{source=..\SamplesVB\PageView\Localization.vb region=localizationImpl}} - -````C# -public class MyEnglishRadPageViewLocalizationProvider : RadPageViewLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case RadPageViewStringId.CloseButtonTooltip: - return "Close Selected Page"; - case RadPageViewStringId.ItemListButtonTooltip: - return "Available Pages"; - case RadPageViewStringId.LeftScrollButtonTooltip: - return "Scroll Strip Left"; - case RadPageViewStringId.RightScrollButtonTooltip: - return "Scroll Strip Right"; - case RadPageViewStringId.ShowMoreButtonsItemCaption: - return "Show More Buttons"; - case RadPageViewStringId.ShowFewerButtonsItemCaption: - return "Show Fewer Buttons"; - case RadPageViewStringId.AddRemoveButtonsItemCaption: - return "Add or Remove Buttons"; - case RadPageViewStringId.ItemCloseButtonTooltip: - return "Close Page"; - case RadPageViewStringId.NewItemTooltipText: - return "Add New Page"; - } - return base.GetLocalizedString(id); - } -} - -```` -````VB.NET -Public Class MyEnglishRadPageViewLocalizationProvider - Inherits RadPageViewLocalizationProvider - Public Overrides Function GetLocalizedString(ByVal id As String) As String - Select Case id - Case RadPageViewStringId.CloseButtonTooltip - Return "Close Selected Page" - Case RadPageViewStringId.ItemListButtonTooltip - Return "Available Pages" - Case RadPageViewStringId.LeftScrollButtonTooltip - Return "Scroll Strip Left" - Case RadPageViewStringId.RightScrollButtonTooltip - Return "Scroll Strip Right" - Case RadPageViewStringId.ShowMoreButtonsItemCaption - Return "Show More Buttons" - Case RadPageViewStringId.ShowFewerButtonsItemCaption - Return "Show Fewer Buttons" - Case RadPageViewStringId.AddRemoveButtonsItemCaption - Return "Add or Remove Buttons" - Case RadPageViewStringId.ItemCloseButtonTooltip - Return "Close Page" - Case RadPageViewStringId.NewItemTooltipText - Return "Add New Page" - End Select - Return MyBase.GetLocalizedString(id) - End Function -End Class - -```` - -{{endregion}} + + -To apply the custom localization provider, instantiate and assign it to the current localization provider: -#### Using the custom localization provider -{{source=..\SamplesCS\PageView\Localization.cs region=localizationUsage}} -{{source=..\SamplesVB\PageView\Localization.vb region=localizationUsage}} +To apply the custom localization provider, instantiate and assign it to the current localization provider: -````C# -RadPageViewLocalizationProvider.CurrentProvider = new MyEnglishRadPageViewLocalizationProvider(); +#### Using the custom localization provider -```` -````VB.NET -RadPageViewLocalizationProvider.CurrentProvider = New MyEnglishRadPageViewLocalizationProvider() + + -```` -{{endregion}} The code provided above illustrates the approach to be used to localize the __RadPageView__ and is not intended as a full translation. diff --git a/controls/pageview/localization/right-to-left-support.md b/controls/pageview/localization/right-to-left-support.md index 9985ce5f4..7cca449d4 100644 --- a/controls/pageview/localization/right-to-left-support.md +++ b/controls/pageview/localization/right-to-left-support.md @@ -13,20 +13,11 @@ previous_url: pageview-localization-rtl You can present the content of your **RadPageView** instance in a right-to-left direction by setting the __RightToLeft__ property to *Yes*: -{{source=..\SamplesCS\CommandBar\FloatingStrips.cs region=rtl}} -{{source=..\SamplesVB\CommandBar\FloatingStrips.vb region=rtl}} + + -````C# - -this.radCommandBar1.RightToLeft = RightToLeft.Yes; -```` -````VB.NET -Me.RadCommandBar1.RightToLeft = Windows.Forms.RightToLeft.Yes -```` - -{{endregion}} Please note that this feature reorders not only the system buttons, but it also changes the order of your custom items where necessary: diff --git a/controls/pageview/outlookview/using-the-overflow-grip.md b/controls/pageview/outlookview/using-the-overflow-grip.md index 2e221d8db..109d76195 100644 --- a/controls/pageview/outlookview/using-the-overflow-grip.md +++ b/controls/pageview/outlookview/using-the-overflow-grip.md @@ -22,53 +22,19 @@ The Overflow Grip can be used to increase/decrease the amount of currently visib As well as from the UI, the overflow grip can be used programmatically. To do so, you should access the methods exposed by the RadPageViewOutlookElement class by casting the RadPageView’s ViewElement property to RadPageViewOutlookElement. Then, you should call the corresponding methods as the code snippet below demonstrates: -{{source=..\SamplesCS\PageView\OutlookView.cs region=programmingGrip}} -{{source=..\SamplesVB\PageView\OutlookView.vb region=programmingGrip}} + + -````C# -RadPageViewOutlookElement outlookElement = this.radPageView1.ViewElement as RadPageViewOutlookElement; -//Drags the sizing grip one item down. -outlookElement.DragGripDown(); -//Drags the sizing grip one item up. -outlookElement.DragGripUp(); -```` -````VB.NET -Dim outlookElement As RadPageViewOutlookElement = TryCast(Me.radPageView1.ViewElement, RadPageViewOutlookElement) -'Drags the sizing grip one item down. -outlookElement.DragGripDown() -'Drags the sizing grip one item up. -outlookElement.DragGripUp() - -```` - -{{endregion}} You can also use the **HideItems**/**ShowItems** methods to specify how many items will be hidden/shown at once: #### Showing/Hiding items -{{source=..\SamplesCS\PageView\OutlookView.cs region=programmingItems}} -{{source=..\SamplesVB\PageView\OutlookView.vb region=programmingGrip}} - -````C# -RadPageViewOutlookElement outlookElement = this.radPageView1.ViewElement as RadPageViewOutlookElement; -//Drags the sizing grip three items down. -outlookElement.HideItems(3); -//Drags the sizing grip two items up. -outlookElement.ShowItems(2); - -```` -````VB.NET -Dim outlookElement As RadPageViewOutlookElement = TryCast(Me.radPageView1.ViewElement, RadPageViewOutlookElement) -'Drags the sizing grip one item down. -outlookElement.DragGripDown() -'Drags the sizing grip one item up. -outlookElement.DragGripUp() + + -```` -{{endregion}} When items are hidden by using the overflow grip, they appear as a strip of buttons on the overflow panel below the stack: diff --git a/controls/pageview/outlookview/using-the-overflow-menu.md b/controls/pageview/outlookview/using-the-overflow-menu.md index 72d3af728..2400f2383 100644 --- a/controls/pageview/outlookview/using-the-overflow-menu.md +++ b/controls/pageview/outlookview/using-the-overflow-menu.md @@ -19,27 +19,10 @@ The Overflow Menu of the **RadPageView**’s PageViewMode.*Outlook* allows for p As well as from the UI, you can check/uncheck items by using the **RadPageViewOutlookElement**’s API. To do so, you should use the **ViewElement** property of the **RadPageView**, cast it to the **RadPageViewOutlookElement** type and call the corresponding API methods as shown in the code snippet below: -{{source=..\SamplesCS\PageView\OutlookView.cs region=programmingOverflow}} -{{source=..\SamplesVB\PageView\OutlookView.vb region=programmingGrip}} - -````C# -RadPageViewOutlookElement outlookElement = this.radPageView1.ViewElement as RadPageViewOutlookElement; -//Hide the first item -outlookElement.UncheckItem(this.radPageViewPage1.Item as RadPageViewOutlookItem); -//Show the first item again -outlookElement.CheckItem(this.radPageViewPage1.Item as RadPageViewOutlookItem); - -```` -````VB.NET -Dim outlookElement As RadPageViewOutlookElement = TryCast(Me.radPageView1.ViewElement, RadPageViewOutlookElement) -'Drags the sizing grip one item down. -outlookElement.DragGripDown() -'Drags the sizing grip one item up. -outlookElement.DragGripUp() - -```` - -{{endregion}} + + + + >note The **CheckItem**/**UncheckItem** methods accept an instance of the **RadPageViewOutlookItem** class. Since the **Item** property of the **RadPageViewPage** class is of the **RadPageViewItem** type, you should cast the returned result to the required type. > diff --git a/controls/pageview/peek-window.md b/controls/pageview/peek-window.md index 9287d3d12..f42469c1e 100644 --- a/controls/pageview/peek-window.md +++ b/controls/pageview/peek-window.md @@ -15,56 +15,19 @@ RadPageView provides popup preview option for its elements when the mouse is ove ![WinForms RadPageView Peek Window](images/pageview-peek-window001.png) -{{source=..\SamplesCS\PageView\PeekWindow.cs region=EnablePeekWindow}} -{{source=..\SamplesVB\PageView\PeekWindow.vb region=EnablePeekWindow}} + + -````C# -this.radPageView1.EnablePeekPopup = true; - -```` -````VB.NET - -Me.radPageView1.EnablePeekPopup = True - - -```` - -{{endregion}} To set a content for each peek window, we can use the __PeekPopupOpening__ event. In the event handler, we have access to the current hovered RadPageViewItem and depending on it, we can set the __Page.PeekPopupContent__ property. This property is of type __Control__. >The Peek Window will take the size of its content. This needs to be considered while using UserControl as a content of the Peek Window. -{{source=..\SamplesCS\PageView\PeekWindow.cs region=PeekWindowEvent_PageView}} -{{source=..\SamplesVB\PageView\PeekWindow.vb region=PeekWindowEvent_PageView}} - -````C# - -private void RadPageView1_PeekPopupOpening(object sender, Telerik.WinControls.UI.OfficeNavigationBar.RadPageViewPeekPopupEventArgs e) -{ - RadLabel content = new RadLabel(); - content.Text = e.Page.Item.Text; - content.Font = new Font("Segoe UI Semibold", 27f); - content.LoadElementTree(); - e.Page.PeekPopupContent = content; -} - -```` -````VB.NET - -Private Sub RadPageView1_PeekPopupOpening(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.OfficeNavigationBar.RadPageViewPeekPopupEventArgs) - Dim content As RadLabel = New RadLabel() - content.Text = e.Page.Item.Text - content.Font = New Font("Segoe UI Semibold", 27F) - content.LoadElementTree() - e.Page.PeekPopupContent = content -End Sub - + + -```` -{{endregion}} In the following image we can see the Peek Window content when it hosts a custom user control. diff --git a/controls/pageview/stackview/customizing-the-selection-mode.md b/controls/pageview/stackview/customizing-the-selection-mode.md index c1f4e1877..43c274dae 100644 --- a/controls/pageview/stackview/customizing-the-selection-mode.md +++ b/controls/pageview/stackview/customizing-the-selection-mode.md @@ -29,21 +29,9 @@ To set the selection mode you should use the *ItemSelectionMode* property of the #### Setting the ItemSelectionMode property -{{source=..\SamplesCS\PageView\StackView.cs region=itemSelectionMode}} -{{source=..\SamplesVB\PageView\StackView.vb region=itemSelectionMode}} + + -````C# -RadPageViewStackElement stackElement = this.radPageView1.ViewElement as RadPageViewStackElement; -stackElement.ItemSelectionMode = StackViewItemSelectionMode.ContentWithSelected; - -```` -````VB.NET -Dim stackElement As RadPageViewStackElement = TryCast(Me.radPageView1.ViewElement, RadPageViewStackElement) -stackElement.ItemSelectionMode = StackViewItemSelectionMode.ContentWithSelected - -```` - -{{endregion}} >note The **ViewElement** property of the **RadPageView** control returns a reference to the main element of the currently active view in the control. So, to cast the **ViewElement** to any an element representing a specific view type, you should make sure that you have set the **ViewMode** of the **RadPageView** control to this view type. diff --git a/controls/pageview/stackview/customizing-the-stack-position.md b/controls/pageview/stackview/customizing-the-stack-position.md index 70acdf25e..d4fd2e373 100644 --- a/controls/pageview/stackview/customizing-the-stack-position.md +++ b/controls/pageview/stackview/customizing-the-stack-position.md @@ -29,21 +29,10 @@ Regardless the stack position, the content of the selected item is displayed at #### StackPosition -{{source=..\SamplesCS\PageView\StackView.cs region=stackPosition}} -{{source=..\SamplesVB\PageView\StackView.vb region=stackPosition}} + + -````C# -RadPageViewStackElement stackElement = this.radPageView1.ViewElement as RadPageViewStackElement; -stackElement.StackPosition = StackViewPosition.Right; -```` -````VB.NET -Dim stackElement As RadPageViewStackElement = TryCast(Me.radPageView1.ViewElement, RadPageViewStackElement) -stackElement.StackPosition = StackViewPosition.Right - -```` - -{{endregion}} >note The **ViewElement** property of the **RadPageView** control returns a reference to the main element of the currently active view in the control. So, to cast the **ViewElement** to any an element representing a specific view type, you should make sure that you have set the **ViewMode** of the **RadPageView** control to this view type. > diff --git a/controls/pageview/stripview/fitting-items.md b/controls/pageview/stripview/fitting-items.md index 6080e5c8c..0b31a6def 100644 --- a/controls/pageview/stripview/fitting-items.md +++ b/controls/pageview/stripview/fitting-items.md @@ -17,62 +17,27 @@ The main property that controls the behavior of the tabs is the __ItemMode__ pro * *None* - Each item uses its desired size. -{{source=..\SamplesCS\PageView\StripViewFittingItems.cs region=ModeNone}} -{{source=..\SamplesVB\PageView\StripViewFittingItems.vb region=ModeNone}} + + -````C# -RadPageViewStripElement stripElement = this.pageView.ViewElement as RadPageViewStripElement; -stripElement.ItemFitMode = StripViewItemFitMode.None; - -```` -````VB.NET -Dim stripElement As RadPageViewStripElement = TryCast(Me.pageView.ViewElement, RadPageViewStripElement) -stripElement.ItemFitMode = StripViewItemFitMode.None - -```` - -{{endregion}} ![WinForms RadPageView Fitting Items None](images/pageview-strip-view-fitting-items001.png) * *Shrink* - Items are shrunk if their size exceeds the available one. -{{source=..\SamplesCS\PageView\StripViewFittingItems.cs region=ModeShrink}} -{{source=..\SamplesVB\PageView\StripViewFittingItems.vb region=ModeShrink}} + + -````C# -RadPageViewStripElement stripElement1 = this.pageView.ViewElement as RadPageViewStripElement; -stripElement1.ItemFitMode = StripViewItemFitMode.Shrink; -```` -````VB.NET -Dim stripElement1 As RadPageViewStripElement = TryCast(Me.pageView.ViewElement, RadPageViewStripElement) -stripElement1.ItemFitMode = StripViewItemFitMode.Shrink -```` - -{{endregion}} - ![WinForms RadPageView Fitting Items Shrink](images/pageview-strip-view-fitting-items002.gif) * *Fill* - Items are expanded if their size is less than the available one. -{{source=..\SamplesCS\PageView\StripViewFittingItems.cs region=ModeFill}} -{{source=..\SamplesVB\PageView\StripViewFittingItems.vb region=ModeFill}} + + -````C# -RadPageViewStripElement stripElement2 = this.pageView.ViewElement as RadPageViewStripElement; -stripElement2.ItemFitMode = StripViewItemFitMode.Fill; - -```` -````VB.NET -Dim stripElement2 As RadPageViewStripElement = TryCast(Me.pageView.ViewElement, RadPageViewStripElement) -stripElement2.ItemFitMode = StripViewItemFitMode.Fill - -```` - -{{endregion}} ![WinForms RadPageView Fitting Items Fill](images/pageview-strip-view-fitting-items003.gif) @@ -80,97 +45,36 @@ stripElement2.ItemFitMode = StripViewItemFitMode.Fill * *ShrinkAndFill* - Items are either shrinked or expanded when needed. -{{source=..\SamplesCS\PageView\StripViewFittingItems.cs region=ModeShrinkAndFill}} -{{source=..\SamplesVB\PageView\StripViewFittingItems.vb region=ModeShrinkAndFill}} - -````C# -RadPageViewStripElement stripElement3 = this.pageView.ViewElement as RadPageViewStripElement; -stripElement3.ItemFitMode = StripViewItemFitMode.ShrinkAndFill; - -```` -````VB.NET -Dim stripElement3 As RadPageViewStripElement = TryCast(Me.pageView.ViewElement, RadPageViewStripElement) -stripElement3.ItemFitMode = StripViewItemFitMode.ShrinkAndFill + + -```` - -{{endregion}} ![WinForms RadPageView Fitting Items ShrinkAndFill](images/pageview-strip-view-fitting-items004.gif) * *FillHeight* - Items are stretched in the available height of their parent container. -{{source=..\SamplesCS\PageView\StripViewFittingItems.cs region=ModeFillHeight}} -{{source=..\SamplesVB\PageView\StripViewFittingItems.vb region=ModeFillHeight}} - -````C# -RadPageViewStripElement stripElement4 = this.pageView.ViewElement as RadPageViewStripElement; -stripElement4.ItemContainer.MinSize = new System.Drawing.Size(0, 50); -stripElement4.ItemFitMode = StripViewItemFitMode.FillHeight; - -```` -````VB.NET -Dim stripElement4 As RadPageViewStripElement = TryCast(Me.pageView.ViewElement, RadPageViewStripElement) -stripElement4.ItemContainer.MinSize = New System.Drawing.Size(0, 50) + + -```` - -{{endregion}} ![WinForms RadPageView Fitting Items FillHeight](images/pageview-strip-view-fitting-items005.png) * *MultiLine* - Items are arranged in multiLine layout. You can also set the __MultiLineItemFitMode__ property to *None* or *Reflow*. If you set the __MultiLineItemFitMode__ property to *None* you will manually need to set the **Row** property of the items: -{{source=..\SamplesCS\PageView\PageViewMultiLine.cs region=PageViewMultiLineItemFitModeNone}} -{{source=..\SamplesVB\PageView\PageViewMultiLine.vb region=PageViewMultiLineItemFitModeNone}} - -````C# -this.pageView.ViewMode = PageViewMode.Strip; -RadPageViewStripElement stripElement = this.pageView.ViewElement as RadPageViewStripElement; -stripElement.ItemFitMode = StripViewItemFitMode.MultiLine; -stripElement.MultiLineItemFitMode = MultiLineItemFitMode.None; -this.radPageViewPage4.Item.Row = 2; -this.radPageViewPage5.Item.Row = 3; + + -```` -````VB.NET -Me.pageView.ViewMode = PageViewMode.Strip -Dim stripElement As RadPageViewStripElement = TryCast(Me.pageView.ViewElement, RadPageViewStripElement) -stripElement.ItemFitMode = StripViewItemFitMode.MultiLine -stripElement.MultiLineItemFitMode = MultiLineItemFitMode.None -Me.RadPageViewPage4.Item.Row = 2 -Me.RadPageViewPage5.Item.Row = 3 - -```` - -{{endregion}} ![WinForms RadPageView Fitting Items MultiLine](images/pageview-strip-view-fitting-items006.gif) If the **MultiLineItemFitMode** property is set to *Reflow*, the layout will automatically calculate these settings: -{{source=..\SamplesCS\PageView\PageViewMultiLine.cs region=PageViewMultiLineItemFitModeReflow}} -{{source=..\SamplesVB\PageView\PageViewMultiLine.vb region=PageViewMultiLineItemFitModeReflow}} - -````C# -this.pageView.ViewMode = PageViewMode.Strip; -RadPageViewStripElement stripElement1 = this.pageView.ViewElement as RadPageViewStripElement; -stripElement1.ItemFitMode = StripViewItemFitMode.MultiLine; -stripElement1.MultiLineItemFitMode = MultiLineItemFitMode.Reflow; - -```` -````VB.NET -Me.pageView.ViewMode = PageViewMode.Strip -Dim stripElement1 As RadPageViewStripElement = TryCast(Me.pageView.ViewElement, RadPageViewStripElement) -stripElement1.ItemFitMode = StripViewItemFitMode.MultiLine -stripElement1.MultiLineItemFitMode = MultiLineItemFitMode.Reflow - -```` + + -{{endregion}} ![WinForms RadPageView MultiLineItemFitMode Reflow](images/pageview-strip-view-fitting-items007.gif) diff --git a/controls/pageview/stripview/new-item.md b/controls/pageview/stripview/new-item.md index 70208e685..05f297196 100644 --- a/controls/pageview/stripview/new-item.md +++ b/controls/pageview/stripview/new-item.md @@ -31,56 +31,19 @@ You can easily show the *NewItem* by setting the __NewItemVisibility__ property Here is how to set the **NewItemVisibility** property: -{{source=..\SamplesCS\PageView\NewItem.cs region=settingNewItemVisibility}} -{{source=..\SamplesVB\PageView\NewItem.vb region=settingNewItemVisibility}} + + -````C# -RadPageViewStripElement stripElement = this.radPageView1.ViewElement as RadPageViewStripElement; -stripElement.NewItemVisibility = StripViewNewItemVisibility.End; -```` -````VB.NET -Dim stripElement As RadPageViewStripElement = TryCast(Me.RadPageView1.ViewElement, RadPageViewStripElement) -stripElement.NewItemVisibility = StripViewNewItemVisibility.End - -```` - -{{endregion}} ## Handling the Clicked NewItem When the **NewItem** is clicked by the end-user, **RadPageView** throws an event called __NewPageRequested__. There you can create a new **RadPageViewPage** instance and add it to **RadPageView**. In the following code snippet we create a new **RadPageViewPage**, add it to **RadPageView**, select the newly created page, and make sure that the page item is fully visible by calling the **EnsureItemVisible** method. -{{source=..\SamplesCS\PageView\NewItem.cs region=newPageRequested}} -{{source=..\SamplesVB\PageView\NewItem.vb region=newPageRequested}} - -````C# -void radPageView1_NewPageRequested(object sender, EventArgs e) -{ - RadPageView pageView = sender as RadPageView; - RadPageViewStripElement stripElement = pageView.ViewElement as RadPageViewStripElement; - RadPageViewPage page = new RadPageViewPage(); - page.Text = "New Page"; - pageView.Pages.Add(page); - pageView.SelectedPage = page; - pageView.ViewElement.EnsureItemVisible(stripElement.NewItem); -} - -```` -````VB.NET -Private Sub radPageView1_NewPageRequested(ByVal sender As Object, ByVal e As EventArgs) - Dim pageView As RadPageView = TryCast(sender, RadPageView) - Dim stripElement As RadPageViewStripElement = TryCast(pageView.ViewElement, RadPageViewStripElement) - Dim page As New RadPageViewPage() - page.Text = "New Page" - pageView.Pages.Add(page) - pageView.SelectedPage = page - pageView.ViewElement.EnsureItemVisible(stripElement.NewItem) -End Sub - -```` - -{{endregion}} + + + + The result is shown on the screenshot below: diff --git a/controls/pageview/stripview/scrolling-and-overflow-(strip-buttons).md b/controls/pageview/stripview/scrolling-and-overflow-(strip-buttons).md index 3cfdef662..90b99a5d6 100644 --- a/controls/pageview/stripview/scrolling-and-overflow-(strip-buttons).md +++ b/controls/pageview/stripview/scrolling-and-overflow-(strip-buttons).md @@ -15,21 +15,9 @@ The __StripButtons__ property of **RadPageView** in PageViewMode.*Strip* allows #### Accessing the StripButtons property -{{source=..\SamplesCS\PageView\StripView.cs region=scrollingAndOverflow}} -{{source=..\SamplesVB\PageView\StripView.vb region=scrollingAndOverflow}} + + -````C# -RadPageViewStripElement stripElement = (RadPageViewStripElement)this.radPageView1.ViewElement; -stripElement.StripButtons = StripViewButtons.All; - -```` -````VB.NET -Dim stripElement As RadPageViewStripElement = DirectCast(Me.radPageView1.ViewElement, RadPageViewStripElement) -stripElement.StripButtons = StripViewButtons.All - -```` - -{{endregion}} PageViewMode.*Strip* supports the following __StripButtons__ modes: diff --git a/controls/pageview/stripview/strip-element-properties.md b/controls/pageview/stripview/strip-element-properties.md index c10a76b04..2b5852675 100644 --- a/controls/pageview/stripview/strip-element-properties.md +++ b/controls/pageview/stripview/strip-element-properties.md @@ -33,21 +33,10 @@ You can use the following properties to change the behavior of the Strip View: #### Accessing the RadPageViewStripElement properties -{{source=..\SamplesCS\PageView\StripView.cs region=scrollingAndOverflow}} -{{source=..\SamplesVB\PageView\StripView.vb region=scrollingAndOverflow}} + + -````C# -RadPageViewStripElement stripElement = (RadPageViewStripElement)this.radPageView1.ViewElement; -stripElement.StripButtons = StripViewButtons.All; -```` -````VB.NET -Dim stripElement As RadPageViewStripElement = DirectCast(Me.radPageView1.ViewElement, RadPageViewStripElement) -stripElement.StripButtons = StripViewButtons.All - -```` - -{{endregion}} # See Also diff --git a/controls/panels-and-labels/collapsiblepanel/getting-started.md b/controls/panels-and-labels/collapsiblepanel/getting-started.md index 4b5d911af..3d7285b85 100644 --- a/controls/panels-and-labels/collapsiblepanel/getting-started.md +++ b/controls/panels-and-labels/collapsiblepanel/getting-started.md @@ -70,31 +70,10 @@ And this is how it will look if the panel is expanded. #### Handle Events -{{source=..\SamplesCS\PanelsAndLabels\CollapsiblePanel\CollapsiblePanelGettingStarted.cs region=ExpandCollapseHandlers}} -{{source=..\SamplesVB\PanelsAndLabels\CollapsiblePanel\CollapsiblePanelGettingStarted.vb region=ExpandCollapseHandlers}} - -````C# -void radCollapsiblePanel1_Collapsed(object sender, EventArgs e) -{ - this.radCollapsiblePanel1.HeaderText = "Show Grid"; -} -void radCollapsiblePanel1_Expanded(object sender, EventArgs e) -{ - this.radCollapsiblePanel1.HeaderText = "Hide Grid"; -} - -```` -````VB.NET -Private Sub radCollapsiblePanel1_Collapsed(sender As Object, e As EventArgs) - Me.RadCollapsiblePanel1.HeaderText = "Show Grid" -End Sub -Private Sub radCollapsiblePanel1_Expanded(sender As Object, e As EventArgs) - Me.RadCollapsiblePanel1.HeaderText = "Hide Grid" -End Sub - -```` - -{{endregion}} + + + + Our example is ready to be tested. You can start the application and observe the following: diff --git a/controls/panels-and-labels/collapsiblepanel/working-with-radcollapsiblepanel.md b/controls/panels-and-labels/collapsiblepanel/working-with-radcollapsiblepanel.md index 9bf22787b..206c0717c 100644 --- a/controls/panels-and-labels/collapsiblepanel/working-with-radcollapsiblepanel.md +++ b/controls/panels-and-labels/collapsiblepanel/working-with-radcollapsiblepanel.md @@ -19,143 +19,66 @@ __ExpandDirection__ - Indicates the direction of the expand animation. The colla #### RadDirection.Down -{{source=..\SamplesCS\PanelsAndLabels\CollapsiblePanel\CollapsiblePanelGettingStarted.cs region=ExpandDirections1}} -{{source=..\SamplesVB\PanelsAndLabels\CollapsiblePanel\CollapsiblePanelGettingStarted.vb region=ExpandDirections1}} + + -````C# -this.radCollapsiblePanel1.ExpandDirection = RadDirection.Down; -```` -````VB.NET -Me.RadCollapsiblePanel1.ExpandDirection = RadDirection.Down - -```` - -{{endregion}} ![WinForms RadCollapsiblePanel RadDirection Down](images/panels-and-labels-radcollapsiblepanel-methods-and-properties001.png) #### RadDirection.Left -{{source=..\SamplesCS\PanelsAndLabels\CollapsiblePanel\CollapsiblePanelGettingStarted.cs region=ExpandDirections2}} -{{source=..\SamplesVB\PanelsAndLabels\CollapsiblePanel\CollapsiblePanelGettingStarted.vb region=ExpandDirections2}} - -````C# -this.radCollapsiblePanel1.ExpandDirection = RadDirection.Left; + + -```` -````VB.NET -Me.RadCollapsiblePanel1.ExpandDirection = RadDirection.Left - -```` - -{{endregion}} ![WinForms RadCollapsiblePanel RadDirection Left](images/panels-and-labels-radcollapsiblepanel-methods-and-properties002.png) #### RadDirection.Right -{{source=..\SamplesCS\PanelsAndLabels\CollapsiblePanel\CollapsiblePanelGettingStarted.cs region=ExpandDirections3}} -{{source=..\SamplesVB\PanelsAndLabels\CollapsiblePanel\CollapsiblePanelGettingStarted.vb region=ExpandDirections3}} - -````C# -this.radCollapsiblePanel1.ExpandDirection = RadDirection.Right; + + -```` -````VB.NET -Me.RadCollapsiblePanel1.ExpandDirection = RadDirection.Right - -```` - -{{endregion}} ![WinForms RadCollapsiblePanel RadDirection Right](images/panels-and-labels-radcollapsiblepanel-methods-and-properties003.png) #### RadDirection.Up -{{source=..\SamplesCS\PanelsAndLabels\CollapsiblePanel\CollapsiblePanelGettingStarted.cs region=ExpandDirections4}} -{{source=..\SamplesVB\PanelsAndLabels\CollapsiblePanel\CollapsiblePanelGettingStarted.vb region=ExpandDirections4}} - -````C# -this.radCollapsiblePanel1.ExpandDirection = RadDirection.Up; - -```` -````VB.NET -Me.RadCollapsiblePanel1.ExpandDirection = RadDirection.Up - -```` + + -{{endregion}} ![WinForms RadCollapsiblePanel RadDirection Up](images/panels-and-labels-radcollapsiblepanel-methods-and-properties004.png) __EnableAnimation__ - Indicates whether to use animation to expand or collapse the control. -{{source=..\SamplesCS\PanelsAndLabels\CollapsiblePanel\CollapsiblePanelGettingStarted.cs region=EnableAnimation}} -{{source=..\SamplesVB\PanelsAndLabels\CollapsiblePanel\CollapsiblePanelGettingStarted.vb region=EnableAnimation}} + + -````C# -this.radCollapsiblePanel1.EnableAnimation = false; -```` -````VB.NET -Me.RadCollapsiblePanel1.EnableAnimation = False - -```` - -{{endregion}} __ContentSizingMode__ - Indicates whether the controls container will resize to fit the width or the height of its content. -{{source=..\SamplesCS\PanelsAndLabels\CollapsiblePanel\CollapsiblePanelGettingStarted.cs region=ContentSizingMode1}} -{{source=..\SamplesVB\PanelsAndLabels\CollapsiblePanel\CollapsiblePanelGettingStarted.vb region=ContentSizingMode1}} - -````C# -this.radCollapsiblePanel1.ContentSizingMode = CollapsiblePanelContentSizingMode.FitToContentWidth; - -```` -````VB.NET -Me.RadCollapsiblePanel1.ContentSizingMode = CollapsiblePanelContentSizingMode.FitToContentWidth - -```` + + -{{endregion}} ![WinForms RadCollapsiblePanel FitToContentWidth](images/panels-and-labels-radcollapsiblepanel-methods-and-properties005.png) -{{source=..\SamplesCS\PanelsAndLabels\CollapsiblePanel\CollapsiblePanelGettingStarted.cs region=ContentSizingMode2}} -{{source=..\SamplesVB\PanelsAndLabels\CollapsiblePanel\CollapsiblePanelGettingStarted.vb region=ContentSizingMode2}} + + -````C# -this.radCollapsiblePanel1.ContentSizingMode = CollapsiblePanelContentSizingMode.FitToContentHeight; -```` -````VB.NET -Me.RadCollapsiblePanel1.ContentSizingMode = CollapsiblePanelContentSizingMode.FitToContentHeight - -```` - -{{endregion}} ![WinForms RadCollapsiblePanel FitToContentHeight](images/panels-and-labels-radcollapsiblepanel-methods-and-properties006.png) -{{source=..\SamplesCS\PanelsAndLabels\CollapsiblePanel\CollapsiblePanelGettingStarted.cs region=ContentSizingMode3}} -{{source=..\SamplesVB\PanelsAndLabels\CollapsiblePanel\CollapsiblePanelGettingStarted.vb region=ContentSizingMode3}} - -````C# -this.radCollapsiblePanel1.ContentSizingMode = CollapsiblePanelContentSizingMode.FitToContentWidth | CollapsiblePanelContentSizingMode.FitToContentHeight; - -```` -````VB.NET -Me.RadCollapsiblePanel1.ContentSizingMode = CollapsiblePanelContentSizingMode.FitToContentWidth Or CollapsiblePanelContentSizingMode.FitToContentHeight - -```` + + -{{endregion}} ![WinForms RadCollapsiblePanel FitToContentWidth or FitToContentHeight](images/panels-and-labels-radcollapsiblepanel-methods-and-properties007.png) diff --git a/controls/panels-and-labels/groupbox/customizing-appearance/accessing-and-customizing-elements.md b/controls/panels-and-labels/groupbox/customizing-appearance/accessing-and-customizing-elements.md index 50885b6cb..b3451829d 100644 --- a/controls/panels-and-labels/groupbox/customizing-appearance/accessing-and-customizing-elements.md +++ b/controls/panels-and-labels/groupbox/customizing-appearance/accessing-and-customizing-elements.md @@ -33,27 +33,10 @@ The code sample below access the **FillPrimitive** of the header, changes the fi #### Change the GroupBox Header Color -{{source=..\SamplesCS\PanelsAndLabels\GroupBox\Advanced\TPFStructure.cs region=changeTheHeaderColor}} -{{source=..\SamplesVB\PanelsAndLabels\GroupBox\Advanced\TPFStructure.vb region=changeTheHeaderColor}} - -````C# -FillPrimitive fill = ((FillPrimitive)this.radGroupBox1.GroupBoxElement.Children[1].Children[0]); -fill.ShouldPaint = true; -fill.BackColor = Color.Red; -fill.BackColor2 = Color.Yellow; -fill.GradientStyle = Telerik.WinControls.GradientStyles.Linear; - -```` -````VB.NET -Dim fill As FillPrimitive = DirectCast(Me.RadGroupBox1.GroupBoxElement.Children(1).Children(0), FillPrimitive) -fill.ShouldPaint = True -fill.BackColor = Color.Red -fill.BackColor2 = Color.Yellow -fill.GradientStyle = Telerik.WinControls.GradientStyles.Linear - -```` - -{{endregion}} + + + + >note The code samples below are just a demonstration of how you can set node properties programmatically. You will probably prefer to use the Visual Style Builder to create your themes using no code. > diff --git a/controls/panels-and-labels/groupbox/mnemonics.md b/controls/panels-and-labels/groupbox/mnemonics.md index 1a1ecda47..67f3be08f 100644 --- a/controls/panels-and-labels/groupbox/mnemonics.md +++ b/controls/panels-and-labels/groupbox/mnemonics.md @@ -14,18 +14,9 @@ __RadGroupBox__ supports mnemonics out of the box. When its mnemonic key is pres In order to activate this functionality you should specify the character that will be used for a given control by placing the __&__ character before the desired symbol. -{{source=..\SamplesCS\PanelsAndLabels\GroupBox\Advanced\TPFStructure.cs region=SetMenemonic}} -{{source=..\SamplesVB\PanelsAndLabels\GroupBox\Advanced\TPFStructure.vb region=SetMenemonic}} -````C# -radGroupBox1.Text = "Te&st"; + + -```` -````VB.NET -RadGroupBox1.Text = "Te&st" -```` - - -{{endregion}} __UseMnemonic__ is a boolean property which controls whether the __&__ character is displayed as the symbol itself or whether it is used to designate a mnemonic (visualized as an underscore). Its default value is *true* i.e. mnemonics are used by default. diff --git a/controls/panels-and-labels/label/getting-started.md b/controls/panels-and-labels/label/getting-started.md index 310f6a73b..30d43fbe7 100644 --- a/controls/panels-and-labels/label/getting-started.md +++ b/controls/panels-and-labels/label/getting-started.md @@ -48,26 +48,10 @@ To programmatically add a **RadLabel** to a form, create a new instance of a ** #### Adding a RadLabel at Run-time -{{source=..\SamplesCS\PanelsAndLabels\Label\LabelHtmlLikeTextFormatting.cs region=AddLabel}} -{{source=..\SamplesVB\PanelsAndLabels\Label\LabelHtmlLikeTextFormatting.vb region=AddLabel}} -````C# -RadLabel label = new RadLabel(); -this.Controls.Add(label); -label.ForeColor = Color.Green; -label.Text = "I am a RadLabel!"; + + -```` -````VB.NET -Dim label As New RadLabel() -Me.Controls.Add(label) -label.ForeColor = Color.Green -label.Text = "I am a RadLabel!" -```` - - - -{{endregion}} ## Programming RadLabel diff --git a/controls/panels-and-labels/label/html-like-text-formatting.md b/controls/panels-and-labels/label/html-like-text-formatting.md index 593a963c5..e682cee80 100644 --- a/controls/panels-and-labels/label/html-like-text-formatting.md +++ b/controls/panels-and-labels/label/html-like-text-formatting.md @@ -35,19 +35,10 @@ The following code snippet will produce the result shown in the screen-shot belo #### Set HTML-like text formatting to RadLabel text -{{source=..\SamplesCS\PanelsAndLabels\Label\LabelHtmlLikeTextFormatting.cs region=setHtmlText}} -{{source=..\SamplesVB\PanelsAndLabels\Label\LabelHtmlLikeTextFormatting.vb region=setHtmlText}} + + -````C# -this.radLabel1.Text = "This is RadLabel
Arial, Bold
Times, Italic Underline
Size = 9
Sample Text"; -```` -````VB.NET -Me.RadLabel1.Text = "This is RadLabel
Arial, Bold
Times, Italic Underline
Size = 9
Sample Text" - -```` - -{{endregion}} >caption Figure 1: HTML-like Text ![WinForms RadLabel HTML-like Text](images/panels-and-labels-label-html-like-text-formatting001.png) diff --git a/controls/panels-and-labels/panel/getting-started.md b/controls/panels-and-labels/panel/getting-started.md index a07a655a4..c8c4e6cff 100644 --- a/controls/panels-and-labels/panel/getting-started.md +++ b/controls/panels-and-labels/panel/getting-started.md @@ -51,30 +51,10 @@ To programmatically add a **RadPanel** to a form, create a new instance of a ** #### Adding a RadPanel at Run-time -{{source=..\SamplesCS\PanelsAndLabels\Panel\PanelGettingStarted.cs region=AddPanel}} -{{source=..\SamplesVB\PanelsAndLabels\Panel\PanelGettingStarted.vb region=AddPanel}} -````C# -RadPanel panel = new RadPanel(); -this.Controls.Add(panel); -panel.ForeColor = Color.DarkBlue; -panel.BackColor = Color.LightBlue; -panel.PanelElement.PanelBorder.ForeColor = Color.Gray; -panel.Text = "I am a RadPanel!"; - -```` -````VB.NET -Dim panel As New RadPanel() -Me.Controls.Add(panel) -panel.ForeColor = Color.DarkBlue -panel.BackColor = Color.LightBlue -panel.PanelElement.PanelBorder.ForeColor = Color.Gray -panel.Text = "I am a RadPanel!" - -```` - - - -{{endregion}} + + + + ## Programming RadPanel diff --git a/controls/panels-and-labels/separator.md b/controls/panels-and-labels/separator.md index 870a773c9..fdc2b72a2 100644 --- a/controls/panels-and-labels/separator.md +++ b/controls/panels-and-labels/separator.md @@ -38,51 +38,10 @@ Follows a small sample, which demonstrates how to take advantage of the function #### Customize RadSeparator -{{source=..\SamplesCS\PanelsAndLabels\Separator\Separator.cs region=separatorExample}} -{{source=..\SamplesVB\PanelsAndLabels\Separator\Separator.vb region=separatorExample}} - -````C# -radSeparator1.ShadowOffset = new Point(10, 0); -radSeparator1.SeparatorElement.Line1.LineWidth = 5; -radSeparator1.SeparatorElement.Line2.LineWidth = 5; -radSeparator1.ShowShadow = true; -radSeparator1.Orientation = Orientation.Horizontal; -radSeparator1.SeparatorElement.Line1.BackColor = Color.Yellow; -radSeparator1.SeparatorElement.Line1.BackColor2 = Color.Orange; -radSeparator1.SeparatorElement.Line1.BackColor3 = Color.Red; -radSeparator1.SeparatorElement.Line1.NumberOfColors = 3; -radSeparator1.SeparatorElement.Line1.GradientStyle = Telerik.WinControls.GradientStyles.Linear; -radSeparator1.SeparatorElement.Line1.GradientAngle = 0; -radSeparator1.SeparatorElement.Line2.BackColor = Color.Black; -radSeparator1.SeparatorElement.Line2.BackColor2 = Color.Green; -radSeparator1.SeparatorElement.Line2.BackColor3 = Color.LightGreen; -radSeparator1.SeparatorElement.Line2.NumberOfColors = 3; -radSeparator1.SeparatorElement.Line2.GradientStyle = Telerik.WinControls.GradientStyles.Linear; -radSeparator1.SeparatorElement.Line2.GradientAngle = 0; - -```` -````VB.NET -RadSeparator1.ShadowOffset = New Point(10, 0) -RadSeparator1.SeparatorElement.Line1.LineWidth = 5 -RadSeparator1.SeparatorElement.Line2.LineWidth = 5 -RadSeparator1.ShowShadow = True -RadSeparator1.Orientation = Orientation.Horizontal -RadSeparator1.SeparatorElement.Line1.BackColor = Color.Yellow -RadSeparator1.SeparatorElement.Line1.BackColor2 = Color.Orange -RadSeparator1.SeparatorElement.Line1.BackColor3 = Color.Red -RadSeparator1.SeparatorElement.Line1.NumberOfColors = 3 -RadSeparator1.SeparatorElement.Line1.GradientStyle = Telerik.WinControls.GradientStyles.Linear -RadSeparator1.SeparatorElement.Line1.GradientAngle = 0 -RadSeparator1.SeparatorElement.Line2.BackColor = Color.Black -RadSeparator1.SeparatorElement.Line2.BackColor2 = Color.Green -RadSeparator1.SeparatorElement.Line2.BackColor3 = Color.LightGreen -RadSeparator1.SeparatorElement.Line2.NumberOfColors = 3 -RadSeparator1.SeparatorElement.Line2.GradientStyle = Telerik.WinControls.GradientStyles.Linear -RadSeparator1.SeparatorElement.Line2.GradientAngle = 0 - -```` - -{{endregion}} + + + + Here is the result of the following code: diff --git a/controls/panorama/custom-tiles.md b/controls/panorama/custom-tiles.md index b8de92930..b7ee4b493 100644 --- a/controls/panorama/custom-tiles.md +++ b/controls/panorama/custom-tiles.md @@ -21,185 +21,19 @@ The code snippet bellow illustrates how the layout is achieved. There is a [Grid #### Custom Tile Class -{{source=..\SamplesCS\Panorama\CustomTiles.cs region=CustomTileClass}} -{{source=..\SamplesVB\Panorama\CustomTiles.vb region=CustomTileClass}} - -````C# -class CustomTileElement : RadTileElement -{ - LightVisualElement subject; - LightVisualElement startTime; - LightVisualElement endTime; - LightVisualElement alarmIcon; - GridLayout layoutPanel; - protected override void CreateChildElements() - { - base.CreateChildElements(); - layoutPanel = new GridLayout(); - layoutPanel.Columns.Clear(); - layoutPanel.Rows.Clear(); - layoutPanel.StretchHorizontally = false; - layoutPanel.StretchVertically = false; - //add columns - layoutPanel.Columns.Add(new GridLayoutColumn() - { - SizingType = GridLayoutSizingType.Proportional, - ProportionalWidthWeight = 50 - }); - layoutPanel.Columns.Add(new GridLayoutColumn() - { - SizingType = GridLayoutSizingType.Proportional, - ProportionalWidthWeight = 50 - }); - //add rows - layoutPanel.Rows.Add(new GridLayoutRow() - { - SizingType = GridLayoutSizingType.Proportional, - ProportionalHeightWeight = 33 - }); - layoutPanel.Rows.Add(new GridLayoutRow() - { - SizingType = GridLayoutSizingType.Proportional, - ProportionalHeightWeight = 33 - }); - layoutPanel.Rows.Add(new GridLayoutRow() - { - SizingType = GridLayoutSizingType.Proportional, - ProportionalHeightWeight = 34 - }); - subject = new LightVisualElement(); - subject.Text = "WinForms Conference"; - subject.Font = new System.Drawing.Font("Consolas", 18, FontStyle.Underline); - subject.BackColor = Color.Aqua; - subject.TextAlignment = ContentAlignment.MiddleLeft; - subject.Padding = new System.Windows.Forms.Padding(20, 0, 0, 0); - subject.SetValue(GridLayout.RowIndexProperty, 0); - subject.SetValue(GridLayout.ColumnIndexProperty, 0); - subject.SetValue(GridLayout.ColSpanProperty, 2); - startTime = new LightVisualElement(); - startTime.Text = "Start: " + DateTime.Now.ToShortDateString(); - startTime.SetValue(GridLayout.RowIndexProperty, 1); - startTime.SetValue(GridLayout.ColumnIndexProperty, 0); - endTime = new LightVisualElement(); - endTime.Text = "End: " + DateTime.Now.AddDays(3).ToShortDateString(); - endTime.SetValue(GridLayout.RowIndexProperty, 1); - endTime.SetValue(GridLayout.ColumnIndexProperty, 1); - alarmIcon = new LightVisualElement(); - alarmIcon.Image = Image.FromFile(@"../../bell.png").GetThumbnailImage(35, 35, null, IntPtr.Zero); - alarmIcon.ImageLayout = System.Windows.Forms.ImageLayout.None; - alarmIcon.Padding = new System.Windows.Forms.Padding(0, 0, 10, 0); - alarmIcon.ImageAlignment = ContentAlignment.MiddleRight; - alarmIcon.SetValue(GridLayout.RowIndexProperty, 2); - alarmIcon.SetValue(GridLayout.ColumnIndexProperty, 1); - this.layoutPanel.Children.Add(subject); - this.layoutPanel.Children.Add(startTime); - this.layoutPanel.Children.Add(endTime); - this.layoutPanel.Children.Add(alarmIcon); - this.Children.Add(layoutPanel); - } - public CustomTileElement() - { - this.BackColor = ColorTranslator.FromHtml("#008de7"); - } - protected override Type ThemeEffectiveType - { - get - { - return typeof(RadTileElement); - } - } -} - -```` -````VB.NET -Friend Class CustomTileElement - Inherits RadTileElement - Private subject As LightVisualElement - Private startTime As LightVisualElement - Private endTime As LightVisualElement - Private alarmIcon As LightVisualElement - Private layoutPanel As GridLayout - Protected Overrides Sub CreateChildElements() - MyBase.CreateChildElements() - layoutPanel = New GridLayout() - layoutPanel.Columns.Clear() - layoutPanel.Rows.Clear() - layoutPanel.StretchHorizontally = False - layoutPanel.StretchVertically = False - 'add columns - layoutPanel.Columns.Add(New GridLayoutColumn() With {.SizingType = GridLayoutSizingType.Proportional, .ProportionalWidthWeight = 50}) - layoutPanel.Columns.Add(New GridLayoutColumn() With {.SizingType = GridLayoutSizingType.Proportional, .ProportionalWidthWeight = 50}) - 'add rows - layoutPanel.Rows.Add(New GridLayoutRow() With {.SizingType = GridLayoutSizingType.Proportional, .ProportionalHeightWeight = 33}) - layoutPanel.Rows.Add(New GridLayoutRow() With {.SizingType = GridLayoutSizingType.Proportional, .ProportionalHeightWeight = 33}) - layoutPanel.Rows.Add(New GridLayoutRow() With {.SizingType = GridLayoutSizingType.Proportional, .ProportionalHeightWeight = 34}) - subject = New LightVisualElement() - subject.Text = "WinForms Conference" - subject.Font = New System.Drawing.Font("Consolas", 18, FontStyle.Underline) - subject.BackColor = Color.Aqua - subject.TextAlignment = ContentAlignment.MiddleLeft - subject.Padding = New System.Windows.Forms.Padding(20, 0, 0, 0) - subject.SetValue(GridLayout.RowIndexProperty, 0) - subject.SetValue(GridLayout.ColumnIndexProperty, 0) - subject.SetValue(GridLayout.ColSpanProperty, 2) - startTime = New LightVisualElement() - startTime.Text = "Start: " & Date.Now.ToShortDateString() - startTime.SetValue(GridLayout.RowIndexProperty, 1) - startTime.SetValue(GridLayout.ColumnIndexProperty, 0) - endTime = New LightVisualElement() - endTime.Text = "End: " & Date.Now.AddDays(3).ToShortDateString() - endTime.SetValue(GridLayout.RowIndexProperty, 1) - endTime.SetValue(GridLayout.ColumnIndexProperty, 1) - alarmIcon = New LightVisualElement() - alarmIcon.Image = Image.FromFile("../../bell.png").GetThumbnailImage(35, 35, Nothing, IntPtr.Zero) - alarmIcon.ImageLayout = System.Windows.Forms.ImageLayout.None - alarmIcon.Padding = New System.Windows.Forms.Padding(0, 0, 10, 0) - alarmIcon.ImageAlignment = ContentAlignment.MiddleRight - alarmIcon.SetValue(GridLayout.RowIndexProperty, 2) - alarmIcon.SetValue(GridLayout.ColumnIndexProperty, 1) - Me.layoutPanel.Children.Add(subject) - Me.layoutPanel.Children.Add(startTime) - Me.layoutPanel.Children.Add(endTime) - Me.layoutPanel.Children.Add(alarmIcon) - Me.Children.Add(layoutPanel) - End Sub - Public Sub New() - Me.BackColor = ColorTranslator.FromHtml("#008de7") - End Sub - Protected Overrides ReadOnly Property ThemeEffectiveType() As Type - Get - Return GetType(RadTileElement) - End Get - End Property -End Class - -```` - -{{endregion}} + + -You can use the new tile with the following code: -#### Add the new tile to RadPanorama -{{source=..\SamplesCS\Panorama\CustomTiles.cs region=AddTile}} -{{source=..\SamplesVB\Panorama\CustomTiles.vb region=AddTile}} +You can use the new tile with the following code: -````C# -CustomTileElement tile = new CustomTileElement(); -tile.RowSpan = 2; -tile.ColSpan = 4; -radPanorama1.Items.Add(tile); +#### Add the new tile to RadPanorama -```` -````VB.NET -Dim tile As New CustomTileElement() -tile.RowSpan = 2 -tile.ColSpan = 4 -RadPanorama1.Items.Add(tile) + + -```` -{{endregion}} # See Also diff --git a/controls/panorama/customizing-appearance/accessing-and-customizing-elements.md b/controls/panorama/customizing-appearance/accessing-and-customizing-elements.md index 83e080c04..47c86285b 100644 --- a/controls/panorama/customizing-appearance/accessing-and-customizing-elements.md +++ b/controls/panorama/customizing-appearance/accessing-and-customizing-elements.md @@ -37,33 +37,10 @@ You can customize the nested elements at run time as well: #### Customize elements -{{source=..\SamplesCS\Panorama\PanoramaGettingStarted.cs region=CustomizeElements}} -{{source=..\SamplesVB\Panorama\PanoramaGettingStarted.vb region=CustomizeElements}} - -````C# -this.radPanorama1.BackColor=Color.Gray; -this.radTileElement1.BackColor= Color.DarkRed; -this.radTileElement1.BorderColor = Color.Yellow; -this.radTileElement1.TextWrap = true; -this.radTileElement1.ForeColor = Color.Aqua; - -```` -````VB.NET -Me.RadPanorama1.BackColor = Color.Gray -Me.RadTileElement1.BackColor = Color.DarkRed -Me.RadTileElement1.BorderColor = Color.Yellow -Me.RadTileElement1.TextWrap = True -Me.RadTileElement1.ForeColor = Color.Aqua -'#End Region -End Sub -Sub MetodUsedToStoreRegions() -'#region SetTilePosition -Me.RadTileElement1.Row = 1 -Me.RadTileElement1.Column = 0 - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/panorama/drad-and-drop/drag-and-drop.md b/controls/panorama/drad-and-drop/drag-and-drop.md index fc59dcf40..1cfdae4e6 100644 --- a/controls/panorama/drad-and-drop/drag-and-drop.md +++ b/controls/panorama/drad-and-drop/drag-and-drop.md @@ -18,227 +18,17 @@ By default, **RadPanorama** supports drag and drop functionality of the tiles wi ![WinForms RadPanorama Drag Drop](images/panorama-drag-and-drop001.gif) -{{source=..\SamplesCS\Panorama\PanoramaDragDrop.cs region=CustomTileDragDropService}} -{{source=..\SamplesVB\Panorama\PanoramaDragDrop.vb region=CustomTileDragDropService}} + + -````C# -public class CustomTileDragDropService : TileDragDropService -{ - public CustomTileDragDropService(RadPanoramaElement owner) : base(owner) - { - } - - RadPanoramaElement draggedParent; - RadPanoramaElement targetParent; - - protected override void OnPreviewDragOver(RadDragOverEventArgs e) - { - RadTileElement draggedTile = e.DragInstance as RadTileElement; - if (draggedTile != null) - { - draggedParent = GetTileParent(draggedTile); - if (e.HitTarget is RadTileElement) - { - targetParent = GetTileParent(e.HitTarget as RadTileElement); - if (targetParent != draggedParent) - { - e.CanDrop = true; - } - else - { - e.CanDrop = false; - } - } - else - { - e.CanDrop = false; - } - } - } - - private RadPanoramaElement GetTileParent(RadTileElement tile) - { - RadElement current = tile.Parent; - while (current != null) - { - if (current is RadPanoramaElement) - { - current = current as RadPanoramaElement; - break; - } - current = current.Parent; - } - return current as RadPanoramaElement ; - } - - protected override void OnPreviewDragDrop(RadDropEventArgs e) - { - e.Handled = true; - RadTileElement source = this.Context as RadTileElement; - RadTileElement target = e.HitTarget as RadTileElement; - TileGroupElement targetGroup = null; - int insertIndex = 0; - if (source == null) - { - return; - } - draggedParent.Items.Remove(source); - - if (target != null) - { - //groups are available - if (targetParent.Groups.Count > 0) - { - targetGroup = target.Parent.Parent as TileGroupElement; - insertIndex = targetGroup.Items.IndexOf(target); - } - else - { - insertIndex = targetParent.Items.IndexOf(target); - } - if (insertIndex > -1) - { - source.Column = target.Column; - source.Row = target.Row; - if (targetGroup != null) - { - targetGroup.Items.Insert(insertIndex, source); - } - else - { - targetParent.Items.Insert(insertIndex, source); - } - } - } - else - { - targetParent.Items.Add(source); - } - - if (targetGroup != null) - { - AdjustPosition(source, insertIndex, targetGroup.Items); - } - else - { - AdjustPosition(source, insertIndex, targetParent.Items); - } - } - - private void AdjustPosition(RadTileElement source, int insertIndex, RadItemOwnerCollection items) - { - for (int i = insertIndex + 1; i < items.Count; i++) - { - RadTileElement tile = items[i] as RadTileElement; - if (tile.Row == source.Row && tile.Column >= source.Column && tile != source) - { - tile.Column++; - } - } - } -} -```` -````VB.NET -Public Class CustomTileDragDropService - Inherits TileDragDropService - Public Sub New(owner As RadPanoramaElement) - MyBase.New(owner) - End Sub - Private draggedParent As RadPanoramaElement - Private targetParent As RadPanoramaElement - Protected Overrides Sub OnPreviewDragOver(e As RadDragOverEventArgs) - Dim draggedTile As RadTileElement = TryCast(e.DragInstance, RadTileElement) - If draggedTile IsNot Nothing Then - draggedParent = GetTileParent(draggedTile) - If TypeOf e.HitTarget Is RadTileElement Then - targetParent = GetTileParent(TryCast(e.HitTarget, RadTileElement)) - If Not targetParent.Equals(draggedParent) Then - e.CanDrop = True - Else - e.CanDrop = False - End If - Else - e.CanDrop = False - End If - End If - End Sub - Private Function GetTileParent(tile As RadTileElement) As RadPanoramaElement - Dim current As RadElement = tile.Parent - While current IsNot Nothing - If TypeOf current Is RadPanoramaElement Then - current = TryCast(current, RadPanoramaElement) - Exit While - End If - current = current.Parent - End While - Return TryCast(current, RadPanoramaElement) - End Function - Protected Overrides Sub OnPreviewDragDrop(e As RadDropEventArgs) - e.Handled = True - Dim source As RadTileElement = TryCast(Me.Context, RadTileElement) - Dim target As RadTileElement = TryCast(e.HitTarget, RadTileElement) - Dim targetGroup As TileGroupElement = Nothing - Dim insertIndex As Integer = 0 - If source Is Nothing Then - Return - End If - draggedParent.Items.Remove(source) - If target IsNot Nothing Then - 'groups are available - If targetParent.Groups.Count > 0 Then - targetGroup = TryCast(target.Parent.Parent, TileGroupElement) - insertIndex = targetGroup.Items.IndexOf(target) - Else - insertIndex = targetParent.Items.IndexOf(target) - End If - If insertIndex > -1 Then - source.Column = target.Column - source.Row = target.Row - If targetGroup IsNot Nothing Then - targetGroup.Items.Insert(insertIndex, source) - Else - targetParent.Items.Insert(insertIndex, source) - End If - End If - Else - targetParent.Items.Add(source) - End If - If targetGroup IsNot Nothing Then - AdjustPosition(source, insertIndex, targetGroup.Items) - Else - AdjustPosition(source, insertIndex, targetParent.Items) - End If - End Sub - Private Sub AdjustPosition(source As RadTileElement, insertIndex As Integer, items As RadItemOwnerCollection) - For i As Integer = insertIndex + 1 To items.Count - 1 - Dim tile As RadTileElement = TryCast(items(i), RadTileElement) - If tile.Row = source.Row AndAlso tile.Column >= source.Column AndAlso Not tile.Equals(source) Then - tile.Column += 1 - End If - Next - End Sub -End Class - -```` - -{{endregion}} In order to replace the default **TileDragDropService** with the default one, it is necessary to set the PanoramaElement.**DragDropService** property: -{{source=..\SamplesCS\Panorama\PanoramaDragDrop.cs region=ReplaceService}} -{{source=..\SamplesVB\Panorama\PanoramaDragDrop.vb region=ReplaceService}} - -````C# -radPanorama1.PanoramaElement.DragDropService = new CustomTileDragDropService(radPanorama1.PanoramaElement); - -```` -````VB.NET -radPanorama1.PanoramaElement.DragDropService = New CustomTileDragDropService(radPanorama1.PanoramaElement) + + -```` -{{endregion}} # See Also diff --git a/controls/panorama/save-and-load-layout.md b/controls/panorama/save-and-load-layout.md index f1c6202bc..3df962d33 100644 --- a/controls/panorama/save-and-load-layout.md +++ b/controls/panorama/save-and-load-layout.md @@ -16,78 +16,17 @@ Here is a sample demonstrating how you can implement a *Save Layout* button even #### Save layout -{{source=..\SamplesCS\Panorama\SaveLoadLayout.cs region=saveLayout}} -{{source=..\SamplesVB\Panorama\SaveLoadLayout1.vb region=saveLayout}} + + -````C# -private void SaveButton_Click(object sender, EventArgs e) -{ - string s = "default.xml"; - SaveFileDialog dialog = new SaveFileDialog(); - dialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*"; - dialog.Title = "Select a xml file"; - if (dialog.ShowDialog() == DialogResult.OK) - { - s = dialog.FileName; - } - this.radPanorama1.SaveLayout(s); -} -```` -````VB.NET -Private Sub SaveButton_Click(ByVal sender As Object, ByVal e As EventArgs) - Dim s As String = "default.xml" - Dim dialog As SaveFileDialog = New SaveFileDialog() - dialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*" - dialog.Title = "Select a xml file" - - If dialog.ShowDialog() = DialogResult.OK Then - s = dialog.FileName - End If - Me.RadPanorama1.SaveLayout(s) -End Sub - -```` - -{{endregion}} The code snippets below demonstrates how you can implement a *Load Layout* button event handler:  #### Load layout -{{source=..\SamplesCS\Panorama\SaveLoadLayout.cs region=loadLayout}} -{{source=..\SamplesVB\Panorama\SaveLoadLayout1.vb region=loadLayout}} - -````C# -private void LoadButton_Click(object sender, EventArgs e) -{ - string s = "default.xml"; - OpenFileDialog dialog = new OpenFileDialog(); - dialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*"; - dialog.Title = "Select a xml file"; - if (dialog.ShowDialog() == DialogResult.OK) - { - s = dialog.FileName; - } - this.radPanorama1.LoadLayout(s); -} - -```` -````VB.NET -Private Sub LoadButton_Click(ByVal sender As Object, ByVal e As EventArgs) - Dim s As String = "default.xml" - Dim dialog As OpenFileDialog = New OpenFileDialog() - dialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*" - dialog.Title = "Select a xml file" - - If dialog.ShowDialog() = DialogResult.OK Then - s = dialog.FileName - End If - Me.RadPanorama1.LoadLayout(s) -End Sub - -```` + + -{{endregion}} diff --git a/controls/panorama/scrolling.md b/controls/panorama/scrolling.md index c0cbbe656..fd15381ad 100644 --- a/controls/panorama/scrolling.md +++ b/controls/panorama/scrolling.md @@ -15,38 +15,19 @@ previous_url: panorama-scrolling #### Set scroll bar alignment -{{source=..\SamplesCS\Panorama\PanoramaGettingStarted.cs region=ScrollBarAlignment}} -{{source=..\SamplesVB\Panorama\PanoramaGettingStarted.vb region=ScrollBarAlignment}} + + -````C# - -this.radPanorama1.ScrollBarAlignment = HorizontalScrollAlignment.Bottom; -```` -````VB.NET -Me.RadPanorama1.ScrollBarAlignment = HorizontalScrollAlignment.Bottom - -```` - -{{endregion}} The thickness of the scroll bar can be changed by modifying the __ScrollBarThickness__ property of the control: #### Modify scroll bar thickness -{{source=..\SamplesCS\Panorama\PanoramaGettingStarted.cs region=ScrollThickness}} -{{source=..\SamplesVB\Panorama\PanoramaGettingStarted.vb region=ScrollThickness}} - -````C# -this.radPanorama1.ScrollBarThickness = 16; + + -```` -````VB.NET -Me.RadPanorama1.ScrollBarThickness = 16 -```` - -{{endregion}} To change the background image of the view, set the __PanelImage__ property with the desired image. To enable scrolling the background image along with the view, set the __ScrollingBackground__ property to *true*. You will also need to set the __PanelImageSize__ property. Usually, to achieve smooth background scrolling, the width of the panel image should be larger than the client width of the control and smaller than the total width of the tile layout. To edit more properties of the image, you can access its element via the PanoramaElement.__BackgroundImagePrimitive__ property. The following code demonstrates how to setup a tiling background image and a background scrolling: @@ -54,76 +35,10 @@ To change the background image of the view, set the __PanelImage__ property with #### Set tiling backgroung image -{{source=..\SamplesCS\Panorama\PanoramaGettingStarted.cs region=SetTilingBackground}} -{{source=..\SamplesVB\Panorama\PanoramaGettingStarted.vb region=SetTilingBackground}} - -````C# - -void PanoramaGettingStarted_Load(object sender, EventArgs e) -{ - radPanorama1.ScrollingBackground = true; - - this.radPanorama1.PanelImage = Resources.bg_pattern; - this.radPanorama1.PanoramaElement.BackgroundImagePrimitive.ImageLayout = ImageLayout.Tile; - this.radPanorama1.SizeChanged += new EventHandler(radPanorama1_SizeChanged); - this.radPanorama1.PanoramaElement.ScrollBar.PropertyChanged += new PropertyChangedEventHandler(ScrollBar_PropertyChanged); - UpdateImageSize(); -} - -void ScrollBar_PropertyChanged(object sender, PropertyChangedEventArgs e) -{ - if (e.PropertyName == "Maximum") - { - UpdateImageSize(); - } -} - -void radPanorama1_SizeChanged(object sender, EventArgs e) -{ - UpdateImageSize(); -} - -private void UpdateImageSize() -{ - int width = (this.radPanorama1.Width + this.radPanorama1.PanoramaElement.ScrollBar.Maximum) / 2; - if (width < radPanorama1.Width) - { - width = radPanorama1.Width; - } - this.radPanorama1.PanelImageSize = new Size(width, radPanorama1.Height); - this.radPanorama1.PanoramaElement.UpdateViewOnScroll(); -} - -```` -````VB.NET -Private Sub PanoramaGettingStarted_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load - RadPanorama1.ScrollingBackground = True - Me.RadPanorama1.PanelImage = My.Resources.bg_pattern - Me.RadPanorama1.PanoramaElement.BackgroundImagePrimitive.ImageLayout = ImageLayout.Tile - AddHandler Me.RadPanorama1.SizeChanged, AddressOf radPanorama1_SizeChanged - AddHandler Me.RadPanorama1.PanoramaElement.ScrollBar.PropertyChanged, AddressOf ScrollBar_PropertyChanged - UpdateImageSize() -End Sub -Private Sub ScrollBar_PropertyChanged(sender As Object, e As PropertyChangedEventArgs) - If e.PropertyName = "Maximum" Then - UpdateImageSize() - End If -End Sub -Private Sub radPanorama1_SizeChanged(sender As Object, e As EventArgs) Handles RadPanorama1.SizeChanged - UpdateImageSize() -End Sub -Private Sub UpdateImageSize() - Dim width As Integer = (Me.RadPanorama1.Width + Me.RadPanorama1.PanoramaElement.ScrollBar.Maximum) / 2 - If width < RadPanorama1.Width Then - width = RadPanorama1.Width - End If - Me.RadPanorama1.PanelImageSize = New Drawing.Size(width, 768) - Me.RadPanorama1.PanoramaElement.UpdateViewOnScroll() -End Sub - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/panorama/tiles.md b/controls/panorama/tiles.md index ceb5c7b83..d6e254f32 100644 --- a/controls/panorama/tiles.md +++ b/controls/panorama/tiles.md @@ -17,22 +17,10 @@ To set the location of a tile, set its __Column__ and __Row__ properties either #### Set tile's position -{{source=..\SamplesCS\Panorama\PanoramaGettingStarted.cs region=SetTilePosition}} -{{source=..\SamplesVB\Panorama\PanoramaGettingStarted.vb region=SetTilePosition}} + + -````C# - -this.radTileElement1.Row = 1; -this.radTileElement1.Column = 0; -```` -````VB.NET -Me.RadTileElement1.Row = 1 -Me.RadTileElement1.Column = 0 - -```` - -{{endregion}} ![WinForms RadPanorama Row Column Property](images/panorama-tiles001.png) @@ -43,34 +31,10 @@ To change the span of a tile, set its __RowSpan__ and __ColSpan__ properties. Th The __CellPadding__ property specifies the offset of the tile according to the bounds of the cells. The following code snippet demonstrates using the __RowSpan__, __ColSpan__ and __CellPadding__ properties. -{{source=..\SamplesCS\Panorama\PanoramaGettingStarted.cs region=Padding}} -{{source=..\SamplesVB\Panorama\PanoramaGettingStarted.vb region=Padding}} - -````C# - -this.radTileElement1.RowSpan = 2; -this.radTileElement1.CellPadding = new Padding(5); -this.radTileElement2.ColSpan = 2; -this.radTileElement2.Column = 2; -this.radTileElement2.CellPadding = new Padding(5); -this.radTileElement3.Row = 1; -this.radTileElement3.Column = 1; -this.radTileElement3.CellPadding = new Padding(5); - -```` -````VB.NET -Me.RadTileElement1.RowSpan = 2 -Me.RadTileElement1.CellPadding = New Padding(5) -Me.RadTileElement2.ColSpan = 2 -Me.RadTileElement2.Column = 2 -Me.RadTileElement2.CellPadding = New Padding(5) -Me.RadTileElement3.Row = 1 -Me.RadTileElement3.Column = 1 -Me.RadTileElement3.CellPadding = New Padding(5) - -```` - -{{endregion}} + + + + ![WinForms RadPanorama CellPadding](images/panorama-tiles002.png) @@ -82,71 +46,19 @@ To change the content element, you can edit the contents of the tiles' __Items__ #### Add live tiles -{{source=..\SamplesCS\Panorama\PanoramaGettingStarted.cs region=LiveTiles}} -{{source=..\SamplesVB\Panorama\PanoramaGettingStarted.vb region=LiveTiles}} - -````C# - -radLiveTileElement1.Items.Add(new LightVisualElement() -{ - Text = "Movie Idea: Pirates of the Carribean" -}); -radLiveTileElement1.Items.Add(new LightVisualElement() -{ - Text = "Movie Idea: Inception" -}); -radLiveTileElement1.Items.Add(new LightVisualElement() -{ - Text = "Movie Idea: The Expendables" -}); -radLiveTileElement1.Items.Add(new LightVisualElement() -{ - Text = "Movie Idea: Harry Potter and the Deathly Hallows" -}); - -```` -````VB.NET -RadLiveTileElement1.Items.Add(New LightVisualElement() With { _ - .Text = "Movie Idea: Pirates of the Carribean" _ -}) -RadLiveTileElement1.Items.Add(New LightVisualElement() With { _ - .Text = "Movie Idea: Inception" _ -}) -RadLiveTileElement1.Items.Add(New LightVisualElement() With { _ - .Text = "Movie Idea: The Expendables" _ -}) -RadLiveTileElement1.Items.Add(New LightVisualElement() With { _ - .Text = "Movie Idea: Harry Potter and the Deathly Hallows" _ -}) - -```` - -{{endregion}} + + -The following properties are responsible for controlling the behavior of the transition between content elements: -#### Customize Animation -{{source=..\SamplesCS\Panorama\PanoramaGettingStarted.cs region=AnimationProperties}} -{{source=..\SamplesVB\Panorama\PanoramaGettingStarted.vb region=AnimationProperties}} +The following properties are responsible for controlling the behavior of the transition between content elements: -````C# - -this.radLiveTileElement1.AnimationFrames = 15; //sets the number of frames in a transition -this.radLiveTileElement1.AnimationInterval = 30; //sets the interval between each frame in the transition in miliseconds -this.radLiveTileElement1.ContentChangeInterval = 7000; //sets the interval between each content change -this.radLiveTileElement1.TransitionType = ContentTransitionType.SlideUp; //sets the type of the transition animation +#### Customize Animation -```` -````VB.NET -Me.RadLiveTileElement1.AnimationFrames = 15 'sets the number of frames in a transition -Me.RadLiveTileElement1.AnimationInterval = 30 'sets the interval between each frame in the transition in miliseconds -Me.RadLiveTileElement1.ContentChangeInterval = 7000 'sets the interval between each content change -Me.RadLiveTileElement1.TransitionType = ContentTransitionType.SlideUp 'sets the type of the transition animation + + -```` -{{endregion}} ![WinForms RadPanorama Custom Animation](images/panorama-tiles003.gif) @@ -158,63 +70,10 @@ You can find below a sample code snippet demonstrating how to add groups to **Ra #### Populating With Data Programmatically -{{source=..\SamplesCS\Panorama\PanoramaGettingStarted.cs region=PopulateWithData}} -{{source=..\SamplesVB\Panorama\PanoramaGettingStarted.vb region=PopulateWithData}} - -````C# - -TileGroupElement group1 = new TileGroupElement(); -group1.Text = "Group 1"; -TileGroupElement group2 = new TileGroupElement(); -group2.Text = "Group 2"; -radPanorama1.Groups.Add(group1); -radPanorama1.Groups.Add(group2); -radPanorama1.ShowGroups = true; - -RadTileElement tile1 = new RadTileElement(); -tile1.Text = "Tile 1"; -tile1.ColSpan = 2; -group1.Items.Add(tile1); - -RadTileElement tile2 = new RadTileElement(); -tile2.Text = "Tile 2"; -tile2.ColSpan = 2; -group2.Items.Add(tile2); - -RadTileElement tile3 = new RadTileElement(); -tile3.Text = "Tile 3"; -group2.RowsCount = 3; -tile3.Row = 1; -tile3.RowSpan = 2; -group2.Items.Add(tile3); - -```` -````VB.NET -Dim group1 As New TileGroupElement() -group1.Text = "Group 1" -Dim group2 As New TileGroupElement() -group2.Text = "Group 2" -RadPanorama1.Groups.Add(group1) -RadPanorama1.Groups.Add(group2) -RadPanorama1.ShowGroups = True -Dim tile1 As New RadTileElement() -tile1.Text = "Tile 1" -tile1.ColSpan = 2 -group1.Items.Add(tile1) -Dim tile2 As New RadTileElement() -tile2.Text = "Tile 2" -tile2.ColSpan = 2 -group2.Items.Add(tile2) -Dim tile3 As New RadTileElement() -tile3.Text = "Tile 3" -group2.RowsCount = 3 -tile3.Row = 1 -tile3.RowSpan = 2 -group2.Items.Add(tile3) - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/pdfviewer/customize-and-extensibility/customize-pdf-rendering.md b/controls/pdfviewer/customize-and-extensibility/customize-pdf-rendering.md index ceed039ba..1e23fec40 100644 --- a/controls/pdfviewer/customize-and-extensibility/customize-pdf-rendering.md +++ b/controls/pdfviewer/customize-and-extensibility/customize-pdf-rendering.md @@ -53,89 +53,20 @@ Inheriting from __IPdfFilter__ will result in the following: #### Creating Custom Filter -{{source=..\SamplesCS\PdfViewer\PdfDecoder.cs region=CustomFilter}} -{{source=..\SamplesVB\PdfViewer\PdfDecoder.vb region=CustomFilter}} - -````C# - -public class CustomFilter : Telerik.Windows.Documents.Fixed.FormatProviders.Pdf.Filters.IPdfFilter -{ - public byte[] Encode(PdfObject encodedObject, byte[] inputData) - { - throw new NotImplementedException(); - } - - public byte[] Decode(PdfObject decodedObject, byte[] inputData, DecodeParameters decodeParameters) - { - throw new NotImplementedException(); - } - - public string Name - { - get - { - throw new NotImplementedException(); - } - } -} - -```` -````VB.NET -Public Class CustomFilter - Implements Telerik.Windows.Documents.Fixed.FormatProviders.Pdf.Filters.IPdfFilter - Public Function Encode(encodedObject As PdfObject, inputData As Byte()) As Byte() Implements IPdfFilter.Encode - ' TODO: Implement this method - Throw New NotImplementedException() - End Function - Public Function Decode(decodedObject As PdfObject, inputData As Byte(), _ - decodeParameters As DecodeParameters) As Byte() Implements IPdfFilter.Decode - ' TODO: Implement this method - Throw New NotImplementedException() - End Function - Public ReadOnly Property Name() As String Implements IPdfFilter.Name - Get - ' TODO: Implement this property getter - Throw New NotImplementedException() - End Get - End Property -End Class - -```` - -{{endregion}} - + + + + + You should also register the filter as follows: #### Registering Filters -{{source=..\SamplesCS\PdfViewer\PdfDecoder.cs region=RegisterFilter}} -{{source=..\SamplesVB\PdfViewer\PdfDecoder.vb region=RegisterFilter}} - -````C# - -private CustomFilter _filter; - -public PdfDecoder() -{ - InitializeComponent(); - - _filter = new CustomFilter(); - FiltersManager.RegisterFilter(_filter ); -} - -```` -````VB.NET -Private _filter As CustomFilter -Public Sub New() - InitializeComponent() - _filter = New CustomFilter() - FiltersManager.RegisterFilter(_filter) -End Sub - -```` - -{{endregion}} - + + + + + The result that a custom filter should return depends on the type of the filter. For the binary filters it is enough to decode the byte array into decoded byte array using the respective algorithm. As for the filters listed below, additional transformation is required. __RadPdfViewer__ expects these filters to return data that depends on the decoded object's colors space and bits per component (there are such properties in the decodedObject). The resulting byte array should contain exactly BitsPerComponent bits for each color component in the color space. For example, if you have RGB color space and 8 bits per component, the resulting byte array should contains a single byte value for each Red, Green and Blue value (for each pixel) in the decoded image. diff --git a/controls/pdfviewer/features/annotations.md b/controls/pdfviewer/features/annotations.md index 616785148..4c17fc546 100644 --- a/controls/pdfviewer/features/annotations.md +++ b/controls/pdfviewer/features/annotations.md @@ -18,187 +18,46 @@ The current API includes the following members, which allow customization of the #### AnnotationClicked Event Handler -{{source=..\SamplesCS\PdfViewer\PdfAnnotations.cs region=AnnotationClicked}} -{{source=..\SamplesVB\PdfViewer\PdfAnnotations.vb region=AnnotationClicked}} - -````C# - -private void radPdfViewer1_AnnotationClicked(object sender, Telerik.Windows.Documents.Fixed.Model.Annotations.EventArgs.AnnotationEventArgs e) -{ - Telerik.Windows.Documents.Fixed.Model.Annotations.Link l = e.Annotation as Telerik.Windows.Documents.Fixed.Model.Annotations.Link; - if (l == null) - { - return; - } - Telerik.Windows.Documents.Fixed.Model.Actions.UriAction a = l.Action as Telerik.Windows.Documents.Fixed.Model.Actions.UriAction; - if (a == null) - { - return; - } - MessageBox.Show(a.Uri.ToString()); - e.Handled = true; -} - -```` -````VB.NET -Private Sub radPdfViewer1_AnnotationClicked(sender As Object, e As Telerik.Windows.Documents.Fixed.Model.Annotations.EventArgs.AnnotationEventArgs) - Dim l As Telerik.Windows.Documents.Fixed.Model.Annotations.Link = TryCast(e.Annotation, Telerik.Windows.Documents.Fixed.Model.Annotations.Link) - If l Is Nothing Then - Return - End If - Dim a As Telerik.Windows.Documents.Fixed.Model.Actions.UriAction = TryCast(l.Action, Telerik.Windows.Documents.Fixed.Model.Actions.UriAction) - If a Is Nothing Then - Return - End If - MessageBox.Show(a.Uri.ToString()) - e.Handled = True -End Sub - -```` - -{{endregion}} + + + + * __HyperlinkClicked__ event of RadPdfViewer: This event is similar to AnnotationClicked, but it is raised only when you click on the hyperlink type annotations. It allows you to cancel the navigation to the associated URI or to modify the click action. The HyperlinkClickedEventArgs gives access to the URL, which can be manually checked if it is trusted. With the 2024 Q3 (2024.3.924), the default navigation behavior of the hyperlinks is to automatically open only valid and trusted addresses. If needed, the navigation can be canceled by either setting the __Handled__ property of the event args to _true_ or the __IsTrustedUrl__ property to _false_. Below is an example of using this event to prompt that the clicked hyperlink might be unsafe and provide the opportunity to cancel the navigation process upon receiving the end user confirmation: #### HyperlinkClicked Event Handler -{{source=..\SamplesCS\PdfViewer\PdfAnnotations.cs region=HyperlinkClicked}} -{{source=..\SamplesVB\PdfViewer\PdfAnnotations.vb region=HyperlinkClicked}} - -````C# -private void RadPdfViewer1_HyperlinkClicked(object sender, Telerik.WinControls.Hyperlinks.HyperlinkClickedEventArgs e) -{ - var link = e.URL; - if (link.EndsWith("exe")) - { - e.Handled = true; MessageBoxResult Result = System.Windows.MessageBox.Show("You are about to open an executable file. Do you want to proceed", "Possible unsafe link", MessageBoxButton.YesNo, MessageBoxImage.Question); - if (Result == MessageBoxResult.Yes) - { - Process.Start(new ProcessStartInfo() - { - FileName = link, - UseShellExecute = true - }); - } - } -} - -```` -````VB.NET -Private Sub RadPdfViewer1_HyperlinkClicked(sender As Object, e As HyperlinkClickedEventArgs) - Dim link = e.URL - If link.EndsWith("exe") Then - e.Handled = True - Dim Result As MessageBoxResult = System.Windows.MessageBox.Show("You are about to open an executable file. Do you want to proceed", "Possible unsafe link", MessageBoxButton.YesNo, MessageBoxImage.Question) - If Result = MessageBoxResult.Yes Then - Process.Start(New ProcessStartInfo() With { - .FileName = link, - .UseShellExecute = True - }) - End If - End If -End Sub - -```` - -{{endregion}} + + + * __Annotations__ property of __RadFixedDocument__ – A collection which returns all annotations in the document. For example, you can retrieve all links using the following code: #### Get Annotation Links -{{source=..\SamplesCS\PdfViewer\PdfAnnotations.cs region=GetAllLinks}} -{{source=..\SamplesVB\PdfViewer\PdfAnnotations.vb region=GetAllLinks}} - -````C# - -private IEnumerable GetAllLinks(Telerik.Windows.Documents.Fixed.Model.RadFixedDocument document) -{ - foreach (Telerik.Windows.Documents.Fixed.Model.Annotations.Annotation a in document.Annotations) - { - Telerik.Windows.Documents.Fixed.Model.Annotations.Link l = a as Telerik.Windows.Documents.Fixed.Model.Annotations.Link; - if (l != null) - { - yield return l; - } - } -} - -```` -````VB.NET -Private Iterator Function GetAllLinks(document As Telerik.Windows.Documents.Fixed.Model.RadFixedDocument) As IEnumerable(Of Telerik.Windows.Documents.Fixed.Model.Annotations.Link) - For Each a As Telerik.Windows.Documents.Fixed.Model.Annotations.Annotation In document.Annotations - Dim l As Telerik.Windows.Documents.Fixed.Model.Annotations.Link = TryCast(a, Telerik.Windows.Documents.Fixed.Model.Annotations.Link) - If l IsNot Nothing Then - Yield l - End If - Next -End Function - -```` - -{{endregion}} + + + + The bookmarks in terms of “docx bookmarks” are not explicitly saved in PDF files. They are persisted only if there are Link annotations to them, so you can use the snippet below to retrieve all destinations that have links to them: #### Get Annotation Bookmarks -{{source=..\SamplesCS\PdfViewer\PdfAnnotations.cs region=Bookmarks}} -{{source=..\SamplesVB\PdfViewer\PdfAnnotations.vb region=Bookmarks}} - -````C# - -private IEnumerable GetAllBookmarks(Telerik.Windows.Documents.Fixed.Model.RadFixedDocument document) -{ - foreach (Telerik.Windows.Documents.Fixed.Model.Annotations.Annotation a in document.Annotations) - { - Telerik.Windows.Documents.Fixed.Model.Annotations.Link l = a as Telerik.Windows.Documents.Fixed.Model.Annotations.Link; - if (l != null && l.Destination != null) - { - yield return l.Destination; - } - } -} - -```` -````VB.NET -Private Iterator Function GetAllBookmarks(document As Telerik.Windows.Documents.Fixed.Model.RadFixedDocument) As IEnumerable(Of Telerik.Windows.Documents.Fixed.Model.Navigation.Destination) - For Each a As Telerik.Windows.Documents.Fixed.Model.Annotations.Annotation In document.Annotations - Dim l As Telerik.Windows.Documents.Fixed.Model.Annotations.Link = TryCast(a, Telerik.Windows.Documents.Fixed.Model.Annotations.Link) - If l IsNot Nothing AndAlso l.Destination IsNot Nothing Then - Yield l.Destination - End If - Next -End Function - -```` - -{{endregion}} + + -In this way, creating some UI containing all bookmarks would be possible. Then, you could implement the same action as the one being executed when a hyperlink is clicked, i.e. scroll the document to the specific place in the document where the destination of the link is placed. The following code can be used for this purpose – navigating to a specific destination: -#### Navigate to Destination -{{source=..\SamplesCS\PdfViewer\PdfAnnotations.cs region=GoToDestination}} -{{source=..\SamplesVB\PdfViewer\PdfAnnotations.vb region=GoToDestination}} +In this way, creating some UI containing all bookmarks would be possible. Then, you could implement the same action as the one being executed when a hyperlink is clicked, i.e. scroll the document to the specific place in the document where the destination of the link is placed. The following code can be used for this purpose – navigating to a specific destination: -````C# - -private void GoToDestination(Telerik.Windows.Documents.Fixed.Model.Navigation.Destination destination) -{ - this.radPdfViewer1.PdfViewerElement.GoToDestination(destination); -} +#### Navigate to Destination -```` -````VB.NET -Private Sub GoToDestination(destination As Telerik.Windows.Documents.Fixed.Model.Navigation.Destination) - Me.RadPdfViewer1.PdfViewerElement.GoToDestination(destination) -End Sub + + -```` -{{endregion}} ## See Also diff --git a/controls/pdfviewer/features/digital-signature.md b/controls/pdfviewer/features/digital-signature.md index a94041441..34343c950 100644 --- a/controls/pdfviewer/features/digital-signature.md +++ b/controls/pdfviewer/features/digital-signature.md @@ -97,72 +97,9 @@ The **Signature** class exposes two methods allowing you to validate a signature #### Example 1: Validate a field -{{source=..\SamplesCS\PdfViewer\DigitalSignatureCode.cs region=DigitalSignatureCode_1}} -{{source=..\SamplesVB\PdfViewer\DigitalSignatureCode.vb region=DigitalSignatureCode_1}} -````C# -string validationStatus; -// For simplicity, the example handles only the first signature. -SignatureField firstSignatureField = this.pdfViewer.Document.AcroForm.FormFields.FirstOrDefault(field => field.FieldType == FormFieldType.Signature) as SignatureField; -if (firstSignatureField != null && firstSignatureField.Signature != null) -{ - SignatureValidationResult validationResult; - if (firstSignatureField.Signature.TryValidate(out validationResult)) - { - if (!validationResult.IsDocumentModified) - { - if (validationResult.IsCertificateValid) - { - validationStatus = "Valid"; - } - else - { - validationStatus = "Unknown"; - } - } - else - { - validationStatus = "Invalid"; - } - } - else - { - validationStatus = "Invalid"; - } -} -else -{ - validationStatus = "None"; -} - -```` -````VB.NET -Dim validationStatus As String -' For simplicity, the example handles only the first signature. -Dim firstSignatureField As SignatureField = TryCast(Me.pdfViewer.Document.AcroForm.FormFields.FirstOrDefault(Function(field) field.FieldType = FormFieldType.Signature), SignatureField) -If firstSignatureField IsNot Nothing AndAlso firstSignatureField.Signature IsNot Nothing Then - Dim validationResult As SignatureValidationResult = Nothing - If firstSignatureField.Signature.TryValidate(validationResult) Then - If Not validationResult.IsDocumentModified Then - If validationResult.IsCertificateValid Then - validationStatus = "Valid" - Else - validationStatus = "Unknown" - End If - Else - validationStatus = "Invalid" - End If - Else - validationStatus = "Invalid" - End If -Else - validationStatus = "None" -End If - -```` - - -{{endregion}} - + + + ## Limitations diff --git a/controls/pdfviewer/features/navigation.md b/controls/pdfviewer/features/navigation.md index 04ef86dc1..63f814d7b 100644 --- a/controls/pdfviewer/features/navigation.md +++ b/controls/pdfviewer/features/navigation.md @@ -14,68 +14,19 @@ You can use the __PageUp__, __PageDown__, __GoToPage__ methods to navigate throu #### Page Navigation -{{source=..\SamplesCS\PdfViewer\PdfPublicApi.cs region=PageNavigation}} -{{source=..\SamplesVB\PdfViewer\PdfPublicApi.vb region=PageNavigation}} + + -````C# -private void buttonPageUp_Click(object sender, EventArgs e) -{ - this.radPdfViewer1.PdfViewerElement.PageUp(); -} -private void buttonPageDown_Click(object sender, EventArgs e) -{ - this.radPdfViewer1.PdfViewerElement.PageDown(); -} -private void buttonGotoPage_Click(object sender, EventArgs e) -{ - this.radPdfViewer1.PdfViewerElement.GoToPage(3); -} -```` -````VB.NET -Private Sub buttonPageUp_Click(sender As Object, e As EventArgs) Handles buttonPageUp.Click - Me.radPdfViewer1.PdfViewerElement.PageUp() -End Sub -Private Sub buttonPageDown_Click(sender As Object, e As EventArgs) Handles buttonPageDown.Click - Me.radPdfViewer1.PdfViewerElement.PageDown() -End Sub -Private Sub buttonGotoPage_Click(sender As Object, e As EventArgs) Handles buttonGotoPage.Click - Me.radPdfViewer1.PdfViewerElement.GoToPage(3) -End Sub - -```` - -{{endregion}} Additionally, you can control the precise scroll position by using the __Scroll__ method which scrolls the view with a specified offset or the __ScrollTo__ method which scrolls the view to an exact position: #### Scrolling -{{source=..\SamplesCS\PdfViewer\PdfPublicApi.cs region=Scrolling}} -{{source=..\SamplesVB\PdfViewer\PdfPublicApi.vb region=Scrolling}} - -````C# -private void buttonScroll_Click(object sender, EventArgs e) -{ - this.radPdfViewer1.PdfViewerElement.Scroll(30, 30); -} -private void buttonScrollTo_Click(object sender, EventArgs e) -{ - this.radPdfViewer1.PdfViewerElement.ScrollTo(0, 300); -} - -```` -````VB.NET -Private Sub buttonScroll_Click(sender As Object, e As EventArgs) Handles buttonScroll.Click - Me.radPdfViewer1.PdfViewerElement.Scroll(30, 30) -End Sub -Private Sub buttonScrollTo_Click(sender As Object, e As EventArgs) Handles buttonScrollTo.Click - Me.radPdfViewer1.PdfViewerElement.ScrollTo(0, 300) -End Sub + + -```` -{{endregion}} # See Also diff --git a/controls/pdfviewer/features/printing-support.md b/controls/pdfviewer/features/printing-support.md index 25bbfdea8..1bf5d330a 100644 --- a/controls/pdfviewer/features/printing-support.md +++ b/controls/pdfviewer/features/printing-support.md @@ -35,21 +35,10 @@ __RadPdfViewer__ also exposes the two known methods which allow you to easily pr #### Printing -{{source=..\SamplesCS\PdfViewer\PdfGettingStarted.cs region=PrintMethods}} -{{source=..\SamplesVB\PdfViewer\PdfGettingStarted.vb region=PrintMethods}} + + -````C# -this.radPdfViewer1.Print(); -this.radPdfViewer1.PrintPreview(); -```` -````VB.NET -Me.RadPdfViewer1.Print() -Me.RadPdfViewer1.PrintPreview() - -```` - -{{endregion}} # See Also diff --git a/controls/pdfviewer/features/save-as.md b/controls/pdfviewer/features/save-as.md index 6a481cf75..cd2dbe75e 100644 --- a/controls/pdfviewer/features/save-as.md +++ b/controls/pdfviewer/features/save-as.md @@ -22,16 +22,8 @@ You can save the loaded document programmatically by using the **SaveDocument** #### Save As -{{source=..\SamplesCS\PdfViewer\PdfUI.cs region=SaveAs}} -{{source=..\SamplesVB\PdfViewer\PdfUI.vb region=SaveAs}} + + -````C# -this.radPdfViewer1.SaveDocument(filePath); -```` -````VB.NET -Me.RadPdfViewer1.SaveDocument(filePath) -```` - -{{endregion}} diff --git a/controls/pdfviewer/features/text/text-position.md b/controls/pdfviewer/features/text/text-position.md index ac4dd998b..c32dfe5f5 100644 --- a/controls/pdfviewer/features/text/text-position.md +++ b/controls/pdfviewer/features/text/text-position.md @@ -75,21 +75,11 @@ The caret position of __RadFixedDocument__ is also a __TextPosition__ object and #### CaretPosition -{{source=..\SamplesCS\PdfViewer\PdfTextManipulation.cs region=CaretPosition}} -{{source=..\SamplesVB\PdfViewer\PdfTextManipulation.vb region=CaretPosition}} - -````C# - -this.radPdfViewer1.PdfViewerElement.Document.CaretPosition.MoveToEndOfDocument(); - -```` -````VB.NET -Me.RadPdfViewer1.PdfViewerElement.Document.CaretPosition.MoveToEndOfDocument() - -```` - -{{endregion}} - + + + + + This will not only move the caret to the end of the document, but will also scroll the document to bring it into view, as the view port follows the caret. diff --git a/controls/pdfviewer/features/text/text-search.md b/controls/pdfviewer/features/text/text-search.md index 88c60b995..4c2b5cba7 100644 --- a/controls/pdfviewer/features/text/text-search.md +++ b/controls/pdfviewer/features/text/text-search.md @@ -75,32 +75,10 @@ All Find methods return a **SearchResult** object (or a collection of SearchResu #### Example: Searching in a document -{{source=..\SamplesCS\PdfViewer\PdfTextManipulation.cs region=Find}} -{{source=..\SamplesVB\PdfViewer\PdfTextManipulation.vb region=Find}} - -````C# -SearchResult result = this.radPdfViewer1.Find("RadPdfViewer", TextSearchOptions.Default); - if (result == SearchResult.NotFound) - { - RadMessageBox.Show("String not found"); - } - else - { - this.radPdfViewer1.Select(result); - } - -```` -````VB.NET -Dim result As SearchResult = Me.radPdfViewer1.Find("RadPdfViewer", TextSearchOptions.Default) -If result = SearchResult.NotFound Then - RadMessageBox.Show("String not found") -Else - Me.radPdfViewer1.Select(result) -End If - -```` - -{{endregion}} + + + + ### TextSearchOptions diff --git a/controls/pdfviewer/features/text/text-selection.md b/controls/pdfviewer/features/text/text-selection.md index 0a7d8d380..c2285b990 100644 --- a/controls/pdfviewer/features/text/text-selection.md +++ b/controls/pdfviewer/features/text/text-selection.md @@ -19,19 +19,10 @@ In order to be able to select text from the UI, __RadPdfViewer__ must be in *Tex #### ViewerMode -{{source=..\SamplesCS\PdfViewer\PdfTextManipulation.cs region=ViewerMode}} -{{source=..\SamplesVB\PdfViewer\PdfTextManipulation.vb region=ViewerMode}} + + -````C# -this.radPdfViewer1.ViewerMode = Telerik.WinControls.UI.FixedDocumentViewerMode.TextSelection; -```` -````VB.NET -Me.RadPdfViewer1.ViewerMode = Telerik.WinControls.UI.FixedDocumentViewerMode.TextSelection - -```` - -{{endregion}} ## Programmatic Selection @@ -69,30 +60,10 @@ Their names show clearly the action they execute.Here is an example showing how #### Text selection -{{source=..\SamplesCS\PdfViewer\PdfTextManipulation.cs region=TextSelection}} -{{source=..\SamplesVB\PdfViewer\PdfTextManipulation.vb region=TextSelection}} - -````C# - -Telerik.Windows.Documents.Fixed.Text.TextPosition start = new Telerik.Windows.Documents.Fixed.Text.TextPosition(this.radPdfViewer1.Document.CaretPosition); -start.MoveToCurrentWordStart(); -Telerik.Windows.Documents.Fixed.Text.TextPosition end = new Telerik.Windows.Documents.Fixed.Text.TextPosition(this.radPdfViewer1.Document.CaretPosition); -end.MoveToCurrentWordEnd(); -this.radPdfViewer1.Document.Selection.SetSelection(start, end); -RadMessageBox.Show(this.radPdfViewer1.Document.Selection.GetSelectedText()); + + -```` -````VB.NET -Dim start As New Telerik.Windows.Documents.Fixed.Text.TextPosition(Me.RadPdfViewer1.Document.CaretPosition) -start.MoveToCurrentWordStart() -Dim [end] As New Telerik.Windows.Documents.Fixed.Text.TextPosition(Me.RadPdfViewer1.Document.CaretPosition) -[end].MoveToCurrentWordEnd() -Me.RadPdfViewer1.Document.Selection.SetSelection(start, [end]) -RadMessageBox.Show(Me.RadPdfViewer1.Document.Selection.GetSelectedText()) -```` - -{{endregion}} There are various methods in the API of RadPdfViewerElement which you can use to manipulate the text selection. @@ -100,136 +71,28 @@ The __SelectAll__, __DeselectAll__, __Select__ methods allow you to set the sele #### Select/Deselect -{{source=..\SamplesCS\PdfViewer\PdfPublicApi.cs region=Select}} -{{source=..\SamplesVB\PdfViewer\PdfPublicApi.vb region=Select}} - -````C# -private void buttonSelectAll_Click(object sender, EventArgs e) -{ - this.radPdfViewer1.PdfViewerElement.SelectAll(); -} -private void buttonDeselectAll_Click(object sender, EventArgs e) -{ - this.radPdfViewer1.PdfViewerElement.DeselectAll(); -} -private void buttonSelect_Click(object sender, EventArgs e) -{ - Telerik.Windows.Documents.Fixed.Text.TextPosition startPosition = new Telerik.Windows.Documents.Fixed.Text.TextPosition(this.radPdfViewer1.Document); - Telerik.Windows.Documents.Fixed.Text.TextPosition endPosition = new Telerik.Windows.Documents.Fixed.Text.TextPosition(this.radPdfViewer1.Document); - startPosition.MoveToLineStart(); - endPosition.MoveToLineEnd(); - //Select the first line in the document - this.radPdfViewer1.PdfViewerElement.Select(startPosition, endPosition); -} - -```` -````VB.NET -Private Sub buttonSelectAll_Click(sender As Object, e As EventArgs) Handles buttonSelectAll.Click - Me.radPdfViewer1.PdfViewerElement.SelectAll() -End Sub -Private Sub buttonDeselectAll_Click(sender As Object, e As EventArgs) Handles buttonDeselectAll.Click - Me.radPdfViewer1.PdfViewerElement.DeselectAll() -End Sub -Private Sub buttonSelect_Click(sender As Object, e As EventArgs) Handles buttonSelect.Click - Dim startPosition As New Telerik.Windows.Documents.Fixed.Text.TextPosition(Me.radPdfViewer1.Document) - Dim endPosition As New Telerik.Windows.Documents.Fixed.Text.TextPosition(Me.radPdfViewer1.Document) - startPosition.MoveToLineStart() - endPosition.MoveToLineEnd() - 'Select the first line in the document - Me.radPdfViewer1.PdfViewerElement.[Select](startPosition, endPosition) -End Sub - -```` - -{{endregion}} + + + + You can use the __GetSelectedText__, __GetSelectedTextAsync__ methods to get the currently selected text. The __GetSelectedTextAsync__ method does this operation asynchronously and calls the specified callback function when ready. The __Copy__ method copies the current selection to the clipboard. It executes the operation in the background, so the text is not copied to the clipboard until the waiting indicator is visible.The following sample demonstrates using these methods: #### Get Selection Async -{{source=..\SamplesCS\PdfViewer\PdfPublicApi.cs region=GetSelectedText}} -{{source=..\SamplesVB\PdfViewer\PdfPublicApi.vb region=GetSelectedText}} - -````C# -private void butonGetSelectedText_Click(object sender, EventArgs e) -{ - RadMessageBox.Show("The current selection: " + this.radPdfViewer1.PdfViewerElement.GetSelectedText()); -} -private void buttonGetSelectedTextAsync_Click(object sender, EventArgs e) -{ - this.radPdfViewer1.PdfViewerElement.GetSelectedTextAsync(delegate(string text) { MessageBox.Show("Selected text: " + text); }); -} -private void buttonCopy_Click(object sender, EventArgs e) -{ - this.radPdfViewer1.PdfViewerElement.Copy(); -} - -```` -````VB.NET -Private Sub buttonGetSelectedText_Click(sender As Object, e As EventArgs) Handles buttonGetSelectedText.Click - RadMessageBox.Show("The current selection: " & Me.radPdfViewer1.PdfViewerElement.GetSelectedText()) -End Sub -Private Sub buttonGetSelectedTextAsync_Click(sender As Object, e As EventArgs) Handles buttonGetSelectedTextAsync.Click - Me.radPdfViewer1.PdfViewerElement.GetSelectedTextAsync(Function(text As String) - MessageBox.Show("Selected text: " & text) - End Function) -End Sub -Private Sub buttonCopy_Click(sender As Object, e As EventArgs) Handles buttonCopy.Click - Me.radPdfViewer1.PdfViewerElement.Copy() -End Sub - -```` - -{{endregion}} + + + + The __Find__ and __FindPrevious__ methods are used to perform text search forwards or backwards respectively. These methods return the result in a special __SearchResult__ structure which provides information about the result: #### Find Next -{{source=..\SamplesCS\PdfViewer\PdfPublicApi.cs region=Search}} -{{source=..\SamplesVB\PdfViewer\PdfPublicApi.vb region=Search}} - -````C# -private void buttonFindNext_Click(object sender, EventArgs e) -{ - Telerik.Windows.Documents.Fixed.Search.SearchResult res; - if (this.checkSearchBackwards.IsChecked) - { - res = this.radPdfViewer1.PdfViewerElement.FindPrevious("WinForms"); - } - else - { - res = this.radPdfViewer1.PdfViewerElement.Find("WinForms"); - } - if (res == Telerik.Windows.Documents.Fixed.Search.SearchResult.NotFound) - { - RadMessageBox.Show("String not found"); - } - else - { - RadMessageBox.Show("Result found on page " + res.Range.StartPosition.Page.PageNo); - } -} - -```` -````VB.NET -Private Sub buttonFindNext_Click(sender As Object, e As EventArgs) Handles buttonFindNext.Click - Dim res As Telerik.Windows.Documents.Fixed.Search.SearchResult - If Me.checkSearchBackwards.IsChecked Then - res = Me.radPdfViewer1.PdfViewerElement.FindPrevious("WinForms") - Else - res = Me.radPdfViewer1.PdfViewerElement.Find("WinForms") - End If - If res Is Telerik.Windows.Documents.Fixed.Search.SearchResult.NotFound Then - RadMessageBox.Show("String not found") - Else - RadMessageBox.Show("Result found on page " & res.Range.StartPosition.Page.PageNo) - End If -End Sub - -```` - -{{endregion}} + + + + >note There are no genuine words in PDF, so the viewer uses a greedy text recognition method. That is why it is not guaranteed that it would find the exact start and end position of a word. > diff --git a/controls/pdfviewer/features/thumbnails.md b/controls/pdfviewer/features/thumbnails.md index 7cf0c7ad9..3219630fd 100644 --- a/controls/pdfviewer/features/thumbnails.md +++ b/controls/pdfviewer/features/thumbnails.md @@ -20,19 +20,10 @@ You can control whether the thumbnail element is visible by setting the __Enable #### Enable Thumbnails -{{source=..\SamplesCS\PdfViewer\PdfPublicApi.cs region=EnableThumbnails}} -{{source=..\SamplesVB\PdfViewer\PdfPublicApi.vb region=EnableThumbnails}} + + -````C# -this.radPdfViewer1.EnableThumbnails = true; -```` -````VB.NET -Me.radPdfViewer1.EnableThumbnails = True - -```` - -{{endregion}} ## Thumbnails API @@ -40,57 +31,28 @@ You can show or hide the thumbnails programmatically with following methods Show #### Show/Hide Thumbnails -{{source=..\SamplesCS\PdfViewer\PdfPublicApi.cs region=ShowHideThumbnails}} -{{source=..\SamplesVB\PdfViewer\PdfPublicApi.vb region=ShowHideThumbnails}} - -````C# -this.radPdfViewer1.ShowThubnails(); -this.radPdfViewer1.HideThumbnails(); - -```` -````VB.NET -Me.radPdfViewer1.ShowThubnails() -Me.radPdfViewer1.HideThumbnails() + + -```` -{{endregion}} You can customize the size of the thumbnails with __ThumbnailsScaleFactor__ property. This property sets the size of the thumbnails between 0 and 1 where 1 is the page in full size. By default this property is set to 0.15 which means 15% of the normal page size. #### ThumbnailsScaleFactor -{{source=..\SamplesCS\PdfViewer\PdfPublicApi.cs region=ThumbnailsScaleFactor}} -{{source=..\SamplesVB\PdfViewer\PdfPublicApi.vb region=ThumbnailsScaleFactor}} + + -````C# -this.radPdfViewer1.ThumbnailListWidth = 300; -```` -````VB.NET -Me.radPdfViewer1.ThumbnailListWidth = 300 - -```` - -{{endregion}} You can customize the width of the thumbnails list with the __ThumbnailListWidth__ property. Default value of this property is 200. #### ThumbnailListWidth -{{source=..\SamplesCS\PdfViewer\PdfPublicApi.cs region=ThumbnailListWidth}} -{{source=..\SamplesVB\PdfViewer\PdfPublicApi.vb region=ThumbnailListWidth}} - -````C# -this.radPdfViewer1.ThumbnailListWidth = 300; - -```` -````VB.NET -Me.radPdfViewer1.ThumbnailListWidth = 300 + + -```` -{{endregion}} # See Also diff --git a/controls/pdfviewer/getting-started.md b/controls/pdfviewer/getting-started.md index d96d0ef39..3d50d1729 100644 --- a/controls/pdfviewer/getting-started.md +++ b/controls/pdfviewer/getting-started.md @@ -56,78 +56,37 @@ There is also a property for the above setting which you can set in your code: #### ViewerMode Property -{{source=..\SamplesCS\PdfViewer\PdfGettingStarted.cs region=Modes}} -{{source=..\SamplesVB\PdfViewer\PdfGettingStarted.vb region=Modes}} + + -````C# -this.radPdfViewer1.ViewerMode = FixedDocumentViewerMode.TextSelection; -```` -````VB.NET -Me.RadPdfViewer1.ViewerMode = FixedDocumentViewerMode.TextSelection - -```` - -{{endregion}} Loading a PDF document is done via the __LoadDocument__ method. It accepts either a filename or an input stream as an argument. #### LoadDocument Method -{{source=..\SamplesCS\PdfViewer\PdfGettingStarted.cs region=Loading}} -{{source=..\SamplesVB\PdfViewer\PdfGettingStarted.vb region=Loading}} - -````C# -this.radPdfViewer1.LoadDocument(Application.StartupPath + "\\PdfViewer\\Sample.pdf"); + + -```` -````VB.NET -Me.RadPdfViewer1.LoadDocument(Application.StartupPath & "\PdfViewer\Sample.pdf") -```` - -{{endregion}} The calls above will start to load the specified document asynchronously. When the loading finishes, the __DocumentLoaded__ event will fire: #### DocumentLoaded Event -{{source=..\SamplesCS\PdfViewer\PdfGettingStarted.cs region=DocumentLoaded}} -{{source=..\SamplesVB\PdfViewer\PdfGettingStarted.vb region=DocumentLoaded}} - -````C# -void radPdfViewer1_DocumentLoaded(object sender, EventArgs e) -{ - RadMessageBox.Show("The document was loaded."); -} + + -```` -````VB.NET -Private Sub radPdfViewer1_DocumentLoaded(sender As Object, e As EventArgs) - RadMessageBox.Show("The document was loaded.") -End Sub -```` - -{{endregion}} Respectively, to unload a document, you can use the __UnloadDocument__ method #### UnloadDocument Method -{{source=..\SamplesCS\PdfViewer\PdfGettingStarted.cs region=Unloading}} -{{source=..\SamplesVB\PdfViewer\PdfGettingStarted.vb region=Unloading}} - -````C# -this.radPdfViewer1.UnloadDocument(); - -```` -````VB.NET -Me.RadPdfViewer1.UnloadDocument() + + -```` -{{endregion}} To provide to the end-user an additional set of abilities for manipulating the document, you can use __RadPdfViewerNavigator__. To do this, drag it from the toolbox to your form and set its __AssociatedViewer__ from its __SmartTag__ menu. @@ -136,19 +95,10 @@ To provide to the end-user an additional set of abilities for manipulating the d You can also set this in your code by using the __AssociatedPdfViewer__ property of the __PdfViewerNavigator__. -{{source=..\SamplesCS\PdfViewer\PdfGettingStarted.cs region=Navigator}} -{{source=..\SamplesVB\PdfViewer\PdfGettingStarted.vb region=Navigator}} - -````C# -this.radPdfViewerNavigator1.AssociatedViewer = this.radPdfViewer1; - -```` -````VB.NET -Me.RadPdfViewerNavigator1.AssociatedViewer = Me.RadPdfViewer1 + + -```` -{{endregion}} ## Assembly References diff --git a/controls/pdfviewer/how-to/handle-rendering-events.md b/controls/pdfviewer/how-to/handle-rendering-events.md index f454d3fb5..299047406 100644 --- a/controls/pdfviewer/how-to/handle-rendering-events.md +++ b/controls/pdfviewer/how-to/handle-rendering-events.md @@ -19,108 +19,17 @@ position: 0 #### Initial Setup and Events Subscription. -{{source=..\SamplesCS\PdfViewer\WaitingBarForm.cs region=InitialSetup}} -{{source=..\SamplesVB\PdfViewer\WaitingBarForm.vb region=InitialSetup}} -````C# -public WaitingBarForm() -{ - InitializeComponent(); - - this.radPdfViewer1.DocumentLoaded += RadPdfViewer1_DocumentLoaded; - this.radPdfViewer1.ViewerMode = FixedDocumentViewerMode.None; - this.radPdfViewer1.FitFullPage = true; -} -protected override void OnShown(EventArgs e) -{ - base.OnShown(e); - this.radPdfViewer1.LoadDocument(@"..\..\PdfViewer\ObjectiveC.pdf"); -} -private void RadPdfViewer1_DocumentLoaded(object sender, EventArgs e) -{ - this.radPdfViewer1.PageRenderStarted += OnPageRenderStarted; - this.radPdfViewer1.PageRenderCompleted += OnPageRenderCompleted; -} + + -```` -````VB.NET -Public Sub New() - InitializeComponent() - AddHandler Me.radPdfViewer1.DocumentLoaded, AddressOf RadPdfViewer1_DocumentLoaded - Me.radPdfViewer1.ViewerMode = FixedDocumentViewerMode.None - Me.radPdfViewer1.FitFullPage = True -End Sub -Protected Overrides Sub OnShown(e As EventArgs) - MyBase.OnShown(e) - Me.radPdfViewer1.LoadDocument("..\..\PdfViewer\ObjectiveC.pdf") -End Sub -Private Sub RadPdfViewer1_DocumentLoaded(sender As Object, e As EventArgs) - AddHandler Me.radPdfViewer1.PageRenderStarted, AddressOf OnPageRenderStarted - AddHandler Me.radPdfViewer1.PageRenderCompleted, AddressOf OnPageRenderCompleted -End Sub -```` - - - -{{endregion}} #### Events Handling -{{source=..\SamplesCS\PdfViewer\WaitingBarForm.cs region=EventsHandling}} -{{source=..\SamplesVB\PdfViewer\WaitingBarForm.vb region=EventsHandling}} -````C# -private void OnPageRenderCompleted(object sender, EventArgs e) -{ - if (this.radPdfViewer1.InvokeRequired) - { - this.radPdfViewer1.BeginInvoke((MethodInvoker)delegate - { - if (this.radPdfViewer1.PdfViewerElement.IsWaiting()) - { - this.radPdfViewer1.PdfViewerElement.StopWaiting(); - } - }); - } -} -private void OnPageRenderStarted(object sender, EventArgs e) -{ - if (this.radPdfViewer1.InvokeRequired) - { - this.radPdfViewer1.BeginInvoke((MethodInvoker)delegate - { - if (!this.radPdfViewer1.PdfViewerElement.IsWaiting()) - { - this.radPdfViewer1.PdfViewerElement.StartWaiting(); - } - }); - } -} - -```` -````VB.NET -Private Sub OnPageRenderCompleted(sender As Object, e As EventArgs) - If Me.radPdfViewer1.InvokeRequired Then - Me.radPdfViewer1.BeginInvoke(New Action(Function() - If Me.radPdfViewer1.PdfViewerElement.IsWaiting() Then - Me.radPdfViewer1.PdfViewerElement.StopWaiting() - End If - End Function)) - End If -End Sub -Private Sub OnPageRenderStarted(sender As Object, e As EventArgs) - If Me.radPdfViewer1.InvokeRequired Then - Me.radPdfViewer1.BeginInvoke(New Action(Function() - If Not Me.radPdfViewer1.PdfViewerElement.IsWaiting() Then - Me.radPdfViewer1.PdfViewerElement.StartWaiting() - End If - End Function)) - End If -End Sub - -```` + + -{{endregion}} # See Also diff --git a/controls/pdfviewer/localization.md b/controls/pdfviewer/localization.md index f0ab73ab4..ad9a9bfeb 100644 --- a/controls/pdfviewer/localization.md +++ b/controls/pdfviewer/localization.md @@ -21,321 +21,19 @@ Below is a sample implementation of an English localization provider: #### RadPdfViewer Localization -{{source=..\SamplesCS\PdfViewer\PdfLocalization.cs region=localization}} -{{source=..\SamplesVB\PdfViewer\PdfLocalization.vb region=localization}} + + -````C# -public class MyLocalizationProvider : PdfViewerLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case PdfViewerStringId.ContextMenuCopy: - return "&Copy"; - case PdfViewerStringId.ContextMenuSelectAll: - return "Select &All"; - case PdfViewerStringId.ContextMenuDeselectAll: - return "&Deselect All"; - case PdfViewerStringId.ContextMenuHand: - return "&Hand"; - case PdfViewerStringId.ContextMenuSelection: - return "&Selection"; - case PdfViewerStringId.ContextMenuPreviousPage: - return "&Previous Page"; - case PdfViewerStringId.ContextMenuNextPage: - return "&Next Page"; - case PdfViewerStringId.ContextMenuPrint: - return "P&rint..."; - case PdfViewerStringId.ContextMenuFind: - return "&Find Next"; - case PdfViewerStringId.NavigatorOpenButton: - return "Open"; - case PdfViewerStringId.NavigatorPrintButton: - return "Print"; - case PdfViewerStringId.RotateCounterclockwiseButton: - return "Rotate Counterclockwise"; - case PdfViewerStringId.RotateClockwiseButton: - return "Rotate Clockwise"; - case PdfViewerStringId.NavigatorPreviousPageButton: - return "Previous page"; - case PdfViewerStringId.NavigatorNextPageButton: - return "Next page"; - case PdfViewerStringId.NavigatorCurrentPageTextBox: - return "Current page"; - case PdfViewerStringId.NavigatorTotalPagesLabel: - return "Total pages"; - case PdfViewerStringId.NavigatorZoomInButton: - return "Zoom in"; - case PdfViewerStringId.NavigatorZoomOutButton: - return "Zoom out"; - case PdfViewerStringId.NavigatorZoomDropDown: - return "Zoom drop-down"; - case PdfViewerStringId.NavigatorHandToolButton: - return "Pan"; - case PdfViewerStringId.NavigatorSelectToolButton: - return "Selection"; - case PdfViewerStringId.NavigatorFindNextButton: - return "Find next"; - case PdfViewerStringId.NavigatorFindPreviousButton: - return "Find previous"; - case PdfViewerStringId.NavigatorSearchTextBox: - return "Search"; - case PdfViewerStringId.NavigatorNoResultMessage: - return "No results found according to the specified criteria."; - case PdfViewerStringId.NavigatorNoResultMessageHeader: - return "Information"; - case PdfViewerStringId.NavigatorDefaultStrip: - return "Default strip"; - case PdfViewerStringId.PrintPreviewGroupBoxPreview: - return "Preview"; - case PdfViewerStringId.PrintPreviewGroupBoxOrientation: - return "Orientation"; - case PdfViewerStringId.PrintPreviewGroupBoxSettings: - return "Settings"; - case PdfViewerStringId.PrintPreviewButtonPrint: - return "Print"; - case PdfViewerStringId.PrintPreviewButtonCancel: - return "Cancel"; - case PdfViewerStringId.PrintPreviewButtonWatermark: - return "Watermark"; - case PdfViewerStringId.PrintPreviewButtonSettings: - return "Print Settings"; - case PdfViewerStringId.PrintPreviewLabelPageSizeInches: - return "{0:F2} x {1:F2} Inches"; - case PdfViewerStringId.PrintPreviewLabelPageSizeCm: - return "{0:F2}cm x {1:F2}cm"; - case PdfViewerStringId.PrintPreviewLabelScale: - return "Scale: {0}%"; - case PdfViewerStringId.PrintPreviewLabelCurrentPage: - return "Page {0} of {1}"; - case PdfViewerStringId.PrintPreviewFormTitle: - return "Print Preview"; - case PdfViewerStringId.PrintPreviewPrintError: - return "Error printing the document!"; - case PdfViewerStringId.PrintPreviewRadioPortrait: - return "Portrait"; - case PdfViewerStringId.PrintPreviewRadioLandscape: - return "Landscape"; - case PdfViewerStringId.PrintPreviewRadioAuto: - return "Auto"; - case PdfViewerStringId.NavigatorFitToWidthButton: - return "Fit To Width"; - case PdfViewerStringId.NavigatorFitToPageButton: - return "Fit Full Page"; - case PdfViewerStringId.PageThumbnailsLabel: - return "Page Thumbnails"; - case PdfViewerStringId.SaveButton: - return "Save As"; - case PdfViewerStringId.CloseButton: - return "Close"; - case PdfViewerStringId.NavigatorShowSignatureButton: - return "Signature Panel"; - case PdfViewerStringId.SignatureDialogTitle: - return "Signature Validation Status"; - case PdfViewerStringId.SignaturePanel_Invalid: - return "At least one signature is invalid."; - case PdfViewerStringId.SignaturePanel_Unknown: - return "At least one signature has problems."; - case PdfViewerStringId.SignaturePanel_Valid: - return "Signed and all signatures are valid."; - case PdfViewerStringId.SignaturePropertiesDialogHeader: - return "Signature Validation Status"; - case PdfViewerStringId.SignaturePropertiesDialogViewModel_IsDocumentModified_False: - return "The document is not modified since this signature was applied."; - case PdfViewerStringId.SignaturePropertiesDialogViewModel_IsDocumentModified_True: - return "The document has been altered or corrupted since the Signature was applied."; - case PdfViewerStringId.SignaturePropertiesDialogViewModel_SignatureIsInvalid: - return "Signature is Invalid."; - case PdfViewerStringId.SignaturePropertiesDialogViewModel_SignatureIsUnknown: - return "Signature validity is Unknown."; - case PdfViewerStringId.SignaturePropertiesDialogViewModel_SignatureIsValid: - return "Signature is Valid, signed by "; - case PdfViewerStringId.SignaturePropertiesDialogViewModel_SignerValidity_Unknown: - return "The signer's identity is unknown."; - case PdfViewerStringId.SignaturePropertiesDialogViewModel_SignerValidity_UntrustedRoot: - return "The signer's identity is unknown because it has not been included in your list of trusted certificates and none of its parent certificates are trusted."; - case PdfViewerStringId.SignaturePropertiesDialogViewModel_SignerValidity_Valid: - return "The signer's identity is valid."; - case PdfViewerStringId.SelectCertButton: - return "Select"; - case PdfViewerStringId.SignButton: - return "Sign"; - case PdfViewerStringId.EnterAPassTextBox: - return "Enter a password"; - case PdfViewerStringId.SelectCertTextBox: - return "Select certificate"; - } - return base.GetLocalizedString(id); - } -} -```` -````VB.NET -Public Class MyLocalizationProvider - Inherits PdfViewerLocalizationProvider - Public Overrides Function GetLocalizedString(ByVal id As String) As String - Select Case id - Case PdfViewerStringId.ContextMenuCopy - Return "&Copy" - Case PdfViewerStringId.ContextMenuSelectAll - Return "Select &All" - Case PdfViewerStringId.ContextMenuDeselectAll - Return "&Deselect All" - Case PdfViewerStringId.ContextMenuHand - Return "&Hand" - Case PdfViewerStringId.ContextMenuSelection - Return "&Selection" - Case PdfViewerStringId.ContextMenuPreviousPage - Return "&Previous Page" - Case PdfViewerStringId.ContextMenuNextPage - Return "&Next Page" - Case PdfViewerStringId.ContextMenuPrint - Return "P&rint..." - Case PdfViewerStringId.ContextMenuFind - Return "&Find Next" - Case PdfViewerStringId.NavigatorOpenButton - Return "Open" - Case PdfViewerStringId.NavigatorPrintButton - Return "Print" - Case PdfViewerStringId.RotateCounterclockwiseButton - Return "Rotate Counterclockwise" - Case PdfViewerStringId.RotateClockwiseButton - Return "Rotate Clockwise" - Case PdfViewerStringId.NavigatorPreviousPageButton - Return "Previous page" - Case PdfViewerStringId.NavigatorNextPageButton - Return "Next page" - Case PdfViewerStringId.NavigatorCurrentPageTextBox - Return "Current page" - Case PdfViewerStringId.NavigatorTotalPagesLabel - Return "Total pages" - Case PdfViewerStringId.NavigatorZoomInButton - Return "Zoom in" - Case PdfViewerStringId.NavigatorZoomOutButton - Return "Zoom out" - Case PdfViewerStringId.NavigatorZoomDropDown - Return "Zoom drop-down" - Case PdfViewerStringId.NavigatorHandToolButton - Return "Pan" - Case PdfViewerStringId.NavigatorSelectToolButton - Return "Selection" - Case PdfViewerStringId.NavigatorFindNextButton - Return "Find next" - Case PdfViewerStringId.NavigatorFindPreviousButton - Return "Find previous" - Case PdfViewerStringId.NavigatorSearchTextBox - Return "Search" - Case PdfViewerStringId.NavigatorNoResultMessage - Return "No results found according to the specified criteria." - Case PdfViewerStringId.NavigatorNoResultMessageHeader - Return "Information" - Case PdfViewerStringId.NavigatorDefaultStrip - Return "Default strip" - Case PdfViewerStringId.PrintPreviewGroupBoxPreview - Return "Preview" - Case PdfViewerStringId.PrintPreviewGroupBoxOrientation - Return "Orientation" - Case PdfViewerStringId.PrintPreviewGroupBoxSettings - Return "Settings" - Case PdfViewerStringId.PrintPreviewButtonPrint - Return "Print" - Case PdfViewerStringId.PrintPreviewButtonCancel - Return "Cancel" - Case PdfViewerStringId.PrintPreviewButtonWatermark - Return "Watermark" - Case PdfViewerStringId.PrintPreviewButtonSettings - Return "Print Settings" - Case PdfViewerStringId.PrintPreviewLabelPageSizeInches - Return "{0:F2} x {1:F2} Inches" - Case PdfViewerStringId.PrintPreviewLabelPageSizeCm - Return "{0:F2}cm x {1:F2}cm" - Case PdfViewerStringId.PrintPreviewLabelScale - Return "Scale: {0}%" - Case PdfViewerStringId.PrintPreviewLabelCurrentPage - Return "Page {0} of {1}" - Case PdfViewerStringId.PrintPreviewFormTitle - Return "Print Preview" - Case PdfViewerStringId.PrintPreviewPrintError - Return "Error printing the document!" - Case PdfViewerStringId.PrintPreviewRadioPortrait - Return "Portrait" - Case PdfViewerStringId.PrintPreviewRadioLandscape - Return "Landscape" - Case PdfViewerStringId.PrintPreviewRadioAuto - Return "Auto" - Case PdfViewerStringId.NavigatorFitToWidthButton - Return "Fit To Width" - Case PdfViewerStringId.NavigatorFitToPageButton - Return "Fit Full Page" - Case PdfViewerStringId.PageThumbnailsLabel - Return "Page Thumbnails" - Case PdfViewerStringId.SaveButton - Return "Save As" - Case PdfViewerStringId.CloseButton - Return "Close" - Case PdfViewerStringId.NavigatorShowSignatureButton - Return "Signature Panel" - Case PdfViewerStringId.SignatureDialogTitle - Return "Signature Validation Status" - Case PdfViewerStringId.SignaturePanel_Invalid - Return "At least one signature is invalid." - Case PdfViewerStringId.SignaturePanel_Unknown - Return "At least one signature has problems." - Case PdfViewerStringId.SignaturePanel_Valid - Return "Signed and all signatures are valid." - Case PdfViewerStringId.SignaturePropertiesDialogHeader - Return "Signature Validation Status" - Case PdfViewerStringId.SignaturePropertiesDialogViewModel_IsDocumentModified_False - Return "The document is not modified since this signature was applied." - Case PdfViewerStringId.SignaturePropertiesDialogViewModel_IsDocumentModified_True - Return "The document has been altered or corrupted since the Signature was applied." - Case PdfViewerStringId.SignaturePropertiesDialogViewModel_SignatureIsInvalid - Return "Signature is Invalid." - Case PdfViewerStringId.SignaturePropertiesDialogViewModel_SignatureIsUnknown - Return "Signature validity is Unknown." - Case PdfViewerStringId.SignaturePropertiesDialogViewModel_SignatureIsValid - Return "Signature is Valid, signed by " - Case PdfViewerStringId.SignaturePropertiesDialogViewModel_SignerValidity_Unknown - Return "The signer's identity is unknown." - Case PdfViewerStringId.SignaturePropertiesDialogViewModel_SignerValidity_UntrustedRoot - Return "The signer's identity is unknown because it has not been included in your list of trusted certificates and none of its parent certificates are trusted." - Case PdfViewerStringId.SignaturePropertiesDialogViewModel_SignerValidity_Valid - Return "The signer's identity is valid." - Case PdfViewerStringId.SelectCertButton - Return "Select" - Case PdfViewerStringId.SignButton - Return "Sign" - Case PdfViewerStringId.EnterAPassTextBox - Return "Enter a password" - Case PdfViewerStringId.SelectCertTextBox - Return "Select certificate" - End Select - Return MyBase.GetLocalizedString(id) - End Function -End Class - -```` - -{{endregion}} To apply the custom localization provider, instantiate and assign it to the current localization provider: #### Changing the Localization Provider -{{source=..\SamplesCS\PdfViewer\PdfLocalization.cs region=change}} -{{source=..\SamplesVB\PdfViewer\PdfLocalization.vb region=change}} - -````C# -PdfViewerLocalizationProvider.CurrentProvider = new MyLocalizationProvider(); - -```` -````VB.NET -PdfViewerLocalizationProvider.CurrentProvider = New MyLocalizationProvider() + + -```` -{{endregion}} # See Also diff --git a/controls/pdfviewer/rotation.md b/controls/pdfviewer/rotation.md index a65b0fd21..382ccbf23 100644 --- a/controls/pdfviewer/rotation.md +++ b/controls/pdfviewer/rotation.md @@ -18,34 +18,17 @@ The __Rotate__ method is intended to rotate the pages of the loaded document at #### Using the Rotate method: -{{source=..\SamplesCS\PdfViewer\RotationAndExport.cs region=RotateMethod}} -{{source=..\SamplesVB\PdfViewer\RotationAndExport.vb region=RotateMethod}} -````C# -radPdfViewer1.Rotate(RotationAngle.Degrees180); + + -```` -````VB.NET -radPdfViewer1.Rotate(RotationAngle.Degrees180) -```` - - -{{endregion}} You can use the __RotationAngle__ property to rotate the pages or get the current rotation angle. #### Using RotationAngle property -{{source=..\SamplesCS\PdfViewer\RotationAndExport.cs region=RotationAngleProperty}} -{{source=..\SamplesVB\PdfViewer\RotationAndExport.vb region=RotationAngleProperty}} -````C# -radPdfViewer1.RotationAngle = RotationAngle.Degrees270; - -```` -````VB.NET -radPdfViewer1.RotationAngle = RotationAngle.Degrees270 + + -```` -{{endregion}} diff --git a/controls/pdfviewer/save-document.md b/controls/pdfviewer/save-document.md index ef3863a1a..568c5032d 100644 --- a/controls/pdfviewer/save-document.md +++ b/controls/pdfviewer/save-document.md @@ -15,38 +15,18 @@ The __SaveDocument__ method allows you to save the currently loaded document in #### Using SaveDocument method. -{{source=..\SamplesCS\PdfViewer\RotationAndExport.cs region=SaveAs}} -{{source=..\SamplesVB\PdfViewer\RotationAndExport.vb region=SaveAs}} -````C# -radPdfViewer1.SaveDocument(@"D:\MyFile.pdf"); + + -```` -````VB.NET -radPdfViewer1.SaveDocument("D:\MyFile.pdf") -```` - - - -{{endregion}} You can use the __GetDocumentAsStream__ method to retrieve the document stream: #### Get the document stream -{{source=..\SamplesCS\PdfViewer\RotationAndExport.cs region=SaveStream}} -{{source=..\SamplesVB\PdfViewer\RotationAndExport.vb region=SaveStream}} -````C# -var stream = radPdfViewer1.GetDocumentAsStream(); - -```` -````VB.NET -Dim stream = radPdfViewer1.GetDocumentAsStream() - -```` - + + -{{endregion}} ## Save from the PdfViewerNavigator diff --git a/controls/pdfviewer/ui/context-menu.md b/controls/pdfviewer/ui/context-menu.md index 07530fb49..c3279f999 100644 --- a/controls/pdfviewer/ui/context-menu.md +++ b/controls/pdfviewer/ui/context-menu.md @@ -14,42 +14,19 @@ __RadPdfViewer__ has a default context menu - __PdfViewerContextMenu__ which pro #### New Context Menu -{{source=..\SamplesCS\PdfViewer\PdfPublicApi.cs region=ChangeContextMenu}} -{{source=..\SamplesVB\PdfViewer\PdfPublicApi.vb region=ChangeContextMenu}} + + -````C# -this.radPdfViewer1.RadContextMenu = this.radContextMenu1; -```` -````VB.NET -Me.radPdfViewer1.RadContextMenu = Me.radContextMenu1 - -```` - -{{endregion}} You can also use the __ShowMenu__ method to show the context menu programmatically at a specified location. #### Show Context Menu -{{source=..\SamplesCS\PdfViewer\PdfPublicApi.cs region=ShowContextMenu}} -{{source=..\SamplesVB\PdfViewer\PdfPublicApi.vb region=ShowContextMenu}} - -````C# -private void buttonShowMenu_Click(object sender, EventArgs e) -{ - this.radPdfViewer1.PdfViewerElement.ShowMenu(new Point(100, 100)); -} + + -```` -````VB.NET -Private Sub buttonShowMenu_Click(sender As Object, e As EventArgs) Handles buttonShowMenu.Click - Me.radPdfViewer1.PdfViewerElement.ShowMenu(New Point(100, 100)) -End Sub -```` - -{{endregion}} The context menu can change dynamically. For example, when the Text Selection mode is enabled, *Copy* and *Select All* items are displayed in the menu with a separator below them: @@ -61,37 +38,10 @@ Additionally, you can easily add a custom menu item to the context menu. You can #### Add New Menu Item -{{source=..\SamplesCS\PdfViewer\PdfUI.cs region=CustomContextMenuItem}} -{{source=..\SamplesVB\PdfViewer\PdfUI.vb region=CustomContextMenuItem}} - -````C# -public PdfUI() -{ - InitializeComponent(); - RadMenuItem item = new RadMenuItem("MyItem"); - item.Click += item_Click; - this.radPdfViewer1.PdfViewerElement.ContextMenu.Items.Add(item); -} -private void item_Click(object sender, EventArgs e) -{ - RadMessageBox.Show("Perform your custom action here"); -} - -```` -````VB.NET -Public Sub New() - InitializeComponent() - Dim item As New RadMenuItem("MyItem") - AddHandler item.Click, AddressOf item_Click - Me.RadPdfViewer1.PdfViewerElement.ContextMenu.Items.Add(item) -End Sub -Private Sub item_Click(sender As Object, e As EventArgs) - RadMessageBox.Show("Perform your custom action here") -End Sub - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/pdfviewer/ui/document-modes.md b/controls/pdfviewer/ui/document-modes.md index e84721bbf..4249a0118 100644 --- a/controls/pdfviewer/ui/document-modes.md +++ b/controls/pdfviewer/ui/document-modes.md @@ -26,19 +26,10 @@ This document presenter displays a single page at a time inside the viewer. The #### Fit Full Page -{{source=..\SamplesCS\PdfViewer\PdfUI.cs region=FitFullPage}} -{{source=..\SamplesVB\PdfViewer\PdfUI.vb region=FitFullPage}} + + -````C# -this.radPdfViewer1.FitFullPage = true; -```` -````VB.NET -Me.RadPdfViewer1.FitFullPage = True - -```` - -{{endregion}} >caption Figure 2: Fit Full Width @@ -48,19 +39,10 @@ Me.RadPdfViewer1.FitFullPage = True This mode fills the window with each page and scroll through pages continuously. -{{source=..\SamplesCS\PdfViewer\PdfUI.cs region=FitToWidth}} -{{source=..\SamplesVB\PdfViewer\PdfUI.vb region=FitToWidth}} - -````C# -this.radPdfViewer1.FitToWidth = true; - -```` -````VB.NET -Me.RadPdfViewer1.FitToWidth = True + + -```` -{{endregion}} >caption Figure 3: Fit To Width diff --git a/controls/pdfviewer/ui/rotation.md b/controls/pdfviewer/ui/rotation.md index 31845e04a..5d98575f0 100644 --- a/controls/pdfviewer/ui/rotation.md +++ b/controls/pdfviewer/ui/rotation.md @@ -22,18 +22,9 @@ __RotationAngle__ is an enumeration that specifies the angle at which the docume #### RotationAngle -{{source=..\SamplesCS\PdfViewer\PdfUI.cs region=Rotate}} -{{source=..\SamplesVB\PdfViewer\PdfUI.vb region=Rotate}} + + -````C# -this.radPdfViewer1.Rotate(Telerik.WinControls.UI.RotationAngle.Degrees90); -```` -````VB.NET -Me.RadPdfViewer1.Rotate(RotationAngle.Degrees90) - -```` - -{{endregion}} The current angle at which the pages are rotated can be retrieved using the read-only **RotationAngle** property of **RadPdfViewer**. diff --git a/controls/pdfviewer/ui/viewer-modes.md b/controls/pdfviewer/ui/viewer-modes.md index febe519bb..67aedb979 100644 --- a/controls/pdfviewer/ui/viewer-modes.md +++ b/controls/pdfviewer/ui/viewer-modes.md @@ -39,19 +39,10 @@ The mode of the viewer is set using the __ViewerMode__ property: #### With Code -{{source=..\SamplesCS\PdfViewer\PdfUI.cs region=ViewerMode}} -{{source=..\SamplesVB\PdfViewer\PdfUI.vb region=ViewerMode}} + + -````C# -this.radPdfViewer1.ViewerMode = FixedDocumentViewerMode.TextSelection; -```` -````VB.NET -Me.RadPdfViewer1.ViewerMode = FixedDocumentViewerMode.TextSelection - -```` - -{{endregion}} # See Also diff --git a/controls/picturebox/features/context-menu.md b/controls/picturebox/features/context-menu.md index ee1811c62..ef79d72bd 100644 --- a/controls/picturebox/features/context-menu.md +++ b/controls/picturebox/features/context-menu.md @@ -17,19 +17,10 @@ The context menu will appear every time the user right-clicks on the **RadPictur The context menu is enabled by default. If you want to disable it you can use the **ContextMenuEnabled** property: #### Disable context menu -{{source=..\SamplesCS\PictureBox\PictureBoxGettingStarted.cs region=DisableContextMenu}} -{{source=..\SamplesVB\PictureBox\PictureBoxGettingStarted.vb region=DisableContextMenu}} + + -````C# -this.radPictureBox1.ContextMenuEnabled = false; - -```` -````VB.NET -Me.RadPictureBox1.ContextMenuEnabled = False -```` - -{{endregion}} **RadPictureBox** exposes **ContextMenuProperties** that defines the properties related to the context menu. Through it you can easily access the default context menu items: - OpenItem @@ -49,61 +40,19 @@ The default context menu in **RadPictureBox** can be customized in the **Context In order to remove an item you can use the Items.**Remove** method and pass the desired item as a parameter in the **ContextMenuOpening** event: -{{source=..\SamplesCS\PictureBox\PictureBoxGettingStarted.cs region=RemoveItem}} -{{source=..\SamplesVB\PictureBox\PictureBoxGettingStarted.vb region=RemoveItem}} + + -````C# -private void RadPictureBox1_ContextMenuOpening(object sender, CancelEventArgs e) -{ - this.radPictureBox1.ContextMenuDropDown.Items.Remove(this.radPictureBox1.ContextMenuProperties.EditItem); -} - -```` -````VB.NET -Private Sub RadPictureBox1_ContextMenuOpening(ByVal sender As Object, ByVal e As CancelEventArgs) - Me.RadPictureBox1.ContextMenuDropDown.Items.Remove(Me.RadPictureBox1.ContextMenuProperties.EditItem) -End Sub - -```` -{{endregion}} ### Adding new item to the context menu In order to add a new item to the context menu you should create new menu item instance and add it to the Items collection: -{{source=..\SamplesCS\PictureBox\PictureBoxGettingStarted.cs region=AddItem}} -{{source=..\SamplesVB\PictureBox\PictureBoxGettingStarted.vb region=AddItem}} + + -````C# -RadMenuItem customMenuItem = new RadMenuItem(); -private void RadPictureBox1_ContextMenuOpening1(object sender, CancelEventArgs e) -{ - customMenuItem.Text = "Download"; - RadMenuSeparatorItem separator = new RadMenuSeparatorItem(); - if (!this.radPictureBox1.ContextMenuDropDown.Items.Contains(customMenuItem)) - { - this.radPictureBox1.ContextMenuDropDown.Items.Add(customMenuItem); - this.radPictureBox1.ContextMenuDropDown.Items.Add(separator); - } -} - -```` -````VB.NET -Private customMenuItem As RadMenuItem = New RadMenuItem() -Private Sub RadPictureBox1_ContextMenuOpening1(ByVal sender As Object, ByVal e As CancelEventArgs) - customMenuItem.Text = "Download" - Dim separator As RadMenuSeparatorItem = New RadMenuSeparatorItem() - - If Not Me.RadPictureBox1.ContextMenuDropDown.Items.Contains(customMenuItem) Then - Me.RadPictureBox1.ContextMenuDropDown.Items.Add(customMenuItem) - Me.RadPictureBox1.ContextMenuDropDown.Items.Add(separator) - End If -End Sub -```` - -{{endregion}} >note You can subscribe to the **RadMenuItem.Click** event of the newly added item and execute the desired action when the item is clicked. @@ -138,9 +87,6 @@ End Sub ```` -{{endregion}} - - ## Context menu events **RadPictureBox** exposes the following useful events: diff --git a/controls/picturebox/features/edit.md b/controls/picturebox/features/edit.md index 06951a271..a85984443 100644 --- a/controls/picturebox/features/edit.md +++ b/controls/picturebox/features/edit.md @@ -39,57 +39,17 @@ If you are trying to edit SVG image you will get the following warning message: Below is demonstrated how to customize the ResizeDialog and set the checked state of the Preserve Aspect Ratio checkbox which by default is unchecked. -{{source=..\SamplesCS\PictureBox\PictureBoxGettingStarted.cs region=CustomizeDialog}} -{{source=..\SamplesVB\PictureBox\PictureBoxGettingStarted.vb region=CustomizeDialog}} - -````C# -public class CustomImageEditorDialogFactory : ImageEditorDialogFactory -{ - public override ImageEditorBaseDialog CreateDialog(Type type, RadImageEditorElement imageEditorElement) - { - ImageEditorBaseDialog dialog = base.CreateDialog(type, imageEditorElement); - if (dialog is ResizeDialog) - { - ((RadCheckBox)dialog.Controls[0].Controls["radCheckBoxAspectRation"]).Checked = true; - - } - return dialog; - } -} - -```` -````VB.NET -Public Class CustomImageEditorDialogFactory - Inherits ImageEditorDialogFactory - Public Overrides Function CreateDialog(ByVal type As Type, ByVal imageEditorElement As RadImageEditorElement) As ImageEditorBaseDialog - Dim dialog As ImageEditorBaseDialog = MyBase.CreateDialog(type, imageEditorElement) - - If TypeOf dialog Is ResizeDialog Then - CType(dialog.Controls(0).Controls("radCheckBoxAspectRation"), RadCheckBox).Checked = True - End If - Return dialog - End Function -End Class - -```` - -{{endregion}} + + -Finally, you need to apply this custom factory to your **PictureBoxImageEditorDialog**: -{{source=..\SamplesCS\PictureBox\PictureBoxGettingStarted.cs region=ApplyCustomFactory}} -{{source=..\SamplesVB\PictureBox\PictureBoxGettingStarted.vb region=ApplyCustomFactory}} -````C# -this.radPictureBox1.ImageEditorDialog.ImageEditor.ImageEditorElement.DialogFactory = new CustomImageEditorDialogFactory(); +Finally, you need to apply this custom factory to your **PictureBoxImageEditorDialog**: -```` -````VB.NET -Me.RadPictureBox1.ImageEditorDialog.ImageEditor.ImageEditorElement.DialogFactory = New CustomImageEditorDialogFactory() + + -```` -{{endregion}} # See Also diff --git a/controls/picturebox/features/pan-and-zoom.md b/controls/picturebox/features/pan-and-zoom.md index b25702af6..41f4114f4 100644 --- a/controls/picturebox/features/pan-and-zoom.md +++ b/controls/picturebox/features/pan-and-zoom.md @@ -21,19 +21,9 @@ If you do not what the scrollbars to be displayed you can disable them. Thus, th #### Disable scrollbars -{{source=..\SamplesCS\PictureBox\PictureBoxGettingStarted.cs region=DisableScrollbars}} -{{source=..\SamplesVB\PictureBox\PictureBoxGettingStarted.vb region=DisableScrollbars}} + + -````C# -this.radPictureBox1.ShowScrollBars = false; - -```` -````VB.NET -Me.RadPictureBox1.ShowScrollBars = False - -```` - -{{endregion}} ## Zoom properties @@ -54,57 +44,23 @@ Me.RadPictureBox1.ShowScrollBars = False The control exposes an API for zooming programmatically. * The **Zoom** method performs a zoom operation by given steps count: -{{source=..\SamplesCS\PictureBox\PictureBoxGettingStarted.cs region=Zoom}} -{{source=..\SamplesVB\PictureBox\PictureBoxGettingStarted.vb region=Zoom}} - -````C# -this.radPictureBox1.ZoomProperties.Zoom(5); - -```` -````VB.NET -Me.RadPictureBox1.ZoomProperties.Zoom(5) - -```` + + -{{endregion}} * The **ZoomIn** method performs a zoom-in operation with one step, according to the **ZoomStep** value. This method has an overload that performs a zoom-in according to the **ZoomStep** value operation with a specified count of steps: -{{source=..\SamplesCS\PictureBox\PictureBoxGettingStarted.cs region=ZoomIn}} -{{source=..\SamplesVB\PictureBox\PictureBoxGettingStarted.vb region=ZoomIn}} + + -````C# -this.radPictureBox1.ZoomProperties.ZoomIn(); -this.radPictureBox1.ZoomProperties.ZoomIn(5); - -```` -````VB.NET -Me.RadPictureBox1.ZoomProperties.ZoomIn() -Me.RadPictureBox1.ZoomProperties.ZoomIn(5) - -```` - -{{endregion}} * The **ZoomOut** method performs a zoom-out operation with one step, according to the **ZoomStep** value. This method has an overload that performs a zoom-out according to the **ZoomStep** value operation with a specified count of steps: -{{source=..\SamplesCS\PictureBox\PictureBoxGettingStarted.cs region=ZoomOut}} -{{source=..\SamplesVB\PictureBox\PictureBoxGettingStarted.vb region=ZoomOut}} - -````C# -this.radPictureBox1.ZoomProperties.ZoomOut(); -this.radPictureBox1.ZoomProperties.ZoomOut(5); - -```` -````VB.NET -Me.RadPictureBox1.ZoomProperties.ZoomOut() -Me.RadPictureBox1.ZoomProperties.ZoomOut(5) - -```` + + -{{endregion}} You can also reset all the zoom settings by calling the **ResetZoom** method. diff --git a/controls/picturebox/features/working-with-panels.md b/controls/picturebox/features/working-with-panels.md index 74aba9983..7751e03ae 100644 --- a/controls/picturebox/features/working-with-panels.md +++ b/controls/picturebox/features/working-with-panels.md @@ -18,45 +18,9 @@ position: 4 #### Adding Buttons to Panels -{{source=..\SamplesCS\PictureBox\PictureBoxGettingStarted.cs region=Panels}} -{{source=..\SamplesVB\PictureBox\PictureBoxGettingStarted.vb region=Panels}} + + -````C# -RadButtonElement button = new RadButtonElement("Add New"); -button.SvgImage = RadSvgImage.FromFile(@"..//..//PictureBox//symbol-add.svg"); -button.TextImageRelation = TextImageRelation.ImageBeforeText; -this.radPictureBox1.TopPanel.LeftItems.Add(button); - -button = new RadButtonElement("Download"); -button.SvgImage = RadSvgImage.FromFile(@"..//..//PictureBox//symbol-download.svg"); -button.TextImageRelation = TextImageRelation.ImageBeforeText; -this.radPictureBox1.TopPanel.RightItems.Add(button); - -button = new RadButtonElement("Favourites"); -button.SvgImage = RadSvgImage.FromFile(@"..//..//PictureBox//heart-filled.svg"); -button.TextImageRelation = TextImageRelation.ImageBeforeText; -this.radPictureBox1.TopPanel.CenterItems.Add(button); - -```` -````VB.NET -Dim button As RadButtonElement = New RadButtonElement("Add New") -button.SvgImage = RadSvgImage.FromFile("..//..//PictureBox//symbol-add.svg") -button.TextImageRelation = TextImageRelation.ImageBeforeText -Me.RadPictureBox1.TopPanel.LeftItems.Add(button) - -button = New RadButtonElement("Download") -button.SvgImage = RadSvgImage.FromFile("..//..//PictureBox//symbol-download.svg") -button.TextImageRelation = TextImageRelation.ImageBeforeText -Me.RadPictureBox1.TopPanel.RightItems.Add(button) - -button = New RadButtonElement("Favourites") -button.SvgImage = RadSvgImage.FromFile("..//..//PictureBox//heart-filled.svg") -button.TextImageRelation = TextImageRelation.ImageBeforeText -Me.RadPictureBox1.TopPanel.CenterItems.Add(button) - -```` - -{{endregion}} ![WinForms RadPictureBox Adding Buttons to Panels](images/customizing-appearance001.png) @@ -72,19 +36,10 @@ The display mode can be changed through **PanelDisplayMode** property. #### Setting PanelDisplayMode to be always visible -{{source=..\SamplesCS\PictureBox\PictureBoxGettingStarted.cs region=PanelDisplayMode}} -{{source=..\SamplesVB\PictureBox\PictureBoxGettingStarted.vb region=PanelDisplayMode}} - -````C# -this.radPictureBox1.PanelDisplayMode = PictureBoxPanelDisplayMode.Always; - -```` -````VB.NET -Me.RadPictureBox1.PanelDisplayMode = PictureBoxPanelDisplayMode.Always + + -```` -{{endregion}} >note When **PanelDisplayMode** is set to *OnMouseHover*, the **AllowPanelAnimations** property indicates whether to show animations when showing and hiding panels. @@ -94,19 +49,9 @@ If you have horizontal as well as vertical panel displayed in **RadPictureBox** #### Setting PanelOverflowMode -{{source=..\SamplesCS\PictureBox\PictureBoxGettingStarted.cs region=PanelOverflowMode}} -{{source=..\SamplesVB\PictureBox\PictureBoxGettingStarted.vb region=PanelOverflowMode}} - -````C# -this.radPictureBox1.PanelOverflowMode = PictureBoxPanelOverflowMode.HorizontalOverVertical; - -```` -````VB.NET -Me.RadPictureBox1.PanelOverflowMode = PictureBoxPanelOverflowMode.HorizontalOverVertical - -```` + + -{{endregion}} # See Also diff --git a/controls/picturebox/getting-started.md b/controls/picturebox/getting-started.md index 73db4bc23..dfc3726ed 100644 --- a/controls/picturebox/getting-started.md +++ b/controls/picturebox/getting-started.md @@ -43,21 +43,10 @@ By default, the control is shown with no image icon: You can use the **DefaultSvgImage/DefaultImage** and **DefaultText** properties to customize both the image icon and text according to your needs: -{{source=..\SamplesCS\PictureBox\PictureBoxGettingStarted.cs region=DefaultImageAndText}} -{{source=..\SamplesVB\PictureBox\PictureBoxGettingStarted.vb region=DefaultImageAndText}} + + -````C# -this.radPictureBox1.DefaultSvgImage = RadSvgImage.FromFile(@"..//..//PictureBox//noimage.svg"); -this.radPictureBox1.DefaultText = "No image available"; -```` -````VB.NET -Me.RadPictureBox1.DefaultSvgImage = RadSvgImage.FromFile("..//..//PictureBox//noimage.svg") -Me.RadPictureBox1.DefaultText = "No image available" - -```` - -{{endregion}} ![WinForms RadPictureBox Customize Default Look](images/picturebox-getting-started003.png) @@ -67,35 +56,17 @@ To load an image in **RadPictureBox** control you can use **SvgImage** or **Imag - **Load an image**: -{{source=..\SamplesCS\PictureBox\PictureBoxGettingStarted.cs region=LoadImage}} -{{source=..\SamplesVB\PictureBox\PictureBoxGettingStarted.vb region=LoadImage}} - -````C# -this.radPictureBox1.Image = Image.FromFile(@"..//..//PictureBox//emoticon-happy.png"); - -```` -````VB.NET -Me.RadPictureBox1.Image = Image.FromFile("..//..//PictureBox//emoticon-happy.png") + + -```` -{{endregion}} - **Load SVG image**: -{{source=..\SamplesCS\PictureBox\PictureBoxGettingStarted.cs region=LoadSvgImage}} -{{source=..\SamplesVB\PictureBox\PictureBoxGettingStarted.vb region=LoadSvgImage}} - -````C# -this.radPictureBox1.SvgImage = RadSvgImage.FromFile(@"..//..//PictureBox//emoticon-happy.svg"); + + -```` -````VB.NET -Me.RadPictureBox1.SvgImage = RadSvgImage.FromFile("..//..//PictureBox//emoticon-happy.svg") - -```` -{{endregion}} ![WinForms RadPictureBox Load an Image](images/picturebox-getting-started002.png) diff --git a/controls/picturebox/localization.md b/controls/picturebox/localization.md index 5f0b51632..fe2a6a436 100644 --- a/controls/picturebox/localization.md +++ b/controls/picturebox/localization.md @@ -20,109 +20,16 @@ Override the **GetLocalizedString(string id)** method and provide a translation Below is a sample implementation of an English localization provider: -{{source=..\SamplesCS\PictureBox\PictureBoxLocalizationProvider.cs region=LocalizationProvider}} -{{source=..\SamplesVB\PictureBox\PictureBoxLocalizationProvider.vb region=LocalizationProvider}} + + -````C# -public class EnglishPictureBoxLocalizationProvider : RadPictureBoxLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case RadPictureBoxStringId.NoPictureText: return "No image"; - case RadPictureBoxStringId.CutMenuItem: return "Cut"; - case RadPictureBoxStringId.CopyMenuItem: return "Copy"; - case RadPictureBoxStringId.PasteMenuItem: return "Paste"; - case RadPictureBoxStringId.OpenMenuItem: return "Open"; - case RadPictureBoxStringId.SaveMenuItem: return "Save"; - case RadPictureBoxStringId.RemoveMenuItem: return "Remove"; - case RadPictureBoxStringId.EditMenuItem: return "Edit image"; - case RadPictureBoxStringId.DefaultImageSaveName: return "Image"; - case RadPictureBoxStringId.ErrorLoadingImageCaption: return "Error loading image"; - case RadPictureBoxStringId.ErrorLoadingImageText: return "Could not load the image."; - case RadPictureBoxStringId.ErrorSavingImageCaption: return "Error saving image"; - case RadPictureBoxStringId.ErrorSavingImageText: return "Could not save the image."; - case RadPictureBoxStringId.ImageEditorDialogHeader: return "Image Editor Dialog"; - case RadPictureBoxStringId.ImageEditorDialogOkButton: return "OK"; - case RadPictureBoxStringId.ImageEditorDialogCancelButton: return "Cancel"; - case RadPictureBoxStringId.EditSvgDialogImageCaption: return "Warning - Cannot edit SVG"; - case RadPictureBoxStringId.EditSvgDialogImageText: return "RadPictureBox cannot edit SVG images.\r\nWould you like to convert the SVG to a raster image and start editing?"; - - default: return string.Empty; - } - } -} - -```` -````VB.NET -Public Class EnglishPictureBoxLocalizationProvider - Inherits RadPictureBoxLocalizationProvider - - Public Overrides Function GetLocalizedString(ByVal id As String) As String - Select Case id - Case RadPictureBoxStringId.NoPictureText - Return "No image" - Case RadPictureBoxStringId.CutMenuItem - Return "Cut" - Case RadPictureBoxStringId.CopyMenuItem - Return "Copy" - Case RadPictureBoxStringId.PasteMenuItem - Return "Paste" - Case RadPictureBoxStringId.OpenMenuItem - Return "Open" - Case RadPictureBoxStringId.SaveMenuItem - Return "Save" - Case RadPictureBoxStringId.RemoveMenuItem - Return "Remove" - Case RadPictureBoxStringId.EditMenuItem - Return "Edit image" - Case RadPictureBoxStringId.DefaultImageSaveName - Return "Image" - Case RadPictureBoxStringId.ErrorLoadingImageCaption - Return "Error loading image" - Case RadPictureBoxStringId.ErrorLoadingImageText - Return "Could not load the image." - Case RadPictureBoxStringId.ErrorSavingImageCaption - Return "Error saving image" - Case RadPictureBoxStringId.ErrorSavingImageText - Return "Could not save the image." - Case RadPictureBoxStringId.ImageEditorDialogHeader - Return "Image Editor Dialog" - Case RadPictureBoxStringId.ImageEditorDialogOkButton - Return "OK" - Case RadPictureBoxStringId.ImageEditorDialogCancelButton - Return "Cancel" - Case RadPictureBoxStringId.EditSvgDialogImageCaption - Return "Warning - Cannot edit SVG" - Case RadPictureBoxStringId.EditSvgDialogImageText - Return "RadPictureBox cannot edit SVG images." & vbCrLf & "Would you like to convert the SVG to a raster image and start editing?" - Case Else - Return String.Empty - End Select - End Function -End Class - -```` - -{{endregion}} To apply the custom localization provider, instantiate and assign it to the current localization provider: ### Assigning the Current Localization Provider -{{source=..\SamplesCS\PictureBox\PictureBoxLocalizationProvider.cs region=AssignLocalizationProvider}} -{{source=..\SamplesVB\PictureBox\PictureBoxLocalizationProvider.vb region=AssignLocalizationProvider}} - -````C# -RadPictureBoxLocalizationProvider.CurrentProvider = new EnglishPictureBoxLocalizationProvider(); - -```` -````VB.NET -RadPictureBoxLocalizationProvider.CurrentProvider = new EnglishPictureBoxLocalizationProvider() - -```` + + -{{endregion}} diff --git a/controls/pipspager/data-binding.md b/controls/pipspager/data-binding.md index 81cefb034..532499343 100644 --- a/controls/pipspager/data-binding.md +++ b/controls/pipspager/data-binding.md @@ -18,150 +18,17 @@ The following example demonstrates a basic scenario where **RadPipsPager** is us #### Bind RadPipsPager -{{source=..\SamplesCS\PipsPager\PipsPagerGettingStarted.cs region=BindingPipsPager}} -{{source=..\SamplesVB\PipsPager\PipsPagerGettingStarted.vb region=BindingPipsPager}} + + -````C# -BindingSource bindingSource = new BindingSource(); -BindingList list = new BindingList() -{ -new Person("1", "Nancy Davolio"), -new Person("2", "Andrew Fuller"), -new Person("3", "Janet Leverling"), -new Person("4", "Margaret Peacock") -}; -bindingSource.DataSource = list; -this.radPipsPager1.BindingSource = bindingSource; - -//bind slide view to show data -LightVisualElement template = new LightVisualElement(); -this.radSlideView1.Mappings.Add(new Mapping(template, LightVisualElement.TextProperty, nameof(Person.Name))); -this.radSlideView1.TemplateElement = template; -this.radSlideView1.BindingSource = bindingSource; -```` -````VB.NET -Dim bindingSource As BindingSource = New BindingSource() -Dim list As BindingList(Of Person) = New BindingList(Of Person)() From { - New Person("1", "Nancy Davolio"), - New Person("2", "Andrew Fuller"), - New Person("3", "Janet Leverling"), - New Person("4", "Margaret Peacock") -} -bindingSource.DataSource = list -Me.radPipsPager1.BindingSource = bindingSource - -'bind slide view to show data -Dim template As LightVisualElement = New LightVisualElement() -Me.radSlideView1.Mappings.Add(New Mapping(template, LightVisualElement.TextProperty, NameOf(Person.Name))) -Me.radSlideView1.TemplateElement = template -Me.radSlideView1.BindingSource = bindingSource - -```` #### Sample Data Object -{{source=..\SamplesCS\PipsPager\PipsPagerGettingStarted.cs region=SampleDataObject}} -{{source=..\SamplesVB\PipsPager\PipsPagerGettingStarted.vb region=SampleDataObject}} + + -````C# -public class Person : INotifyPropertyChanged -{ - private string id; - private string name; - public event PropertyChangedEventHandler PropertyChanged; - public Person(string id, string name) - { - this.id = id; - this.name = name; - } - public string Id - { - get - { - return this.id; - } - set - { - if (this.id != value) - { - this.id = value; - OnPropertyChanged("Id"); - } - } - } - public string Name - { - get - { - return this.name; - } - set - { - if (this.name != value) - { - this.name = value; - OnPropertyChanged("Name"); - } - } - } - protected virtual void OnPropertyChanged(string propertyName) - { - if (PropertyChanged != null) - { - PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); - } - } -} -```` -````VB.NET - - Public Class Person - Inherits INotifyPropertyChanged - - Private id As String - Private name As String - Public Event PropertyChanged As PropertyChangedEventHandler - - Public Sub New(ByVal id As String, ByVal name As String) - Me.id = id - Me.name = name - End Sub - - Public Property Id As String - Get - Return Me.id - End Get - Set(ByVal value As String) - - If Me.id <> value Then - Me.id = value - OnPropertyChanged("Id") - End If - End Set - End Property - - Public Property Name As String - Get - Return Me.name - End Get - Set(ByVal value As String) - - If Me.name <> value Then - Me.name = value - OnPropertyChanged("Name") - End If - End Set - End Property - - Protected Overridable Sub OnPropertyChanged(ByVal propertyName As String) - RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName)) - End Sub - End Class -End Class - -```` ![WinForms RadPipsPager Bounding](images/pipspager-data-binding.png) @@ -169,17 +36,10 @@ End Class In unbound mode, the **NumberOfPages** property determines the amount of pips items that are shown. -{{source=..\SamplesCS\SlideView\GettingStartedGallery.cs region=BindingPipsPager}} -{{source=..\SamplesVB\SlideView\GettingStartedGallery.vb region=BindingPipsPager}} + + -````C# -this.radPipsPager1.NumberOfPages = 2; - -```` -````VB.NET -Me.radPipsPager1.NumberOfPages = 2 -```` Then, you can handle the **SelectedIndexChanged** event to get notified when the user changes the selected **PipsPagerItem**. The **SelectedPipChangedEventArgs** gives access to the new and old pip. diff --git a/controls/pipspager/getting-started.md b/controls/pipspager/getting-started.md index ffd35aa59..0a717fafc 100644 --- a/controls/pipspager/getting-started.md +++ b/controls/pipspager/getting-started.md @@ -53,55 +53,10 @@ Follow the steps: 5\. Set the __BindingSource__ property of RadSlideView and RadPipsPager. -{{source=..\SamplesCS\SlideView\GettingStartedGallery.cs region=PipsSlider}} -{{source=..\SamplesVB\SlideView\GettingStartedGallery.vb region=PipsSlider}} - -````C# - -BindingSource source = new BindingSource(); -DataTable table = new DataTable(); -table.Columns.Add("Title", typeof(string)); -table.Rows.Add("Venice"); -table.Rows.Add("Rome"); -table.Rows.Add("Florence"); - -this.radSlideView1.BindingSource = source; -this.radPipsPager1.BindingSource = source; -this.radPipsPager1.ButtonsVisibility = ButtonsVisibility.Visible; -this.radSlideView1.ButtonsVisibility = ButtonsVisibility.VisibleOnMouseOver; -source.DataSource = table; - -LightVisualElement titleTemplate = new LightVisualElement(); -titleTemplate.ForeColor = Color.DarkGray; -titleTemplate.DrawText = true; -titleTemplate.Font = new Font("Verdana", 12f, FontStyle.Bold); -this.radSlideView1.Mappings.Add(new Mapping(titleTemplate, LightVisualElement.TextProperty, table.Columns[0].ColumnName)); -this.radSlideView1.TemplateElement = titleTemplate; - -```` -````VB.NET - - Dim source As BindingSource = New BindingSource() -Dim table As DataTable = New DataTable() -table.Columns.Add("Title", GetType(String)) -table.Rows.Add("Venice") -table.Rows.Add("Rome") -table.Rows.Add("Florence") -Me.radSlideView1.BindingSource = source -Me.radPipsPager1.BindingSource = source -Me.radPipsPager1.ButtonsVisibility = ButtonsVisibility.Visible -Me.radSlideView1.ButtonsVisibility = ButtonsVisibility.VisibleOnMouseOver -source.DataSource = table -Dim titleTemplate As LightVisualElement = New LightVisualElement() -titleTemplate.ForeColor = Color.DarkGray -titleTemplate.DrawText = True -titleTemplate.Font = New Font("Verdana", 12.0F, FontStyle.Bold) -Me.radSlideView1.Mappings.Add(New Mapping(titleTemplate, LightVisualElement.TextProperty, table.Columns(0).ColumnName)) -Me.radSlideView1.TemplateElement = titleTemplate - -```` - -{{endregion}} + + + + >note More advanced TemplateElement is demonstrated in the Demo application >> SlideView/ PipsPager >> First look example which also shows the smooth integration between RadSlideView and [RadPipsPager]({%slug pipspager-overview%}). diff --git a/controls/pivotgrid/binding-with-radchartview.md b/controls/pivotgrid/binding-with-radchartview.md index 0d7bfca67..2acfb4374 100644 --- a/controls/pivotgrid/binding-with-radchartview.md +++ b/controls/pivotgrid/binding-with-radchartview.md @@ -15,19 +15,10 @@ The reports generated by **RadPivotGrid** can be easily visualized in [RadChartV #### Setting RadChartView Data Source -{{source=..\SamplesCS\PivotGrid\PivotGridBindingWithChart.cs region=SetDataSource}} -{{source=..\SamplesVB\PivotGrid\PivotGridBindingWithChart.vb region=SetDataSource}} + + -````C# -this.radChartView1.DataSource = this.radPivotGrid1; -```` -````VB.NET -Me.radChartView1.DataSource = Me.radPivotGrid1 - -```` - -{{endregion}} >caption Figure 1: Associating a Chart ![WinForms RadPivotGrid Associating a Chart](images/pivotgrid-binding-with-radchartview001.png) @@ -40,25 +31,9 @@ In some cases, including the __SubTotal__ and __GrandTotal__ values in the visua #### Totals Settings -{{source=..\SamplesCS\PivotGrid\PivotGridBindingWithChart.cs region=ChooseDisplayedTotals}} -{{source=..\SamplesVB\PivotGrid\PivotGridBindingWithChart.vb region=ChooseDisplayedTotals}} - -````C# -this.radPivotGrid1.ChartDataProvider.IncludeColumnSubTotals = false; -this.radPivotGrid1.ChartDataProvider.IncludeRowSubTotals = false; -this.radPivotGrid1.ChartDataProvider.IncludeColumnGrandTotals = false; -this.radPivotGrid1.ChartDataProvider.IncludeRowSubTotals = false; - -```` -````VB.NET -Me.radPivotGrid1.ChartDataProvider.IncludeColumnSubTotals = False -Me.radPivotGrid1.ChartDataProvider.IncludeRowSubTotals = False -Me.radPivotGrid1.ChartDataProvider.IncludeColumnGrandTotals = False -Me.radPivotGrid1.ChartDataProvider.IncludeRowSubTotals = False + + -```` - -{{endregion}} You can change the type of the generated series to one of the categorical types: __Bar, Line, Area__. Additionally, you can choose which of the pivot axes will be used for generating series: @@ -71,63 +46,28 @@ You can change the type of the generated series to one of the categorical types: #### Series Type -{{source=..\SamplesCS\PivotGrid\PivotGridBindingWithChart.cs region=ChooseSeriesAndAxes}} -{{source=..\SamplesVB\PivotGrid\PivotGridBindingWithChart.vb region=ChooseSeriesAndAxes}} - -````C# -this.radPivotGrid1.ChartDataProvider.GeneratedSeriesType = Telerik.WinControls.UI.GeneratedSeriesType.Line; -this.radPivotGrid1.ChartDataProvider.SeriesAxis = Telerik.Pivot.Core.PivotAxis.Rows; -this.radPivotGrid1.ChartDataProvider.EnableNulls = true; - -```` -````VB.NET -Me.radPivotGrid1.ChartDataProvider.GeneratedSeriesType = Telerik.WinControls.UI.GeneratedSeriesType.Line -Me.radPivotGrid1.ChartDataProvider.SeriesAxis = Telerik.Pivot.Core.PivotAxis.Rows -Me.radPivotGrid1.ChartDataProvider.EnableNulls = True + + -```` -{{endregion}} You have the option to choose whether the entire report should be visualized or only the selected parts of it. There is also an option to delay the updates so that **RadChartView** does not update constantly during selection. #### Visualizing Data -{{source=..\SamplesCS\PivotGrid\PivotGridBindingWithChart.cs region=ConfigureReport}} -{{source=..\SamplesVB\PivotGrid\PivotGridBindingWithChart.vb region=ConfigureReport}} + + -````C# -this.radPivotGrid1.ChartDataProvider.SelectionOnly = true; -this.radPivotGrid1.ChartDataProvider.DelayUpdate = true; -this.radPivotGrid1.ChartDataProvider.DelayAmount = 500; -```` -````VB.NET -Me.radPivotGrid1.ChartDataProvider.SelectionOnly = True -Me.radPivotGrid1.ChartDataProvider.DelayUpdate = True -Me.radPivotGrid1.ChartDataProvider.DelayAmount = 500 - -```` - -{{endregion}} You can change the delimiter that is put between the group names when generating chart categories. This can be useful for avoiding confusion if the default dash delimiter (“-“) is used in some of the group names. #### Group Names Delimiter -{{source=..\SamplesCS\PivotGrid\PivotGridBindingWithChart.cs region=SetDelimiter}} -{{source=..\SamplesVB\PivotGrid\PivotGridBindingWithChart.vb region=SetDelimiter}} - -````C# -this.radPivotGrid1.ChartDataProvider.GroupNameDelimiter = " -> "; + + -```` -````VB.NET -Me.radPivotGrid1.ChartDataProvider.GroupNameDelimiter = " -> " -```` - -{{endregion}} ## PivotGridChartDataProvider Events @@ -135,41 +75,10 @@ There are two events that allow you to modify the settings of the generated seri #### Chart Events -{{source=..\SamplesCS\PivotGrid\PivotGridBindingWithChart.cs region=replaceOrModifySeries}} -{{source=..\SamplesVB\PivotGrid\PivotGridBindingWithChart.vb region=replaceOrModifySeries}} - -````C# -void ChartDataProvider_UpdateCompleted(object sender, EventArgs e) -{ - if (this.radPivotGrid1.ChartDataProvider.GeneratedSeriesType != GeneratedSeriesType.Bar) - { - foreach (CartesianSeries series in this.radChartView1.Series) - { - series.CombineMode = ChartSeriesCombineMode.Stack; - } - } -} -void ChartDataProvider_SeriesCreating(object sender, Telerik.WinControls.UI.SeriesCreatingEventArgs e) -{ - e.Series = new BarSeries(); -} - -```` -````VB.NET -Private Sub ChartDataProvider_UpdateCompleted(sender As Object, e As EventArgs) - If Me.radPivotGrid1.ChartDataProvider.GeneratedSeriesType <> GeneratedSeriesType.Bar Then - For Each series As CartesianSeries In Me.radChartView1.Series - series.CombineMode = ChartSeriesCombineMode.Stack - Next - End If -End Sub -Private Sub ChartDataProvider_SeriesCreating(sender As Object, e As Telerik.WinControls.UI.SeriesCreatingEventArgs) - e.Series = New BarSeries() -End Sub - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/pivotgrid/calculated-fields.md b/controls/pivotgrid/calculated-fields.md index 6b92e28e9..44b01bc96 100644 --- a/controls/pivotgrid/calculated-fields.md +++ b/controls/pivotgrid/calculated-fields.md @@ -26,66 +26,10 @@ The first task is to decide what the calculation formula that you want to use is #### Custom Calculated Field -{{source=..\SamplesCS\PivotGrid\PivotGridCalculatedFields.cs region=CalculatedFieldClass}} -{{source=..\SamplesVB\PivotGrid\PivotGridCalculatedFields.vb region=CalculatedFieldClass}} - -````C# -public class CommissionCalculatedField : CalculatedField -{ - private RequiredField extendPriceField; - public CommissionCalculatedField() - { - this.Name = "Commission"; - this.extendPriceField = RequiredField.ForProperty("ExtendedPrice"); - } - protected override IEnumerable RequiredFields() - { - yield return this.extendPriceField; - } - protected override AggregateValue CalculateValue(IAggregateValues aggregateValues) - { - var aggregateValue = aggregateValues.GetAggregateValue(this.extendPriceField); - if (aggregateValue.IsError()) - { - return aggregateValue; - } - double extendedPrice = aggregateValue.ConvertOrDefault(); - if (extendedPrice > 15000) - { - return new DoubleAggregateValue(extendedPrice * 0.1); - } - return null; - } -} - -```` -````VB.NET -Public Class CommissionCalculatedField - Inherits CalculatedField - Private extendPriceField As RequiredField - Public Sub New() - Me.Name = "Commission" - Me.extendPriceField = RequiredField.ForProperty("ExtendedPrice") - End Sub - Protected Overrides Function RequiredFields() As IEnumerable(Of RequiredField) - Return New List(Of RequiredField) From {extendPriceField} - End Function - Protected Overrides Function CalculateValue(aggregateValues As IAggregateValues) As AggregateValue - Dim aggregateValue = aggregateValues.GetAggregateValue(Me.extendPriceField) - If aggregateValue.IsError() Then - Return aggregateValue - End If - Dim extendedPrice As Double = aggregateValue.ConvertOrDefault(Of Double)() - If extendedPrice > 15000 Then - Return New DoubleAggregateValue(extendedPrice * 0.1) - End If - Return Nothing - End Function -End Class - -```` - -{{endregion}} + + + + >caption Figure 1: Calculated Field in RadPivotFieldList @@ -95,28 +39,10 @@ Now it is time to add a new instance of this class to the **CalculatedFields** c #### Adding Calculated Fields -{{source=..\SamplesCS\PivotGrid\PivotGridCalculatedFields.cs region=AddCalculatedField}} -{{source=..\SamplesVB\PivotGrid\PivotGridCalculatedFields.vb region=AddCalculatedField}} - -````C# - using (radPivotGrid1.PivotGridElement.DeferRefresh()) - { - CommissionCalculatedField calculatedField = new CommissionCalculatedField(); - calculatedField.Name = "Commission"; - ((LocalDataSourceProvider)this.radPivotGrid1.DataProvider).CalculatedFields.Add(calculatedField); - } - -```` -````VB.NET -Using radPivotGrid1.PivotGridElement.DeferRefresh() - Dim calculatedField As New CommissionCalculatedField() - calculatedField.Name = "Commission" - DirectCast(Me.radPivotGrid1.DataProvider, LocalDataSourceProvider).CalculatedFields.Add(calculatedField) -End Using + + -```` -{{endregion}} >important If you add calculated fields in code behind, you have to set the __ItemsSource__ of __LocalDataSourceProvider__ after you have added all calculated fields or to wrap the code between (including setting the __ItemsSource__ ) __BeginInit/EndInit__ methods (or inside __using DeferRefresh() { ... }__ section ). > diff --git a/controls/pivotgrid/calculated-items.md b/controls/pivotgrid/calculated-items.md index 4322a5609..e886219b6 100644 --- a/controls/pivotgrid/calculated-items.md +++ b/controls/pivotgrid/calculated-items.md @@ -19,72 +19,17 @@ With __RadPivotGrid__ you are able to create different Groups that will be shown #### Calculated Item -{{source=..\SamplesCS\PivotGrid\PivotGridCalculatedItems.cs region=CalculatedItemClasses}} -{{source=..\SamplesVB\PivotGrid\PivotGridCalculatedItems.vb region=CalculatedItemClasses}} - -````C# -public class MenAverageSales : CalculatedItem -{ - protected override AggregateValue GetValue(IAggregateSummaryValues aggregateSummaryValues) - { - AggregateValue[] aggregateValues = { - aggregateSummaryValues.GetAggregateValue("Andrew Fuller"), - aggregateSummaryValues.GetAggregateValue("Michael Suyama"), - aggregateSummaryValues.GetAggregateValue("Robert King"), - aggregateSummaryValues.GetAggregateValue("Steven Buchanan") - }; - if (aggregateValues.ContainsError()) - { - return AggregateValue.ErrorAggregateValue; - } - double average = aggregateValues.Average(av => av.ConvertOrDefault()); - return new DoubleAggregateValue(average); - } -} - -```` -````VB.NET -Public Class MenAverageSales - Inherits CalculatedItem - Protected Overrides Function GetValue(aggregateSummaryValues As IAggregateSummaryValues) As AggregateValue - Dim aggregateValues As AggregateValue() = {aggregateSummaryValues.GetAggregateValue("Andrew Fuller"), aggregateSummaryValues.GetAggregateValue("Michael Suyama"), aggregateSummaryValues.GetAggregateValue("Robert King"), aggregateSummaryValues.GetAggregateValue("Steven Buchanan")} - If aggregateValues.ContainsError() Then - Return AggregateValue.ErrorAggregateValue - End If - Dim average As Double = aggregateValues.Average(Function(av) av.ConvertOrDefault(Of Double)()) - Return New DoubleAggregateValue(average) - End Function -End Class - -```` - -{{endregion}} + + -As you can see the calculated item will show the average sales of four people. Now we just have to add it to the **PropertyGroupDescription**. In our case this will be the *Salesperson* group: -{{source=..\SamplesCS\PivotGrid\PivotGridCalculatedItems.cs region=AddCalcItemWithoutSortOrder}} -{{source=..\SamplesVB\PivotGrid\PivotGridCalculatedItems.vb region=AddCalcItemWithoutSortOrder}} -````C# -PropertyGroupDescription salesPersonGroupDescription = new PropertyGroupDescription(); -salesPersonGroupDescription.PropertyName = "Salesperson"; -MenAverageSales calculatedItem = new MenAverageSales(); -calculatedItem.GroupName = "Average Sales (Men)"; -salesPersonGroupDescription.CalculatedItems.Add(calculatedItem); -localProvider.ColumnGroupDescriptions.Add(salesPersonGroupDescription); +As you can see the calculated item will show the average sales of four people. Now we just have to add it to the **PropertyGroupDescription**. In our case this will be the *Salesperson* group: -```` -````VB.NET -Dim salesPersonGroupDescription As New PropertyGroupDescription() -salesPersonGroupDescription.PropertyName = "Salesperson" -Dim calculatedItem As New MenAverageSales() -calculatedItem.GroupName = "Average Sales (Men)" -salesPersonGroupDescription.CalculatedItems.Add(calculatedItem) -localProvider.ColumnGroupDescriptions.Add(salesPersonGroupDescription) + + -```` -{{endregion}} >caption Figure 1: RadPivotGrid Calculated Item @@ -96,40 +41,10 @@ Calculated items can be added only to Group Descriptions. If you are using __Rad #### PrepareDescriptionForField Event -{{source=..\SamplesCS\PivotGrid\PivotGridCalculatedItems.cs region=localProvider_PrepareDescriptionForField}} -{{source=..\SamplesVB\PivotGrid\PivotGridCalculatedItems.vb region=localProvider_PrepareDescriptionForField}} - -````C# -void localProvider_PrepareDescriptionForField(object sender, PrepareDescriptionForFieldEventArgs e) -{ - if (e.DescriptionType == DataProviderDescriptionType.Group && e.FieldInfo.DisplayName == "Salesperson") - { - var description = e.Description as Telerik.Pivot.Core.PropertyGroupDescription; - if (description != null) - { - var calculatedItem = new MenAverageSales(); - calculatedItem.GroupName = "Average Sales (Men)"; - description.CalculatedItems.Add(calculatedItem); - } - } -} - -```` -````VB.NET -Private Sub localProvider_PrepareDescriptionForField(sender As Object, e As PrepareDescriptionForFieldEventArgs) - If e.DescriptionType = DataProviderDescriptionType.Group AndAlso e.FieldInfo.DisplayName = "Salesperson" Then - Dim description = TryCast(e.Description, Telerik.Pivot.Core.PropertyGroupDescription) - If description IsNot Nothing Then - Dim calculatedItem = New MenAverageSales() - calculatedItem.GroupName = "Average Sales (Men)" - description.CalculatedItems.Add(calculatedItem) - End If - End If -End Sub - -```` - -{{endregion}} + + + + ## Solve Order @@ -137,45 +52,10 @@ If you have calculated items in both rows and columns group descriptions, you ha #### SolveOrder Property -{{source=..\SamplesCS\PivotGrid\PivotGridCalculatedItems.cs region=AddCalcItemWithSortOrder}} -{{source=..\SamplesVB\PivotGrid\PivotGridCalculatedItems.vb region=AddCalcItemWithSortOrder}} - -````C# -PropertyGroupDescription salesPersonGroupDescription = new PropertyGroupDescription(); -salesPersonGroupDescription.PropertyName = "Salesperson"; -MenAverageSales menAvgSalesCalculatedItem = new MenAverageSales(); -menAvgSalesCalculatedItem .GroupName = "Average Sales (Men)"; -menAvgSalesCalculatedItem .SolveOrder = 1; -salesPersonGroupDescription.CalculatedItems.Add(menAvgSalesCalculatedItem); -PropertyGroupDescription countryGroupDescription = new PropertyGroupDescription(); -countryGroupDescription.PropertyName = "Country"; -CA caCalculatedItem = new CA(); -caCalculatedItem.GroupName = "CA"; -caCalculatedItem.SolveOrder = 2; -countryGroupDescription.CalculatedItems.Add(caCalculatedItem); -localProvider.ColumnGroupDescriptions.Add(salesPersonGroupDescription); -localProvider.RowGroupDescriptions.Add(countryGroupDescription); - -```` -````VB.NET -Dim salesPersonGroupDescription As New PropertyGroupDescription() -salesPersonGroupDescription.PropertyName = "Salesperson" -Dim menAvgSalesCalculatedItem As New MenAverageSales() -menAvgSalesCalculatedItem.GroupName = "Average Sales (Men)" -menAvgSalesCalculatedItem.SolveOrder = 1 -salesPersonGroupDescription.CalculatedItems.Add(menAvgSalesCalculatedItem) -Dim countryGroupDescription As New PropertyGroupDescription() -countryGroupDescription.PropertyName = "Country" -Dim caCalculatedItem As New CA() -caCalculatedItem.GroupName = "CA" -caCalculatedItem.SolveOrder = 2 -countryGroupDescription.CalculatedItems.Add(caCalculatedItem) -localProvider.ColumnGroupDescriptions.Add(salesPersonGroupDescription) -localProvider.RowGroupDescriptions.Add(countryGroupDescription) - -```` - -{{endregion}} + + + + Here is the result: diff --git a/controls/pivotgrid/context-menu.md b/controls/pivotgrid/context-menu.md index d8a340152..1128974da 100644 --- a/controls/pivotgrid/context-menu.md +++ b/controls/pivotgrid/context-menu.md @@ -20,108 +20,17 @@ The PivotGridContextMenuBase.**Context** property provides information about the #### Initialize and Set Custom Menu -{{source=..\SamplesCS\PivotGrid\PivotGridConextMenuForm.cs region=SetContextMenu}} -{{source=..\SamplesVB\PivotGrid\PivotGridConextMenuForm.vb region=SetContextMenu}} -````C# -public PivotGridConextMenuForm() -{ - InitializeComponent(); - MyPivotGridContextMenu menu = new MyPivotGridContextMenu(this.radPivotGrid1); - this.radPivotGrid1.PivotGridElement.ContextMenu = menu; -} + + -```` -````VB.NET -Public Sub New() - InitializeComponent() - Dim menu As New MyPivotGridContextMenu(Me.radPivotGrid1) - Me.radPivotGrid1.PivotGridElement.ContextMenu = menu -End Sub - -```` - - - -{{endregion}} #### Custom Context Menu Class -{{source=..\SamplesCS\PivotGrid\PivotGridConextMenuForm.cs region=CustomContextMenu}} -{{source=..\SamplesVB\PivotGrid\PivotGridConextMenuForm.vb region=CustomContextMenu}} -````C# -public class MyPivotGridContextMenu : PivotGridContextMenu -{ - public MyPivotGridContextMenu(RadPivotGrid pivotGrid) : base(pivotGrid.PivotGridElement) - { - } - - protected override void AdjustItemsForContext() - { - base.AdjustItemsForContext(); - - if (this.Context is PivotCellElement) - { - RadMenuItem customMenuItem = new RadMenuItem(); - customMenuItem.Text = "Export to Excel"; - RadMenuSeparatorItem separator = new RadMenuSeparatorItem(); - this.Items.Add(separator); - customMenuItem.Click += customMenuItem_Click; - this.Items.Add(customMenuItem); - } - } - - private void customMenuItem_Click(object sender, EventArgs e) - { - RadMenuItem item = sender as RadMenuItem; - - if (this.Context is PivotCellElement) - { - PivotCellElement pivotCell = this.Context as PivotCellElement; - RadPivotGrid pivot = pivotCell.ElementTree.Control as RadPivotGrid; - RadMessageBox.Show("Export to Excel"); - } - } -} - -```` -````VB.NET -Public Class MyPivotGridContextMenu - Inherits PivotGridContextMenu - - Public Sub New(ByVal pivotGrid As RadPivotGrid) - MyBase.New(pivotGrid.PivotGridElement) - End Sub - - Protected Overrides Sub AdjustItemsForContext() - MyBase.AdjustItemsForContext() - - If TypeOf Me.Context Is PivotCellElement Then - Dim customMenuItem As RadMenuItem = New RadMenuItem() - customMenuItem.Text = "Export to Excel" - Dim separator As RadMenuSeparatorItem = New RadMenuSeparatorItem() - Me.Items.Add(separator) - customMenuItem.Click += AddressOf customMenuItem_Click - Me.Items.Add(customMenuItem) - End If - End Sub - - Private Sub customMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) - Dim item As RadMenuItem = TryCast(sender, RadMenuItem) - - If TypeOf Me.Context Is PivotCellElement Then - Dim pivotCell As PivotCellElement = TryCast(Me.Context, PivotCellElement) - Dim pivot As RadPivotGrid = TryCast(pivotCell.ElementTree.Control, RadPivotGrid) - RadMessageBox.Show("Export to Excel") - End If - End Sub -End Class - -```` - + + -{{endregion}} # See Also diff --git a/controls/pivotgrid/custom-aggregation.md b/controls/pivotgrid/custom-aggregation.md index 1f916b807..e22599ddb 100644 --- a/controls/pivotgrid/custom-aggregation.md +++ b/controls/pivotgrid/custom-aggregation.md @@ -26,90 +26,10 @@ Our new function will be almost the same as the already available __AggregateFun #### Custom Function Logic -{{source=..\SamplesCS\PivotGrid\SqrtSumAggregateFunction.cs region=AggregateFunction}} -{{source=..\SamplesVB\PivotGrid\SqrtSumAggregateFunction.vb region=AggregateFunction}} -````C# -public class SqrtSumAggregateFunction : Telerik.Pivot.Core.Aggregates.AggregateFunction -{ - public override string DisplayName - { - get { return "Sqrt Of Sum"; } - } - protected override AggregateValue CreateAggregate(Type dataType) - { - return new SqrtSumAggregate(); - } - public override string GetStringFormat(Type dataType, string format) - { - if (format == null) - { - return "G"; - } - return format; - } - public override string ToString() - { - return "Sqrt Of Sum"; - } - public override bool Equals(object obj) - { - return obj is SqrtSumAggregateFunction; - } - protected override void CloneCore(Telerik.Pivot.Core.Cloneable source) - { - } - protected override Telerik.Pivot.Core.Cloneable CreateInstanceCore() - { - return new SqrtSumAggregateFunction(); - } - protected override AggregateValue CreateAggregate(IAggregateContext context) - { - return this.CreateAggregate(context.DataType); - } -} + + -```` -````VB.NET -Imports System.Globalization -Imports Telerik.Pivot.Core -Imports Telerik.Pivot.Core.Aggregates -Public Class SqrtSumAggregateFunction - Inherits Telerik.Pivot.Core.Aggregates.AggregateFunction - Public Overrides ReadOnly Property DisplayName() As String - Get - Return "Sqrt Of Sum" - End Get - End Property - Protected Overrides Function CreateAggregate(dataType As Type) As AggregateValue - Return New SqrtSumAggregate() - End Function - Public Overrides Function GetStringFormat(dataType As Type, format As String) As String - If format Is Nothing Then - Return "G" - End If - Return format - End Function - Public Overrides Function ToString() As String - Return "Sqrt Of Sum" - End Function - Public Overrides Function Equals(obj As Object) As Boolean - Return TypeOf obj Is SqrtSumAggregateFunction - End Function - Protected Overrides Sub CloneCore(source As Telerik.Pivot.Core.Cloneable) - End Sub - Protected Overrides Function CreateInstanceCore() As Telerik.Pivot.Core.Cloneable - Return New SqrtSumAggregateFunction() - End Function - Protected Overrides Function CreateAggregate(context As IAggregateContext) As AggregateValue - Return Me.CreateAggregate(context.DataType) - End Function -End Class -```` - - - -{{endregion}} ## Defining a Custom Aggregate Value @@ -117,97 +37,11 @@ We also need to create a custom aggregate value class which will be used by our #### Custom Aggregate Logic -{{source=..\SamplesCS\PivotGrid\SqrtSumAggregateFunction.cs region=AggregateValue}} -{{source=..\SamplesVB\PivotGrid\SqrtSumAggregateFunction.vb region=AggregateValue}} -````C# -public sealed class SqrtSumAggregate : AggregateValue, IConvertibleAggregateValue -{ - private double sum; - private bool hasError = false; - protected override object GetValueOverride() - { - return Math.Round(Math.Sqrt(this.sum), 2); - } - protected override void AccumulateOverride(object value) - { - this.sum += Convert.ToDouble(value, CultureInfo.InvariantCulture); - } - protected override void MergeOverride(AggregateValue childAggregate) - { - var sumAggregate = childAggregate as SqrtSumAggregate; - if (sumAggregate != null) - { - this.sum += sumAggregate.sum; - } - else - { - double doubleValue; - if (AggregateValueExtensions.TryConvertValue(childAggregate, out doubleValue)) - { - this.sum += doubleValue; - } - else - { - this.sum = 0; - this.hasError = true; - } - } - } - bool IConvertibleAggregateValue.TryConvertValue(out double value) - { - if (this.hasError) - { - value = 0; - return false; - } - value = (double)this.sum; - return true; - } -} - -```` -````VB.NET -Public NotInheritable Class SqrtSumAggregate - Inherits AggregateValue - Implements IConvertibleAggregateValue(Of Double) - Private sum As Double - Private hasError As Boolean = False - Protected Overrides Function GetValueOverride() As Object - Return Math.Round(Math.Sqrt(Me.sum), 2) - End Function - Protected Overrides Sub AccumulateOverride(value As Object) - Me.sum += Convert.ToDouble(value, CultureInfo.InvariantCulture) - End Sub - Protected Overrides Sub MergeOverride(childAggregate As AggregateValue) - Dim sumAggregate = TryCast(childAggregate, SqrtSumAggregate) - If sumAggregate IsNot Nothing Then - Me.sum += sumAggregate.sum - Else - Dim doubleValue As Double - If AggregateValueExtensions.TryConvertValue(Of Double)(childAggregate, doubleValue) Then - Me.sum += doubleValue - Else - Me.sum = 0 - Me.hasError = True - End If - End If - End Sub - Private Function IConvertibleAggregateValue_TryConvertValue(ByRef value As Double) As Boolean Implements IConvertibleAggregateValue(Of Double).TryConvertValue - If Me.hasError Then - value = 0 - Return False - End If - value = CDbl(Me.sum) - Return True - End Function -End Class - -```` + + -{{endregion}} - ## Assigning the Custom Function We can make use of our new function by assigning it to the __AggregateFunction__ property of a __PropertyAggregateDescription__ object before setting it to our pivot. @@ -216,30 +50,10 @@ We can make use of our new function by assigning it to the __AggregateFunction__ #### Using the Custom Aggregate Function -{{source=..\SamplesCS\PivotGrid\PivotGridCustomAggregation.cs region=CustomFunctionUsage}} -{{source=..\SamplesVB\PivotGrid\PivotGridCustomAggregation.vb region=CustomFunctionUsage}} -````C# -LocalDataSourceProvider dataProvider = new LocalDataSourceProvider(); -dataProvider.ItemsSource = dataset.Orders; -dataProvider.AggregateDescriptions.Add(new PropertyAggregateDescription() { PropertyName = "Freight", AggregateFunction = new SqrtSumAggregateFunction() }); -this.radPivotGrid1.DataProvider = dataProvider; - -```` -````VB.NET -Dim dataProvider As New LocalDataSourceProvider() -dataProvider.ItemsSource = dataset.Orders -dataProvider.AggregateDescriptions.Add(New PropertyAggregateDescription() With { _ -.PropertyName = "Freight", _ -.AggregateFunction = New SqrtSumAggregateFunction() _ -}) -Me.RadPivotGrid1.DataProvider = dataProvider - -```` - -{{endregion}} + + -{{endregion}} >important If you add calculated fields in code behind, you have to set the __ItemsSource__ of __LocalDataSourceProvider__ after you have added all calculated fields or to wrap the code between (including setting the __ItemsSource__ ) __BeginInit/EndInit__ methods (or inside __using DeferRefresh() { ... }__ section ). > diff --git a/controls/pivotgrid/customizing-appearance/formatting-appearance.md b/controls/pivotgrid/customizing-appearance/formatting-appearance.md index f9367f8a1..110b2ec18 100644 --- a/controls/pivotgrid/customizing-appearance/formatting-appearance.md +++ b/controls/pivotgrid/customizing-appearance/formatting-appearance.md @@ -23,47 +23,10 @@ Using the **CellFormatting** event you can also set various properties of the ** #### CellFormatting Event -{{source=..\SamplesCS\PivotGrid\PivotGridFormattingAppearance.cs region=CellFormatting}} -{{source=..\SamplesVB\PivotGrid\PivotGridFormattingAppearance.vb region=CellFormatting}} - -````C# -void radPivotGrid1_CellFormatting(object sender, PivotCellEventArgs e) -{ - if (e.CellElement.Row.Name == "August" && !e.CellElement.IsInGrandTotalColumn) - { - e.CellElement.BackColor = Color.LightCyan; - e.CellElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid; - } - else if (e.CellElement.Row.Name == "November" && !e.CellElement.IsInGrandTotalColumn) - { - e.CellElement.BackColor = Color.LightGreen; - e.CellElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid; - } - else - { - e.CellElement.ResetValue(LightVisualElement.BackColorProperty, Telerik.WinControls.ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.GradientStyleProperty, Telerik.WinControls.ValueResetFlags.Local); - } -} - -```` -````VB.NET -Private Sub radPivotGrid1_CellFormatting(sender As Object, e As PivotCellEventArgs) - If e.CellElement.Row.Name = "August" AndAlso Not e.CellElement.IsInGrandTotalColumn Then - e.CellElement.BackColor = Color.LightCyan - e.CellElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid - ElseIf e.CellElement.Row.Name = "November" AndAlso Not e.CellElement.IsInGrandTotalColumn Then - e.CellElement.BackColor = Color.LightGreen - e.CellElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid - Else - e.CellElement.ResetValue(LightVisualElement.BackColorProperty, Telerik.WinControls.ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.GradientStyleProperty, Telerik.WinControls.ValueResetFlags.Local) - End If -End Sub - -```` - -{{endregion}} + + + + ## GroupElementFormatting @@ -74,51 +37,10 @@ The **GroupElementFormatting** event can be used for styling the group cells: #### GroupElementFormatting Event -{{source=..\SamplesCS\PivotGrid\PivotGridFormattingAppearance.cs region=Group}} -{{source=..\SamplesVB\PivotGrid\PivotGridFormattingAppearance.vb region=Group}} - -````C# -void PivotGridElement_GroupElementFormatting(object sender, PivotGroupElementEventArgs e) -{ - if (e.GroupElement.Data.Name == "1996") - { - e.GroupElement.BackColor = Color.LightCyan; - } - else if (e.GroupElement.Data.Name == "1997") - { - e.GroupElement.BackColor = Color.LightGreen; - } - else if (e.GroupElement.Data.Name.Contains("Total")) - { - e.GroupElement.ForeColor = Color.DarkRed; - e.GroupElement.BackColor = Color.White; - } - else - { - e.GroupElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local); - e.GroupElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local); - } -} - -```` -````VB.NET -Private Sub PivotGridElement_GroupElementFormatting(ByVal sender As Object, ByVal e As PivotGroupElementEventArgs) - If e.GroupElement.Data.Name = "1996" Then - e.GroupElement.BackColor = Color.LightCyan - ElseIf e.GroupElement.Data.Name = "1997" Then - e.GroupElement.BackColor = Color.LightGreen - ElseIf e.GroupElement.Data.Name.Contains("Total") Then - e.GroupElement.ForeColor = Color.DarkRed - e.GroupElement.BackColor = Color.White - Else - e.GroupElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local) - e.GroupElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local) - End If -End Sub - -```` - -{{endregion}} + + + + ## ErrorString and EmpltyValueString @@ -126,21 +48,10 @@ Using the __ErrorString__ and __EmpltyValueString__ properties of RadPivotGrid, #### Error and Empty Value Strings -{{source=..\SamplesCS\PivotGrid\PivotGridFormattingAppearance.cs region=SetFormatStrings}} -{{source=..\SamplesVB\PivotGrid\PivotGridFormattingAppearance.vb region=SetFormatStrings}} - -````C# -this.radPivotGrid1.ErrorString = "Error"; -this.radPivotGrid1.EmptyValueString = "No Data"; - -```` -````VB.NET -Me.RadPivotGrid1.ErrorString = "Error" -Me.RadPivotGrid1.EmptyValueString = "No Data" + + -```` -{{endregion}} # See Also diff --git a/controls/pivotgrid/dialogs/custom-dialogs.md b/controls/pivotgrid/dialogs/custom-dialogs.md index 2c9ef7d4c..4e0f118c8 100644 --- a/controls/pivotgrid/dialogs/custom-dialogs.md +++ b/controls/pivotgrid/dialogs/custom-dialogs.md @@ -23,93 +23,28 @@ The functions list displayed in the dialog can be modified. It can also be exten >note The [Custom Aggregation]({%slug winforms/pivotgrid/custom-aggregation%}) article discusses in details the API for creating custom functions as well as it includes the source code of the custom function used below. -{{source=..\SamplesCS\PivotGrid\PivotGridDialogs.cs region=MyAggregateOptionsDialog}} -{{source=..\SamplesVB\PivotGrid\PivotGridDialogs.vb region=MyAggregateOptionsDialog}} -````C# -class MyAggregateOptionsDialog : AggregateOptionsDialog -{ - public override void LoadSettings(Telerik.Pivot.Core.PropertyAggregateDescriptionBase aggregateDescription) - { - base.LoadSettings(aggregateDescription); - this.Text = "This is a custom dialog"; - } - protected override IEnumerable GetDefaultAggregateFunctions(AggregateDescriptionBase aggregateDescription) - { - IEnumerable functions = base.GetDefaultAggregateFunctions(aggregateDescription); - IEnumerable customFunctions = functions.Concat(new List { new SqrtSumAggregateFunction() }); - return customFunctions; - } -} - -```` -````VB.NET -Class MyAggregateOptionsDialog - Inherits AggregateOptionsDialog - Public Overrides Sub LoadSettings(aggregateDescription As Telerik.Pivot.Core.PropertyAggregateDescriptionBase) - MyBase.LoadSettings(aggregateDescription) - Me.Text = "This is a custom dialog" - End Sub - Protected Overrides Function GetDefaultAggregateFunctions(ByVal aggregateDescription As AggregateDescriptionBase) As IEnumerable(Of Object) - Dim functions As IEnumerable(Of Object) = MyBase.GetDefaultAggregateFunctions(aggregateDescription) - Dim customFunctions As IEnumerable(Of Object) = functions.Concat(New List(Of Object) From {New SqrtSumAggregateFunction()}) - Return customFunctions - End Function -End Class - -```` - - - -{{endregion}} + + -When RadPivotGrid and **RadPivotFieldList** need a dialog, they use the __PivotGridDialogsFactory__ to create an instance of a dialog. To replace the default dialogs with your custom ones, you need to implement a custom factory as show below. -#### Custom PivotGridDialogsFactory -{{source=..\SamplesCS\PivotGrid\PivotGridDialogs.cs region=MyDialogsFactory}} -{{source=..\SamplesVB\PivotGrid\PivotGridDialogs.vb region=MyDialogsFactory}} +When RadPivotGrid and **RadPivotFieldList** need a dialog, they use the __PivotGridDialogsFactory__ to create an instance of a dialog. To replace the default dialogs with your custom ones, you need to implement a custom factory as show below. -````C# -class MyDialogsFactory : PivotGridDialogsFactory -{ - public override IAggregateOptionsDialog CreateAggregateOptionsDialog() - { - return new MyAggregateOptionsDialog(); - } -} +#### Custom PivotGridDialogsFactory -```` -````VB.NET -Class MyDialogsFactory - Inherits PivotGridDialogsFactory - Public Overrides Function CreateAggregateOptionsDialog() As IAggregateOptionsDialog - Return New MyAggregateOptionsDialog() - End Function -End Class + + -```` -{{endregion}} Then, you need to assign it to RadPivotGrid and RadPivotFieldList: #### Set Custom Factory -{{source=..\SamplesCS\PivotGrid\PivotGridDialogs.cs region=SetFactories}} -{{source=..\SamplesVB\PivotGrid\PivotGridDialogs.vb region=SetFactories}} - -````C# -this.radPivotGrid1.DialogsFactory = new MyDialogsFactory(); -this.radPivotFieldList1.DialogsFactory = new MyDialogsFactory(); - -```` -````VB.NET -Me.radPivotGrid1.DialogsFactory = New MyDialogsFactory() -Me.radPivotFieldList1.DialogsFactory = New MyDialogsFactory() + + -```` -{{endregion}} # See Also diff --git a/controls/pivotgrid/drilldown.md b/controls/pivotgrid/drilldown.md index 5ce4026db..fc66fb3d9 100644 --- a/controls/pivotgrid/drilldown.md +++ b/controls/pivotgrid/drilldown.md @@ -22,45 +22,10 @@ In the example below we will handle RadPivotGrid.__MouseDoubleClick__ event and #### GetUnderlyingData Method -{{source=..\SamplesCS\PivotGrid\PivotGridDrillDownForm.cs region=GetUnderlyingDataMethod}} -{{source=..\SamplesVB\PivotGrid\PivotGridDrillDownForm.vb region=GetUnderlyingDataMethod}} -````C# -private void radPivotGrid1_MouseDoubleClick(object sender, MouseEventArgs e) -{ - if (e.Button == MouseButtons.Left) - { - RadPivotGrid pivotGrid = (RadPivotGrid)sender; - PivotCellElement cell = pivotGrid.ElementTree.GetElementAtPoint(e.Location) as PivotCellElement; - if (cell != null) - { - var row = cell.Row.Group; - var column = cell.Column.Group; - LocalDataSourceProvider localProvider = pivotGrid.DataProvider as LocalDataSourceProvider; - localProvider.GetUnderlyingData(row, column); - } - } -} - -```` -````VB.NET -Private Sub radPivotGrid1_MouseDoubleClick(sender As Object, e As MouseEventArgs) - If e.Button = MouseButtons.Left Then - Dim pivotGrid As RadPivotGrid = DirectCast(sender, RadPivotGrid) - Dim cell As PivotCellElement = TryCast(pivotGrid.ElementTree.GetElementAtPoint(e.Location), PivotCellElement) - If cell IsNot Nothing Then - Dim row = cell.Row.Group - Dim column = cell.Column.Group - Dim localProvider As LocalDataSourceProvider = TryCast(pivotGrid.DataProvider, LocalDataSourceProvider) - localProvider.GetUnderlyingData(row, column) - End If - End If -End Sub - -```` - - - -{{endregion}} + + + + The underlying data can be retrieved by handling the __GetUnderlyingDataCompleted__ event and accessing the __DrillDownCompletedEventArgs__ arguments: @@ -73,37 +38,10 @@ The underlying data can be retrieved by handling the __GetUnderlyingDataComplete #### GetUnderlyingDataCompleted Event -{{source=..\SamplesCS\PivotGrid\PivotGridDrillDownForm.cs region=GetUnderlyingDataCompletedEvent}} -{{source=..\SamplesVB\PivotGrid\PivotGridDrillDownForm.vb region=GetUnderlyingDataCompletedEvent}} -````C# -private void provider_GetUnderlyingDataCompleted(object sender, Telerik.Pivot.Core.DrillDown.DrillDownCompletedEventArgs e) -{ - IEnumerable underlyingData = e.Result; - this.radGridView1.BeginInvoke(new Action(() => - { - if (e.InnerExceptions.Count == 0) - { - this.radGridView1.DataSource = underlyingData; - } - })); -} - -```` -````VB.NET -Private Sub provider_GetUnderlyingDataCompleted(sender As Object, e As Telerik.Pivot.Core.DrillDown.DrillDownCompletedEventArgs) - Dim underlyingData As IEnumerable = e.Result - Me.radGridView1.BeginInvoke(New Action(Function() - If e.InnerExceptions.Count = 0 Then - Me.radGridView1.DataSource = underlyingData - End If - End Function)) -End Sub - -```` - - - -{{endregion}} + + + + # See Also diff --git a/controls/pivotgrid/expand-behavior.md b/controls/pivotgrid/expand-behavior.md index 8179be96f..66a1b8dab 100644 --- a/controls/pivotgrid/expand-behavior.md +++ b/controls/pivotgrid/expand-behavior.md @@ -36,28 +36,10 @@ __RadPivotGrid__ has two properties to control the expand behavior - __RowGroups #### Expanding Groups -{{source=..\SamplesCS\PivotGrid\ExpandBehavior.cs region=expand}} -{{source=..\SamplesVB\PivotGrid\ExpandBehavior.vb region=expand}} + + -````C# - -RadPivotGrid pivot = new RadPivotGrid(); -pivot.RowGroupsExpandBehavior = new GroupsExpandBehavior() -{ - Expanded = false, - UpToLevel = 2 -}; -pivot.ColumnGroupsExpandBehavior = new GroupsExpandBehavior() { Expanded = false }; -```` -````VB.NET -Dim pivot As New RadPivotGrid() -pivot.RowGroupsExpandBehavior = New GroupsExpandBehavior() With {.Expanded = False, .UpToLevel = 2} -pivot.ColumnGroupsExpandBehavior = New GroupsExpandBehavior() With {.Expanded = False} - -```` - -{{endregion}} ## Change Behavior at Run-time @@ -65,41 +47,10 @@ If you want to collapse all groups in __RadPivotGrid__ you can change the behavi #### Changing Expand Behavior -{{source=..\SamplesCS\PivotGrid\ExpandBehavior.cs region=click}} -{{source=..\SamplesVB\PivotGrid\ExpandBehavior.vb region=click}} - -````C# - -public void ExpandGroupsButton_Click(object sender, RoutedEventArgs e) -{ - (this.pivot.RowGroupsExpandBehavior as GroupsExpandBehavior).Expanded = true; - (this.pivot.ColumnGroupsExpandBehavior as GroupsExpandBehavior).Expanded = true; - this.pivot.DataProvider.Refresh(); -} - -private void CollapseGroupsButton_Click(object sender, RoutedEventArgs e) -{ - (this.pivot.RowGroupsExpandBehavior as GroupsExpandBehavior).Expanded = false; - (this.pivot.ColumnGroupsExpandBehavior as GroupsExpandBehavior).Expanded = false; - this.pivot.DataProvider.Refresh(); -} - -```` -````VB.NET -Public Sub ExpandGroupsButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) - TryCast(Me.pivot.RowGroupsExpandBehavior, GroupsExpandBehavior).Expanded = True - TryCast(Me.pivot.ColumnGroupsExpandBehavior, GroupsExpandBehavior).Expanded = True - Me.pivot.DataProvider.Refresh() -End Sub -Private Sub CollapseGroupsButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) - TryCast(Me.pivot.RowGroupsExpandBehavior, GroupsExpandBehavior).Expanded = False - TryCast(Me.pivot.ColumnGroupsExpandBehavior, GroupsExpandBehavior).Expanded = False - Me.pivot.DataProvider.Refresh() -End Sub - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/pivotgrid/exporting-data/export-to-excel-via-excelml-format.md b/controls/pivotgrid/exporting-data/export-to-excel-via-excelml-format.md index 329ef168d..be6043bee 100644 --- a/controls/pivotgrid/exporting-data/export-to-excel-via-excelml-format.md +++ b/controls/pivotgrid/exporting-data/export-to-excel-via-excelml-format.md @@ -21,113 +21,46 @@ This method offers exporting functionality and does not require MS Office instal Before running export to ExcelML, you have to initialize the PivotExportToExcelML class. The constructor takes one parameter: the **RadPivotGrid** that will be exported: -{{source=..\SamplesCS\PivotGrid\PivotGridExport.cs region=ExportToExcelIMLInitialization}} -{{source=..\SamplesVB\PivotGrid\PivotGridExport.vb region=ExportToExcelIMLInitialization}} + + -````C# -PivotExportToExcelML exporter = new PivotExportToExcelML(this.radPivotGrid1); -```` -````VB.NET -Dim exporter As PivotExportToExcelML = New PivotExportToExcelML(Me.radPivotGrid1) - -```` - -{{endregion}} ## Exporting Visual Settings Using the PivotExcelML method allows you to export the visual settings (themes) to the Excel file. ExcelML has also a visual representation of the alternating column color. The row height is exported with the default DPI transformation (60pixels = 72points). You can enable exporting visual settings through the ExportVisualSettings property. By default the value of this property is true: -{{source=..\SamplesCS\PivotGrid\PivotGridExport.cs region=SettingExportVisualSettings}} -{{source=..\SamplesVB\PivotGrid\PivotGridExport.vb region=SettingExportVisualSettings}} - -````C# -exporter.ExportVisualSettings = true; + + -```` -````VB.NET -exporter.ExportVisualSettings = True -```` - -{{endregion}} ## Setting the sheet name You can specify the sheet name through __SheetName__ property. If your data is large enough to be split on more than one sheet, then the export method adds index to the names of the next sheets. -{{source=..\SamplesCS\PivotGrid\PivotGridExport.cs region=SettingTheSheetName}} -{{source=..\SamplesVB\PivotGrid\PivotGridExport.vb region=SettingTheSheetName}} - -````C# -exporter.SheetName = "Sheet"; + + -```` -````VB.NET -exporter.SheetName = "Sheet" -```` - -{{endregion}} ## RunExport method Exporting data to Excel is done through the __RunExport__ method of __PivotExportToExcelML__ object. The RunExport method accepts a string parameter with a valid file path. Consider the code sample below: -{{source=..\SamplesCS\PivotGrid\PivotGridExport.cs region=ExportToExcelInExcelMLFormat}} -{{source=..\SamplesVB\PivotGrid\PivotGridExport.vb region=ExportToExcelInExcelMLFormat}} - -````C# -string fileName = "c:\\Sheet1.xls"; -exporter.RunExport(fileName); - -```` -````VB.NET -Dim fileName As String = "c:\Sheet1.xls" -exporter.RunExport(fileName) + + -```` -{{endregion}} ## Events __ExcelCellFormating__ event: It gives an access to a single cell’s __SingleStyleElement__ that allows you to make additional formatting (adding border, setting alignment, text font, colors, changing cell value, etc.) for every excel cell related to the exported RadPivotGrid: -{{source=..\SamplesCS\PivotGrid\PivotGridExport.cs region=ExcelCellFormating}} -{{source=..\SamplesVB\PivotGrid\PivotGridExport.vb region=ExcelCellFormating}} - -````C# -void exporter_PivotExcelCellFormatting(object sender, Telerik.WinControls.UI.Export.ExcelPivotCellExportingEventArgs e) -{ - decimal value = 0; - if (decimal.TryParse(e.Cell.Text, out value)) - { - if(value>1000) - e.Cell.BackColor = System.Drawing.Color.Red; - if (value < 100) - e.Cell.BackColor = System.Drawing.Color.Green; - } -} - -```` -````VB.NET -Private Sub exporter_PivotExcelCellFormatting(sender As Object, e As Telerik.WinControls.UI.Export.ExcelPivotCellExportingEventArgs) - Dim value As Decimal = 0 - If Decimal.TryParse(e.Cell.Text, value) Then - If value > 1000 Then - e.Cell.BackColor = System.Drawing.Color.Red - End If - If value < 100 Then - e.Cell.BackColor = System.Drawing.Color.Green - End If - End If -End Sub - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/pivotgrid/exporting-data/export-to-pdf.md b/controls/pivotgrid/exporting-data/export-to-pdf.md index b8ebcf134..d9c123a94 100644 --- a/controls/pivotgrid/exporting-data/export-to-pdf.md +++ b/controls/pivotgrid/exporting-data/export-to-pdf.md @@ -26,59 +26,19 @@ Before exporting to PDF, you have to initialize the __PivotGridPdfExport__ class #### PivotGridPdfExport Class -{{source=..\SamplesCS\Pivotgrid\PdfExportCode.cs region=RunExport}} -{{source=..\SamplesVB\Pivotgrid\PdfExportCode.vb region=Runexport}} + + -````C# -PivotGridPdfExport exporter = new PivotGridPdfExport(radPivotGrid1); -PdfExportRenderer renderer = new PdfExportRenderer(); -exporter.RunExport(@"C:\PivotData.pdf", renderer); -```` -````VB.NET -Dim exporter As New PivotGridPdfExport(radPivotGrid1) -Dim renderer As New PdfExportRenderer() -exporter.RunExport("C:\PivotData.pdf", renderer) - -```` - -{{endregion}} The __RunExport__ method has several overloads allowing the user to export using a stream as well: #### Running Export Synchronously Using a Stream -{{source=..\SamplesCS\Pivotgrid\PdfExportCode.cs region=StreamRunExport}} -{{source=..\SamplesVB\Pivotgrid\PdfExportCode.vb region=StreamRunExport}} - -````C# -string exportFile = @"..\..\exportedData.pdf"; -using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) -{ - Telerik.WinControls.Export.PivotGridPdfExport pdfExporter = new Telerik.WinControls.Export.PivotGridPdfExport(radPivotGrid1); - Telerik.WinControls.Export.PdfExportRenderer pdfRenderer = new Telerik.WinControls.Export.PdfExportRenderer(); - pdfExporter.RunExport(ms, pdfRenderer); - using (System.IO.FileStream fileStream = new System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write)) - { - ms.WriteTo(fileStream); - } -} - -```` -````VB.NET -Dim exportFile As String = "..\..\exportedData.pdf" -Using ms As New System.IO.MemoryStream() - Dim pdfExporter As New Telerik.WinControls.Export.PivotGridPdfExport(radPivotGrid1) - Dim pdfRenderer As New Telerik.WinControls.Export.PdfExportRenderer() - pdfExporter.RunExport(ms, pdfRenderer) - Using fileStream As New System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write) - ms.WriteTo(fileStream) - End Using -End Using - -```` - -{{endregion}} + + + + ## Properties @@ -120,77 +80,19 @@ The __PivotGrid__ can be exported asynchronously as well. The following example #### Running Export Asynchronously -{{source=..\SamplesCS\Pivotgrid\PdfExportCode.cs region=Async}} -{{source=..\SamplesVB\Pivotgrid\PdfExportCode.vb region=Async}} + + -````C# - -PivotGridPdfExport exporter = new PivotGridPdfExport(radPivotGrid1); -PdfExportRenderer renderer = new PdfExportRenderer(); -exporter.RunExportAsync(@"C:\PivotData.pdf", renderer); -```` -````VB.NET -Dim exporter As New PivotGridPdfExport(radPivotGrid1) -Dim renderer As New PdfExportRenderer() -exporter.RunExportAsync("C:\PivotData.pdf", renderer) - -```` - -{{endregion}} The __RunExportAsync__ method has several overloads allowing the user to export using a stream as well: #### Running Export Asynchronously Overloads -{{source=..\SamplesCS\Pivotgrid\PdfExportCode.cs region=StreamRunExportAsync}} -{{source=..\SamplesVB\Pivotgrid\PdfExportCode.vb region=StreamRunExportAsync}} - -````C# - -private void buttonRunExportAsync_Click(object sender, EventArgs e) -{ - System.IO.MemoryStream ms = new System.IO.MemoryStream(); - Telerik.WinControls.Export.PivotGridPdfExport exporter = new Telerik.WinControls.Export.PivotGridPdfExport(radPivotGrid1); - Telerik.WinControls.Export.PdfExportRenderer renderer = new Telerik.WinControls.Export.PdfExportRenderer(); - exporter.AsyncExportCompleted += exporter_AsyncExportCompleted; - exporter.RunExportAsync(ms, renderer); -} - -private void exporter_AsyncExportCompleted(object sender, AsyncCompletedEventArgs e) -{ - RunWorkerCompletedEventArgs args = e as RunWorkerCompletedEventArgs; - string exportFile = @"..\..\exportedAsyncData.pdf"; - using (System.IO.FileStream fileStream = new System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write)) - { - MemoryStream ms = args.Result as MemoryStream; - ms.WriteTo(fileStream); - ms.Close(); - } -} - -```` -````VB.NET -Private Sub buttonRunExportAsync_Click(sender As Object, e As EventArgs) - Dim ms As New System.IO.MemoryStream() - Dim exporter As New Telerik.WinControls.Export.PivotGridPdfExport(radPivotGrid1) - Dim renderer As New Telerik.WinControls.Export.PdfExportRenderer() - AddHandler exporter.AsyncExportCompleted, AddressOf exporter_AsyncExportCompleted - exporter.RunExportAsync(ms, renderer) -End Sub -Private Sub exporter_AsyncExportCompleted(sender As Object, e As AsyncCompletedEventArgs) - Dim args As RunWorkerCompletedEventArgs = TryCast(e, RunWorkerCompletedEventArgs) - Dim exportFile As String = "..\..\exportedAsyncData.pdf" - Using fileStream As New System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write) - Dim ms As MemoryStream = TryCast(args.Result, MemoryStream) - ms.WriteTo(fileStream) - ms.Close() - End Using -End Sub - -```` - -{{endregion}} + + + + There are two events that can be used with the asynchronous export: diff --git a/controls/pivotgrid/exporting-data/spread-export.md b/controls/pivotgrid/exporting-data/spread-export.md index c33c24a54..ffb86b8c9 100644 --- a/controls/pivotgrid/exporting-data/spread-export.md +++ b/controls/pivotgrid/exporting-data/spread-export.md @@ -49,131 +49,35 @@ To use the spread export functionality, an instance of the __PivotGridSpreadExpo #### Running Export Synchronously -{{source=..\SamplesCS\PivotGrid\PivotSpreadExport.cs region=ExportingData}} -{{source=..\SamplesVB\PivotGrid\PivotSpreadExport.vb region=ExportingData}} + + -````C# - -PivotGridSpreadExport spreadExport = new PivotGridSpreadExport(this.radPivotGrid1); -spreadExport.RunExport(@"..\..\exported-file.xlsx", new SpreadExportRenderer()); -```` -````VB.NET -Dim spreadExport As New PivotGridSpreadExport(Me.RadPivotGrid1) -spreadExport.RunExport("..\..\exported-file.xlsx", New SpreadExportRenderer()) - -```` - -{{endregion}} The __RunExport__ method has several overloads allowing the user to export using a stream as well: #### Running Export Synchronously Using a Stream -{{source=..\SamplesCS\PivotGrid\PivotSpreadExport.cs region=StreamRunExport}} -{{source=..\SamplesVB\PivotGrid\PivotSpreadExport.vb region=StreamRunExport}} - -````C# - -string exportFile = @"..\..\exportedData.xlsx"; -using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) -{ - Telerik.WinControls.Export.PivotGridSpreadExport exporter = new Telerik.WinControls.Export.PivotGridSpreadExport(this.radPivotGrid1); - Telerik.WinControls.Export.SpreadExportRenderer renderer = new Telerik.WinControls.Export.SpreadExportRenderer(); - exporter.RunExport(ms, renderer); - - using (System.IO.FileStream fileStream = new System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write)) - { - ms.WriteTo(fileStream); - } -} - -```` -````VB.NET -Dim exportFile As String = "..\..\exportedData.xlsx" -Using ms As New System.IO.MemoryStream() - Dim exporter As New Telerik.WinControls.Export.PivotGridSpreadExport(Me.RadPivotGrid1) - Dim renderer As New Telerik.WinControls.Export.SpreadExportRenderer() - exporter.RunExport(ms, renderer) - Using fileStream As New System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write) - ms.WriteTo(fileStream) - End Using -End Using - -```` - -{{endregion}} + + -#### Running Export Asynchronously -{{source=..\SamplesCS\PivotGrid\PivotSpreadExport.cs region=ExportingDataAsync}} -{{source=..\SamplesVB\PivotGrid\PivotSpreadExport.vb region=ExportingDataAsync}} -````C# -PivotGridSpreadExport spreadExport = new PivotGridSpreadExport(this.radPivotGrid1); -spreadExport.RunExportAsync(@"..\..\exported-file.xlsx", new SpreadExportRenderer()); +#### Running Export Asynchronously -```` -````VB.NET -Dim spreadExport As New PivotGridSpreadExport(Me.RadPivotGrid1) -spreadExport.RunExportAsync("..\..\exported-file.xlsx", New SpreadExportRenderer()) + + -```` -{{endregion}} The __RunExportAsync__ method has several overloads allowing the user to export using a stream as well: #### Running Export Asynchronously Overloads -{{source=..\SamplesCS\PivotGrid\PivotSpreadExport.cs region=StreamRunExportAsync}} -{{source=..\SamplesVB\PivotGrid\PivotSpreadExport.vb region=StreamRunExportAsync}} + + + -````C# - -private void buttonRunExportAsync_Click(object sender, EventArgs e) -{ - System.IO.MemoryStream ms = new System.IO.MemoryStream(); - Telerik.WinControls.Export.PivotGridSpreadExport exporter = new Telerik.WinControls.Export.PivotGridSpreadExport(this.radPivotGrid1); - Telerik.WinControls.Export.SpreadExportRenderer renderer = new Telerik.WinControls.Export.SpreadExportRenderer(); - exporter.AsyncExportCompleted += exporter_AsyncExportCompleted; - exporter.RunExportAsync(ms, renderer); -} - -private void exporter_AsyncExportCompleted(object sender, AsyncCompletedEventArgs e) -{ - RunWorkerCompletedEventArgs args = e as RunWorkerCompletedEventArgs; - string exportFile = @"..\..\exportedAsyncData.xlsx"; - using (System.IO.FileStream fileStream = new System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write)) - { - MemoryStream ms = args.Result as MemoryStream; - ms.WriteTo(fileStream); - ms.Close(); - } -} - -```` -````VB.NET -Private Sub buttonRunExportAsync_Click(sender As Object, e As EventArgs) - Dim ms As New System.IO.MemoryStream() - Dim exporter As New Telerik.WinControls.Export.PivotGridSpreadExport(Me.RadPivotGrid1) - Dim renderer As New Telerik.WinControls.Export.SpreadExportRenderer() - AddHandler exporter.AsyncExportCompleted, AddressOf exporter_AsyncExportCompleted - exporter.RunExportAsync(ms, renderer) -End Sub -Private Sub exporter_AsyncExportCompleted(sender As Object, e As AsyncCompletedEventArgs) - Dim args As RunWorkerCompletedEventArgs = TryCast(e, RunWorkerCompletedEventArgs) - Dim exportFile As String = "..\..\exportedAsyncData.xlsx" - Using fileStream As New System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write) - Dim ms As MemoryStream = TryCast(args.Result, MemoryStream) - ms.WriteTo(fileStream) - ms.Close() - End Using -End Sub - -```` - -{{endregion}} ## Properties @@ -224,34 +128,10 @@ This is how the displayed in Fig. 1 pivot grid looks after handling the __CellFo #### CellFormatting Event -{{source=..\SamplesCS\PivotGrid\PivotSpreadExport.cs region=Events}} -{{source=..\SamplesVB\PivotGrid\PivotSpreadExport.vb region=Events}} - -````C# - -private void spreadExport_CellFormatting(object sender, PivotGridSpreadExportCellFormattingEventArgs e) -{ - if (e.ColumnIndex % 2 == 0 && e.RowIndex % 2 != 0) - { - e.Cell.BackColor = Color.LightBlue; - e.Cell.ForeColor = Color.Black; - e.Cell.BorderColor = Color.Black; - } -} - -```` -````VB.NET -Private Sub spreadExport_CellFormatting(sender As Object, e As PivotGridSpreadExportCellFormattingEventArgs) - If e.ColumnIndex Mod 2 = 0 AndAlso e.RowIndex Mod 2 <> 0 Then - e.Cell.BackColor = Color.LightBlue - e.Cell.ForeColor = Color.Black - e.Cell.BorderColor = Color.Black - End If -End Sub - -```` - -{{endregion}} + + + + __WorkbookCreated__: This event is triggered on the __SpreadExportRenderer__ object when the workbook is ready to be exported. Allows to introduce final customizations. diff --git a/controls/pivotgrid/filtering/group-filters.md b/controls/pivotgrid/filtering/group-filters.md index 476b03649..efff7a1e6 100644 --- a/controls/pivotgrid/filtering/group-filters.md +++ b/controls/pivotgrid/filtering/group-filters.md @@ -21,19 +21,10 @@ Group filtering is enabled by default. To enable or disable it use the following #### AllowGroupFiltering -{{source=..\SamplesCS\PivotGrid\Filtering\PivotGridGroupFiltering.cs region=AllowGroupFiltering}} -{{source=..\SamplesVB\PivotGrid\Filtering\PivotGridGroupFiltering.vb region=AllowGroupFiltering}} + + -````C# -this.radPivotGrid1.AllowGroupFiltering = true; -```` -````VB.NET -Me.radPivotGrid1.AllowGroupFiltering = True - -```` - -{{endregion}} The end-user can apply group filters using the filter button in the group descriptor elements or via the drop-down menus of the group fields in [RadPivotFieldList]({%slug winforms/pivotgrid/pivot-field-list/radpivotfieldlist%}). The filtering options are similar to the options of the __Report Filters__ with the addition of the __Top10 value filters__. The Top10 filters allow you to select only the top/bottom groups from the order sorted by a given group value. @@ -41,30 +32,10 @@ The end-user can apply group filters using the filter button in the group descri Group filters can be applied to group descriptions by using their __GroupFilter__ property as demonstrated in the following code snippet: -{{source=..\SamplesCS\PivotGrid\Filtering\PivotGridGroupFiltering.cs region=PropertyGroupDescription}} -{{source=..\SamplesVB\PivotGrid\Filtering\PivotGridGroupFiltering.vb region=PropertyGroupDescription}} - -````C# -PropertyGroupDescriptionBase description = (PropertyGroupDescriptionBase)this.radPivotGrid1.RowGroupDescriptions[0]; -LabelGroupFilter filter = new LabelGroupFilter(); -ComparisonCondition condition = new ComparisonCondition(); -condition.Condition = Telerik.Pivot.Core.Filtering.Comparison.Equals; -condition.Than = "UK"; -filter.Condition = condition; -description.GroupFilter = filter; - -```` -````VB.NET -Dim description As PropertyGroupDescriptionBase = Me.radPivotGrid1.RowGroupDescriptions(0) -Dim filter As New LabelGroupFilter() -Dim condition As New ComparisonCondition() -condition.Condition = Telerik.Pivot.Core.Filtering.Comparison.Equals -condition.Than = "UK" -filter.Condition = condition - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/pivotgrid/filtering/report-filters.md b/controls/pivotgrid/filtering/report-filters.md index 357c8f5b0..480da66e5 100644 --- a/controls/pivotgrid/filtering/report-filters.md +++ b/controls/pivotgrid/filtering/report-filters.md @@ -21,19 +21,10 @@ The report filters are displayed as descriptor elements in the report filters ar #### ShowFilterArea Property -{{source=..\SamplesCS\PivotGrid\Filtering\PivotGridReportFiltering.cs region=ShowFilterArea}} -{{source=..\SamplesVB\PivotGrid\Filtering\PivotGridReportFiltering.vb region=ShowFilterArea}} + + -````C# -this.radPivotGrid1.ShowFilterArea = true; -```` -````VB.NET -Me.radPivotGrid1.ShowFilterArea = True - -```` - -{{endregion}} The end-user can add/remove report filters by dragging a field to the report filters area or by using the [RadPivotFieldList]({%slug winforms/pivotgrid/pivot-field-list/radpivotfieldlist%}). Additionally, the filter menu opened by the filter button on the filter descriptor elements allows applying different filter conditions. This can be achieved by either selecting/deselecting items from the list box or by using one of the well-known filtering functions (Equals, Contains, Between, etc.). @@ -49,59 +40,19 @@ The contents of the **FilterDescriptions** collection can also be edited at runt #### Filter Descriptions at Run-time -{{source=..\SamplesCS\PivotGrid\Filtering\PivotGridReportFiltering.cs region=PropertyFilterDescription}} -{{source=..\SamplesVB\PivotGrid\Filtering\PivotGridReportFiltering.vb region=PropertyFilterDescription}} - -````C# -PropertyFilterDescription description = new PropertyFilterDescription(); -ComparisonCondition condition = new ComparisonCondition(); -condition.Condition = Comparison.Equals; -condition.Than = "UK"; -description.PropertyName = "ShipCountry"; -description.Condition = condition; -description.CustomName = "Country"; -this.radPivotGrid1.FilterDescriptions.Add(description); - -```` -````VB.NET -Dim description As New PropertyFilterDescription() -Dim condition As New ComparisonCondition() -condition.Condition = Telerik.Pivot.Core.Filtering.Comparison.Equals -condition.Than = "UK" -description.PropertyName = "ShipCountry" -description.Condition = condition -description.CustomName = "Country" -Me.radPivotGrid1.FilterDescriptions.Add(description) - -```` - -{{endregion}} + + -The __Condition__ property of the __PropertyFilterDescription__ holds the currently applied condition. It can be set with a __ComparisonCondition__ instance as shown above or a __SetCondition__ which allows you to include/exclude specific values: -#### Applying Condition -{{source=..\SamplesCS\PivotGrid\Filtering\PivotGridReportFiltering.cs region=SetCondition}} -{{source=..\SamplesVB\PivotGrid\Filtering\PivotGridReportFiltering.vb region=SetCondition}} +The __Condition__ property of the __PropertyFilterDescription__ holds the currently applied condition. It can be set with a __ComparisonCondition__ instance as shown above or a __SetCondition__ which allows you to include/exclude specific values: -````C# -SetCondition setCondition = new SetCondition(); -setCondition.Comparison = SetComparison.Includes; -setCondition.Items.Add("UK"); -setCondition.Items.Add("Canada"); -setCondition.Items.Add("USA"); +#### Applying Condition -```` -````VB.NET -Dim setCondition As New SetCondition() -setCondition.Comparison = SetComparison.Includes -setCondition.Items.Add("UK") -setCondition.Items.Add("Canada") -setCondition.Items.Add("USA") + + -```` -{{endregion}} # See Also diff --git a/controls/pivotgrid/iterating-cells.md b/controls/pivotgrid/iterating-cells.md index 84d2e7574..ac7772bbc 100644 --- a/controls/pivotgrid/iterating-cells.md +++ b/controls/pivotgrid/iterating-cells.md @@ -15,71 +15,17 @@ To iterate thought the cells in __RadPivotGrid__ you should first retrieve all r #### Iterating Cells -{{source=..\SamplesCS\PivotGrid\IteratingCells.cs region=IterateCells}} -{{source=..\SamplesVB\PivotGrid\PivotIteratingCells.vb region=IterateCells}} + + -````C# - -var rowGroups = radPivotGrid1.PivotGridElement.GetRowGroups(); -var colGroups = radPivotGrid1.PivotGridElement.GetColumnGroups(); -foreach (PivotGroupNode col in colGroups) -{ - foreach (PivotGroupNode row in rowGroups) - { - if (row.Group != null && col.Group != null) - { - var Value = this.radPivotGrid1.PivotGridElement.GetAggregateValue(row.Group, col.Group, false, false); - Debug.WriteLine("Row = {0} , Column ={1}, Value ={2}", row.Name, col.Name, Value); - } - } -} -```` -````VB.NET -Dim rowGroups = radPivotGrid1.PivotGridElement.GetRowGroups() -Dim colGroups = radPivotGrid1.PivotGridElement.GetColumnGroups() -For Each col As PivotGroupNode In colGroups - For Each row As PivotGroupNode In rowGroups - If row.Group IsNot Nothing AndAlso col.Group IsNot Nothing Then - Dim Value = Me.radPivotGrid1.PivotGridElement.GetAggregateValue(row.Group, col.Group, False, False) - Debug.WriteLine("Row = {0} , Column ={1}, Value ={2}", row.Name, col.Name, Value) - End If - Next row -Next col - -```` - -{{endregion}} Using the above approach you can determine if a cell is selected or programmatically select it as well: #### Selecting Cells -{{source=..\SamplesCS\PivotGrid\IteratingCells.cs region=select}} -{{source=..\SamplesVB\PivotGrid\PivotIteratingCells.vb region=select}} - -````C# - -// Print the values of the selected cells. -if (radPivotGrid1.PivotGridElement.IsCellSelected(row, col)) -{ - var Value = this.radPivotGrid1.PivotGridElement.GetAggregateValue(row.Group, col.Group,false, false); - Debug.WriteLine("Row = {0} , Column ={1}, Value ={2}", row.Name, col.Name, Value); -} - -//Select cell in code -radPivotGrid1.PivotGridElement.SelectCell(row, col, false, true); + + -```` -````VB.NET -' Print the values of the selected cells. -If radPivotGrid1.PivotGridElement.IsCellSelected(row, col) Then - Dim Value = Me.radPivotGrid1.PivotGridElement.GetAggregateValue(row.Group, col.Group, False, False) - Debug.WriteLine("Row = {0} , Column ={1}, Value ={2}", row.Name, col.Name, Value) -End If -'Select cell in code -radPivotGrid1.PivotGridElement.SelectCell(row, col, False, True) -```` -{{endregion}} diff --git a/controls/pivotgrid/layout-settings.md b/controls/pivotgrid/layout-settings.md index 6c5a77227..2ac48ae6b 100644 --- a/controls/pivotgrid/layout-settings.md +++ b/controls/pivotgrid/layout-settings.md @@ -23,21 +23,10 @@ You can control the layout type of the column and row headers via the following #### Headers Layout -{{source=..\SamplesCS\PivotGrid\PivotGridLayoutSettings.cs region=LayoutType}} -{{source=..\SamplesVB\PivotGrid\PivotGridLayoutSettings.vb region=LayoutType}} + + -````C# -this.radPivotGrid1.ColumnHeadersLayout = Telerik.WinControls.UI.PivotLayout.Tabular; -this.radPivotGrid1.RowHeadersLayout = Telerik.WinControls.UI.PivotLayout.Compact; -```` -````VB.NET -Me.RadPivotGrid1.ColumnHeadersLayout = Telerik.WinControls.UI.PivotLayout.Tabular -Me.RadPivotGrid1.RowHeadersLayout = Telerik.WinControls.UI.PivotLayout.Compact - -```` - -{{endregion}} ## Sub and Grand Totals @@ -49,25 +38,10 @@ You can also control where SubTotals and GrandTotals are displayed: #### Set Grand and Sub Totals Position -{{source=..\SamplesCS\PivotGrid\PivotGridLayoutSettings.cs region=Totals}} -{{source=..\SamplesVB\PivotGrid\PivotGridLayoutSettings.vb region=Totals}} - -````C# -this.radPivotGrid1.ColumnGrandTotalsPosition = Telerik.WinControls.UI.TotalsPos.First; -this.radPivotGrid1.RowGrandTotalsPosition = Telerik.WinControls.UI.TotalsPos.Last; -this.radPivotGrid1.ColumnsSubTotalsPosition = Telerik.WinControls.UI.TotalsPos.First; -this.radPivotGrid1.RowsSubTotalsPosition = Telerik.WinControls.UI.TotalsPos.Last; + + -```` -````VB.NET -Me.RadPivotGrid1.ColumnGrandTotalsPosition = Telerik.WinControls.UI.TotalsPos.First -Me.RadPivotGrid1.RowGrandTotalsPosition = Telerik.WinControls.UI.TotalsPos.Last -Me.RadPivotGrid1.ColumnsSubTotalsPosition = Telerik.WinControls.UI.TotalsPos.First -Me.RadPivotGrid1.RowsSubTotalsPosition = Telerik.WinControls.UI.TotalsPos.Last -```` - -{{endregion}} When you set the **RowSubTotalsPosition** and **ColumnSubTotalsPosition** property of the group description to a value different than *None*, the pivot renders the subtotals of the corresponding property group. You can alter this and hide the subtotals for a specific group via the **AutoShowSubTotals** property of the corresponding group description object. @@ -77,32 +51,11 @@ When you set the **RowSubTotalsPosition** and **ColumnSubTotalsPosition** proper #### Hiding Sub Totals -{{source=..\SamplesCS\PivotGrid\PivotGridLayoutSettings.cs region=HiddenSubtotals}} -{{source=..\SamplesVB\PivotGrid\PivotGridLayoutSettings.vb region=HiddenSubtotals}} -````C# -this.provider.RowGroupDescriptions.Add(new PropertyGroupDescription() -{ - PropertyName = "Product", - GroupComparer = new GroupNameComparer(), - SortOrder = Telerik.Pivot.Core.SortOrder.Descending, - AutoShowSubTotals = false -}); - -```` -````VB.NET -Me.provider.RowGroupDescriptions.Add(New PropertyGroupDescription() With { -.PropertyName = "Product", -.GroupComparer = New GroupNameComparer(), -.SortOrder = Telerik.Pivot.Core.SortOrder.Descending, -.AutoShowSubTotals = False - }) + + -```` - -{{endregion}} - ## Aggregates When you have added more than one aggregate description, there are special header cells for each aggregate. To control whether these cells are displayed in the column headers area or in the row headers area, and also set the level of the aggregate descriptions in the group tree, you can use the following properties: @@ -113,21 +66,10 @@ When you have added more than one aggregate description, there are special heade #### Set Aggregates Level and Position -{{source=..\SamplesCS\PivotGrid\PivotGridLayoutSettings.cs region=Aggregates}} -{{source=..\SamplesVB\PivotGrid\PivotGridLayoutSettings.vb region=Aggregates}} - -````C# -this.radPivotGrid1.AggregatesPosition = Telerik.Pivot.Core.PivotAxis.Columns; -this.radPivotGrid1.AggregatesLevel = 1; - -```` -````VB.NET -Me.RadPivotGrid1.AggregatesPosition = Telerik.Pivot.Core.PivotAxis.Columns -Me.RadPivotGrid1.AggregatesLevel = 1 + + -```` -{{endregion}} # See Also diff --git a/controls/pivotgrid/localization/localization.md b/controls/pivotgrid/localization/localization.md index ea8ab7f1f..39444fe11 100644 --- a/controls/pivotgrid/localization/localization.md +++ b/controls/pivotgrid/localization/localization.md @@ -1,7 +1,7 @@ --- title: Localization page_title: Localization - RadPivotGrid -description: RadPivotGrid can be localized to display any text and messages in a specific language by using a PivotGridLocalizationProvider. +description: RadPivotGrid can be localized to display any text and messages in a specific language by using a PivotGridLocalizationProvider slug: winforms/pivotgrid/localization/localization tags: localization published: True @@ -15,691 +15,32 @@ To localize __RadPivotGrid__ to display any text and messages in a specific lang * Create a custom __PivotGridLocalizationProvider__ class. -* Override the `GetLocalizedString(string id)` method and provide a translation for the label and user messages. If a translation is not provided, the default value will be returned. This behavior is guaranteed by the call to the base `GetLocalizedString` method in the default clause of the switch statement in the example. +* Override the GetLocalizedString(string id) method and provide a translation for the label and user messages. If a translation is not provided, the default value will be returned. This behavior is guaranteed by the call to the base __GetLocalizedString__ method in the default clause of the switch statement in the example. Below is a sample implementation of an English localization provider: #### Localizing RadPivotGrid Strings -{{source=..\SamplesCS\PivotGrid\Localization\PivotGridLocalization.cs region=CustomProvider}} -{{source=..\SamplesVB\PivotGrid\Localization\PivotGridLocalization.vb region=CustomProvider}} + + -````C# -class MyEnglishPivotGridLoclizationProvider : PivotGridLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case PivotStringId.GrandTotal: return "GrandTotal"; - case PivotStringId.Values: return "Values"; - case PivotStringId.TotalP0: return "Total {0}"; - case PivotStringId.Product: return "Product"; - case PivotStringId.StdDevP: return "StdDevP"; - case PivotStringId.Min: return "Min"; - case PivotStringId.Count: return "Count"; - case PivotStringId.StdDev: return "StdDev"; - case PivotStringId.Sum: return "Sum"; - case PivotStringId.Average: return "Average"; - case PivotStringId.Var: return "Var"; - case PivotStringId.VarP: return "VarP"; - case PivotStringId.GroupP0AggregateP1: return "{0} {1}"; - case PivotStringId.YearGroupField: return "Year"; - case PivotStringId.MonthGroupField: return "Month"; - case PivotStringId.QuarterGroupField: return "Quarter"; - case PivotStringId.WeekGroupField: return "Week"; - case PivotStringId.DayGroupField: return "Day"; - case PivotStringId.HourGroupField: return "Hour"; - case PivotStringId.MinuteGroupField: return "Minute"; - case PivotStringId.SecondsGroupField: return "Seconds"; - case PivotStringId.P0Total: return "{0} Total"; - case PivotStringId.PivotAggregateP0ofP1: return "{0} of {1}"; - case PivotStringId.ExpandCollapseMenuItem: return "Expand"; - case PivotStringId.CollapseAllMenuItems: return "Collapse All"; - case PivotStringId.ExpandAllMenuItems: return "Expand All"; - case PivotStringId.CopyMenuItem: return "Copy"; - case PivotStringId.HideMenuItem: return "Hide"; - case PivotStringId.SortMenuItem: return "Sort"; - case PivotStringId.BestFitMenuItem: return "Best Fit"; - case PivotStringId.ReloadDataMenuItem: return "Reload Data"; - case PivotStringId.FieldListMenuItem: return "Show Field List"; - case PivotStringId.SortAZMenuItem: return "&Sort A-Z"; - case PivotStringId.SortZAMenuItem: return "S&ort Z-A"; - case PivotStringId.SortOptionsMenuItem: return "&More Sort Options ..."; - case PivotStringId.ClearFilterMenuItem: return "&Clear Filter"; - case PivotStringId.LabelFilterMenuItem: return "&Label Filter"; - case PivotStringId.ValueFilterMenuItem: return "&Value Filter"; - case PivotStringId.AllNode: return "(Select All)"; - case PivotStringId.FilterMenuItemEqual: return "&Equals..."; - case PivotStringId.FilterMenuItemDoesNotEquals: return "Does &Not Equal..."; - case PivotStringId.FilterMenuItemBeginsWith: return "Begins W&ith..."; - case PivotStringId.FilterMenuItemDoesNotBeginWith: return "Does No&t Begin With..."; - case PivotStringId.FIlterMenuItemEndsWith: return "Ends Wi&th..."; - case PivotStringId.FilterMenuItemDoesNotEndsWith: return "Does Not End Wit&h..."; - case PivotStringId.FilterMenuItemContains: return "Cont&ains..."; - case PivotStringId.FilterMenuItemDoesNotContain: return "&Does Not Contain..."; - case PivotStringId.FilterMenuItemGreaterThan: return "&Greater Than..."; - case PivotStringId.FilterMenuItemGreaterThanOrEqualTo: return "Greater Than &Or Equal To..."; - case PivotStringId.FilterMenuItemLessThan: return "&Less Than..."; - case PivotStringId.FilterMenuItemLessThanOrEqualTo: return "Less Than Or E&qual To..."; - case PivotStringId.FilterMenuItemBetween: return "Bet&ween..."; - case PivotStringId.FilterMenuItemNotBetween: return "Not &Between..."; - case PivotStringId.TopTenItem: return "&Top 10..."; - case PivotStringId.AllNodeSelectAllSearchResult: return "(Select All Search Result)"; - case PivotStringId.FilterMenuAvailableFilters: return "&Available Filters"; - case PivotStringId.CheckBoxMenuItem: return "Select Multiple Items"; - case PivotStringId.CalculationOptionsDialogNoCalculation: return "No Calculations"; - case PivotStringId.CalculationOptionsDialogPrevious: return "(previous)"; - case PivotStringId.CalculationOptionsDialogNext: return "(next)"; - case PivotStringId.CalculationOptionsDialogGrandTotal: return "% of Grand Total"; - case PivotStringId.CalculationOptionsDialogColumnTotal: return "% of Column Total"; - case PivotStringId.CalculationOptionsDialogRowTotal: return "% of Row Total"; - case PivotStringId.CalculationOptionsDialogOf: return "% Of"; - case PivotStringId.CalculationOptionsDialogDifferenceFrom: return "Difference From"; - case PivotStringId.CalculationOptionsDialogPercentDifferenceFrom: return "% Difference From"; - case PivotStringId.CalculationOptionsDialogRunningTotalIn: return "Running Total In"; - case PivotStringId.CalculationOptionsDialogPercentRunningTotalIn: return "% Running Total In"; - case PivotStringId.CalculationOptionsDialogRankSmallestToLargest: return "Rank Smallest to Largest"; - case PivotStringId.CalculationOptionsDialogRankLargestToSmallest: return "Rank Largest to Smallest"; - case PivotStringId.CalculationOptionsDialogIndex: return "Index"; - case PivotStringId.CalculationOptionsDialogShowValueAs: return "Show value as ({0})"; - case PivotStringId.LabelFilterOptionsDialogEquals: return "equals"; - case PivotStringId.LabelFilterOptionsDialogDoesNotEqual: return "does not equal"; - case PivotStringId.LabelFilterOptionsDialogIsGreaterThen: return "is greater than"; - case PivotStringId.LabelFilterOptionsDialogIsGreaterThanOrEqualTo: return "is greater than or equal to"; - case PivotStringId.LabelFilterOptionsDialogIsLessThan: return "is less than"; - case PivotStringId.LabelFilterOptionsDialogIsLessThanOrEqualTo: return "is less than or equal to"; - case PivotStringId.LabelFilterOptionsDialogBeginsWith: return "begins with"; - case PivotStringId.LabelFilterOptionsDialogDoesNotBeginWith: return "does not begin with"; - case PivotStringId.LabelFilterOptionsDialogEndsWith: return "ends with"; - case PivotStringId.LabelFilterOptionsDialogDoesNotEndsWith: return "does not end with"; - case PivotStringId.LabelFilterOptionsDialogContains: return "contains"; - case PivotStringId.LabelFilterOptionsDialogDoesNotContain: return "does not contain"; - case PivotStringId.LabelFilterOptionsDialogIsBetween: return "is between"; - case PivotStringId.LabelFilterOptionsDialogIsNotBetween: return "is not between"; - case PivotStringId.LabelFilterOptionsDialogLabelFilter: return "Label Filter ({0})"; - case PivotStringId.NumberFormatOptionsDialogCustomFormat: return "Custom format"; - case PivotStringId.NumberFormatOptionsDialogFixedPoint: return "Fixed-point with 2 decimal digits"; - case PivotStringId.NumberFormatOptionsDialogPrefixedCurrency: return "$ prefixed currency with 2 decimal digits"; - case PivotStringId.NumberFormatOptionsDialogPostfixedCurrency: return "€ postfixed currency with 2 decimal digits"; - case PivotStringId.NumberFormatOptionsDialogPostfixedTemperatureC: return "°C postfixed temperature with 2 decimal digits"; - case PivotStringId.NumberFormatOptionsDialogPostfixedTemperatureF: return "°F postfixed temperature with 2 decimal digits"; - case PivotStringId.NumberFormatOptionsDialogExponential: return "Exponential (scientific)"; - case PivotStringId.NumberFormatOptionsDialogFormatOptions: return "Format Options"; - case PivotStringId.NumberFormatOptionsDialogFormatOptionsDescription: return "Format Options ({0})"; - case PivotStringId.SortOptionsDialogSortOptions: return "Sort Options ({0})"; - case PivotStringId.Top10FilterOptionsDialogTop: return "Top"; - case PivotStringId.Top10FilterOptionsDialogBottom: return "Bottom"; - case PivotStringId.Top10FilterOptionsDialogItems: return "Items"; - case PivotStringId.Top10FilterOptionsDialogPercent: return "Percent"; - case PivotStringId.Top10FilterOptionsDialogTop10: return "Top10 Filter ({0})"; - case PivotStringId.ValueFilter: return "Value Filter ({0})"; - case PivotStringId.AggregateOptionsDialogGroupBoxText: return "Summarize Values By"; - case PivotStringId.AggregateOptionsDialogLabelCustomName: return "Custom Name:"; - case PivotStringId.AggregateOptionsDialogLabelDescription: return "Choose the type of calculation that you want to use to summarize data from the selected field."; - case PivotStringId.AggregateOptionsDialogLabelField: return "FieLabelld Name"; - case PivotStringId.AggregateOptionsDialogLabelSourceName: return "Source Name:"; - case PivotStringId.AggregateOptionsDialogText: return "AggregateOptionsDialog"; - case PivotStringId.AggregateOptionsAggregateOptionsText: return "Aggregate Options"; - case PivotStringId.DialogButtonCancel: return "Cancel"; - case PivotStringId.DialogButtonOK: return "OK"; - case PivotStringId.CalculationOptionsDialogText: return "CalculationOptionsDialog"; - case PivotStringId.CalculationOptionsDialogLabelBaseItem: return "Base Item:"; - case PivotStringId.CalculationOptionsDialogLabelBaseField: return "Base Field:"; - case PivotStringId.CalculationOptionsDialogGroupBoxText: return "Show Value As"; - case PivotStringId.LabelFilterOptionsDialogGroupBoxText: return "Show items for which the label"; - case PivotStringId.LabelFilterOptionsDialogText: return "LabelFilterOptionsDialog"; - case PivotStringId.LabelFilterOptionsDialogLabelAnd: return "and"; - case PivotStringId.NumberFormatOptionsDialogFormat: return "Format"; - case PivotStringId.NumberFormatOptionsDialogLabelDescription: - return "The format should identify the measurement type of the value. ($, ¥, €, kg., lb.," + - The format would be used for general computations such as Sum, Average, Min" + -ax and others."; - case PivotStringId.NumberFormatOptionsDialogText: return "NumberFormatOptionsDialog"; - case PivotStringId.NumberFormatOptionsDialogGroupBoxText: return "General Format"; - case PivotStringId.SortOptionsDialogAscending: return "Sort Ascending (A-Z) by:"; - case PivotStringId.SortOptionsDialogDescending: return "Sort Descending (Z-A) by:"; - case PivotStringId.SortOptionsDialogGroupBoxText: return "Sort options"; - case PivotStringId.SortOptionsDialogText: return "SortOptionsDialog"; - case PivotStringId.Top10FilterOptionsDialogGroupBoxText: return "Show"; - case PivotStringId.Top10FilterOptionsDialogLabelBy: return "by"; - case PivotStringId.Top10FilterOptionsDialogText: return "Top10FilterOptionsDialog"; - case PivotStringId.ValueFilterOptionsDialogGroupBox: return "Show items for which"; - case PivotStringId.ValueFilterOptionsDialogText: return "ValueFilterOptionsDialog"; - case PivotStringId.DragDataItemsHere: return "Drag data items here"; - case PivotStringId.DragColumnItemsHere: return "Drag column items here"; - case PivotStringId.DragItemsHere: return "Drag items here"; - case PivotStringId.DragFilterItemsHere: return "Drag filter items here"; - case PivotStringId.DragRowItemsHere: return "Drag row items here"; - case PivotStringId.ResultItemFormat: return "Key: {0}; Aggregates: {1}"; - case PivotStringId.Error: return "Error"; - case PivotStringId.KpiSchemaElementValidatorError: return "Should have at least one KPI member defined (Goal, Status, Trend, Value)"; - case PivotStringId.SchemaElementValidatorMissingPropertyFormat: return "Required property is missing: {0}"; - case PivotStringId.AdomdCellInfoToStringFormat: return "Ordinal: {0} | Value: {1}"; - case PivotStringId.Aggregates: return "Aggregates"; - case PivotStringId.FilterMenuTextBoxItemNullText: return "Search..."; - case PivotStringId.FieldChooserFormButtonAdd: return "Add to"; - case PivotStringId.FieldChooserFormFields: return "Fields:"; - case PivotStringId.FieldChooserFormText: return "Field Chooser"; - case PivotStringId.FieldChooserFormColumnArea: return "Column Area"; - case PivotStringId.FieldChooserFormDataArea: return "Data Area"; - case PivotStringId.FieldChooserFormFilterArea: return "Filter Area"; - case PivotStringId.FieldChooserFormRowArea: return "Row Area"; - case PivotStringId.FieldListlabelChooseFields: return "Choose fields:"; - case PivotStringId.FieldListButtonUpdate: return "Update"; - case PivotStringId.FieldListCheckBoxDeferUpdate: return "Defer Layout Update"; - case PivotStringId.FieldListLabelDrag: return "Drag fields between areas below:"; - case PivotStringId.FieldListLabelRowLabels: return "Row Labels"; - case PivotStringId.FieldListLabelColumnLabels: return "Column Labels"; - case PivotStringId.FieldListLabelReportFilter: return "Report Filter"; - case PivotStringId.None: return "None"; - case PivotStringId.PrintSettingsFitWidth: return "Fit width"; - case PivotStringId.PrintSettingsFitHeight: return "Fit height"; - case PivotStringId.PrintSettingsCompact: return "Compact"; - case PivotStringId.PrintSettingsTabular: return "Tabular"; - case PivotStringId.PrintSettingsFitAll: return "Fit all"; - case PivotStringId.PrintSettingsPrintOrder: return "Print order"; - case PivotStringId.PrintSettingsThenOver: return "Down, then over"; - case PivotStringId.PrintSettingsThenDown: return "Over, then down"; - case PivotStringId.PrintSettingsFontsAndColors: return "Fonts and colors"; - case PivotStringId.PrintSettingsBackground: return "Background"; - case PivotStringId.PrintSettingsNone: return "(none)"; - case PivotStringId.PrintSettingsFont: return "Font"; - case PivotStringId.PrintSettingsGrantTotal: return "GrandTotal cells:"; - case PivotStringId.PrintSettingsDescriptors: return "Aggregate/group descriptors:"; - case PivotStringId.PrintSettingsSubTotal: return "SubTotal cells:"; - case PivotStringId.PrintSettingsHeaderCells: return "Column/row header cells:"; - case PivotStringId.PrintSettingsDataCells: return "Data cells:"; - case PivotStringId.PrintSettingsGridLinesColor: return "Grid lines color:"; - case PivotStringId.PrintSettingsSettings: return "Settings"; - case PivotStringId.PrintSettingsLayuotType: return "Layout Type:"; - case PivotStringId.PrintSettingsScaleMode: return "Scale mode:"; - case PivotStringId.PrintSettingsPrintSelectionOnly: return "Print selection only"; - case PivotStringId.PrintSettingsShowGridLines: return "Show grid lines"; - case PivotStringId.CollapseMenuItem: return "Collapse"; - case PivotStringId.CalcualtedFields: return "Calculated Fields"; - case PivotStringId.Max: return "Max"; - case PivotStringId.NullValue: return "(blank)"; - case PivotStringId.PivotMoreFields: return "More fields"; - case PivotStringId.CellScreenTipValue: return "Value"; - case PivotStringId.CellScreenTipRow: return "Row"; - case PivotStringId.CellScreenTipColumn: return "Column"; - case PivotStringId.SortOptionsContextFromAtoZMenuText: return "Sort from A to Z"; - case PivotStringId.SortOptionsContextFromZtoAMenuText: return "Sort from Z to A"; - case PivotStringId.SortOptionsContextMoreSortingOptionsMenuText: return "More Sorting Options ..."; - case PivotStringId.ContextTop10FilterOptionsMenuText: return "Top10 Filter"; - case PivotStringId.ContextNumberFormatrOptionsMenuText: return "Number Format..."; - case PivotStringId.ContextClearCalculationsrOptionsMenuText: return "Clear Calculations"; - case PivotStringId.ContextMoreCalculationOptionsOptionsMenuText: return "More Calculation Options..."; - case PivotStringId.ContextPercentOfGrandTotalOptionsOptionsMenuText: return "% of GrandTotal"; - case PivotStringId.ContextMoreAggregatOptionsOptionsMenuText: return "More Aggregate Options..."; - case PivotStringId.ContextGroupByYearOptionsMenuText: return "Group by Year"; - case PivotStringId.ContextGroupByQuaterOptionsMenuText: return "Group by Quater"; - case PivotStringId.ContextGroupByMonthOptionsMenuText: return "Group by Month"; - case PivotStringId.ContextGroupByDayhOptionsMenuText: return "Group by Day"; - case PivotStringId.ContextStepText: return "Step"; - case PivotStringId.FieldListDateText: return "Date"; - } - return base.GetLocalizedString(id); - } -} -} -```` -````VB.NET -Class MyEnglishPivotGridLoclizationProvider - Inherits PivotGridLocalizationProvider - Public Overrides Function GetLocalizedString(id As String) As String - Select Case id - Case PivotStringId.GrandTotal - Return "GrandTotal" - Case PivotStringId.Values - Return "Values" - Case PivotStringId.TotalP0 - Return "Total {0}" - Case PivotStringId.Product - Return "Product" - Case PivotStringId.StdDevP - Return "StdDevP" - Case PivotStringId.Min - Return "Min" - Case PivotStringId.Count - Return "Count" - Case PivotStringId.StdDev - Return "StdDev" - Case PivotStringId.Sum - Return "Sum" - Case PivotStringId.Average - Return "Average" - Case PivotStringId.Var - Return "Var" - Case PivotStringId.VarP - Return "VarP" - Case PivotStringId.GroupP0AggregateP1 - Return "{0} {1}" - Case PivotStringId.YearGroupField - Return "Year" - Case PivotStringId.MonthGroupField - Return "Month" - Case PivotStringId.QuarterGroupField - Return "Quarter" - Case PivotStringId.WeekGroupField - Return "Week" - Case PivotStringId.DayGroupField - Return "Day" - Case PivotStringId.HourGroupField - Return "Hour" - Case PivotStringId.MinuteGroupField - Return "Minute" - Case PivotStringId.SecondsGroupField - Return "Seconds" - Case PivotStringId.P0Total - Return "{0} Total" - Case PivotStringId.PivotAggregateP0ofP1 - Return "{0} of {1}" - Case PivotStringId.ExpandCollapseMenuItem - Return "Expand" - Case PivotStringId.CollapseAllMenuItems - Return "Collapse All" - Case PivotStringId.ExpandAllMenuItems - Return "Expand All" - Case PivotStringId.CopyMenuItem - Return "Copy" - Case PivotStringId.HideMenuItem - Return "Hide" - Case PivotStringId.SortMenuItem - Return "Sort" - Case PivotStringId.BestFitMenuItem - Return "Best Fit" - Case PivotStringId.ReloadDataMenuItem - Return "Reload Data" - Case PivotStringId.FieldListMenuItem - Return "Show Field List" - Case PivotStringId.SortAZMenuItem - Return "&Sort A-Z" - Case PivotStringId.SortZAMenuItem - Return "S&ort Z-A" - Case PivotStringId.SortOptionsMenuItem - Return "&More Sort Options ..." - Case PivotStringId.ClearFilterMenuItem - Return "&Clear Filter" - Case PivotStringId.LabelFilterMenuItem - Return "&Label Filter" - Case PivotStringId.ValueFilterMenuItem - Return "&Value Filter" - Case PivotStringId.AllNode - Return "(Select All)" - Case PivotStringId.FilterMenuItemEqual - Return "&Equals..." - Case PivotStringId.FilterMenuItemDoesNotEquals - Return "Does &Not Equal..." - Case PivotStringId.FilterMenuItemBeginsWith - Return "Begins W&ith..." - Case PivotStringId.FilterMenuItemDoesNotBeginWith - Return "Does No&t Begin With..." - Case PivotStringId.FIlterMenuItemEndsWith - Return "Ends Wi&th..." - Case PivotStringId.FilterMenuItemDoesNotEndsWith - Return "Does Not End Wit&h..." - Case PivotStringId.FilterMenuItemContains - Return "Cont&ains..." - Case PivotStringId.FilterMenuItemDoesNotContain - Return "&Does Not Contain..." - Case PivotStringId.FilterMenuItemGreaterThan - Return "&Greater Than..." - Case PivotStringId.FilterMenuItemGreaterThanOrEqualTo - Return "Greater Than &Or Equal To..." - Case PivotStringId.FilterMenuItemLessThan - Return "&Less Than..." - Case PivotStringId.FilterMenuItemLessThanOrEqualTo - Return "Less Than Or E&qual To..." - Case PivotStringId.FilterMenuItemBetween - Return "Bet&ween..." - Case PivotStringId.FilterMenuItemNotBetween - Return "Not &Between..." - Case PivotStringId.TopTenItem - Return "&Top 10..." - Case PivotStringId.AllNodeSelectAllSearchResult - Return "(Select All Search Result)" - Case PivotStringId.FilterMenuAvailableFilters - Return "&Available Filters" - Case PivotStringId.CheckBoxMenuItem - Return "Select Multiple Items" - Case PivotStringId.CalculationOptionsDialogNoCalculation - Return "No Calculations" - Case PivotStringId.CalculationOptionsDialogPrevious - Return "(previous)" - Case PivotStringId.CalculationOptionsDialogNext - Return "(next)" - Case PivotStringId.CalculationOptionsDialogGrandTotal - Return "% of Grand Total" - Case PivotStringId.CalculationOptionsDialogColumnTotal - Return "% of Column Total" - Case PivotStringId.CalculationOptionsDialogRowTotal - Return "% of Row Total" - Case PivotStringId.CalculationOptionsDialogOf - Return "% Of" - Case PivotStringId.CalculationOptionsDialogDifferenceFrom - Return "Difference From" - Case PivotStringId.CalculationOptionsDialogPercentDifferenceFrom - Return "% Difference From" - Case PivotStringId.CalculationOptionsDialogRunningTotalIn - Return "Running Total In" - Case PivotStringId.CalculationOptionsDialogPercentRunningTotalIn - Return "% Running Total In" - Case PivotStringId.CalculationOptionsDialogRankSmallestToLargest - Return "Rank Smallest to Largest" - Case PivotStringId.CalculationOptionsDialogRankLargestToSmallest - Return "Rank Largest to Smallest" - Case PivotStringId.CalculationOptionsDialogIndex - Return "Index" - Case PivotStringId.CalculationOptionsDialogShowValueAs - Return "Show value as ({0})" - Case PivotStringId.LabelFilterOptionsDialogEquals - Return "equals" - Case PivotStringId.LabelFilterOptionsDialogDoesNotEqual - Return "does not equal" - Case PivotStringId.LabelFilterOptionsDialogIsGreaterThen - Return "is greater than" - Case PivotStringId.LabelFilterOptionsDialogIsGreaterThanOrEqualTo - Return "is greater than or equal to" - Case PivotStringId.LabelFilterOptionsDialogIsLessThan - Return "is less than" - Case PivotStringId.LabelFilterOptionsDialogIsLessThanOrEqualTo - Return "is less than or equal to" - Case PivotStringId.LabelFilterOptionsDialogBeginsWith - Return "begins with" - Case PivotStringId.LabelFilterOptionsDialogDoesNotBeginWith - Return "does not begin with" - Case PivotStringId.LabelFilterOptionsDialogEndsWith - Return "ends with" - Case PivotStringId.LabelFilterOptionsDialogDoesNotEndsWith - Return "does not end with" - Case PivotStringId.LabelFilterOptionsDialogContains - Return "contains" - Case PivotStringId.LabelFilterOptionsDialogDoesNotContain - Return "does not contain" - Case PivotStringId.LabelFilterOptionsDialogIsBetween - Return "is between" - Case PivotStringId.LabelFilterOptionsDialogIsNotBetween - Return "is not between" - Case PivotStringId.LabelFilterOptionsDialogLabelFilter - Return "Label Filter ({0})" - Case PivotStringId.NumberFormatOptionsDialogCustomFormat - Return "Custom format" - Case PivotStringId.NumberFormatOptionsDialogFixedPoint - Return "Fixed-point with 2 decimal digits" - Case PivotStringId.NumberFormatOptionsDialogPrefixedCurrency - Return "$ prefixed currency with 2 decimal digits" - Case PivotStringId.NumberFormatOptionsDialogPostfixedCurrency - Return "€ postfixed currency with 2 decimal digits" - Case PivotStringId.NumberFormatOptionsDialogPostfixedTemperatureC - Return "°C postfixed temperature with 2 decimal digits" - Case PivotStringId.NumberFormatOptionsDialogPostfixedTemperatureF - Return "°F postfixed temperature with 2 decimal digits" - Case PivotStringId.NumberFormatOptionsDialogExponential - Return "Exponential (scientific)" - Case PivotStringId.NumberFormatOptionsDialogFormatOptions - Return "Format Options" - Case PivotStringId.NumberFormatOptionsDialogFormatOptionsDescription - Return "Format Options ({0})" - Case PivotStringId.SortOptionsDialogSortOptions - Return "Sort Options ({0})" - Case PivotStringId.Top10FilterOptionsDialogTop - Return "Top" - Case PivotStringId.Top10FilterOptionsDialogBottom - Return "Bottom" - Case PivotStringId.Top10FilterOptionsDialogItems - Return "Items" - Case PivotStringId.Top10FilterOptionsDialogPercent - Return "Percent" - Case PivotStringId.Top10FilterOptionsDialogTop10 - Return "Top10 Filter ({0})" - Case PivotStringId.ValueFilter - Return "Value Filter ({0})" - Case PivotStringId.AggregateOptionsDialogGroupBoxText - Return "Summarize Values By" - Case PivotStringId.AggregateOptionsDialogLabelCustomName - Return "Custom Name:" - Case PivotStringId.AggregateOptionsDialogLabelDescription - Return "Choose the type of calculation that you want to use to summarize data from the selected field." - Case PivotStringId.AggregateOptionsDialogLabelField - Return "FieLabelld Name" - Case PivotStringId.AggregateOptionsDialogLabelSourceName - Return "Source Name:" - Case PivotStringId.AggregateOptionsDialogText - Return "AggregateOptionsDialog" - Case PivotStringId.AggregateOptionsAggregateOptionsText - Return "Aggregate Options" - Case PivotStringId.DialogButtonCancel - Return "Cancel" - Case PivotStringId.DialogButtonOK - Return "OK" - Case PivotStringId.CalculationOptionsDialogText - Return "CalculationOptionsDialog" - Case PivotStringId.CalculationOptionsDialogLabelBaseItem - Return "Base Item:" - Case PivotStringId.CalculationOptionsDialogLabelBaseField - Return "Base Field:" - Case PivotStringId.CalculationOptionsDialogGroupBoxText - Return "Show Value As" - Case PivotStringId.LabelFilterOptionsDialogGroupBoxText - Return "Show items for which the label" - Case PivotStringId.LabelFilterOptionsDialogText - Return "LabelFilterOptionsDialog" - Case PivotStringId.LabelFilterOptionsDialogLabelAnd - Return "and" - Case PivotStringId.NumberFormatOptionsDialogFormat - Return "Format" - Case PivotStringId.NumberFormatOptionsDialogLabelDescription - Return "The format should identify the measurement type of the value. ($, ¥, €, kg., lb.," + "m.) The format would be used for general computations such as Sum, Average, Min" + ", Max and others." - Case PivotStringId.NumberFormatOptionsDialogText - Return "NumberFormatOptionsDialog" - Case PivotStringId.NumberFormatOptionsDialogGroupBoxText - Return "General Format" - Case PivotStringId.SortOptionsDialogAscending - Return "Sort Ascending (A-Z) by:" - Case PivotStringId.SortOptionsDialogDescending - Return "Sort Descending (Z-A) by:" - Case PivotStringId.SortOptionsDialogGroupBoxText - Return "Sort options" - Case PivotStringId.SortOptionsDialogText - Return "SortOptionsDialog" - Case PivotStringId.Top10FilterOptionsDialogGroupBoxText - Return "Show" - Case PivotStringId.Top10FilterOptionsDialogLabelBy - Return "by" - Case PivotStringId.Top10FilterOptionsDialogText - Return "Top10FilterOptionsDialog" - Case PivotStringId.ValueFilterOptionsDialogGroupBox - Return "Show items for which" - Case PivotStringId.ValueFilterOptionsDialogText - Return "ValueFilterOptionsDialog" - Case PivotStringId.DragDataItemsHere - Return "Drag data items here" - Case PivotStringId.DragColumnItemsHere - Return "Drag column items here" - Case PivotStringId.DragItemsHere - Return "Drag items here" - Case PivotStringId.DragFilterItemsHere - Return "Drag filter items here" - Case PivotStringId.DragRowItemsHere - Return "Drag row items here" - Case PivotStringId.ResultItemFormat - Return "Key: {0}; Aggregates: {1}" - Case PivotStringId.[Error] - Return "Error" - Case PivotStringId.KpiSchemaElementValidatorError - Return "Should have at least one KPI member defined (Goal, Status, Trend, Value)" - Case PivotStringId.SchemaElementValidatorMissingPropertyFormat - Return "Required property is missing: {0}" - Case PivotStringId.AdomdCellInfoToStringFormat - Return "Ordinal: {0} | Value: {1}" - Case PivotStringId.Aggregates - Return "Aggregates" - Case PivotStringId.FilterMenuTextBoxItemNullText - Return "Search..." - Case PivotStringId.FieldChooserFormButtonAdd - Return "Add to" - Case PivotStringId.FieldChooserFormFields - Return "Fields:" - Case PivotStringId.FieldChooserFormText - Return "Field Chooser" - Case PivotStringId.FieldChooserFormColumnArea - Return "Column Area" - Case PivotStringId.FieldChooserFormDataArea - Return "Data Area" - Case PivotStringId.FieldChooserFormFilterArea - Return "Filter Area" - Case PivotStringId.FieldChooserFormRowArea - Return "Row Area" - Case PivotStringId.FieldListlabelChooseFields - Return "Choose fields:" - Case PivotStringId.FieldListButtonUpdate - Return "Update" - Case PivotStringId.FieldListCheckBoxDeferUpdate - Return "Defer Layout Update" - Case PivotStringId.FieldListLabelDrag - Return "Drag fields between areas below:" - Case PivotStringId.FieldListLabelRowLabels - Return "Row Labels" - Case PivotStringId.FieldListLabelColumnLabels - Return "Column Labels" - Case PivotStringId.FieldListLabelReportFilter - Return "Report Filter" - Case PivotStringId.None - Return "None" - Case PivotStringId.PrintSettingsFitWidth - Return "Fit width" - Case PivotStringId.PrintSettingsFitHeight - Return "Fit height" - Case PivotStringId.PrintSettingsCompact - Return "Compact" - Case PivotStringId.PrintSettingsTabular - Return "Tabular" - Case PivotStringId.PrintSettingsFitAll - Return "Fit all" - Case PivotStringId.PrintSettingsPrintOrder - Return "Print order" - Case PivotStringId.PrintSettingsThenOver - Return "Down, then over" - Case PivotStringId.PrintSettingsThenDown - Return "Over, then down" - Case PivotStringId.PrintSettingsFontsAndColors - Return "Fonts and colors" - Case PivotStringId.PrintSettingsBackground - Return "Background" - Case PivotStringId.PrintSettingsNone - Return "(none)" - Case PivotStringId.PrintSettingsFont - Return "Font" - Case PivotStringId.PrintSettingsGrantTotal - Return "GrandTotal cells:" - Case PivotStringId.PrintSettingsDescriptors - Return "Aggregate/group descriptors:" - Case PivotStringId.PrintSettingsSubTotal - Return "SubTotal cells:" - Case PivotStringId.PrintSettingsHeaderCells - Return "Column/row header cells:" - Case PivotStringId.PrintSettingsDataCells - Return "Data cells:" - Case PivotStringId.PrintSettingsGridLinesColor - Return "Grid lines color:" - Case PivotStringId.PrintSettingsSettings - Return "Settings" - Case PivotStringId.PrintSettingsLayuotType - Return "Layout Type:" - Case PivotStringId.PrintSettingsScaleMode - Return "Scale mode:" - Case PivotStringId.PrintSettingsPrintSelectionOnly - Return "Print selection only" - Case PivotStringId.PrintSettingsShowGridLines - Return "Show grid lines" - Case PivotStringId.CollapseMenuItem - Return "Collapse" - Case PivotStringId.CalcualtedFields - Return "Calculated Fields" - Case PivotStringId.Max - Return "Max" - Case PivotStringId.NullValue - Return "(blank)" - Case PivotStringId.PivotMoreFields - Return "More fields" - Case PivotStringId.CellScreenTipValue - Return "Value" - Case PivotStringId.CellScreenTipRow - Return "Row" - Case PivotStringId.CellScreenTipColumn - Return "Column" - Case PivotStringId.SortOptionsContextFromAtoZMenuText - Return "Sort from A to Z" - Case PivotStringId.SortOptionsContextFromZtoAMenuText - Return "Sort from Z to A" - Case PivotStringId.SortOptionsContextMoreSortingOptionsMenuText - Return "More Sorting Options ..." - Case PivotStringId.ContextTop10FilterOptionsMenuText - Return "Top10 Filter" - Case PivotStringId.ContextNumberFormatrOptionsMenuText - Return "Number Format..." - Case PivotStringId.ContextClearCalculationsrOptionsMenuText - Return "Clear Calculations" - Case PivotStringId.ContextMoreCalculationOptionsOptionsMenuText - Return "More Calculation Options..." - Case PivotStringId.ContextPercentOfGrandTotalOptionsOptionsMenuText - Return "% of GrandTotal" - Case PivotStringId.ContextMoreAggregatOptionsOptionsMenuText - Return "More Aggregate Options..." - Case PivotStringId.ContextGroupByYearOptionsMenuText - Return "Group by Year" - Case PivotStringId.ContextGroupByQuaterOptionsMenuText - Return "Group by Quater" - Case PivotStringId.ContextGroupByMonthOptionsMenuText - Return "Group by Month" - Case PivotStringId.ContextGroupByDayhOptionsMenuText - Return "Group by Day" - Case PivotStringId.ContextStepText - Return "Step" - Case PivotStringId.FieldListDateText - Return "Date" - End Select - Return MyBase.GetLocalizedString(id) - End Function -End Class - -```` - -{{endregion}} To apply the custom localization provider, instantiate and assign it to the current localization provider: ->note The **RadPivotGrid** localization provider needs to be set in the constructor of the form before calling the `InitializeComponent` method. +>note **RadPivotGrid**`s localization provider needs to be loaded in the constructor of the form prior to calling the __InitializeComponent__ method. +> #### Assigning the Current Localization Provider -{{source=..\SamplesCS\PivotGrid\Localization\PivotGridLocalization.cs region=LocalizePivot}} -{{source=..\SamplesVB\PivotGrid\Localization\PivotGridLocalization.vb region=LocalizePivot}} - -````C# -public PivotGridLocalization() -{ - PivotGridLocalizationProvider.CurrentProvider = new MyEnglishPivotGridLoclizationProvider(); - InitializeComponent(); -} - -```` -````VB.NET -Public Sub New() - PivotGridLocalizationProvider.CurrentProvider = New MyEnglishPivotGridLoclizationProvider() - InitializeComponent() -End Sub + + -```` -{{endregion}} The code provided above illustrates the approach to be used to localize the __RadPivotGrid__ and is not intended as a full translation. -## See Also +# See Also * [How to Translate the Month Names in RadPivotGrid]({%slug translate-month-names-in-pivotgrid%}) diff --git a/controls/pivotgrid/pivot-field-list/customizing-radpivotfieldlist.md b/controls/pivotgrid/pivot-field-list/customizing-radpivotfieldlist.md index 11698346c..0240947af 100644 --- a/controls/pivotgrid/pivot-field-list/customizing-radpivotfieldlist.md +++ b/controls/pivotgrid/pivot-field-list/customizing-radpivotfieldlist.md @@ -22,20 +22,10 @@ __RadPivotFieldList__ internally contains a __RadTreeView__ built with nodes com #### Sorting the Nodes -{{source=..\SamplesCS\PivotGrid\PivotFieldList\PivotGridFieldListCustomizations.cs region=SortTree}} -{{source=..\SamplesVB\PivotGrid\PivotFieldList\PivotGridFieldListCustomizations.vb region=SortTree}} -````C# -this.radPivotFieldList1.FieldsControl.SortOrder = System.Windows.Forms.SortOrder.Ascending; + + -```` -````VB.NET -Me.RadPivotFieldList1.FieldsControl.SortOrder = System.Windows.Forms.SortOrder.Descending -```` - - - -{{endregion}} | Before Hiding | After Hiding | | ------ | ------ | @@ -45,47 +35,15 @@ Me.RadPivotFieldList1.FieldsControl.SortOrder = System.Windows.Forms.SortOrder.D The nodes in the pivot field list are built dynamically so in order to hide a particular node and persist the changes we would need to handle the __UpdateCompleted__ event. -{{source=..\SamplesCS\PivotGrid\PivotFieldList\PivotGridFieldListCustomizations.cs region=SubscribeToUpdateCompleted}} -{{source=..\SamplesVB\PivotGrid\PivotFieldList\PivotGridFieldListCustomizations.vb region=SubscribeToUpdateCompleted}} -````C# -this.radPivotGrid1.UpdateCompleted += radPivotGrid1_UpdateCompleted; - -```` -````VB.NET -AddHandler Me.RadPivotGrid1.UpdateCompleted, AddressOf RadPivotGrid1_UpdateCompleted - -```` + + -{{endregion}} + + -{{source=..\SamplesCS\PivotGrid\PivotFieldList\PivotGridFieldListCustomizations.cs region=HandleUpdateCompleted}} -{{source=..\SamplesVB\PivotGrid\PivotFieldList\PivotGridFieldListCustomizations.vb region=HandleUpdateCompleted}} -````C# -private void radPivotGrid1_UpdateCompleted(object sender, EventArgs e) -{ - RadTreeNode promotionField = this.radPivotFieldList1.FieldsControl.Nodes.Where(n => n.Text == "Promotion").FirstOrDefault(); - if (promotionField != null) - { - promotionField.Visible = false; - } -} -```` -````VB.NET -Private Sub RadPivotGrid1_UpdateCompleted(sender As Object, e As EventArgs) - Dim promotionField As RadTreeNode = Me.RadPivotFieldList1.FieldsControl.Nodes.Where(Function(n) n.Text = "Promotion").FirstOrDefault() - If promotionField IsNot Nothing Then - promotionField.Visible = False - End If -End Sub - -```` - - - -{{endregion}} ## Remove Fields Logically @@ -93,59 +51,21 @@ In the case of a [LocalSourceDataProvider]({%slug winforms/pivotgrid/populating- #### Setup the Providers -{{source=..\SamplesCS\PivotGrid\PivotFieldList\PivotGridFieldListCustomizations.cs region=SetupProviders}} -{{source=..\SamplesVB\PivotGrid\PivotFieldList\PivotGridFieldListCustomizations.vb region=SetupProviders}} -````C# -this.provider = new LocalDataSourceProvider() { ItemsSource = this.orders }; -LocalDataSourceFieldDescriptionsProvider descriptionProvider = new LocalDataSourceFieldDescriptionsProvider(); -descriptionProvider.AddingContainerNode += descriptionProvider_AddingContainerNode; -descriptionProvider.GetDescriptionsDataAsyncCompleted += descriptionProvider_GetDescriptionsDataAsyncCompleted; -this.provider.FieldDescriptionsProvider = descriptionProvider; - -```` -````VB.NET -Me.provider = New LocalDataSourceProvider() With {.ItemsSource = orders} -Dim descriptionProvider As LocalDataSourceFieldDescriptionsProvider = New LocalDataSourceFieldDescriptionsProvider() -AddHandler descriptionProvider.AddingContainerNode, AddressOf descriptionProvider_AddingContainerNode -AddHandler descriptionProvider.GetDescriptionsDataAsyncCompleted, AddressOf descriptionProvider_GetDescriptionsDataAsyncCompleted -Me.provider.FieldDescriptionsProvider = descriptionProvider + + -```` - -{{endregion}} - | Before Canceling | After Canceling | | ------ | ------ | |![WinForms RadPivotGrid Before Canceling](images/pivotgrid-radpivotfieldlist006.png)|![WinForms RadPivotGrid After Canceling](images/pivotgrid-radpivotfieldlist007.png)| #### Cancel Adding a Particular Node -{{source=..\SamplesCS\PivotGrid\PivotFieldList\PivotGridFieldListCustomizations.cs region=HandleAddingContainerNode}} -{{source=..\SamplesVB\PivotGrid\PivotFieldList\PivotGridFieldListCustomizations.vb region=HandleAddingContainerNode}} -````C# -private void descriptionProvider_AddingContainerNode(object sender, ContainerNodeEventArgs e) -{ - if (e.ContainerNode.Name == "Promotion") - { - e.Cancel = true; - } -} - -```` -````VB.NET -Private Sub descriptionProvider_AddingContainerNode(sender As Object, e As ContainerNodeEventArgs) - If e.ContainerNode.Name = "Promotion" Then - e.Cancel = True - End If -End Sub - -```` - + + -{{endregion}} | Before Removing | After Removing | | ------ | ------ | @@ -153,103 +73,26 @@ End Sub #### Remove a Child Date Node -{{source=..\SamplesCS\PivotGrid\PivotFieldList\PivotGridFieldListCustomizations.cs region=HandleGetDescriptionsDataAsyncCompleted}} -{{source=..\SamplesVB\PivotGrid\PivotFieldList\PivotGridFieldListCustomizations.vb region=HandleGetDescriptionsDataAsyncCompleted}} -````C# -private void descriptionProvider_GetDescriptionsDataAsyncCompleted(object sender, GetDescriptionsDataCompletedEventArgs e) -{ - ContainerNode dateNode = e.DescriptionsData.RootFieldInfo.Children.Where(n => n.Name == "Date").FirstOrDefault(); - if (dateNode != null) - { - FieldInfoNode yearNode = dateNode.Children.Where(n => n.Name == "Date.Year").FirstOrDefault() as FieldInfoNode; - if (yearNode != null) - { - dateNode.Children.Remove(yearNode); - } - } -} - -```` -````VB.NET -Private Sub descriptionProvider_GetDescriptionsDataAsyncCompleted(sender As Object, e As GetDescriptionsDataCompletedEventArgs) - Dim dateNode As ContainerNode = e.DescriptionsData.RootFieldInfo.Children.Where(Function(n) n.Name = "Date").FirstOrDefault() - If dateNode IsNot Nothing Then - Dim yearNode As FieldInfoNode = TryCast(dateNode.Children.Where(Function(n) n.Name = "Date.Year").FirstOrDefault(), FieldInfoNode) - If yearNode IsNot Nothing Then - dateNode.Children.Remove(yearNode) - End If - End If -End Sub - -```` - - - -{{endregion}} + + + + ## Formatting Nodes The nodes within the **RadPivotFieldList** can be formatted. You can easily format node elements by handling the **NodeFormatting** event as follows: -{{source=..\SamplesCS\PivotGrid\PivotFieldList\PivotGridFieldListCustomizations.cs region=SubscribeToNodeFormatting}} -{{source=..\SamplesVB\PivotGrid\PivotFieldList\PivotGridFieldListCustomizations.vb region=SubscribeToNodeFormatting}} -````C# -this.radPivotFieldList1.FieldsControl.NodeFormatting += this.FieldsControl_NodeFormatting; - -```` -````VB.NET -AddHandler Me.RadPivotFieldList1.FieldsControl.NodeFormatting, AddressOf FieldsControl_NodeFormatting + + -```` -{{endregion}} Then, introduce the desired customizations to NodeElements: -{{source=..\SamplesCS\PivotGrid\PivotFieldList\PivotGridFieldListCustomizations.cs region=NodeFormatting}} -{{source=..\SamplesVB\PivotGrid\PivotFieldList\PivotGridFieldListCustomizations.vb region=NodeFormatting}} -````C# -private void FieldsControl_NodeFormatting(object sender, TreeNodeFormattingEventArgs e) -{ - if (e.Node.Text == "Product") - { - e.NodeElement.ContentElement.Text = "Custom Product"; - } - if (e.Node.CheckState == Telerik.WinControls.Enumerations.ToggleState.On) - { - e.NodeElement.ContentElement.ForeColor = Color.Red; - e.Node.BackColor = Color.LightGray; - e.Node.GradientStyle = GradientStyles.Solid; - } - else - { - e.NodeElement.ContentElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local); - e.NodeElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local); - e.NodeElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local); - } -} - -```` -````VB.NET -Private Sub FieldsControl_NodeFormatting(sender As Object, e As TreeNodeFormattingEventArgs) - If e.Node.Text = "Product" Then - e.NodeElement.ContentElement.Text = "Custom Product" - End If - - If e.Node.CheckState = Telerik.WinControls.Enumerations.ToggleState.[On] Then - e.NodeElement.ContentElement.ForeColor = Color.Red - e.Node.BackColor = Color.LightGray - e.Node.GradientStyle = GradientStyles.Solid - Else - e.NodeElement.ContentElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local) - e.NodeElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local) - e.NodeElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local) - End If -End Sub - -```` - -{{endregion}} + + + + |![WinForms RadPivotGrid Formatting Nodes](images/pivotgrid-radpivotfieldlist010.png) diff --git a/controls/pivotgrid/populating-with-data/binding-to-icustomtypeprovider.md b/controls/pivotgrid/populating-with-data/binding-to-icustomtypeprovider.md index 5f548db26..e0c2d781f 100644 --- a/controls/pivotgrid/populating-with-data/binding-to-icustomtypeprovider.md +++ b/controls/pivotgrid/populating-with-data/binding-to-icustomtypeprovider.md @@ -18,1031 +18,24 @@ This tutorial demonstrates how to accomplish such a requirement: 1\. Define the Customer class -{{source=..\SamplesCS\PivotGrid\PopulatingWithData\PivotCustomTypeProvider.cs region=DefineCustomer}} -{{source=..\SamplesVB\PivotGrid\PopulatingWithData\PivotCustomTypeProvider.vb region=DefineCustomer}} + + -````C# -public class Customer : ICustomTypeProvider -{ - private CustomTypeHelper helper = new CustomTypeHelper(); - - public string FirstName { get; set; } - - public string LastName { get; set; } - - Type ICustomTypeProvider.GetCustomType() - { - return this.helper.GetCustomType(); - } - - public static void AddProperty(string name) - { - CustomTypeHelper.AddProperty(name); - } - - public static void AddProperty(string name, Type propertyType) - { - CustomTypeHelper.AddProperty(name, propertyType); - } - - public static void AddProperty(string name, Type propertyType, List attributes) - { - CustomTypeHelper.AddProperty(name, propertyType, attributes); - } - - public void SetPropertyValue(string propertyName, object value) - { - this.helper.SetPropertyValue(propertyName, value); - } - - public object GetPropertyValue(string propertyName) - { - return this.helper.GetPropertyValue(propertyName); - } - - public PropertyInfo[] GetProperties() - { - return this.helper.GetProperties(); - } -} - - -```` -````VB.NET - -Public Class Customer - Implements ICustomTypeProvider - - Private helper As CustomTypeHelper(Of Customer) = New CustomTypeHelper(Of Customer)() - Public Property FirstName As String - Public Property LastName As String - - Private Function GetCustomType() As Type Implements ICustomTypeProvider.GetCustomType - Return Me.helper.GetCustomType() - End Function - - Public Shared Sub AddProperty(ByVal name As String) - CustomTypeHelper(Of Customer).AddProperty(name) - End Sub - - Public Shared Sub AddProperty(ByVal name As String, ByVal propertyType As Type) - CustomTypeHelper(Of Customer).AddProperty(name, propertyType) - End Sub - - Public Shared Sub AddProperty(ByVal name As String, ByVal propertyType As Type, ByVal attributes As List(Of Attribute)) - CustomTypeHelper(Of Customer).AddProperty(name, propertyType, attributes) - End Sub - - Public Sub SetPropertyValue(ByVal propertyName As String, ByVal value As Object) - Me.helper.SetPropertyValue(propertyName, value) - End Sub - - Public Function GetPropertyValue(ByVal propertyName As String) As Object - Return Me.helper.GetPropertyValue(propertyName) - End Function - - Public Function GetProperties() As PropertyInfo() - Return Me.helper.GetProperties() - End Function - -```` - -{{endregion}} 2\. Define the CustomTypeHelper class -{{source=..\SamplesCS\PivotGrid\PopulatingWithData\PivotCustomTypeProvider.cs region=DefineHelper}} -{{source=..\SamplesVB\PivotGrid\PopulatingWithData\PivotCustomTypeProvider.vb region=DefineHelper}} - -````C# -internal class CustomTypeHelper : ICustomTypeProvider, INotifyPropertyChanged -{ - private static List customProperties = new List(); - private Dictionary customPropertyValues; - private CustomType ctype; - - public event PropertyChangedEventHandler PropertyChanged; - - private void NotifyPropertyChanged(string info) - { - if (PropertyChanged != null) - { - PropertyChanged(this, new PropertyChangedEventArgs(info)); - } - } - - public CustomTypeHelper() - { - customPropertyValues = new Dictionary(); - foreach (var property in this.GetCustomType().GetProperties()) - { - customPropertyValues.Add(property.Name, null); - } - } - - public static void AddProperty(string name) - { - if (!CheckIfNameExists(name)) - customProperties.Add(new CustomPropertyInfoHelper(name, typeof(string))); - } - - public static void AddProperty(string name, Type propertyType) - { - if (!CheckIfNameExists(name)) - customProperties.Add(new CustomPropertyInfoHelper(name, propertyType)); - } - - public static void AddProperty(string name, Type propertyType, List attributes) - { - if (!CheckIfNameExists(name)) - customProperties.Add(new CustomPropertyInfoHelper(name, propertyType, attributes)); - } - - private static bool CheckIfNameExists(string name) - { - if ((from p in customProperties select p.Name).Contains(name) || (from p in typeof(T).GetProperties() select p.Name).Contains(name)) - throw new Exception("The property with this name already exists: " + name); - else return false; - } - - public void SetPropertyValue(string propertyName, object value) - { - CustomPropertyInfoHelper propertyInfo = (from prop in customProperties where prop.Name == propertyName select prop).FirstOrDefault(); - if (!customPropertyValues.ContainsKey(propertyName)) - customPropertyValues.Add(propertyName, null); - if (ValidateValueType(value, propertyInfo._type)) - { - if (customPropertyValues[propertyName] != value) - { - customPropertyValues[propertyName] = value; - NotifyPropertyChanged(propertyName); - } - } - else throw new Exception("Value is of the wrong type or null for a non-nullable type."); - } - - private bool ValidateValueType(object value, Type type) - { - if (value == null || value is System.DBNull) - // Non-value types can be assigned null. - if (!type.IsValueType) - return true; - else - // Check if the type if a Nullable type. - return (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)); - else - return type.IsAssignableFrom(value.GetType()); - } - - public object GetPropertyValue(string propertyName) - { - if (customPropertyValues.ContainsKey(propertyName)) - return customPropertyValues[propertyName]; - else - throw new Exception("There is no property " + propertyName); - } - - public PropertyInfo[] GetProperties() - { - return this.GetCustomType().GetProperties(); - } - - public Type GetCustomType() - { - if (ctype == null) - { - ctype = new CustomType(typeof(T)); - } - - return ctype; - } - - private class CustomType : Type - { - Type _baseType; - - public CustomType(Type delegatingType) - { - _baseType = delegatingType; - } - - public override Assembly Assembly - { - get { return _baseType.Assembly; } - } - - public override string AssemblyQualifiedName - { - get { return _baseType.AssemblyQualifiedName; } - } - - public override Type BaseType - { - get { return _baseType.BaseType; } - } - - public override string FullName - { - get { return _baseType.FullName; } - } - - public override Guid GUID - { - get { return _baseType.GUID; } - } - - protected override TypeAttributes GetAttributeFlagsImpl() - { - throw new NotImplementedException(); - } - - protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) - { - - throw new NotImplementedException(); - } - - public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) - { - return _baseType.GetConstructors(bindingAttr); - } - - public override Type GetElementType() - { - return _baseType.GetElementType(); - } - - public override EventInfo GetEvent(string name, BindingFlags bindingAttr) - { - return _baseType.GetEvent(name, bindingAttr); - } - - public override EventInfo[] GetEvents(BindingFlags bindingAttr) - { - return _baseType.GetEvents(bindingAttr); - } - - public override FieldInfo GetField(string name, BindingFlags bindingAttr) - { - return _baseType.GetField(name, bindingAttr); - } - - public override FieldInfo[] GetFields(BindingFlags bindingAttr) - { - return _baseType.GetFields(bindingAttr); - } - - public override Type GetInterface(string name, bool ignoreCase) - { - return _baseType.GetInterface(name, ignoreCase); - } - - public override Type[] GetInterfaces() - { - return _baseType.GetInterfaces(); - } - - public override MemberInfo[] GetMembers(BindingFlags bindingAttr) - { - return _baseType.GetMembers(bindingAttr); - } - - protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) - { - throw new NotImplementedException(); - } - - public override MethodInfo[] GetMethods(BindingFlags bindingAttr) - { - return _baseType.GetMethods(bindingAttr); - } - - public override Type GetNestedType(string name, BindingFlags bindingAttr) - { - return _baseType.GetNestedType(name, bindingAttr); - } - - public override Type[] GetNestedTypes(BindingFlags bindingAttr) - { - return _baseType.GetNestedTypes(bindingAttr); - } - - public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) - { - PropertyInfo[] clrProperties = _baseType.GetProperties(bindingAttr); - if (clrProperties != null) - { - return clrProperties.Concat(customProperties).ToArray(); - } - else - return customProperties.ToArray(); - } - - protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) - { - // Look for the CLR property with this name first. - PropertyInfo propertyInfo = (from prop in GetProperties(bindingAttr) where prop.Name == name select prop).FirstOrDefault(); - if (propertyInfo == null) - { - // If the CLR property was not found, return a custom property - propertyInfo = (from prop in customProperties where prop.Name == name select prop).FirstOrDefault(); - } - return propertyInfo; - } - - protected override bool HasElementTypeImpl() - { - throw new NotImplementedException(); - } - - public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, string[] namedParameters) - { - return _baseType.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters); - } - - protected override bool IsArrayImpl() - { - throw new NotImplementedException(); - } - - protected override bool IsByRefImpl() - { - throw new NotImplementedException(); - } - - protected override bool IsCOMObjectImpl() - { - throw new NotImplementedException(); - } - - protected override bool IsPointerImpl() - { - throw new NotImplementedException(); - } - - protected override bool IsPrimitiveImpl() - { - return _baseType.IsPrimitive; - } - - public override Module Module - { - get { return _baseType.Module; } - } - - public override string Namespace - { - get { return _baseType.Namespace; } - } - - public override Type UnderlyingSystemType - { - get { return _baseType.UnderlyingSystemType; } - } - - public override object[] GetCustomAttributes(Type attributeType, bool inherit) - { - return _baseType.GetCustomAttributes(attributeType, inherit); - } - - public override object[] GetCustomAttributes(bool inherit) - { - return _baseType.GetCustomAttributes(inherit); - } - - public override bool IsDefined(Type attributeType, bool inherit) - { - return _baseType.IsDefined(attributeType, inherit); - } - - public override string Name - { - get { return _baseType.Name; } - } - } - - // Custom implementation of the PropertyInfo - private class CustomPropertyInfoHelper : PropertyInfo - { - public string _name; - public Type _type; - public List _attributes = new List(); - - - public CustomPropertyInfoHelper(string name, Type type) - { - _name = name; - _type = type; - } - - public CustomPropertyInfoHelper(string name, Type type, List attributes) - { - _name = name; - _type = type; - _attributes = attributes; - } - - public override PropertyAttributes Attributes - { - get { throw new NotImplementedException(); } - } - - public override bool CanRead - { - get { return true; } - } - - public override bool CanWrite - { - get { return true; } - } - - public override MethodInfo[] GetAccessors(bool nonPublic) - { - throw new NotImplementedException(); - } - - public override MethodInfo GetGetMethod(bool nonPublic) - { - throw new NotImplementedException(); - } - - public override ParameterInfo[] GetIndexParameters() - { - throw new NotImplementedException(); - } - - public override MethodInfo GetSetMethod(bool nonPublic) - { - throw new NotImplementedException(); - } - - // Returns the value from the dictionary stored in the Customer's instance. - public override object GetValue(object obj, BindingFlags invokeAttr, Binder binder, object[] index, System.Globalization.CultureInfo culture) - { - - return obj.GetType().GetMethod("GetPropertyValue").Invoke(obj, new[] { _name }); - } - - public override Type PropertyType - { - get { return _type; } - } - - // Sets the value in the dictionary stored in the Customer's instance. - public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, System.Globalization.CultureInfo culture) - { - obj.GetType().GetMethod("SetPropertyValue").Invoke(obj, new[] { _name, value }); - } - - public override Type DeclaringType - { - get { throw new NotImplementedException(); } - } - - public override object[] GetCustomAttributes(Type attributeType, bool inherit) - { - var attrs = from a in _attributes where a.GetType() == attributeType select a; - return attrs.ToArray(); - } - - public override object[] GetCustomAttributes(bool inherit) - { - return _attributes.ToArray(); - } - - public override bool IsDefined(Type attributeType, bool inherit) - { - throw new NotImplementedException(); - } - - public override string Name - { - get { return _name; } - } - - public override Type ReflectedType - { - get { throw new NotImplementedException(); } - } - - internal List CustomAttributesInternal - { - get { return _attributes; } - } - } -} -#endregion - + + -```` -````VB.NET -Friend Class CustomTypeHelper(Of T) - Implements ICustomTypeProvider - Implements INotifyPropertyChanged - - Private Shared customProperties As List(Of CustomPropertyInfoHelper) = New List(Of CustomPropertyInfoHelper)() - Private customPropertyValues As Dictionary(Of String, Object) - Private [ctype] As CustomType - Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged - - Private Sub NotifyPropertyChanged(ByVal info As String) - RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info)) - End Sub - - Public Sub New() - customPropertyValues = New Dictionary(Of String, Object)() - - For Each [property] In Me.GetCustomType().GetProperties() - customPropertyValues.Add([property].Name, Nothing) - Next - End Sub - - Public Shared Sub AddProperty(ByVal name As String) - If Not CheckIfNameExists(name) Then customProperties.Add(New CustomPropertyInfoHelper(name, GetType(String))) - End Sub - - Public Shared Sub AddProperty(ByVal name As String, ByVal propertyType As Type) - If Not CheckIfNameExists(name) Then customProperties.Add(New CustomPropertyInfoHelper(name, propertyType)) - End Sub - - Public Shared Sub AddProperty(ByVal name As String, ByVal propertyType As Type, ByVal attributes As List(Of Attribute)) - If Not CheckIfNameExists(name) Then customProperties.Add(New CustomPropertyInfoHelper(name, propertyType, attributes)) - End Sub - - Private Shared Function CheckIfNameExists(ByVal _name As String) As Boolean - If (From p In customProperties Select p.Name).Contains(_name) OrElse (From p In GetType(T).GetProperties() Select p.Name).Contains(_name) Then - Throw New Exception("The property with this name already exists: " & _name) - Else - Return False - End If - End Function - - Public Sub SetPropertyValue(ByVal propertyName As String, ByVal value As Object) - Dim propertyInfo As CustomPropertyInfoHelper = (From prop In customProperties Where prop.Name = propertyName Select prop).FirstOrDefault() - If Not customPropertyValues.ContainsKey(propertyName) Then customPropertyValues.Add(propertyName, Nothing) - - If ValidateValueType(value, propertyInfo._type) Then - - If customPropertyValues(propertyName) <> value Then - customPropertyValues(propertyName) = value - NotifyPropertyChanged(propertyName) - End If - Else - Throw New Exception("Value is of the wrong type or null for a non-nullable type.") - End If - End Sub - - Private Function ValidateValueType(ByVal value As Object, ByVal type As Type) As Boolean - If value Is Nothing OrElse TypeOf value Is System.DBNull Then - - If Not type.IsValueType Then - Return True - Else - Return (type.IsGenericType AndAlso type.GetGenericTypeDefinition() = GetType(Nullable(Of))) - End If - Else - Return type.IsAssignableFrom(value.[GetType]()) - End If - End Function - - Public Function GetPropertyValue(ByVal propertyName As String) As Object - If customPropertyValues.ContainsKey(propertyName) Then - Return customPropertyValues(propertyName) - Else - Throw New Exception("There is no property " & propertyName) - End If - End Function - - Public Function GetProperties() As PropertyInfo() - Return Me.GetCustomType().GetProperties() - End Function - - Public Function GetCustomType() As Type Implements ICustomTypeProvider.GetCustomType - If [ctype] Is Nothing Then - [ctype] = New CustomType(GetType(T)) - End If - - Return [ctype] - End Function - - Private Class CustomType - Inherits Type - - Private _baseType As Type - - Public Sub New(ByVal delegatingType As Type) - _baseType = delegatingType - End Sub - - Public Overrides ReadOnly Property Assembly As Assembly - Get - Return _baseType.Assembly - End Get - End Property - - Public Overrides ReadOnly Property AssemblyQualifiedName As String - Get - Return _baseType.AssemblyQualifiedName - End Get - End Property - - Public Overrides ReadOnly Property BaseType As Type - Get - Return _baseType.BaseType - End Get - End Property - - Public Overrides ReadOnly Property FullName As String - Get - Return _baseType.FullName - End Get - End Property - - Public Overrides ReadOnly Property GUID As Guid - Get - Return _baseType.GUID - End Get - End Property - - Protected Overrides Function GetAttributeFlagsImpl() As TypeAttributes - Throw New NotImplementedException() - End Function - - Protected Overrides Function GetConstructorImpl(ByVal bindingAttr As BindingFlags, ByVal binder As Binder, - ByVal callConvention As CallingConventions, ByVal types As Type(), - ByVal modifiers As ParameterModifier()) As ConstructorInfo - Throw New NotImplementedException() - End Function - - Public Overrides Function GetConstructors(ByVal bindingAttr As BindingFlags) As ConstructorInfo() - Return _baseType.GetConstructors(bindingAttr) - End Function - - Public Overrides Function GetElementType() As Type - Return _baseType.GetElementType() - End Function - - Public Overrides Function GetEvent(ByVal name As String, ByVal bindingAttr As BindingFlags) As EventInfo - Return _baseType.GetEvent(name, bindingAttr) - End Function - - Public Overrides Function GetEvents(ByVal bindingAttr As BindingFlags) As EventInfo() - Return _baseType.GetEvents(bindingAttr) - End Function - - Public Overrides Function GetField(ByVal name As String, ByVal bindingAttr As BindingFlags) As FieldInfo - Return _baseType.GetField(name, bindingAttr) - End Function - - Public Overrides Function GetFields(ByVal bindingAttr As BindingFlags) As FieldInfo() - Return _baseType.GetFields(bindingAttr) - End Function - - Public Overrides Function GetInterface(ByVal name As String, ByVal ignoreCase As Boolean) As Type - Return _baseType.GetInterface(name, ignoreCase) - End Function - - Public Overrides Function GetInterfaces() As Type() - Return _baseType.GetInterfaces() - End Function - - Public Overrides Function GetMembers(ByVal bindingAttr As BindingFlags) As MemberInfo() - Return _baseType.GetMembers(bindingAttr) - End Function - - Protected Overrides Function GetMethodImpl(ByVal name As String, ByVal bindingAttr As BindingFlags, ByVal binder As Binder, - ByVal callConvention As CallingConventions, ByVal types As Type(), - ByVal modifiers As ParameterModifier()) As MethodInfo - Throw New NotImplementedException() - End Function - - Public Overrides Function GetMethods(ByVal bindingAttr As BindingFlags) As MethodInfo() - Return _baseType.GetMethods(bindingAttr) - End Function - - Public Overrides Function GetNestedType(ByVal name As String, ByVal bindingAttr As BindingFlags) As Type - Return _baseType.GetNestedType(name, bindingAttr) - End Function - - Public Overrides Function GetNestedTypes(ByVal bindingAttr As BindingFlags) As Type() - Return _baseType.GetNestedTypes(bindingAttr) - End Function - - Public Overrides Function GetProperties(ByVal bindingAttr As BindingFlags) As PropertyInfo() - Dim clrProperties As PropertyInfo() = _baseType.GetProperties(bindingAttr) - - If clrProperties IsNot Nothing Then - Return clrProperties.Concat(customProperties).ToArray() - Else - Return customProperties.ToArray() - End If - End Function - - Protected Overrides Function GetPropertyImpl(ByVal name As String, ByVal bindingAttr As BindingFlags, ByVal binder As Binder, - ByVal returnType As Type, ByVal types As Type(), ByVal modifiers As ParameterModifier()) As PropertyInfo - Dim propertyInfo As PropertyInfo = (From prop In GetProperties(bindingAttr) Where prop.Name = name Select prop).FirstOrDefault() - - If propertyInfo Is Nothing Then - propertyInfo = (From prop In customProperties Where prop.Name = name Select prop).FirstOrDefault() - End If - - Return propertyInfo - End Function - - Protected Overrides Function HasElementTypeImpl() As Boolean - Throw New NotImplementedException() - End Function - - Public Overrides Function InvokeMember(ByVal name As String, ByVal invokeAttr As BindingFlags, ByVal binder As Binder, - ByVal target As Object, ByVal args As Object(), ByVal modifiers As ParameterModifier(), - ByVal culture As System.Globalization.CultureInfo, ByVal namedParameters As String()) As Object - Return _baseType.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters) - End Function - - Protected Overrides Function IsArrayImpl() As Boolean - Throw New NotImplementedException() - End Function - - Protected Overrides Function IsByRefImpl() As Boolean - Throw New NotImplementedException() - End Function - - Protected Overrides Function IsCOMObjectImpl() As Boolean - Throw New NotImplementedException() - End Function - - Protected Overrides Function IsPointerImpl() As Boolean - Throw New NotImplementedException() - End Function - - Protected Overrides Function IsPrimitiveImpl() As Boolean - Return _baseType.IsPrimitive - End Function - - Public Overrides ReadOnly Property [Module] As [Module] - Get - Return _baseType.[Module] - End Get - End Property - - Public Overrides ReadOnly Property [Namespace] As String - Get - Return _baseType.[Namespace] - End Get - End Property - - Public Overrides ReadOnly Property UnderlyingSystemType As Type - Get - Return _baseType.UnderlyingSystemType - End Get - End Property - - Public Overrides Function GetCustomAttributes(ByVal attributeType As Type, ByVal inherit As Boolean) As Object() - Return _baseType.GetCustomAttributes(attributeType, inherit) - End Function - - Public Overrides Function GetCustomAttributes(ByVal inherit As Boolean) As Object() - Return _baseType.GetCustomAttributes(inherit) - End Function - - Public Overrides Function IsDefined(ByVal attributeType As Type, ByVal inherit As Boolean) As Boolean - Return _baseType.IsDefined(attributeType, inherit) - End Function - - Public Overrides ReadOnly Property Name As String - Get - Return _baseType.Name - End Get - End Property - End Class - - Private Class CustomPropertyInfoHelper - Inherits PropertyInfo - - Public _name As String - Public _type As Type - Public _attributes As List(Of Attribute) = New List(Of Attribute)() - - Public Sub New(ByVal name As String, ByVal type As Type) - _name = name - _type = type - End Sub - - Public Sub New(ByVal name As String, ByVal type As Type, ByVal attributes As List(Of Attribute)) - _name = name - _type = type - _attributes = attributes - End Sub - - Public Overrides ReadOnly Property Attributes As PropertyAttributes - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides ReadOnly Property CanRead As Boolean - Get - Return True - End Get - End Property - - Public Overrides ReadOnly Property CanWrite As Boolean - Get - Return True - End Get - End Property - - Public Overrides Function GetAccessors(ByVal nonPublic As Boolean) As MethodInfo() - Throw New NotImplementedException() - End Function - - Public Overrides Function GetGetMethod(ByVal nonPublic As Boolean) As MethodInfo - Throw New NotImplementedException() - End Function - - Public Overrides Function GetIndexParameters() As ParameterInfo() - Throw New NotImplementedException() - End Function - - Public Overrides Function GetSetMethod(ByVal nonPublic As Boolean) As MethodInfo - Throw New NotImplementedException() - End Function - - Public Overrides Function GetValue(ByVal obj As Object, ByVal invokeAttr As BindingFlags, ByVal binder As Binder, - ByVal index As Object(), ByVal culture As System.Globalization.CultureInfo) As Object - Return obj.[GetType]().GetMethod("GetPropertyValue").Invoke(obj, {_name}) - End Function - - Public Overrides ReadOnly Property PropertyType As Type - Get - Return _type - End Get - End Property - - Public Overrides Sub SetValue(ByVal obj As Object, ByVal value As Object, ByVal invokeAttr As BindingFlags, - ByVal binder As Binder, ByVal index As Object(), ByVal culture As System.Globalization.CultureInfo) - obj.[GetType]().GetMethod("SetPropertyValue").Invoke(obj, {_name, value}) - End Sub - - Public Overrides ReadOnly Property DeclaringType As Type - Get - Throw New NotImplementedException() - End Get - End Property - - Public Overrides Function GetCustomAttributes(ByVal attributeType As Type, ByVal inherit As Boolean) As Object() - Dim attrs = From a In _attributes Where a.[GetType]() = attributeType Select a - Return attrs.ToArray() - End Function - - Public Overrides Function GetCustomAttributes(ByVal inherit As Boolean) As Object() - Return _attributes.ToArray() - End Function - - Public Overrides Function IsDefined(ByVal attributeType As Type, ByVal inherit As Boolean) As Boolean - Throw New NotImplementedException() - End Function - - Public Overrides ReadOnly Property Name As String - Get - Return _name - End Get - End Property - - Public Overrides ReadOnly Property ReflectedType As Type - Get - Throw New NotImplementedException() - End Get - End Property - - Friend ReadOnly Property CustomAttributesInternal As List(Of Attribute) - Get - Return _attributes - End Get - End Property - End Class -End Class - - -```` - -{{endregion}} 3\.Last, we will setup the RadPivotGrid control: -{{source=..\SamplesCS\PivotGrid\PopulatingWithData\PivotCustomTypeProvider.cs region=Usage}} -{{source=..\SamplesVB\PivotGrid\PopulatingWithData\PivotCustomTypeProvider.vb region=Usage}} - -````C# - -private List customers = new List(); -private LocalDataSourceProvider localDataProvider; - -public PivotCustomTypeProvider() -{ - InitializeComponent(); - - this.localDataProvider = new LocalDataSourceProvider(); - this.radPivotGrid1.DataProvider = this.localDataProvider; - - this.localDataProvider.RowGroupDescriptions.Add(new PropertyGroupDescription() - { - PropertyName = "FirstName" - }); - - this.localDataProvider.ColumnGroupDescriptions.Add(new PropertyGroupDescription() - { - PropertyName = "Married" - }); - - this.localDataProvider.ColumnGroupDescriptions.Add(new PropertyGroupDescription() - { - PropertyName = "LastName" - }); - - this.localDataProvider.AggregateDescriptions.Add(new PropertyAggregateDescription() - { - PropertyName = "Age", - AggregateFunction = AggregateFunctions.Average - }); - - Customer.AddProperty("Address", typeof(string)); - Customer.AddProperty("Age", typeof(int?)); - Customer.AddProperty("Married", typeof(bool?)); - Customer.AddProperty("Income", typeof(double?)); - - Customer customer1 = new Customer { FirstName = "Mary", LastName = "Smith" }; - customer1.SetPropertyValue("Address", "C1 address"); - customer1.SetPropertyValue("Age", 40); - customer1.SetPropertyValue("Married", true); - customer1.SetPropertyValue("Income", 100000.0); - - Customer customer2 = new Customer { FirstName = "John", LastName = "Smith" }; - customer2.SetPropertyValue("Address", "C2 address"); - customer2.SetPropertyValue("Age", 45); - customer2.SetPropertyValue("Married", false); - customer2.SetPropertyValue("Income", 75000.0); - - this.customers.Add(customer1); - this.customers.Add(customer2); - this.localDataProvider.ItemsSource = this.customers; -} - -```` -````VB.NET - -Private customers As List(Of Customer) -Private localDataProvider As LocalDataSourceProvider - -Public Sub New() - InitializeComponent() - customers = New List(Of Customer)() - Me.localDataProvider = New LocalDataSourceProvider() - Me.RadPivotGrid1.DataProvider = Me.localDataProvider - Me.localDataProvider.RowGroupDescriptions.Add(New PropertyGroupDescription() With { - .PropertyName = "FirstName" - }) - Me.localDataProvider.ColumnGroupDescriptions.Add(New PropertyGroupDescription() With { - .PropertyName = "Married" - }) - Me.localDataProvider.ColumnGroupDescriptions.Add(New PropertyGroupDescription() With { - .PropertyName = "LastName" - }) - Me.localDataProvider.AggregateDescriptions.Add(New PropertyAggregateDescription() With { - .PropertyName = "Age", - .AggregateFunction = AggregateFunctions.Average - }) - Customer.AddProperty("Address", GetType(String)) - Customer.AddProperty("Age", GetType(Integer?)) - Customer.AddProperty("Married", GetType(Boolean?)) - Customer.AddProperty("Income", GetType(Double?)) - Dim customer1 As Customer = New Customer With { - .FirstName = "Mary", - .LastName = "Smith" - } - customer1.SetPropertyValue("Address", "C1 address") - customer1.SetPropertyValue("Age", 40) - customer1.SetPropertyValue("Married", True) - customer1.SetPropertyValue("Income", 100000.0) - Dim customer2 As Customer = New Customer With { - .FirstName = "John", - .LastName = "Smith" - } - customer2.SetPropertyValue("Address", "C2 address") - customer2.SetPropertyValue("Age", 45) - customer2.SetPropertyValue("Married", False) - customer2.SetPropertyValue("Income", 75000.0) - Me.customers.Add(customer1) - Me.customers.Add(customer2) - Me.localDataProvider.ItemsSource = Me.customers -End Sub + + -```` -{{endregion}} The achieved result is illustrated below: diff --git a/controls/pivotgrid/populating-with-data/using-the-adomddataprovider.md b/controls/pivotgrid/populating-with-data/using-the-adomddataprovider.md index 40a149f0b..1daacb462 100644 --- a/controls/pivotgrid/populating-with-data/using-the-adomddataprovider.md +++ b/controls/pivotgrid/populating-with-data/using-the-adomddataprovider.md @@ -50,29 +50,10 @@ To show data in **RadPivotGrid** and **RadPivotFieldList** we have to connect to #### Connecting to OLAP Cube -{{source=..\SamplesCS\PivotGrid\PopulatingWithData\PivotGridUsingAdomdDataProvider.cs region=DefininingAdomdDataProvider}} -{{source=..\SamplesVB\PivotGrid\PopulatingWithData\PivotGridUsingAdomdDataProvider.vb region=DefininingAdomdDataProvider}} - -````C# -AdomdDataProvider provider = new AdomdDataProvider(); -AdomdConnectionSettings settings = new AdomdConnectionSettings(); -settings.Cube = "Adventure Works"; -settings.Database = "Adventure Works DW 2008R2"; -settings.ConnectionString = "Data Source=https://demos.telerik.com/olap/msmdpump.dll;Catalog=Adventure Works DW 2008R2"; -provider.ConnectionSettings = settings; - -```` -````VB.NET -Dim provider As New AdomdDataProvider() -Dim settings As New AdomdConnectionSettings() -settings.Cube = "Adventure Works" -settings.Database = "Adventure Works DW 2008R2" -settings.ConnectionString = "Data Source=https://demos.telerik.com/olap/msmdpump.dll;Catalog=Adventure Works DW 2008R2" -provider.ConnectionSettings = settings - -```` - -{{endregion}} + + + + ## Defining Group Descriptions @@ -98,43 +79,10 @@ The **AdomdAggregateDescription** is used to define data that has to be aggregat #### Adding Adomd Descriptions -{{source=..\SamplesCS\PivotGrid\PopulatingWithData\PivotGridUsingAdomdDataProvider.cs region=DefiningDescriptors}} -{{source=..\SamplesVB\PivotGrid\PopulatingWithData\PivotGridUsingAdomdDataProvider.vb region=DefiningDescriptors}} - -````C# -provider.BeginInit(); -provider.RowGroupDescriptions.Add(new AdomdGroupDescription() { MemberName = "[Date].[Calendar Year]" }); -provider.RowGroupDescriptions.Add(new AdomdGroupDescription() { MemberName = "[Date].[Calendar Quarter of Year]" }); -provider.ColumnGroupDescriptions.Add(new AdomdGroupDescription() { MemberName = "[Promotion].[Promotion Category]" }); -provider.ColumnGroupDescriptions.Add(new AdomdGroupDescription() { MemberName = "[Product].[Category]" }); -provider.AggregateDescriptions.Add(new AdomdAggregateDescription() { MemberName = "[Measures].[Internet Order Quantity]" }); -provider.EndInit(); -this.radPivotGrid1.PivotGridElement.DataProvider = provider; - -```` -````VB.NET -provider.BeginInit() -provider.RowGroupDescriptions.Add(New AdomdGroupDescription() With { _ - .MemberName = "[Date].[Calendar Year]" _ -}) -provider.RowGroupDescriptions.Add(New AdomdGroupDescription() With { _ - .MemberName = "[Date].[Calendar Quarter of Year]" _ -}) -provider.ColumnGroupDescriptions.Add(New AdomdGroupDescription() With { _ - .MemberName = "[Promotion].[Promotion Category]" _ -}) -provider.ColumnGroupDescriptions.Add(New AdomdGroupDescription() With { _ - .MemberName = "[Product].[Category]" _ -}) -provider.AggregateDescriptions.Add(New AdomdAggregateDescription() With { _ - .MemberName = "[Measures].[Internet Order Quantity]" _ -}) -provider.EndInit() -Me.RadPivotGrid1.PivotGridElement.DataProvider = provider - -```` - -{{endregion}} + + + + ## Distinct Values Limit diff --git a/controls/pivotgrid/populating-with-data/using-the-datasource-property.md b/controls/pivotgrid/populating-with-data/using-the-datasource-property.md index 51e17329f..2943dd711 100644 --- a/controls/pivotgrid/populating-with-data/using-the-datasource-property.md +++ b/controls/pivotgrid/populating-with-data/using-the-datasource-property.md @@ -15,69 +15,10 @@ Similarly to other WinForms data controls, **RadPivotGrid** can be populated wit #### Setting DataSource and DataMember -{{source=..\SamplesCS\PivotGrid\PopulatingWithData\PivotGridUsingTheDataSourceProperty.cs region=FillWithData}} -{{source=..\SamplesVB\PivotGrid\PopulatingWithData\PivotGridUsingTheDataSourceProperty.vb region=FillWithData}} - -````C# -this.radPivotGrid1.RowGroupDescriptions.Add(new DateTimeGroupDescription() { PropertyName = "OrderDate", Step = DateTimeStep.Year, GroupComparer = new GroupNameComparer() }); -this.radPivotGrid1.RowGroupDescriptions.Add(new DateTimeGroupDescription() { PropertyName = "OrderDate", Step = DateTimeStep.Quarter, GroupComparer = new GroupNameComparer() }); -this.radPivotGrid1.RowGroupDescriptions.Add(new DateTimeGroupDescription() { PropertyName = "OrderDate", Step = DateTimeStep.Month, GroupComparer = new GroupNameComparer() }); -this.radPivotGrid1.ColumnGroupDescriptions.Add(new PropertyGroupDescription() { PropertyName = "EmployeeID", GroupComparer = new GrandTotalComparer() }); -this.radPivotGrid1.AggregateDescriptions.Add(new PropertyAggregateDescription() { PropertyName = "Freight", AggregateFunction = AggregateFunctions.Sum }); -this.radPivotGrid1.AggregateDescriptions.Add(new PropertyAggregateDescription() { PropertyName = "Freight", AggregateFunction = AggregateFunctions.Average }); -this.radPivotGrid1.FilterDescriptions.Add(new PropertyFilterDescription() { PropertyName = "ShipCountry", CustomName = "Country" }); -NwindDataSet dataset = new NwindDataSet(); -SamplesCS.DataSources.NwindDataSetTableAdapters.OrdersTableAdapter adapter = new SamplesCS.DataSources.NwindDataSetTableAdapters.OrdersTableAdapter(); -adapter.Fill(dataset.Orders); -BindingSource bs = new BindingSource(); -bs.DataSource = dataset; -bs.DataMember = "Orders"; -this.radPivotGrid1.DataSource = bs; - -```` -````VB.NET -Me.RadPivotGrid1.RowGroupDescriptions.Add(New DateTimeGroupDescription() With { - .PropertyName = "OrderDate", - .[Step] = DateTimeStep.Year, - .GroupComparer = New GroupNameComparer() -}) -Me.RadPivotGrid1.RowGroupDescriptions.Add(New DateTimeGroupDescription() With { - .PropertyName = "OrderDate", - .[Step] = DateTimeStep.Quarter, - .GroupComparer = New GroupNameComparer() -}) -Me.RadPivotGrid1.RowGroupDescriptions.Add(New DateTimeGroupDescription() With { - .PropertyName = "OrderDate", - .[Step] = DateTimeStep.Month, - .GroupComparer = New GroupNameComparer() -}) -Me.RadPivotGrid1.ColumnGroupDescriptions.Add(New PropertyGroupDescription() With { - .PropertyName = "EmployeeID", - .GroupComparer = New GrandTotalComparer() -}) -Me.RadPivotGrid1.AggregateDescriptions.Add(New PropertyAggregateDescription() With { - .PropertyName = "Freight", - .AggregateFunction = AggregateFunctions.Sum -}) -Me.RadPivotGrid1.AggregateDescriptions.Add(New PropertyAggregateDescription() With { - .PropertyName = "Freight", - .AggregateFunction = AggregateFunctions.Average -}) -Me.RadPivotGrid1.FilterDescriptions.Add(New PropertyFilterDescription() With { - .PropertyName = "ShipCountry", - .CustomName = "Country" -}) -Dim dataset As New NwindDataSet() -Dim adapter As New NwindDataSetTableAdapters.OrdersTableAdapter() -adapter.Fill(dataset.Orders) -Dim bs As New BindingSource() -bs.DataSource = dataset -bs.DataMember = "Orders" -Me.RadPivotGrid1.DataSource = bs - -```` - -{{endregion}} + + + + >note When you set the DataSource and DataMember properties, RadPivotGrid will automatically prepare a **LocalDataSourceProvider** and use it internally. > @@ -92,47 +33,9 @@ The local data source provider is built dynamically while binding **RadPivotGrid #### Setting Culture -{{source=..\SamplesCS\PivotGrid\PopulatingWithData\PivotGridUsingTheDataSourceProperty.cs region=LocalizingDataProvider}} -{{source=..\SamplesVB\PivotGrid\PopulatingWithData\PivotGridUsingTheDataSourceProperty.vb region=LocalizingDataProvider}} -````C# -public PivotGridUsingTheDataSourceProperty() -{ - InitializeComponent(); - FillWithData(); - this.radPivotGrid1.UpdateCompleted += RadPivotGrid1_UpdateCompleted; -} -private void RadPivotGrid1_UpdateCompleted(object sender, EventArgs e) -{ - this.radPivotGrid1.UpdateCompleted -= RadPivotGrid1_UpdateCompleted; - LocalDataSourceProvider dataProvider = this.radPivotGrid1.DataProvider as LocalDataSourceProvider; - if (dataProvider != null) - { - dataProvider.Culture = new System.Globalization.CultureInfo("de-DE"); - dataProvider.Refresh(); - } -} - -```` -````VB.NET -Public Sub New() - InitializeComponent() - FillWithData() - AddHandler Me.RadPivotGrid1.UpdateCompleted, AddressOf RadPivotGrid1_UpdateCompleted -End Sub -Private Sub RadPivotGrid1_UpdateCompleted(sender As Object, e As EventArgs) - RemoveHandler Me.RadPivotGrid1.UpdateCompleted, AddressOf RadPivotGrid1_UpdateCompleted - Dim dataProvider = TryCast(Me.RadPivotGrid1.DataProvider, LocalDataSourceProvider) - If dataProvider IsNot Nothing Then - dataProvider.Culture = New System.Globalization.CultureInfo("de-DE") - dataProvider.Refresh() - End If -End Sub - -```` - - - -{{endregion}} + + + # See Also diff --git a/controls/pivotgrid/populating-with-data/using-the-localsourcedataprovider.md b/controls/pivotgrid/populating-with-data/using-the-localsourcedataprovider.md index 0e1dae7ef..4c8dd8cfb 100644 --- a/controls/pivotgrid/populating-with-data/using-the-localsourcedataprovider.md +++ b/controls/pivotgrid/populating-with-data/using-the-localsourcedataprovider.md @@ -19,21 +19,10 @@ You can create an object of type **LocalDataSourceProvider** and assign it to Ra #### Set ItemSource -{{source=..\SamplesCS\PivotGrid\PopulatingWithData\PivotGridUsingTheLocalSourceDataProvider.cs region=InitializeProvider}} -{{source=..\SamplesVB\PivotGrid\PopulatingWithData\PivotGridUsingTheLocalSourceDataProvider.vb region=InitializeProvider}} + + -````C# -LocalDataSourceProvider dataProvider = new LocalDataSourceProvider(); -dataProvider.ItemsSource = dataset.Orders; -```` -````VB.NET -Dim dataProvider As New LocalDataSourceProvider() -dataProvider.ItemsSource = dataset.Orders - -```` - -{{endregion}} >note The **ItemSource** can be any collection that implements IEnumerable interface or even a DataTable. > @@ -49,60 +38,19 @@ The **LocalDataSourceProvider** is using four different collections for the data #### Add Row Descriptions -{{source=..\SamplesCS\PivotGrid\PopulatingWithData\PivotGridUsingTheLocalSourceDataProvider.cs region=RowGroupDescriptions}} -{{source=..\SamplesVB\PivotGrid\PopulatingWithData\PivotGridUsingTheLocalSourceDataProvider.vb region=RowGroupDescriptions}} - -````C# -dataProvider.BeginInit(); -dataProvider.RowGroupDescriptions.Add(new DateTimeGroupDescription() { PropertyName = "OrderDate", Step = DateTimeStep.Year, GroupComparer = new GroupNameComparer() }); -dataProvider.RowGroupDescriptions.Add(new DateTimeGroupDescription() { PropertyName = "OrderDate", Step = DateTimeStep.Quarter, GroupComparer = new GroupNameComparer() }); -dataProvider.RowGroupDescriptions.Add(new DateTimeGroupDescription() { PropertyName = "OrderDate", Step = DateTimeStep.Month, GroupComparer = new GroupNameComparer() }); -dataProvider.EndInit(); - -```` -````VB.NET -dataProvider.BeginInit() -dataProvider.RowGroupDescriptions.Add(New DateTimeGroupDescription() With { _ - .PropertyName = "OrderDate", _ - .[Step] = DateTimeStep.Year, _ - .GroupComparer = New GroupNameComparer() _ -}) -dataProvider.RowGroupDescriptions.Add(New DateTimeGroupDescription() With { _ - .PropertyName = "OrderDate", _ - .[Step] = DateTimeStep.Quarter, _ - .GroupComparer = New GroupNameComparer() _ -}) -dataProvider.RowGroupDescriptions.Add(New DateTimeGroupDescription() With { _ - .PropertyName = "OrderDate", _ - .[Step] = DateTimeStep.Month, _ - .GroupComparer = New GroupNameComparer() _ -}) -dataProvider.EndInit() - -```` - -{{endregion}} + + -* __ColumnGroupDescription__: The data added to this description will be shown as columns headers in RadPivotGrid and RadPivotFieldList. The properties can be defined as **PropertyGroupDescription**, **DateTimeGroupDescription**, **DoubleGroupDescription** or you can create custom implementation of **PropertyGroupDescriptionBase** class.Here's how to define the column group descriptions in your application: -#### Add Columns Descriptions -{{source=..\SamplesCS\PivotGrid\PopulatingWithData\PivotGridUsingTheLocalSourceDataProvider.cs region=ColumnGroupDescriptions}} -{{source=..\SamplesVB\PivotGrid\PopulatingWithData\PivotGridUsingTheLocalSourceDataProvider.vb region=ColumnGroupDescriptions}} +* __ColumnGroupDescription__: The data added to this description will be shown as columns headers in RadPivotGrid and RadPivotFieldList. The properties can be defined as **PropertyGroupDescription**, **DateTimeGroupDescription**, **DoubleGroupDescription** or you can create custom implementation of **PropertyGroupDescriptionBase** class.Here's how to define the column group descriptions in your application: -````C# -dataProvider.ColumnGroupDescriptions.Add(new PropertyGroupDescription() { PropertyName = "EmployeeID", GroupComparer = new GrandTotalComparer() }); +#### Add Columns Descriptions -```` -````VB.NET -dataProvider.ColumnGroupDescriptions.Add(New PropertyGroupDescription() With { _ - .PropertyName = "EmployeeID", _ - .GroupComparer = New GrandTotalComparer() _ -}) + + -```` -{{endregion}} * __AggregateDescriptions__: The data added to this description will be aggregated and included in RadPivotGrid as cells. The properties can be defined as **PropertyAggregateDescription** or you can create custom implementation of **PropertyAggregateDescriptionBase** class. @@ -113,52 +61,19 @@ Here's how to define the aggregate descriptions in your application: #### Add Aggregate Descriptions -{{source=..\SamplesCS\PivotGrid\PopulatingWithData\PivotGridUsingTheLocalSourceDataProvider.cs region=AggregateDescriptions}} -{{source=..\SamplesVB\PivotGrid\PopulatingWithData\PivotGridUsingTheLocalSourceDataProvider.vb region=AggregateDescriptions}} - -````C# -dataProvider.BeginInit(); -dataProvider.AggregateDescriptions.Add(new PropertyAggregateDescription() { PropertyName = "Freight", AggregateFunction = AggregateFunctions.Sum }); -dataProvider.AggregateDescriptions.Add(new PropertyAggregateDescription() { PropertyName = "Freight", AggregateFunction = AggregateFunctions.Average }); -dataProvider.EndInit(); + + -```` -````VB.NET -dataProvider.BeginInit() -dataProvider.AggregateDescriptions.Add(New PropertyAggregateDescription() With { _ - .PropertyName = "Freight", _ - .AggregateFunction = AggregateFunctions.Sum _ -}) -dataProvider.AggregateDescriptions.Add(New PropertyAggregateDescription() With { _ - .PropertyName = "Freight", _ - .AggregateFunction = AggregateFunctions.Average _ -}) -dataProvider.EndInit() -```` - -{{endregion}} * __FilterDescriptions__: The data added to this description will be filtered and after that included in RadPivotGrid. The properties can be defined as **PropertyFilterDescription** or you can create custom implementation of **PropertyFilterDescriptionBase** class. #### Add Filter Descriptions -{{source=..\SamplesCS\PivotGrid\PopulatingWithData\PivotGridUsingTheLocalSourceDataProvider.cs region=FilterDescriptions}} -{{source=..\SamplesVB\PivotGrid\PopulatingWithData\PivotGridUsingTheLocalSourceDataProvider.vb region=FilterDescriptions}} - -````C# -dataProvider.FilterDescriptions.Add(new PropertyFilterDescription() { PropertyName = "ShipCountry", CustomName = "Country" }); + + -```` -````VB.NET -dataProvider.FilterDescriptions.Add(New PropertyFilterDescription() With { _ - .PropertyName = "ShipCountry", _ - .CustomName = "Country" _ -}) -```` - -{{endregion}} ## Adding Property Descriptors @@ -186,19 +101,10 @@ To apply the already defined data provider, use the following property: #### Set Data Provider -{{source=..\SamplesCS\PivotGrid\PopulatingWithData\PivotGridUsingTheLocalSourceDataProvider.cs region=ApplyingDataProvider}} -{{source=..\SamplesVB\PivotGrid\PopulatingWithData\PivotGridUsingTheLocalSourceDataProvider.vb region=ApplyingDataProvider}} - -````C# -this.radPivotGrid1.DataProvider = dataProvider; + + -```` -````VB.NET -Me.RadPivotGrid1.DataProvider = dataProvider -```` - -{{endregion}} ## The Culture Property @@ -206,19 +112,10 @@ The groups formed by the **DateTimeGroupDescription** as well as the number form #### Provider Culture -{{source=..\SamplesCS\PivotGrid\PopulatingWithData\PivotGridUsingTheLocalSourceDataProvider.cs region=culture}} -{{source=..\SamplesVB\PivotGrid\PopulatingWithData\PivotGridUsingTheLocalSourceDataProvider.vb region=culture}} - -````C# -dataProvider.Culture = new System.Globalization.CultureInfo("de-DE"); - -```` -````VB.NET -dataProvider.Culture = New System.Globalization.CultureInfo("de-DE") + + -```` -{{endregion}} # See Also diff --git a/controls/pivotgrid/populating-with-data/using-the-queryabledataprovider.md b/controls/pivotgrid/populating-with-data/using-the-queryabledataprovider.md index 64aacd551..43c155c9f 100644 --- a/controls/pivotgrid/populating-with-data/using-the-queryabledataprovider.md +++ b/controls/pivotgrid/populating-with-data/using-the-queryabledataprovider.md @@ -20,21 +20,10 @@ You can create an object of type __QueryableDataProvider__ and assign it to __Ra #### Set IQueryable Source -{{source=..\SamplesCS\PivotGrid\PopulatingWithData\PivotGridUsingTheQueryableDataProvider.cs region=InitializeProvider}} -{{source=..\SamplesVB\PivotGrid\PopulatingWithData\PivotGridUsingTheQueryableDataProvider.vb region=InitializeProvider}} + + -````C# -this.queryableDataProvider = new QueryableDataProvider() { Source = dataset.Orders.AsQueryable() }; -```` -````VB.NET -Me.queryableDataProvider = New QueryableDataProvider() With { - .Source = dataset.Orders.AsQueryable() -} - -```` - -{{endregion}} >note The Source can be any collection that implements the IQuearyable interface. > @@ -52,40 +41,10 @@ Here's how to define the __RowGroupDescriptions__ in your application: #### Adding Queryable Row Descriptions -{{source=..\SamplesCS\PivotGrid\PopulatingWithData\PivotGridUsingTheQueryableDataProvider.cs region=RowGroupDescriptions}} -{{source=..\SamplesVB\PivotGrid\PopulatingWithData\PivotGridUsingTheQueryableDataProvider.vb region=RowGroupDescriptions}} - -````C# -QueryablePropertyGroupDescription shipCountryGroupDescription = new QueryablePropertyGroupDescription(); -shipCountryGroupDescription.PropertyName = "ShipCountry"; -QueryableDoubleGroupDescription freightCountryGroupDescription = new QueryableDoubleGroupDescription(); -freightCountryGroupDescription.PropertyName = "Freight"; ; -QueryableDateTimeGroupDescription orderDateCountryGroupDescription = new QueryableDateTimeGroupDescription(); -orderDateCountryGroupDescription.PropertyName = "OrderDate"; -using (queryableDataProvider.DeferRefresh()) -{ - queryableDataProvider.RowGroupDescriptions.Add(shipCountryGroupDescription); - queryableDataProvider.RowGroupDescriptions.Add(freightCountryGroupDescription); - queryableDataProvider.RowGroupDescriptions.Add(orderDateCountryGroupDescription); -} - -```` -````VB.NET -Dim shipCountryGroupDescription As New QueryablePropertyGroupDescription() -shipCountryGroupDescription.PropertyName = "ShipCountry" -Dim freightCountryGroupDescription As New QueryableDoubleGroupDescription() -freightCountryGroupDescription.PropertyName = "Freight" -Dim orderDateCountryGroupDescription As New QueryableDateTimeGroupDescription() -orderDateCountryGroupDescription.PropertyName = "OrderDate" -Using queryableDataProvider.DeferRefresh() - queryableDataProvider.RowGroupDescriptions.Add(shipCountryGroupDescription) - queryableDataProvider.RowGroupDescriptions.Add(freightCountryGroupDescription) - queryableDataProvider.RowGroupDescriptions.Add(orderDateCountryGroupDescription) -End Using - -```` - -{{endregion}} + + + + * __ColumnGroupDescription__: The data added to this description will be shown as columns headers in __RadPivotGrid__ and __RadPivotFieldList__. The properties can be defined as __QueryablePropertyGroupDescription__, __QueryableDateTimeGroupDescription__, __QueryableDoubleGroupDescription__ or you can create custom implementation of the __QueryableGroupDescription__ class. @@ -93,24 +52,10 @@ Here's how to define the __ColumnGroupDescriptions__ in your application: #### Adding Queryable Column Descriptions -{{source=..\SamplesCS\PivotGrid\PopulatingWithData\PivotGridUsingTheQueryableDataProvider.cs region=ColumnGroupDescriptions}} -{{source=..\SamplesVB\PivotGrid\PopulatingWithData\PivotGridUsingTheQueryableDataProvider.vb region=ColumnGroupDescriptions}} + + -````C# -this.queryableDataProvider.ColumnGroupDescriptions.Add(new QueryableDoubleGroupDescription -{ - PropertyName = "Freight" -}); -```` -````VB.NET -Me.queryableDataProvider.ColumnGroupDescriptions.Add(New QueryableDoubleGroupDescription() With { - .PropertyName = "Freight" -}) - -```` - -{{endregion}} * __AggregateDescriptions__: The data added to this description will be aggregated and included in __RadPivotGrid__ as cells. The properties can be defined as __QueryablePropertyAggregateDescription__ or you can create custom implementation of the __QueryableAggregateDescription__ class. @@ -121,44 +66,10 @@ Here's how to define the __AggregateDescriptions__ in your application: #### Adding Queryable Aggregate Descriptions -{{source=..\SamplesCS\PivotGrid\PopulatingWithData\PivotGridUsingTheQueryableDataProvider.cs region=AggregateDescriptions}} -{{source=..\SamplesVB\PivotGrid\PopulatingWithData\PivotGridUsingTheQueryableDataProvider.vb region=AggregateDescriptions}} - -````C# -QueryablePropertyAggregateDescription freightAggregateDescription = new QueryablePropertyAggregateDescription -{ - PropertyName = "Freight", - StringFormat = "C", - AggregateFunction = QueryableAggregateFunction.Max -}; -QueryablePropertyAggregateDescription shipViaAggregateDescription = new QueryablePropertyAggregateDescription -{ - PropertyName = "ShipVia" -}; -using (queryableDataProvider.DeferRefresh()) -{ - queryableDataProvider.AggregateDescriptions.Add(freightAggregateDescription); - queryableDataProvider.AggregateDescriptions.Add(shipViaAggregateDescription); -} - -```` -````VB.NET -Dim freightAggregateDescription As New QueryablePropertyAggregateDescription() With { - .PropertyName = "Freight", - .StringFormat = "C", - .AggregateFunction = QueryableAggregateFunction.Max -} -Dim shipViaAggregateDescription As New QueryablePropertyAggregateDescription() With { - .PropertyName = "ShipVia" -} -Using queryableDataProvider.DeferRefresh() - queryableDataProvider.AggregateDescriptions.Add(freightAggregateDescription) - queryableDataProvider.AggregateDescriptions.Add(shipViaAggregateDescription) -End Using - -```` - -{{endregion}} + + + + * __FilterDescriptions__: The data added to this description will be filtered and after that included in __RadPivotGrid__. The properties can be defined as __QueryablePropertyFilterDescription__ or you can create custom implementation of __QueryableFilterDescription__ class. @@ -166,31 +77,9 @@ Here's how to define the __FilterDescriptions__ in your application: #### Adding Queryable Filter Descriptions -{{source=..\SamplesCS\PivotGrid\PopulatingWithData\PivotGridUsingTheQueryableDataProvider.cs region=FilterDescritions}} -{{source=..\SamplesVB\PivotGrid\PopulatingWithData\PivotGridUsingTheQueryableDataProvider.vb region=FilterDescritions}} - -````C# -QueryableIntervalCondition intervalCondition = new QueryableIntervalCondition(); -intervalCondition.From = 10; -intervalCondition.To = 200; -QueryablePropertyFilterDescription freightFilterDescription = new QueryablePropertyFilterDescription(); -freightFilterDescription.PropertyName = "Freight"; -freightFilterDescription.Condition = intervalCondition; -this.queryableDataProvider.FilterDescriptions.Add(freightFilterDescription); - -```` -````VB.NET -Dim intervalCondition As New QueryableIntervalCondition() -intervalCondition.From = 10 -intervalCondition.[To] = 200 -Dim freightFilterDescription As New QueryablePropertyFilterDescription() -freightFilterDescription.PropertyName = "Freight" -freightFilterDescription.Condition = intervalCondition -Me.queryableDataProvider.FilterDescriptions.Add(freightFilterDescription) + + -```` - -{{endregion}} ## Adding Property Descriptors @@ -219,19 +108,10 @@ To apply the already defined data provider, use the following property: #### Set Data Provider -{{source=..\SamplesCS\PivotGrid\PopulatingWithData\PivotGridUsingTheQueryableDataProvider.cs region=ApplyingDataProvider}} -{{source=..\SamplesVB\PivotGrid\PopulatingWithData\PivotGridUsingTheQueryableDataProvider.vb region=ApplyingDataProvider}} - -````C# -this.radPivotGrid1.PivotGridElement.DataProvider = queryableDataProvider; - -```` -````VB.NET -Me.RadPivotGrid1.PivotGridElement.DataProvider = queryableDataProvider + + -```` -{{endregion}} # See Also diff --git a/controls/pivotgrid/populating-with-data/using-the-xmladataprovider.md b/controls/pivotgrid/populating-with-data/using-the-xmladataprovider.md index 25e2f02ae..38f68b0f6 100644 --- a/controls/pivotgrid/populating-with-data/using-the-xmladataprovider.md +++ b/controls/pivotgrid/populating-with-data/using-the-xmladataprovider.md @@ -48,29 +48,10 @@ To show data in RadPivotGrid and RadPivotFieldList we have to connect to OLAP Cu #### Connecting to OLAP Cube -{{source=..\SamplesCS\PivotGrid\PopulatingWithData\PivotGridUsingXmlaDataProvider.cs region=DefininingXmlaDataProvider}} -{{source=..\SamplesVB\PivotGrid\PopulatingWithData\PivotGridUsingXmlaDataProvider.vb region=DefininingXmlaDataProvider}} - -````C# -XmlaDataProvider provider = new XmlaDataProvider(); -XmlaConnectionSettings settings = new XmlaConnectionSettings(); -settings.Cube = "Adventure Works"; -settings.Database = "Adventure Works DW 2008R2"; -settings.ServerAddress = "https://demos.telerik.com/olap/msmdpump.dll"; -provider.ConnectionSettings = settings; - -```` -````VB.NET -Dim provider As New XmlaDataProvider() -Dim settings As New XmlaConnectionSettings() -settings.Cube = "Adventure Works" -settings.Database = "Adventure Works DW 2008R2" -settings.ServerAddress = "https://demos.telerik.com/olap/msmdpump.dll" -provider.ConnectionSettings = settings - -```` - -{{endregion}} + + + + You can set credentials if your connection requires username and password. The Credentials property of XmlaDataProvider expects object of type XmlaNetworkCredential which gives you properties for UserName, Password, SecurePassword and Domain. @@ -100,43 +81,10 @@ Here is how to define these decriptors: #### Adding Xmla Descriptions -{{source=..\SamplesCS\PivotGrid\PopulatingWithData\PivotGridUsingXmlaDataProvider.cs region=DefiningDescriptors}} -{{source=..\SamplesVB\PivotGrid\PopulatingWithData\PivotGridUsingXmlaDataProvider.vb region=DefiningDescriptors}} - -````C# -provider.BeginInit(); -provider.RowGroupDescriptions.Add(new XmlaGroupDescription() { MemberName = "[Date].[Calendar Year]" }); -provider.RowGroupDescriptions.Add(new XmlaGroupDescription() { MemberName = "[Date].[Calendar Quarter of Year]" }); -provider.ColumnGroupDescriptions.Add(new XmlaGroupDescription() { MemberName = "[Promotion].[Promotion Category]" }); -provider.ColumnGroupDescriptions.Add(new XmlaGroupDescription() { MemberName = "[Product].[Category]" }); -provider.AggregateDescriptions.Add(new XmlaAggregateDescription() { MemberName = "[Measures].[Internet Order Quantity]" }); -provider.EndInit(); -this.radPivotGrid1.PivotGridElement.DataProvider = provider; - -```` -````VB.NET -provider.BeginInit() -provider.RowGroupDescriptions.Add(New XmlaGroupDescription() With { _ - .MemberName = "[Date].[Calendar Year]" _ -}) -provider.RowGroupDescriptions.Add(New XmlaGroupDescription() With { _ - .MemberName = "[Date].[Calendar Quarter of Year]" _ -}) -provider.ColumnGroupDescriptions.Add(New XmlaGroupDescription() With { _ - .MemberName = "[Promotion].[Promotion Category]" _ -}) -provider.ColumnGroupDescriptions.Add(New XmlaGroupDescription() With { _ - .MemberName = "[Product].[Category]" _ -}) -provider.AggregateDescriptions.Add(New XmlaAggregateDescription() With { _ - .MemberName = "[Measures].[Internet Order Quantity]" _ -}) -provider.EndInit() -Me.RadPivotGrid1.PivotGridElement.DataProvider = provider - -```` - -{{endregion}} + + + + ## Distinct Values Limit diff --git a/controls/pivotgrid/printing-support/events-and-customization.md b/controls/pivotgrid/printing-support/events-and-customization.md index d89013321..32e7a18b3 100644 --- a/controls/pivotgrid/printing-support/events-and-customization.md +++ b/controls/pivotgrid/printing-support/events-and-customization.md @@ -19,54 +19,10 @@ previous_url: pivotgrid-printing-support-events-and-customization #### Formatting Print Cells -{{source=..\SamplesCS\PivotGrid\PivotGridPrinting.cs region=Formatting}} -{{source=..\SamplesVB\PivotGrid\PivotGridPrinting.vb region=Formatting}} + + -````C# -private void radPivotGrid1_PrintElementFormatting(object sender, Telerik.WinControls.UI.PrintElementEventArgs e) -{ - PivotCellPrintElement cell = e.PrintElement as PivotCellPrintElement; - if (cell != null && cell.Value != null && (Convert.ToDouble(cell.Value)) < 100) - { - cell.BackColor = Color.Red; - } - if (cell != null && cell.Value != null && (Convert.ToDouble(cell.Value)) > 500) - { - cell.BackColor = Color.Green; - } -} -private void radPivotGrid1_PrintElementPaint(object sender, PrintElementPaintEventArgs e) -{ - PivotCellPrintElement cell = e.PrintElement as PivotCellPrintElement; - if (cell != null && cell.Value == null) - { - Brush b = new HatchBrush(HatchStyle.BackwardDiagonal, Color.LightGray, Color.Transparent); - e.Graphics.FillRectangle(b, e.Bounds); - } -} -```` -````VB.NET -Private Sub radPivotGrid1_PrintElementFormatting(sender As Object, e As Telerik.WinControls.UI.PrintElementEventArgs) - Dim cell As PivotCellPrintElement = TryCast(e.PrintElement, PivotCellPrintElement) - If cell IsNot Nothing AndAlso cell.Value IsNot Nothing AndAlso (Convert.ToDouble(cell.Value)) < 100 Then - cell.BackColor = Color.Red - End If - If cell IsNot Nothing AndAlso cell.Value IsNot Nothing AndAlso (Convert.ToDouble(cell.Value)) > 500 Then - cell.BackColor = Color.Green - End If -End Sub -Private Sub radPivotGrid1_PrintElementPaint(sender As Object, e As PrintElementPaintEventArgs) - Dim cell As PivotCellPrintElement = TryCast(e.PrintElement, PivotCellPrintElement) - If cell IsNot Nothing AndAlso cell.Value Is Nothing Then - Dim b As Brush = New HatchBrush(HatchStyle.BackwardDiagonal, Color.LightGray, Color.Transparent) - e.Graphics.FillRectangle(b, e.Bounds) - End If -End Sub - -```` - -{{endregion}} # See Also diff --git a/controls/pivotgrid/printing-support/overview.md b/controls/pivotgrid/printing-support/overview.md index b0e4697b5..b044fae9f 100644 --- a/controls/pivotgrid/printing-support/overview.md +++ b/controls/pivotgrid/printing-support/overview.md @@ -17,21 +17,10 @@ RadPivotGrid has two public methods available for printing – __Print__ and __P #### Print with Dialog -{{source=..\SamplesCS\PivotGrid\PivotGridPrinting.cs region=Print}} -{{source=..\SamplesVB\PivotGrid\PivotGridPrinting.vb region=Print}} + + -````C# -this.radPivotGrid1.Print(); -this.radPivotGrid1.Print(true); -```` -````VB.NET -Me.radPivotGrid1.Print() -Me.radPivotGrid1.Print(True) - -```` - -{{endregion}} >caption Figure 1: Print Dialog @@ -41,19 +30,10 @@ The other available method is __PrintPreview__. It opens a new **RadPrintPreview #### Print Preview Dialog -{{source=..\SamplesCS\PivotGrid\PivotGridPrinting.cs region=PrintPreview}} -{{source=..\SamplesVB\PivotGrid\PivotGridPrinting.vb region=PrintPreview}} - -````C# -this.radPivotGrid1.PrintPreview(); - -```` -````VB.NET -Me.radPivotGrid1.PrintPreview() + + -```` -{{endregion}} >caption Figure 2: RadPrintPreviewDialog diff --git a/controls/pivotgrid/printing-support/pivotgridprintstyle.md b/controls/pivotgrid/printing-support/pivotgridprintstyle.md index a9da8e361..53d370172 100644 --- a/controls/pivotgrid/printing-support/pivotgridprintstyle.md +++ b/controls/pivotgrid/printing-support/pivotgridprintstyle.md @@ -17,127 +17,55 @@ You can modify the default font of the different cell types by using the followi #### Setting Print Font -{{source=..\SamplesCS\PivotGrid\PivotGridPrinting.cs region=PrintStyleFont}} -{{source=..\SamplesVB\PivotGrid\PivotGridPrinting.vb region=PrintStyleFont}} + + -````C# -this.radPivotGrid1.PrintStyle.DataCellsFont = new Font("Segoe UI Light", 8, FontStyle.Regular); -this.radPivotGrid1.PrintStyle.HeaderCellsFont = new Font("Segoe UI Light", 8, FontStyle.Bold); -this.radPivotGrid1.PrintStyle.DecriptorsFont = new Font("Segoe UI Light", 9, FontStyle.Regular); -this.radPivotGrid1.PrintStyle.SubTotalCellsFont = new Font("Segoe UI Light", 8, FontStyle.Italic); -this.radPivotGrid1.PrintStyle.GrandTotalCellsFont = new Font("Segoe UI Light", 8, FontStyle.Italic | FontStyle.Bold); -```` -````VB.NET -Me.radPivotGrid1.PrintStyle.DataCellsFont = New Font("Segoe UI Light", 8, FontStyle.Regular) -Me.radPivotGrid1.PrintStyle.HeaderCellsFont = New Font("Segoe UI Light", 8, FontStyle.Bold) -Me.radPivotGrid1.PrintStyle.DecriptorsFont = New Font("Segoe UI Light", 9, FontStyle.Regular) -Me.radPivotGrid1.PrintStyle.SubTotalCellsFont = New Font("Segoe UI Light", 8, FontStyle.Italic) -Me.radPivotGrid1.PrintStyle.GrandTotalCellsFont = New Font("Segoe UI Light", 8, FontStyle.Italic Or FontStyle.Bold) - -```` - -{{endregion}} In a similar fashion, you can modify the background color for the different cell types: #### Setting Background Color -{{source=..\SamplesCS\PivotGrid\PivotGridPrinting.cs region=PrintStyleColor}} -{{source=..\SamplesVB\PivotGrid\PivotGridPrinting.vb region=PrintStyleColor}} - -````C# -this.radPivotGrid1.PrintStyle.CellBackColor = Color.Wheat; -this.radPivotGrid1.PrintStyle.HeadersBackColor = Color.Gray; -this.radPivotGrid1.PrintStyle.DescriptorsBackColor = Color.Yellow; -this.radPivotGrid1.PrintStyle.SubTotalsBackColor = Color.LightBlue; -this.radPivotGrid1.PrintStyle.GrandTotalsBackColor= Color.Blue; + + -```` -````VB.NET -Me.radPivotGrid1.PrintStyle.CellBackColor = Color.Wheat -Me.radPivotGrid1.PrintStyle.HeadersBackColor = Color.Gray -Me.radPivotGrid1.PrintStyle.DescriptorsBackColor = Color.Yellow -Me.radPivotGrid1.PrintStyle.SubTotalsBackColor = Color.LightBlue -Me.radPivotGrid1.PrintStyle.GrandTotalsBackColor = Color.Blue -```` - -{{endregion}} Sometimes the reports generated by **RadPivotGrid** can be larger than a single page. In this case you can choose to scale the report so that it fits the page area: #### Scaling Printed Pivot -{{source=..\SamplesCS\PivotGrid\PivotGridPrinting.cs region=ScaleMode}} -{{source=..\SamplesVB\PivotGrid\PivotGridPrinting.vb region=ScaleMode}} - -````C# -this.radPivotGrid1.PrintStyle.ScaleMode = Telerik.WinControls.UI.PivotPrintScaleMode.FitAll; - -```` -````VB.NET -Me.radPivotGrid1.PrintStyle.ScaleMode = Telerik.WinControls.UI.PivotPrintScaleMode.FitAll + + -```` -{{endregion}} If you do not want to scale the report, you can choose the order in which pages are printed: #### Setting Page Order -{{source=..\SamplesCS\PivotGrid\PivotGridPrinting.cs region=PageOrder}} -{{source=..\SamplesVB\PivotGrid\PivotGridPrinting.vb region=PageOrder}} + + -````C# -this.radPivotGrid1.PrintStyle.PageOrder = Telerik.WinControls.UI.PivotGridPrintPageOrder.DownThenOver; -```` -````VB.NET -Me.radPivotGrid1.PrintStyle.PageOrder = Telerik.WinControls.UI.PivotGridPrintPageOrder.DownThenOver - -```` - -{{endregion}} To save some spaces, you can enable __CompactLayout__ mode for the printed pages: #### CompactLayout Mode -{{source=..\SamplesCS\PivotGrid\PivotGridPrinting.cs region=Layout}} -{{source=..\SamplesVB\PivotGrid\PivotGridPrinting.vb region=Layout}} - -````C# -this.radPivotGrid1.PrintStyle.LayoutType = Telerik.WinControls.UI.PivotLayout.Compact; -this.radPivotGrid1.PrintStyle.ComactLayoutIndent = 20; + + -```` -````VB.NET -Me.radPivotGrid1.PrintStyle.LayoutType = Telerik.WinControls.UI.PivotLayout.Compact -Me.radPivotGrid1.PrintStyle.ComactLayoutIndent = 20 -```` - -{{endregion}} Additionally, if you do not want to print the entire report but only the selected parts, you can set the following property: #### Print Selection -{{source=..\SamplesCS\PivotGrid\PivotGridPrinting.cs region=PrintSelection}} -{{source=..\SamplesVB\PivotGrid\PivotGridPrinting.vb region=PrintSelection}} - -````C# -this.radPivotGrid1.PrintStyle.PrintSelectionOnly = true; - -```` -````VB.NET -Me.radPivotGrid1.PrintStyle.PrintSelectionOnly = True + + -```` -{{endregion}} # See Also diff --git a/controls/pivotgrid/save-and-load-layout/overview.md b/controls/pivotgrid/save-and-load-layout/overview.md index 39d6bde96..572a7f02e 100644 --- a/controls/pivotgrid/save-and-load-layout/overview.md +++ b/controls/pivotgrid/save-and-load-layout/overview.md @@ -17,79 +17,19 @@ Here is a sample demonstrating how you can implement a Save Layout button event #### SaveLayout -{{source=..\SamplesCS\PivotGrid\PivotGridSaveLoadLayout.cs region=SaveLayout}} -{{source=..\SamplesVB\PivotGrid\PivotGridSaveLoadLayout.vb region=SaveLayout}} - -````C# - -private void radButtonSaveLayout_Click(object sender, EventArgs e) -{ - string s = "default.xml"; - SaveFileDialog dialog = new SaveFileDialog(); - dialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*"; - dialog.Title = "Select a xml file"; - if (dialog.ShowDialog() == DialogResult.OK) - { - s = dialog.FileName; - } - this.radPivotGrid1.SaveLayout(s); -} - -```` -````VB.NET -Private Sub RadButtonSaveLayout_Click(sender As Object, e As EventArgs) Handles RadButtonSaveLayout.Click - Dim s As String = "default.xml" - Dim dialog As New SaveFileDialog() - dialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*" - dialog.Title = "Select a xml file" - If dialog.ShowDialog() = DialogResult.OK Then - s = dialog.FileName - End If - Me.RadPivotGrid1.SaveLayout(s) -End Sub - -```` - -{{endregion}} + + + + The code snippet below demonstrates how you can implement a Load Layout button event handler. #### LoadLayout -{{source=..\SamplesCS\PivotGrid\PivotGridSaveLoadLayout.cs region=LoadLayout}} -{{source=..\SamplesVB\PivotGrid\PivotGridSaveLoadLayout.vb region=LoadLayout}} - -````C# - -private void radButtonLoadLayout_Click(object sender, EventArgs e) -{ - string s = "default.xml"; - OpenFileDialog dialog = new OpenFileDialog(); - dialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*"; - dialog.Title = "Select a xml file"; - if (dialog.ShowDialog() == DialogResult.OK) - { - s = dialog.FileName; - } - this.radPivotGrid1.LoadLayout(s); -} - -```` -````VB.NET -Private Sub RadButtonLoadLayout_Click(sender As Object, e As EventArgs) Handles RadButtonLoadLayout.Click - Dim s As String = "default.xml" - Dim dialog As New OpenFileDialog() - dialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*" - dialog.Title = "Select a xml file" - If dialog.ShowDialog() = DialogResult.OK Then - s = dialog.FileName - End If - Me.RadPivotGrid1.LoadLayout(s) -End Sub - -```` - -{{endregion}} + + + + >important This API should be used only if the data binding has been performed via the __DataSource__ property or using a __LocalSourceDataProvider__. The API also does not export custom aggregate functions. For SAAS cubes and custom aggregation serialization please refer to: diff --git a/controls/pivotgrid/save-and-load-layout/serialize-adomddataprovider.md b/controls/pivotgrid/save-and-load-layout/serialize-adomddataprovider.md index 3db68840a..f3198ee5e 100644 --- a/controls/pivotgrid/save-and-load-layout/serialize-adomddataprovider.md +++ b/controls/pivotgrid/save-and-load-layout/serialize-adomddataprovider.md @@ -18,319 +18,33 @@ We've added the DataContract attribute to all classes used by __AdomdDataProvide #### Define Members -{{source=..\SamplesCS\PivotGrid\PivotGridSerializeCubeDataProvider.cs region=DataProviderSettings}} -{{source=..\SamplesVB\PivotGrid\PivotGridSerializeCubeDataProvider.vb region=DataProviderSettings}} + + -````C# - -[DataContract] -public class DataProviderSettings -{ - [DataMember] - public object[] Aggregates { get; set; } - - [DataMember] - public object[] Filters { get; set; } - - [DataMember] - public object[] Rows { get; set; } - - [DataMember] - public object[] Columns { get; set; } - - [DataMember] - public int AggregatesLevel { get; set; } - [DataMember] - public PivotAxis AggregatesPosition { get; set; } -} -```` -````VB.NET - _ -Public Class DataProviderSettings - _ - Public Property Aggregates() As Object() - Get - Return m_Aggregates - End Get - Set(value As Object()) - m_Aggregates = value - End Set - End Property - Private m_Aggregates As Object() - _ - Public Property Filters() As Object() - Get - Return m_Filters - End Get - Set(value As Object()) - m_Filters = value - End Set - End Property - Private m_Filters As Object() - _ - Public Property Rows() As Object() - Get - Return m_Rows - End Get - Set(value As Object()) - m_Rows = value - End Set - End Property - Private m_Rows As Object() - _ - Public Property Columns() As Object() - Get - Return m_Columns - End Get - Set(value As Object()) - m_Columns = value - End Set - End Property - Private m_Columns As Object() - _ - Public Property AggregatesLevel() As Integer - Get - Return m_AggregatesLevel - End Get - Set(value As Integer) - m_AggregatesLevel = value - End Set - End Property - Private m_AggregatesLevel As Integer - _ - Public Property AggregatesPosition() As PivotAxis - Get - Return m_AggregatesPosition - End Get - Set(value As PivotAxis) - m_AggregatesPosition = value - End Set - End Property - Private m_AggregatesPosition As PivotAxis -End Class - -```` - -{{endregion}} The next step is to implement the serializer. When serializing the provider, you have to create an instance of the __DataProviderSettings__ class and set all of the properties. After that you can serialize the instance to a file or a stream. When using __DataContractSerializer__ you have to pass a collection of *KnownTypes* to the serializer. That's why we've created a new __AdomdPivotSerializationHelper__ class which has a static member - __KnownTypes__. It consits of all types you'll need in order to serialize __AdomdDataProvider__. #### Data Provider Implementation -{{source=..\SamplesCS\PivotGrid\PivotGridSerializeCubeDataProvider.cs region=DataProviderSerializer}} -{{source=..\SamplesVB\PivotGrid\PivotGridSerializeCubeDataProvider.vb region=DataProviderSerializer}} - -````C# - -public abstract class DataProviderSerializer -{ - public abstract IEnumerable KnownTypes { get; } - - public string Serialize(object context) - { - string serialized = string.Empty; - IDataProvider dataProvider = context as IDataProvider; - if (dataProvider != null) - { - MemoryStream stream = new MemoryStream(); - - DataProviderSettings settings = new DataProviderSettings() - { - Aggregates = dataProvider.Settings.AggregateDescriptions.OfType().ToArray(), - Filters = dataProvider.Settings.FilterDescriptions.OfType().ToArray(), - Rows = dataProvider.Settings.RowGroupDescriptions.OfType().ToArray(), - Columns = dataProvider.Settings.ColumnGroupDescriptions.OfType().ToArray(), - AggregatesLevel = dataProvider.Settings.AggregatesLevel, - AggregatesPosition = dataProvider.Settings.AggregatesPosition - }; - - DataContractSerializer serializer = new DataContractSerializer(typeof(DataProviderSettings), KnownTypes); - serializer.WriteObject(stream, settings); - stream.Position = 0; - var streamReader = new StreamReader(stream); - serialized += streamReader.ReadToEnd(); - } - - return serialized; - } - - public void Deserialize(object context, string savedValue) - { - IDataProvider dataProvider = context as IDataProvider; - if (dataProvider != null) - { - var stream = new MemoryStream(); - var tw = new StreamWriter(stream); - tw.Write(savedValue); - tw.Flush(); - stream.Position = 0; - - DataContractSerializer serializer = new DataContractSerializer(typeof(DataProviderSettings), KnownTypes); - var result = serializer.ReadObject(stream); - - dataProvider.Settings.AggregateDescriptions.Clear(); - foreach (var aggregateDescription in (result as DataProviderSettings).Aggregates) - { - dataProvider.Settings.AggregateDescriptions.Add(aggregateDescription); - } - - dataProvider.Settings.FilterDescriptions.Clear(); - foreach (var filterDescription in (result as DataProviderSettings).Filters) - { - dataProvider.Settings.FilterDescriptions.Add(filterDescription); - } - - dataProvider.Settings.RowGroupDescriptions.Clear(); - foreach (var rowDescription in (result as DataProviderSettings).Rows) - { - dataProvider.Settings.RowGroupDescriptions.Add(rowDescription); - } - - dataProvider.Settings.ColumnGroupDescriptions.Clear(); - foreach (var columnDescription in (result as DataProviderSettings).Columns) - { - dataProvider.Settings.ColumnGroupDescriptions.Add(columnDescription); - } - - dataProvider.Settings.AggregatesPosition = (result as DataProviderSettings).AggregatesPosition; - dataProvider.Settings.AggregatesLevel = (result as DataProviderSettings).AggregatesLevel; - } - } -} - -```` -````VB.NET -Public MustInherit Class DataProviderSerializer - Public MustOverride ReadOnly Property KnownTypes() As IEnumerable(Of Type) - Public Function Serialize(context As Object) As String - Dim serialized As String = String.Empty - Dim dataProvider As IDataProvider = TryCast(context, IDataProvider) - If dataProvider IsNot Nothing Then - Dim stream As New MemoryStream() - Dim settings As New DataProviderSettings() With { - .Aggregates = dataProvider.Settings.AggregateDescriptions.OfType(Of Object)().ToArray(), - .Filters = dataProvider.Settings.FilterDescriptions.OfType(Of Object)().ToArray(), - .Rows = dataProvider.Settings.RowGroupDescriptions.OfType(Of Object)().ToArray(), - .Columns = dataProvider.Settings.ColumnGroupDescriptions.OfType(Of Object)().ToArray(), - .AggregatesLevel = dataProvider.Settings.AggregatesLevel, - .AggregatesPosition = dataProvider.Settings.AggregatesPosition - } - Dim serializer As New DataContractSerializer(GetType(DataProviderSettings), KnownTypes) - serializer.WriteObject(stream, settings) - stream.Position = 0 - Dim streamReader = New StreamReader(stream) - serialized += streamReader.ReadToEnd() - End If - Return serialized - End Function - Public Sub Deserialize(context As Object, savedValue As String) - Dim dataProvider As IDataProvider = TryCast(context, IDataProvider) - If dataProvider IsNot Nothing Then - Dim stream = New MemoryStream() - Dim tw = New StreamWriter(stream) - tw.Write(savedValue) - tw.Flush() - stream.Position = 0 - Dim serializer As New DataContractSerializer(GetType(DataProviderSettings), KnownTypes) - Dim result = serializer.ReadObject(stream) - dataProvider.Settings.AggregateDescriptions.Clear() - For Each aggregateDescription As AggregateDescriptionBase In TryCast(result, DataProviderSettings).Aggregates - dataProvider.Settings.AggregateDescriptions.Add(aggregateDescription) - Next - dataProvider.Settings.FilterDescriptions.Clear() - For Each filterDescription As FilterDescription In TryCast(result, DataProviderSettings).Filters - dataProvider.Settings.FilterDescriptions.Add(filterDescription) - Next - dataProvider.Settings.RowGroupDescriptions.Clear() - Dim rows = TryCast(result, DataProviderSettings).Rows - For index = 0 To rows.Count - 1 - dataProvider.Settings.RowGroupDescriptions.Add(rows(index)) - Next - dataProvider.Settings.ColumnGroupDescriptions.Clear() - Dim columns = TryCast(result, DataProviderSettings).Columns - For index = 0 To columns.Count - 1 - dataProvider.Settings.ColumnGroupDescriptions.Add(columns(index)) - Next - dataProvider.Settings.AggregatesPosition = TryCast(result, DataProviderSettings).AggregatesPosition - dataProvider.Settings.AggregatesLevel = TryCast(result, DataProviderSettings).AggregatesLevel - End If - End Sub -End Class + + -```` -{{endregion}} -{{source=..\SamplesCS\PivotGrid\PivotGridSerializeCubeDataProvider.cs region=AdomdProviderSerializer}} -{{source=..\SamplesVB\PivotGrid\PivotGridSerializeCubeDataProvider.vb region=AdomdProviderSerializer}} + + -````C# - -public class AdomdProviderSerializer : DataProviderSerializer -{ - public override IEnumerable KnownTypes - { - get - { - return AdomdPivotSerializationHelper.KnownTypes; - } - } -} -```` -````VB.NET -Public Class AdomdProviderSerializer - Inherits DataProviderSerializer - Public Overrides ReadOnly Property KnownTypes() As IEnumerable(Of Type) - Get - Return AdomdPivotSerializationHelper.KnownTypes - End Get - End Property -End Class - -```` - -{{endregion}} So the last step is to serialize the provider and deserialize it. #### Using the AdomdProviderSerializer -{{source=..\SamplesCS\PivotGrid\PivotGridSerializeCubeDataProvider.cs region=SampleUsageAdomd}} -{{source=..\SamplesVB\PivotGrid\PivotGridSerializeCubeDataProvider.vb region=SampleUsageAdomd}} - -````C# - -string lastAdomdSerializadProvider = ""; - -private void serializeAdomdBtn_Click(object sender, EventArgs e) -{ - AdomdProviderSerializer serializeProvider = new AdomdProviderSerializer(); - this.lastAdomdSerializadProvider = serializeProvider.Serialize(this.radPivotGrid1.DataProvider); -} - -private void deserializeAdomdBtn_Click(object sender, EventArgs e) -{ - AdomdProviderSerializer provider = new AdomdProviderSerializer(); - provider.Deserialize(this.radPivotGrid1.DataProvider, this.lastAdomdSerializadProvider); -} - -```` -````VB.NET -Private lastAdomdSerializadProvider As String = "" -Private Sub serializeAdomdBtn_Click(sender As Object, e As EventArgs) Handles serializeAdomdBtn.Click - Dim serializeProvider As New AdomdProviderSerializer() - Me.lastAdomdSerializadProvider = serializeProvider.Serialize(Me.RadPivotGrid1.DataProvider) -End Sub -Private Sub deserializeAdomdBtn_Click(sender As Object, e As EventArgs) Handles deserializeAdomdBtn.Click - Dim provider As New AdomdProviderSerializer() - provider.Deserialize(Me.RadPivotGrid1.DataProvider, Me.lastAdomdSerializadProvider) -End Sub + + -```` -{{endregion}} # See Also diff --git a/controls/pivotgrid/save-and-load-layout/serialize-custom-aggregates.md b/controls/pivotgrid/save-and-load-layout/serialize-custom-aggregates.md index 3abc0618c..de75d79da 100644 --- a/controls/pivotgrid/save-and-load-layout/serialize-custom-aggregates.md +++ b/controls/pivotgrid/save-and-load-layout/serialize-custom-aggregates.md @@ -21,332 +21,35 @@ We've added the DataContract attribute to all classes used by __LocalDataSourceP #### Define Members -{{source=..\SamplesCS\PivotGrid\PivotGridSerializeCubeDataProvider.cs region=DataProviderSettings}} -{{source=..\SamplesVB\PivotGrid\PivotGridSerializeCubeDataProvider.vb region=DataProviderSettings}} -````C# - -[DataContract] -public class DataProviderSettings -{ - [DataMember] - public object[] Aggregates { get; set; } - - [DataMember] - public object[] Filters { get; set; } - - [DataMember] - public object[] Rows { get; set; } - - [DataMember] - public object[] Columns { get; set; } - - [DataMember] - public int AggregatesLevel { get; set; } - [DataMember] - public PivotAxis AggregatesPosition { get; set; } -} + + -```` -````VB.NET - _ -Public Class DataProviderSettings - _ - Public Property Aggregates() As Object() - Get - Return m_Aggregates - End Get - Set(value As Object()) - m_Aggregates = value - End Set - End Property - Private m_Aggregates As Object() - _ - Public Property Filters() As Object() - Get - Return m_Filters - End Get - Set(value As Object()) - m_Filters = value - End Set - End Property - Private m_Filters As Object() - _ - Public Property Rows() As Object() - Get - Return m_Rows - End Get - Set(value As Object()) - m_Rows = value - End Set - End Property - Private m_Rows As Object() - _ - Public Property Columns() As Object() - Get - Return m_Columns - End Get - Set(value As Object()) - m_Columns = value - End Set - End Property - Private m_Columns As Object() - _ - Public Property AggregatesLevel() As Integer - Get - Return m_AggregatesLevel - End Get - Set(value As Integer) - m_AggregatesLevel = value - End Set - End Property - Private m_AggregatesLevel As Integer - _ - Public Property AggregatesPosition() As PivotAxis - Get - Return m_AggregatesPosition - End Get - Set(value As PivotAxis) - m_AggregatesPosition = value - End Set - End Property - Private m_AggregatesPosition As PivotAxis -End Class -```` - - - -{{endregion}} The next step is to implement the serializer. When serializing the provider, you have to create an instance of the __DataProviderSettings__ class and set all of the properties. After that you can serialize the instance to a file or a stream. When using __DataContractSerializer__ you have to pass a collection of *KnownTypes* to the serializer. That's why we've created a new __PivotSerializationHelper__ class which has a static member - __KnownTypes__. It consits of all types you'll need in order to serialize __LocalDataSourceProvider__. #### Data Provider Implementation -{{source=..\SamplesCS\PivotGrid\PivotGridSerializeCubeDataProvider.cs region=DataProviderSerializer}} -{{source=..\SamplesVB\PivotGrid\PivotGridSerializeCubeDataProvider.vb region=DataProviderSerializer}} -````C# - -public abstract class DataProviderSerializer -{ - public abstract IEnumerable KnownTypes { get; } - - public string Serialize(object context) - { - string serialized = string.Empty; - IDataProvider dataProvider = context as IDataProvider; - if (dataProvider != null) - { - MemoryStream stream = new MemoryStream(); - - DataProviderSettings settings = new DataProviderSettings() - { - Aggregates = dataProvider.Settings.AggregateDescriptions.OfType().ToArray(), - Filters = dataProvider.Settings.FilterDescriptions.OfType().ToArray(), - Rows = dataProvider.Settings.RowGroupDescriptions.OfType().ToArray(), - Columns = dataProvider.Settings.ColumnGroupDescriptions.OfType().ToArray(), - AggregatesLevel = dataProvider.Settings.AggregatesLevel, - AggregatesPosition = dataProvider.Settings.AggregatesPosition - }; - - DataContractSerializer serializer = new DataContractSerializer(typeof(DataProviderSettings), KnownTypes); - serializer.WriteObject(stream, settings); - stream.Position = 0; - var streamReader = new StreamReader(stream); - serialized += streamReader.ReadToEnd(); - } - - return serialized; - } - - public void Deserialize(object context, string savedValue) - { - IDataProvider dataProvider = context as IDataProvider; - if (dataProvider != null) - { - var stream = new MemoryStream(); - var tw = new StreamWriter(stream); - tw.Write(savedValue); - tw.Flush(); - stream.Position = 0; - - DataContractSerializer serializer = new DataContractSerializer(typeof(DataProviderSettings), KnownTypes); - var result = serializer.ReadObject(stream); - - dataProvider.Settings.AggregateDescriptions.Clear(); - foreach (var aggregateDescription in (result as DataProviderSettings).Aggregates) - { - dataProvider.Settings.AggregateDescriptions.Add(aggregateDescription); - } - - dataProvider.Settings.FilterDescriptions.Clear(); - foreach (var filterDescription in (result as DataProviderSettings).Filters) - { - dataProvider.Settings.FilterDescriptions.Add(filterDescription); - } - - dataProvider.Settings.RowGroupDescriptions.Clear(); - foreach (var rowDescription in (result as DataProviderSettings).Rows) - { - dataProvider.Settings.RowGroupDescriptions.Add(rowDescription); - } - - dataProvider.Settings.ColumnGroupDescriptions.Clear(); - foreach (var columnDescription in (result as DataProviderSettings).Columns) - { - dataProvider.Settings.ColumnGroupDescriptions.Add(columnDescription); - } - - dataProvider.Settings.AggregatesPosition = (result as DataProviderSettings).AggregatesPosition; - dataProvider.Settings.AggregatesLevel = (result as DataProviderSettings).AggregatesLevel; - } - } -} - -```` -````VB.NET -Public MustInherit Class DataProviderSerializer - Public MustOverride ReadOnly Property KnownTypes() As IEnumerable(Of Type) - Public Function Serialize(context As Object) As String - Dim serialized As String = String.Empty - Dim dataProvider As IDataProvider = TryCast(context, IDataProvider) - If dataProvider IsNot Nothing Then - Dim stream As New MemoryStream() - Dim settings As New DataProviderSettings() With { - .Aggregates = dataProvider.Settings.AggregateDescriptions.OfType(Of Object)().ToArray(), - .Filters = dataProvider.Settings.FilterDescriptions.OfType(Of Object)().ToArray(), - .Rows = dataProvider.Settings.RowGroupDescriptions.OfType(Of Object)().ToArray(), - .Columns = dataProvider.Settings.ColumnGroupDescriptions.OfType(Of Object)().ToArray(), - .AggregatesLevel = dataProvider.Settings.AggregatesLevel, - .AggregatesPosition = dataProvider.Settings.AggregatesPosition - } - Dim serializer As New DataContractSerializer(GetType(DataProviderSettings), KnownTypes) - serializer.WriteObject(stream, settings) - stream.Position = 0 - Dim streamReader = New StreamReader(stream) - serialized += streamReader.ReadToEnd() - End If - Return serialized - End Function - Public Sub Deserialize(context As Object, savedValue As String) - Dim dataProvider As IDataProvider = TryCast(context, IDataProvider) - If dataProvider IsNot Nothing Then - Dim stream = New MemoryStream() - Dim tw = New StreamWriter(stream) - tw.Write(savedValue) - tw.Flush() - stream.Position = 0 - Dim serializer As New DataContractSerializer(GetType(DataProviderSettings), KnownTypes) - Dim result = serializer.ReadObject(stream) - dataProvider.Settings.AggregateDescriptions.Clear() - For Each aggregateDescription As AggregateDescriptionBase In TryCast(result, DataProviderSettings).Aggregates - dataProvider.Settings.AggregateDescriptions.Add(aggregateDescription) - Next - dataProvider.Settings.FilterDescriptions.Clear() - For Each filterDescription As FilterDescription In TryCast(result, DataProviderSettings).Filters - dataProvider.Settings.FilterDescriptions.Add(filterDescription) - Next - dataProvider.Settings.RowGroupDescriptions.Clear() - Dim rows = TryCast(result, DataProviderSettings).Rows - For index = 0 To rows.Count - 1 - dataProvider.Settings.RowGroupDescriptions.Add(rows(index)) - Next - dataProvider.Settings.ColumnGroupDescriptions.Clear() - Dim columns = TryCast(result, DataProviderSettings).Columns - For index = 0 To columns.Count - 1 - dataProvider.Settings.ColumnGroupDescriptions.Add(columns(index)) - Next - dataProvider.Settings.AggregatesPosition = TryCast(result, DataProviderSettings).AggregatesPosition - dataProvider.Settings.AggregatesLevel = TryCast(result, DataProviderSettings).AggregatesLevel - End If - End Sub -End Class - -```` - + + -{{endregion}} >important The custom function needs to be added the collection already containing the known types. -{{source=..\SamplesCS\PivotGrid\PivotGridSerializeCustomAggregate.cs region=LocalDataSourceSerializer}} -{{source=..\SamplesVB\PivotGrid\PivotGridSerializeCustomAggregate.vb region=LocalDataSourceSerializer}} -````C# -public class LocalDataSourceSerializer : DataProviderSerializer -{ - private IEnumerable myKnownTypes = PivotSerializationHelper.KnownTypes.Concat(new List() - { - typeof(SqrtSumAggregateFunction) - }); - public override IEnumerable KnownTypes - { - get - { - return myKnownTypes; - } - } -} + + -```` -````VB.NET -Public Class LocalDataSourceSerializer - Inherits DataProviderSerializer - Private myKnownTypes As IEnumerable(Of Type) = PivotSerializationHelper.KnownTypes.Concat(New List(Of Type)() From { - GetType(SqrtSumAggregateFunction) - }) - Public Overrides ReadOnly Property KnownTypes() As IEnumerable(Of Type) - Get - Return myKnownTypes - End Get - End Property -End Class -```` - - - -{{endregion}} So the last step is to serialize the provider and deserialize it. #### Using the Custom Serializer -{{source=..\SamplesCS\PivotGrid\PivotGridSerializeCustomAggregate.cs region=SampleUsageCustomAggregation}} -{{source=..\SamplesVB\PivotGrid\PivotGridSerializeCustomAggregate.vb region=SampleUsageCustomAggregation}} -````C# -private string s = @"..\..\custom.xml"; -private void serializeBtnClick(object sender, EventArgs e) -{ - //Serialzie - this.lastSerializadProvider = serializer.Serialize(this.radPivotGrid1.DataProvider); - File.WriteAllText(s, this.lastSerializadProvider); -} -private void deserializeBtnClick(object sender, EventArgs e) -{ - //Deserialzie - this.lastSerializadProvider = File.ReadAllText(s); - serializer.Deserialize(this.radPivotGrid1.DataProvider, this.lastSerializadProvider); -} - -```` -````VB.NET -Private s As String = "..\..\custom.xml" -Private Sub serializeBtnClick(sender As Object, e As EventArgs) - 'Serialzie - Me.lastSerializadProvider = serializer.Serialize(Me.radPivotGrid1.DataProvider) - File.WriteAllText(s, Me.lastSerializadProvider) -End Sub -Private Sub deserializeBtnClick(sender As Object, e As EventArgs) - 'Deserialzie - Me.lastSerializadProvider = File.ReadAllText(s) - serializer.Deserialize(Me.radPivotGrid1.DataProvider, Me.lastSerializadProvider) -End Sub - -```` - + + -{{endregion}} # See Also diff --git a/controls/pivotgrid/save-and-load-layout/serialize-xmladdataprovider.md b/controls/pivotgrid/save-and-load-layout/serialize-xmladdataprovider.md index 639dc356d..d4ece56ed 100644 --- a/controls/pivotgrid/save-and-load-layout/serialize-xmladdataprovider.md +++ b/controls/pivotgrid/save-and-load-layout/serialize-xmladdataprovider.md @@ -18,318 +18,33 @@ We've added the DataContract attribute to all classes used by __XmlaDataProvider #### Define Members -{{source=..\SamplesCS\PivotGrid\PivotGridSerializeCubeDataProvider.cs region=DataProviderSettings}} -{{source=..\SamplesVB\PivotGrid\PivotGridSerializeCubeDataProvider.vb region=DataProviderSettings}} + + -````C# - -[DataContract] -public class DataProviderSettings -{ - [DataMember] - public object[] Aggregates { get; set; } - - [DataMember] - public object[] Filters { get; set; } - - [DataMember] - public object[] Rows { get; set; } - - [DataMember] - public object[] Columns { get; set; } - - [DataMember] - public int AggregatesLevel { get; set; } - [DataMember] - public PivotAxis AggregatesPosition { get; set; } -} -```` -````VB.NET - _ -Public Class DataProviderSettings - _ - Public Property Aggregates() As Object() - Get - Return m_Aggregates - End Get - Set(value As Object()) - m_Aggregates = value - End Set - End Property - Private m_Aggregates As Object() - _ - Public Property Filters() As Object() - Get - Return m_Filters - End Get - Set(value As Object()) - m_Filters = value - End Set - End Property - Private m_Filters As Object() - _ - Public Property Rows() As Object() - Get - Return m_Rows - End Get - Set(value As Object()) - m_Rows = value - End Set - End Property - Private m_Rows As Object() - _ - Public Property Columns() As Object() - Get - Return m_Columns - End Get - Set(value As Object()) - m_Columns = value - End Set - End Property - Private m_Columns As Object() - _ - Public Property AggregatesLevel() As Integer - Get - Return m_AggregatesLevel - End Get - Set(value As Integer) - m_AggregatesLevel = value - End Set - End Property - Private m_AggregatesLevel As Integer - _ - Public Property AggregatesPosition() As PivotAxis - Get - Return m_AggregatesPosition - End Get - Set(value As PivotAxis) - m_AggregatesPosition = value - End Set - End Property - Private m_AggregatesPosition As PivotAxis -End Class - -```` - -{{endregion}} The next step is to implement the serializer. When serializing the provider, you have to create an instance of the __DataProviderSettings__ class and set all of the properties. After that you can serialize the instance to a file or a stream. When using __DataContractSerializer__ you have to pass a collection of *KnownTypes* to the serializer. That's why we've created a new __XmlaPivotSerializationHelper__ class which has a static member - __KnownTypes__. It consits of all types you'll need in order to serialize __XmlaDataProvider__. #### Data Provider Implementation -{{source=..\SamplesCS\PivotGrid\PivotGridSerializeCubeDataProvider.cs region=DataProviderSerializer}} -{{source=..\SamplesVB\PivotGrid\PivotGridSerializeCubeDataProvider.vb region=DataProviderSerializer}} - -````C# - -public abstract class DataProviderSerializer -{ - public abstract IEnumerable KnownTypes { get; } - - public string Serialize(object context) - { - string serialized = string.Empty; - IDataProvider dataProvider = context as IDataProvider; - if (dataProvider != null) - { - MemoryStream stream = new MemoryStream(); - - DataProviderSettings settings = new DataProviderSettings() - { - Aggregates = dataProvider.Settings.AggregateDescriptions.OfType().ToArray(), - Filters = dataProvider.Settings.FilterDescriptions.OfType().ToArray(), - Rows = dataProvider.Settings.RowGroupDescriptions.OfType().ToArray(), - Columns = dataProvider.Settings.ColumnGroupDescriptions.OfType().ToArray(), - AggregatesLevel = dataProvider.Settings.AggregatesLevel, - AggregatesPosition = dataProvider.Settings.AggregatesPosition - }; - - DataContractSerializer serializer = new DataContractSerializer(typeof(DataProviderSettings), KnownTypes); - serializer.WriteObject(stream, settings); - stream.Position = 0; - var streamReader = new StreamReader(stream); - serialized += streamReader.ReadToEnd(); - } - - return serialized; - } - - public void Deserialize(object context, string savedValue) - { - IDataProvider dataProvider = context as IDataProvider; - if (dataProvider != null) - { - var stream = new MemoryStream(); - var tw = new StreamWriter(stream); - tw.Write(savedValue); - tw.Flush(); - stream.Position = 0; - - DataContractSerializer serializer = new DataContractSerializer(typeof(DataProviderSettings), KnownTypes); - var result = serializer.ReadObject(stream); - - dataProvider.Settings.AggregateDescriptions.Clear(); - foreach (var aggregateDescription in (result as DataProviderSettings).Aggregates) - { - dataProvider.Settings.AggregateDescriptions.Add(aggregateDescription); - } - - dataProvider.Settings.FilterDescriptions.Clear(); - foreach (var filterDescription in (result as DataProviderSettings).Filters) - { - dataProvider.Settings.FilterDescriptions.Add(filterDescription); - } - - dataProvider.Settings.RowGroupDescriptions.Clear(); - foreach (var rowDescription in (result as DataProviderSettings).Rows) - { - dataProvider.Settings.RowGroupDescriptions.Add(rowDescription); - } - - dataProvider.Settings.ColumnGroupDescriptions.Clear(); - foreach (var columnDescription in (result as DataProviderSettings).Columns) - { - dataProvider.Settings.ColumnGroupDescriptions.Add(columnDescription); - } - - dataProvider.Settings.AggregatesPosition = (result as DataProviderSettings).AggregatesPosition; - dataProvider.Settings.AggregatesLevel = (result as DataProviderSettings).AggregatesLevel; - } - } -} - -```` -````VB.NET -Public MustInherit Class DataProviderSerializer - Public MustOverride ReadOnly Property KnownTypes() As IEnumerable(Of Type) - Public Function Serialize(context As Object) As String - Dim serialized As String = String.Empty - Dim dataProvider As IDataProvider = TryCast(context, IDataProvider) - If dataProvider IsNot Nothing Then - Dim stream As New MemoryStream() - Dim settings As New DataProviderSettings() With { - .Aggregates = dataProvider.Settings.AggregateDescriptions.OfType(Of Object)().ToArray(), - .Filters = dataProvider.Settings.FilterDescriptions.OfType(Of Object)().ToArray(), - .Rows = dataProvider.Settings.RowGroupDescriptions.OfType(Of Object)().ToArray(), - .Columns = dataProvider.Settings.ColumnGroupDescriptions.OfType(Of Object)().ToArray(), - .AggregatesLevel = dataProvider.Settings.AggregatesLevel, - .AggregatesPosition = dataProvider.Settings.AggregatesPosition - } - Dim serializer As New DataContractSerializer(GetType(DataProviderSettings), KnownTypes) - serializer.WriteObject(stream, settings) - stream.Position = 0 - Dim streamReader = New StreamReader(stream) - serialized += streamReader.ReadToEnd() - End If - Return serialized - End Function - Public Sub Deserialize(context As Object, savedValue As String) - Dim dataProvider As IDataProvider = TryCast(context, IDataProvider) - If dataProvider IsNot Nothing Then - Dim stream = New MemoryStream() - Dim tw = New StreamWriter(stream) - tw.Write(savedValue) - tw.Flush() - stream.Position = 0 - Dim serializer As New DataContractSerializer(GetType(DataProviderSettings), KnownTypes) - Dim result = serializer.ReadObject(stream) - dataProvider.Settings.AggregateDescriptions.Clear() - For Each aggregateDescription As AggregateDescriptionBase In TryCast(result, DataProviderSettings).Aggregates - dataProvider.Settings.AggregateDescriptions.Add(aggregateDescription) - Next - dataProvider.Settings.FilterDescriptions.Clear() - For Each filterDescription As FilterDescription In TryCast(result, DataProviderSettings).Filters - dataProvider.Settings.FilterDescriptions.Add(filterDescription) - Next - dataProvider.Settings.RowGroupDescriptions.Clear() - Dim rows = TryCast(result, DataProviderSettings).Rows - For index = 0 To rows.Count - 1 - dataProvider.Settings.RowGroupDescriptions.Add(rows(index)) - Next - dataProvider.Settings.ColumnGroupDescriptions.Clear() - Dim columns = TryCast(result, DataProviderSettings).Columns - For index = 0 To columns.Count - 1 - dataProvider.Settings.ColumnGroupDescriptions.Add(columns(index)) - Next - dataProvider.Settings.AggregatesPosition = TryCast(result, DataProviderSettings).AggregatesPosition - dataProvider.Settings.AggregatesLevel = TryCast(result, DataProviderSettings).AggregatesLevel - End If - End Sub -End Class + + -```` -{{endregion}} -{{source=..\SamplesCS\PivotGrid\PivotGridSerializeCubeDataProvider.cs region=XmlaProviderSerializer}} -{{source=..\SamplesVB\PivotGrid\PivotGridSerializeCubeDataProvider.vb region=XmlaProviderSerializer}} + + -````C# - -public class XmlaProviderSerializer : DataProviderSerializer -{ - public override IEnumerable KnownTypes - { - get - { - return XmlaPivotSerializationHelper.KnownTypes; - } - } -} -```` -````VB.NET -Public Class XmlaProviderSerializer - Inherits DataProviderSerializer - Public Overrides ReadOnly Property KnownTypes() As IEnumerable(Of Type) - Get - Return XmlaPivotSerializationHelper.KnownTypes - End Get - End Property -End Class - -```` - -{{endregion}} So the last step is to serialize the provider and deserialize it. #### Using the XmlaProviderSerializer -{{source=..\SamplesCS\PivotGrid\PivotGridSerializeCubeDataProvider.cs region=SampleUsageXmla}} -{{source=..\SamplesVB\PivotGrid\PivotGridSerializeCubeDataProvider.vb region=SampleUsageXmla}} - -````C# -string lastXmlaSerializadProvider = ""; - -private void serializeXmlaBtn_Click(object sender, EventArgs e) -{ - XmlaProviderSerializer serializeProvider = new XmlaProviderSerializer(); - this.lastXmlaSerializadProvider = serializeProvider.Serialize(this.radPivotGrid1.DataProvider); -} - -private void deserializeXmlaBtn_Click(object sender, EventArgs e) -{ - XmlaProviderSerializer provider = new XmlaProviderSerializer(); - provider.Deserialize(this.radPivotGrid1.DataProvider, this.lastXmlaSerializadProvider); -} - -```` -````VB.NET -Private lastXmlaSerializadProvider As String = "" -Private Sub serializeXmlaBtn_Click(sender As Object, e As EventArgs) Handles serializeXmlaBtn.Click - Dim serializeProvider As New XmlaProviderSerializer() - Me.lastXmlaSerializadProvider = serializeProvider.Serialize(Me.RadPivotGrid1.DataProvider) -End Sub -Private Sub deserializeXmlaBtn_Click(sender As Object, e As EventArgs) Handles deserializeXmlaBtn.Click - Dim provider As New XmlaProviderSerializer() - provider.Deserialize(Me.RadPivotGrid1.DataProvider, Me.lastXmlaSerializadProvider) -End Sub + + -```` -{{endregion}} # See Also diff --git a/controls/pivotgrid/sorting.md b/controls/pivotgrid/sorting.md index 5a044e2b9..47ba9d6c0 100644 --- a/controls/pivotgrid/sorting.md +++ b/controls/pivotgrid/sorting.md @@ -44,49 +44,19 @@ The sorting can be applied in the code behind or at run-time with the help of ** #### Using the SortOrder Property -{{source=..\SamplesCS\PivotGrid\PivotGridSorting.cs region=SortByGroupName}} -{{source=..\SamplesVB\PivotGrid\PivotGridSorting.vb region=SortByGroupName}} + + -````C# -PropertyGroupDescription propGroupDescription = (PropertyGroupDescription)this.radPivotGrid1.RowGroupDescriptions[0]; -propGroupDescription.SortOrder = Telerik.Pivot.Core.SortOrder.Descending; -this.radPivotGrid1.ReloadData(); -```` -````VB.NET -Dim propGroupDescription As PropertyGroupDescription = DirectCast(Me.radPivotGrid1.RowGroupDescriptions(0), PropertyGroupDescription) -propGroupDescription.SortOrder = Telerik.Pivot.Core.SortOrder.Descending -Me.radPivotGrid1.ReloadData() - -```` - -{{endregion}} * Sorting based on the **GrandTotals** can be *Ascending* or *Descending*. To set such sort mechanism you have to use the **SortOrder** and **GroupComparer** properties: #### Using SortOrder and GroupComparer -{{source=..\SamplesCS\PivotGrid\PivotGridSorting.cs region=SortGrandTotals}} -{{source=..\SamplesVB\PivotGrid\PivotGridSorting.vb region=SortGrandTotals}} - -````C# -PropertyGroupDescription propGroupDescription = (PropertyGroupDescription)this.radPivotGrid1.RowGroupDescriptions[0]; -propGroupDescription.SortOrder = Telerik.Pivot.Core.SortOrder.Descending; -propGroupDescription.GroupComparer = new GrandTotalComparer() { AggregateIndex = 0 }; -this.radPivotGrid1.ReloadData(); - -```` -````VB.NET -Dim propGroupDescription As PropertyGroupDescription = DirectCast(Me.radPivotGrid1.RowGroupDescriptions(0), PropertyGroupDescription) -propGroupDescription.SortOrder = Telerik.Pivot.Core.SortOrder.Descending -propGroupDescription.GroupComparer = New GrandTotalComparer() With { _ - .AggregateIndex = 0 _ -} -Me.radPivotGrid1.ReloadData() + + -```` -{{endregion}} >note The **AggregateIndex** property is set based on the count of your aggregate descriptions. If you have two aggregates the first one will have **AggregateIndex** = 0 and the second - **AggregateIndex** = 1. > diff --git a/controls/propertygrid/attributes.md b/controls/propertygrid/attributes.md index c5aaf90e9..66f842567 100644 --- a/controls/propertygrid/attributes.md +++ b/controls/propertygrid/attributes.md @@ -17,30 +17,10 @@ This article contains a list of some of the more important and more commonly use With the editor attribute you can specify __UITypeEditor__ as well as __BaseInputEditor__ to be used for a given property. -{{source=..\SamplesCS\PropertyGrid\PropertyGridAttributes.cs region=EditorAttribute}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridAttributes.vb region=EditorAttribute}} - -````C# - -[Editor(typeof(PropertyGridBrowseEditor), typeof(BaseInputEditor))] -public string FileLocation { get; set; } - -```` -````VB.NET - _ -Public Property FileLocation() As String - Get - Return m_FileLocation - End Get - Set(value As String) - m_FileLocation = value - End Set -End Property -Private m_FileLocation As String - -```` - -{{endregion}} + + + + >caption Figure 1: EditorAttribute @@ -50,30 +30,10 @@ Private m_FileLocation As String The range attribute allows you to set a minimum and maximum value to be used for a property that is edited with a RadSpinEditor. -{{source=..\SamplesCS\PropertyGrid\PropertyGridAttributes.cs region=RadRangeAttribute}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridAttributes.vb region=RadRangeAttribute}} - -````C# - -[RadRange(1, 5)] -public byte DoorsCount { get; set; } + + -```` -````VB.NET - _ -Public Property DoorsCount() As Byte - Get - Return m_DoorsCount - End Get - Set(value As Byte) - m_DoorsCount = value - End Set -End Property -Private m_DoorsCount As Byte -```` - -{{endregion}} >caption Figure 2: RadRangeAttribute @@ -83,41 +43,10 @@ Private m_DoorsCount As Byte Determines whether the property will be included in the collection of properties RadPropertyGridSHows. -{{source=..\SamplesCS\PropertyGrid\PropertyGridAttributes.cs region=BrowsableAttribute}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridAttributes.vb region=BrowsableAttribute}} - -````C# - -[Browsable(false)] -public int MyHiddenProperty { get; set; } - -public int MyBrowsableProperty { get; set; } - -```` -````VB.NET - _ -Public Property MyHiddenProperty() As Integer - Get - Return m_MyHiddenProperty - End Get - Set(value As Integer) - m_MyHiddenProperty = value - End Set -End Property -Private m_MyHiddenProperty As Integer -Public Property MyBrowsableProperty() As Integer - Get - Return m_MyBrowsableProperty - End Get - Set(value As Integer) - m_MyBrowsableProperty = value - End Set -End Property -Private m_MyBrowsableProperty As Integer - -```` - -{{endregion}} + + + + >caption Figure 3: BrowsableAttribute @@ -127,59 +56,19 @@ Private m_MyBrowsableProperty As Integer Determines whether a property can be edited in RadPropertyGrid or not. -{{source=..\SamplesCS\PropertyGrid\PropertyGridAttributes.cs region=ReadOnlyAttribute}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridAttributes.vb region=ReadOnlyAttribute}} + + -````C# - -[ReadOnly(true)] -public int Count { get; set; } -```` -````VB.NET -<[ReadOnly](True)> _ -Public Property Count() As Integer - Get - Return m_Count - End Get - Set(value As Integer) - m_Count = value - End Set -End Property -Private m_Count As Integer - -```` - -{{endregion}} ## DisplayNameAttribute Determines the text that will be show for a given property. You can also alter the text for a property by setting its Label. -{{source=..\SamplesCS\PropertyGrid\PropertyGridAttributes.cs region=DisplayNameAttribute}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridAttributes.vb region=DisplayNameAttribute}} - -````C# - -[DisplayName("PropertyNameInGerman")] -public double PropertyName { get; set; } + + -```` -````VB.NET - _ -Public Property PropertyName() As Double - Get - Return m_PropertyName - End Get - Set(value As Double) - m_PropertyName = value - End Set -End Property -Private m_PropertyName As Double -```` - -{{endregion}} >caption Figure 4: DisplayNameAttribute @@ -189,30 +78,10 @@ Private m_PropertyName As Double Defines the text that is displayed for a given property in the help bar of RadPropertyGrid. -{{source=..\SamplesCS\PropertyGrid\PropertyGridAttributes.cs region=DescriptionAttribute}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridAttributes.vb region=DescriptionAttribute}} - -````C# - -[Description("The manufacturer of the item")] -public string Manufacturer { get; set; } - -```` -````VB.NET - _ -Public Property Manufacturer() As String - Get - Return m_Manufacturer - End Get - Set(value As String) - m_Manufacturer = value - End Set -End Property -Private m_Manufacturer As String + + -```` -{{endregion}} >caption Figure 5: DisplayNameAttribute @@ -222,40 +91,10 @@ Private m_Manufacturer As String Determines whether a text property will be edited as a password. -{{source=..\SamplesCS\PropertyGrid\PropertyGridAttributes.cs region=PasswordPropertyTextAttribute}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridAttributes.vb region=PasswordPropertyTextAttribute}} - -````C# - -public string Username { get; set; } -[PasswordPropertyText(true)] -public string Password { get; set; } - -```` -````VB.NET -Public Property Username() As String - Get - Return m_Username - End Get - Set(value As String) - m_Username = value - End Set -End Property -Private m_Username As String - _ -Public Property Password() As String - Get - Return m_Password - End Get - Set(value As String) - m_Password = value - End Set -End Property -Private m_Password As String - -```` - -{{endregion}} + + + + >caption Figure 6: PasswordPropertyTextAttribute @@ -265,29 +104,10 @@ Private m_Password As String Defines the default value to which the property will reset. When the property value is set to something different that the default value, it will be marked as modified. -{{source=..\SamplesCS\PropertyGrid\PropertyGridAttributes.cs region=DefaultValueAttribute}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridAttributes.vb region=DefaultValueAttribute}} - -````C# -[DefaultValue(1.35)] -public double Length { get; set; } + + -```` -````VB.NET - _ -Public Property Length() As Decimal - Get - Return m_Length - End Get - Set(value As Decimal) - m_Length = value - End Set -End Property -Private m_Length As Decimal -```` - -{{endregion}} >caption Figure 7: DefaultValueAttribute @@ -297,41 +117,10 @@ Private m_Length As Decimal Defines the category to which the property will be grouped when properties are shown categorized. Any property that does not have this attribute will be categorized in the Misc category. -{{source=..\SamplesCS\PropertyGrid\PropertyGridAttributes.cs region=CategoryAttribute}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridAttributes.vb region=CategoryAttribute}} - -````C# - -[Category("CategoryName")] -public string CategorizedProperty { get; set; } - -public string UncategorizedProperty { get; set; } - -```` -````VB.NET - _ -Public Property CategorizedProperty() As String - Get - Return m_CategorizedProperty - End Get - Set(value As String) - m_CategorizedProperty = value - End Set -End Property -Private m_CategorizedProperty As String -Public Property UncategorizedProperty() As String - Get - Return m_UncategorizedProperty - End Get - Set(value As String) - m_UncategorizedProperty = value - End Set -End Property -Private m_UncategorizedProperty As String - -```` - -{{endregion}} + + + + >caption Figure 8: CategoryAttribute @@ -341,54 +130,10 @@ Private m_UncategorizedProperty As String Defines the order in which items would be ordered when no other ordering is applied (Alphabetical or Categorical alphabetical). The order can also be manipulated through the SortOrder property of PropertyGridItem. Setting the property would override the value from the attribute. -{{source=..\SamplesCS\PropertyGrid\PropertyGridAttributes.cs region=RadSortOrderAttribute}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridAttributes.vb region=RadSortOrderAttribute}} - -````C# - -[RadSortOrder(2)] -public string AProperty { get; set; } -[RadSortOrder(1)] -public string BProperty { get; set; } -[RadSortOrder(0)] -public string CProperty { get; set; } - -```` -````VB.NET - _ -Public Property AProperty() As String - Get - Return m_AProperty - End Get - Set(value As String) - m_AProperty = value - End Set -End Property -Private m_AProperty As String - _ -Public Property BProperty() As String - Get - Return m_BProperty - End Get - Set(value As String) - m_BProperty = value - End Set -End Property -Private m_BProperty As String - _ -Public Property CProperty() As String - Get - Return m_CProperty - End Get - Set(value As String) - m_CProperty = value - End Set -End Property -Private m_CProperty As String - -```` - -{{endregion}} + + + + >caption Figure 9: RadSortOrderAttribute @@ -398,41 +143,10 @@ Private m_CProperty As String The **RadCheckBoxThreeStateAttribute** determines whether properties inside **RadPropertyGrid**, for which a **PropertyGridCheckBoxItemElement** is created, will have a three state check box editor or a two state one. -{{source=..\SamplesCS\PropertyGrid\PropertyGridAttributes.cs region=RadCheckBoxThreeStateAttribute}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridAttributes.vb region=RadCheckBoxThreeStateAttribute}} - -````C# -[RadCheckBoxThreeState(true)] -public bool? AProperty { get; set; } -[RadCheckBoxThreeState(false)] -public ToggleState BProperty { get; set; } - -```` -````VB.NET - -Public Property AProperty() As Nullable(Of Boolean) - Get - Return m_AProperty - End Get - Set(value As Nullable(Of Boolean)) - m_AProperty = value - End Set -End Property -Private m_AProperty As Nullable(Of Boolean) - -Public Property BProperty() As ToggleState - Get - Return m_BProperty - End Get - Set(value As ToggleState) - m_BProperty = value - End Set -End Property -Private m_BProperty As ToggleState - -```` - -{{endregion}} + + + + >caption Figure 10: RadCheckBoxThreeStateAttribute @@ -442,26 +156,10 @@ Private m_BProperty As ToggleState The __TypeConverterAttribute__ specifies what type to use as a converter for the object this attribute is bound to. -{{source=..\SamplesCS\PropertyGrid\PropertyGridAttributes.cs region=TypeConverterAttribute}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridAttributes.vb region=TypeConverterAttribute}} - -````C# -PropertyStoreItem Item1 = new PropertyStoreItem(typeof(string), "BorderType", "Flat"); -Item1.Attributes.Add(new TypeConverterAttribute(typeof(My_TypeConverter))); -store.Add(Item1); -radPropertyGrid1.SelectedObject = store; - -```` -````VB.NET -Dim store As RadPropertyStore = New RadPropertyStore() -Dim Item1 As PropertyStoreItem = New PropertyStoreItem(GetType(String), "BorderType", "Flat") -Item1.Attributes.Add(New TypeConverterAttribute(GetType(My_TypeConverter))) -store.Add(Item1) -radPropertyGrid1.SelectedObject = store + + -```` -{{endregion}} # See Also diff --git a/controls/propertygrid/custom-items.md b/controls/propertygrid/custom-items.md index d0a190d97..fbd5d4637 100644 --- a/controls/propertygrid/custom-items.md +++ b/controls/propertygrid/custom-items.md @@ -20,319 +20,55 @@ Let’s start by specifying the RadPropertyGrid.__SelectedObject__ property, so #### Data Class -{{source=..\SamplesCS\PropertyGrid\PropertyGridCustomItems.cs region=ClassItem}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridCustomItems.vb region=ClassItem}} - -````C# -public class Item -{ - public int Id { get; set; } - public string Title { get; set; } - public DeliveryType DeliveryType { get; set; } - public Item(int id, string title, DeliveryType deliveryType) - { - this.Id = id; - this.Title = title; - this.DeliveryType = deliveryType; - } -} -public enum DeliveryType -{ - Delivery, - PickUp, -} - -```` -````VB.NET -Public Class Item - Public Property Id() As Integer - Get - Return m_Id - End Get - Set(value As Integer) - m_Id = value - End Set - End Property - Private m_Id As Integer - Public Property Title() As String - Get - Return m_Title - End Get - Set(value As String) - m_Title = value - End Set - End Property - Private m_Title As String - Public Property DeliveryType() As DeliveryType - Get - Return m_DeliveryType - End Get - Set(value As DeliveryType) - m_DeliveryType = value - End Set - End Property - Private m_DeliveryType As DeliveryType - Public Sub New(id As Integer, title As String, deliveryType As DeliveryType) - Me.Id = id - Me.Title = title - Me.DeliveryType = deliveryType - End Sub -End Class -Public Enum DeliveryType - Delivery - PickUp -End Enum - -```` - -{{endregion}} + + + + Next, we should create a custom __PropertyGridValueElement__ which is purposed to be used in a derived __PropertyGridItemElement__. Our custom implementation of the __PropertyGridValueElement__ will demonstrate how to insert radio buttons for the Item.__DeliveryType__ property. #### Custom PropertyGridValueElement -{{source=..\SamplesCS\PropertyGrid\PropertyGridCustomItems.cs region=PropertyGridValueElement}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridCustomItems.vb region=PropertyGridValueElement}} - -````C# -public class CustomPropertyGridValueElement : PropertyGridValueElement -{ - StackLayoutElement stackPanel; - protected override void CreateChildElements() - { - base.CreateChildElements(); - stackPanel = new StackLayoutElement(); - stackPanel.Orientation = Orientation.Vertical; - foreach (var enumItem in Enum.GetValues(typeof(DeliveryType))) - { - RadRadioButtonElement rb = new RadRadioButtonElement(); - rb.Text = enumItem.ToString(); - rb.ToggleStateChanged += rb_ToggleStateChanged; - stackPanel.Children.Add(rb); - } - this.Children.Add(stackPanel); - } - private void rb_ToggleStateChanged(object sender, StateChangedEventArgs args) - { - RadRadioButtonElement rb = sender as RadRadioButtonElement; - PropertyGridItem item = this.VisualItem.Data as PropertyGridItem; - if (item != null && rb.Text != item.FormattedValue && rb.ToggleState == ToggleState.On) - { - item.Value = rb.Text; - } - } - public override void Synchronize() - { - PropertyGridItem item = this.VisualItem.Data as PropertyGridItem; - foreach (RadRadioButtonElement rb in stackPanel.Children) - { - if (rb.Text == item.FormattedValue) - { - rb.ToggleState = ToggleState.On; - break; - } - } - } -} - -```` -````VB.NET -Public Class CustomPropertyGridValueElement -Inherits PropertyGridValueElement - Private stackPanel As StackLayoutElement - Protected Overrides Sub CreateChildElements() - MyBase.CreateChildElements() - stackPanel = New StackLayoutElement() - stackPanel.Orientation = Orientation.Vertical - For Each enumItem As Object In [Enum].GetValues(GetType(DeliveryType)) - Dim rb As New RadRadioButtonElement() - rb.Text = enumItem.ToString() - AddHandler rb.ToggleStateChanged, AddressOf rb_ToggleStateChanged - stackPanel.Children.Add(rb) - Next - Me.Children.Add(stackPanel) - End Sub - Private Sub rb_ToggleStateChanged(sender As Object, args As StateChangedEventArgs) - Dim rb As RadRadioButtonElement = TryCast(sender, RadRadioButtonElement) - Dim item As PropertyGridItem = TryCast(Me.VisualItem.Data, PropertyGridItem) - If item IsNot Nothing AndAlso rb.Text <> item.FormattedValue AndAlso rb.ToggleState = ToggleState.[On] Then - item.Value = rb.Text - End If - End Sub - Public Overrides Sub Synchronize() - Dim item As PropertyGridItem = TryCast(Me.VisualItem.Data, PropertyGridItem) - For Each rb As RadRadioButtonElement In stackPanel.Children - If rb.Text = item.FormattedValue Then - rb.ToggleState = ToggleState.[On] - Exit For - End If - Next - End Sub -End Class - -```` - -{{endregion}} + + + + To put this value element in action, we will create a descendant of __PropertyGridItemElement__, and we will override its __CreatePropertyGridValueElement__ method. In order to avoid reusing of the custom element for other items, you can override the PropertyGridItemElement. __IsCompatible__ method and control whether the custom element is applicable for the specific __PropertyGridItem__ . In addition, it is necessary to create another PropertyGridItemElement which is not compatible with your custom item: #### Custom PropertyGridItemElements -{{source=..\SamplesCS\PropertyGrid\PropertyGridCustomItems.cs region=PropertyGridItemElement}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridCustomItems.vb region=PropertyGridItemElement}} - -````C# -public class CustomItemElement : PropertyGridItemElement -{ - protected override PropertyGridValueElement CreatePropertyGridValueElement() - { - return new CustomPropertyGridValueElement(); - } - protected override Type ThemeEffectiveType - { - get - { - return typeof(PropertyGridItemElement); - } - } - public override bool IsCompatible(PropertyGridItemBase data, object context) - { - return data.Label == "DeliveryType"; - } -} -public class DefaultPropertyGridItemElement : PropertyGridItemElement -{ - protected override Type ThemeEffectiveType - { - get - { - return typeof(PropertyGridItemElement); - } - } - public override bool IsCompatible(PropertyGridItemBase data, object context) - { - return data.Label != "DeliveryType"; - } -} - -```` -````VB.NET -Public Class CustomItemElement -Inherits PropertyGridItemElement - Protected Overrides Function CreatePropertyGridValueElement() As PropertyGridValueElement - Return New CustomPropertyGridValueElement() - End Function - Protected Overrides ReadOnly Property ThemeEffectiveType() As Type - Get - Return GetType(PropertyGridItemElement) - End Get - End Property - Public Overrides Function IsCompatible(data As PropertyGridItemBase, context As Object) As Boolean - Return data.Label = "DeliveryType" - End Function -End Class -Public Class DefaultPropertyGridItemElement - Inherits PropertyGridItemElement - Protected Overrides ReadOnly Property ThemeEffectiveType() As Type - Get - Return GetType(PropertyGridItemElement) - End Get - End Property - Public Overrides Function IsCompatible(data As PropertyGridItemBase, context As Object) As Boolean - Return data.Label <> "DeliveryType" - End Function -End Class - -```` - -{{endregion}} + + + + Back to the control, let’s subscribe to the RadPropertyGrid.__CreateItemElement__ event which gives you the opportunity to replace the item created for the __DeliveryType__ property with your custom one: #### Handle CreateItemElement Event -{{source=..\SamplesCS\PropertyGrid\PropertyGridCustomItems.cs region=CreateItemElement}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridCustomItems.vb region=CreateItemElement}} - -````C# -private void radPropertyGrid1_CreateItemElement(object sender, -CreatePropertyGridItemElementEventArgs e) -{ - if (e.ItemElementType == typeof(PropertyGridItemElement)) - { - if (e.Item.Name == "DeliveryType") - { - e.ItemElementType = typeof(CustomItemElement); - } - else - { - e.ItemElementType = typeof(DefaultPropertyGridItemElement); - } - } -} - -```` -````VB.NET -Private Sub radPropertyGrid1_CreateItemElement(sender As Object, e As CreatePropertyGridItemElementEventArgs) - If e.ItemElementType = GetType(PropertyGridItemElement) Then - If e.Item.Name = "DeliveryType" Then - e.ItemElementType = GetType(CustomItemElement) - Else - e.ItemElementType = GetType(DefaultPropertyGridItemElement) - End If - End If -End Sub - -```` - -{{endregion}} + + -The next thing we need to do is to stop entering edit mode when clicking over one of the radio buttons by using the RadPropertyGrid.__Editing__ event. Thus, the user will be allowed to select directly the preferred delivery type without necessity to enter edit mode. -#### Handle Editing Event -{{source=..\SamplesCS\PropertyGrid\PropertyGridCustomItems.cs region=Editing}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridCustomItems.vb region=Editing}} +The next thing we need to do is to stop entering edit mode when clicking over one of the radio buttons by using the RadPropertyGrid.__Editing__ event. Thus, the user will be allowed to select directly the preferred delivery type without necessity to enter edit mode. -````C# -private void radPropertyGrid1_Editing(object sender, - PropertyGridItemEditingEventArgs e) -{ - if (e.Item.Name == "DeliveryType") - { - e.Cancel = true; - } -} +#### Handle Editing Event -```` -````VB.NET -Private Sub radPropertyGrid1_Editing(sender As Object, e As PropertyGridItemEditingEventArgs) - If e.Item.Name = "DeliveryType" Then - e.Cancel = True - End If -End Sub + + -```` -{{endregion}} The last thing we should update is to adjust the PropertyGridElement.PropertyTableElement.__ItemHeight__ property with such a value to fit the available content: #### Set Item Height -{{source=..\SamplesCS\PropertyGrid\PropertyGridCustomItems.cs region=ItemHeight}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridCustomItems.vb region=ItemHeight}} - -````C# -this.radPropertyGrid1.PropertyGridElement.PropertyTableElement.ItemHeight = Enum.GetValues(typeof(DeliveryType)).Length * 20; - -```` -````VB.NET -Me.radPropertyGrid1.PropertyGridElement.PropertyTableElement.ItemHeight = [Enum].GetValues(GetType(DeliveryType)).Length * 20 + + -```` -{{endregion}} >note As of R3 2021 SP1 RadPropertyGrid supports individual item's height. As the control does not expose the items directly, there is no Items collection, the data item can be accessed in the **CreateItemElement** or the **ItemFormatting** event. Then, specify the Item.**ItemHeight** property to the desired height. diff --git a/controls/propertygrid/customizing-appearance/customization.md b/controls/propertygrid/customizing-appearance/customization.md index 07ab8d0ce..7a2d1d80c 100644 --- a/controls/propertygrid/customizing-appearance/customization.md +++ b/controls/propertygrid/customizing-appearance/customization.md @@ -33,65 +33,10 @@ Here is an example on how you can change the back color of the subitems and also #### Customizing Items -{{source=..\SamplesCS\PropertyGrid\PropertyGridCustomization.cs region=itemFormatting}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridCustomization.vb region=itemFormatting}} - -````C# -void radPropertyGrid1_ItemFormatting(object sender, PropertyGridItemFormattingEventArgs e) -{ - //set the back color of all child items to yellow - if (e.Item.Level > 0) - { - e.VisualElement.BackColor = Color.LightCyan; - } - else - { - e.VisualElement.ResetValue(LightVisualElement.BackColorProperty, Telerik.WinControls.ValueResetFlags.Local); - } - //set the back color of items with value True to LightGreen and with value equal to False to Red - PropertyGridItem item = e.Item as PropertyGridItem; - if (item != null && item.Value != null) - { - if (item.Value.ToString() == "True") - { - e.VisualElement.BackColor = Color.LightGreen; - } - else if (item.Value.ToString() == "False") - { - e.VisualElement.BackColor = Color.LightCoral; - } - } - else - { - e.VisualElement.ResetValue(LightVisualElement.BackColorProperty, Telerik.WinControls.ValueResetFlags.Local); - } -} - -```` -````VB.NET -Private Sub radPropertyGrid1_ItemFormatting(ByVal sender As Object, ByVal e As PropertyGridItemFormattingEventArgs) - 'set the back color of all child items to yellow - If e.Item.Level > 0 Then - e.VisualElement.BackColor = Color.LightCyan - Else - e.VisualElement.ResetValue(LightVisualElement.BackColorProperty, Telerik.WinControls.ValueResetFlags.Local) - End If - 'set the back color of items with value True to LightGreen and with value equal to False to Red - Dim item As PropertyGridItem = TryCast(e.Item, PropertyGridItem) - If item IsNot Nothing AndAlso item.Value IsNot Nothing Then - If item.Value.ToString() = "True" Then - e.VisualElement.BackColor = Color.LightGreen - ElseIf item.Value.ToString() = "False" Then - e.VisualElement.BackColor = Color.LightCoral - End If - Else - e.VisualElement.ResetValue(LightVisualElement.BackColorProperty, Telerik.WinControls.ValueResetFlags.Local) - End If -End Sub - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/propertygrid/editors/customizing-editor-behavior.md b/controls/propertygrid/editors/customizing-editor-behavior.md index 3445cabd5..246762121 100644 --- a/controls/propertygrid/editors/customizing-editor-behavior.md +++ b/controls/propertygrid/editors/customizing-editor-behavior.md @@ -21,65 +21,18 @@ The following sample demonstrates how to change the default font of __PropertyGr #### Customize editor -{{source=..\SamplesCS\PropertyGrid\Editors\PropertyGridCustomizingEditorBehavior.cs region=CustomizeEditor}} -{{source=..\SamplesVB\PropertyGrid\Editors\PropertyGridCustomizingEditorBehavior.vb region=CustomizeEditor}} + + -````C# -void radPropertyGrid1_EditorInitialized(object sender, Telerik.WinControls.UI.PropertyGridItemEditorInitializedEventArgs e) -{ - PropertyGridTextBoxEditor editor = e.Editor as PropertyGridTextBoxEditor; - if (editor != null) - { - ((RadTextBoxElement)editor.EditorElement).Font = new Font(FontFamily.Families[12], 10, FontStyle.Bold); - } - -} - -```` -````VB.NET -Private Sub radPropertyGrid1_EditorInitialized(ByVal sender As Object, ByVal e As PropertyGridItemEditorInitializedEventArgs) - Dim editor As PropertyGridTextBoxEditor = TryCast(e.Editor, PropertyGridTextBoxEditor) - - If Not editor Is Nothing Then - CType(editor.EditorElement, RadTextBoxElement).Font = New Font(FontFamily.Families(12), 10, FontStyle.Bold) - End If -End Sub - -```` - -{{endregion}} # PropertyGridSpinEditor null values support. The following snippet shows how you can enable the null values support in the spin editor: -{{source=..\SamplesCS\PropertyGrid\Editors\PropertyGridCustomizingEditorBehavior.cs region=NullValues}} -{{source=..\SamplesVB\PropertyGrid\Editors\PropertyGridCustomizingEditorBehavior.vb region=NullValues}} -````C# -void radPropertyGrid_EditorInitialized(object sender, Telerik.WinControls.UI.PropertyGridItemEditorInitializedEventArgs e) -{ - PropertyGridSpinEditor editor = e.Editor as PropertyGridSpinEditor; - if (editor != null) - { - BaseSpinEditorElement el = editor.EditorElement as BaseSpinEditorElement; - el.EnableNullValueInput = true; - } -} - -```` -````VB.NET -Private Sub radPropertyGrid_EditorInitialized(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.PropertyGridItemEditorInitializedEventArgs) - Dim editor As PropertyGridSpinEditor = TryCast(e.Editor, PropertyGridSpinEditor) - If editor IsNot Nothing Then - Dim el As BaseSpinEditorElement = TryCast(editor.EditorElement, BaseSpinEditorElement) - el.EnableNullValueInput = True - End If -End Sub - -```` - -{{endregion}} + + + # See Also diff --git a/controls/propertygrid/editors/handling-editors'-events.md b/controls/propertygrid/editors/handling-editors'-events.md index c382f3937..94ad69b4f 100644 --- a/controls/propertygrid/editors/handling-editors'-events.md +++ b/controls/propertygrid/editors/handling-editors'-events.md @@ -19,68 +19,10 @@ For example, you may need to set specific text in the editor when the user press #### How to Handle Events -{{source=..\SamplesCS\PropertyGrid\Editors\PropertyGridHandlingEditorsEvents.cs region=handlingEvents}} -{{source=..\SamplesVB\PropertyGrid\Editors\PropertyGridHandlingEditorsEvents.vb region=handlingEvents}} - -````C# -public PropertyGridHandlingEditorsEvents() -{ - InitializeComponent(); - this.radPropertyGrid1.EditorInitialized += new PropertyGridItemEditorInitializedEventHandler(radPropertyGrid1_EditorInitialized); -} -bool tbSubscribed = false; -void radPropertyGrid1_EditorInitialized(object sender, PropertyGridItemEditorInitializedEventArgs e) -{ - PropertyGridTextBoxEditor editor = e.Editor as PropertyGridTextBoxEditor; - if (editor != null) - { - if (!tbSubscribed) - { - tbSubscribed = true; - RadTextBoxElement tbElement = (RadTextBoxElement)editor.EditorElement; - tbElement.KeyDown += new KeyEventHandler(tbElement_KeyDown); - } - } -} -void tbElement_KeyDown(object sender, KeyEventArgs e) -{ - if (e.Control) - { - if (e.KeyCode == Keys.D) - { - ((RadTextBoxElement)sender).Text = "Default text"; - } - } -} - -```` -````VB.NET -Public Sub New() - InitializeComponent() - AddHandler RadPropertyGrid1.EditorInitialized, AddressOf radPropertyGrid1_EditorInitialized -End Sub -Private tbSubscribed As Boolean = False -Private Sub radPropertyGrid1_EditorInitialized(ByVal sender As Object, ByVal e As PropertyGridItemEditorInitializedEventArgs) - Dim editor As PropertyGridTextBoxEditor = TryCast(e.Editor, PropertyGridTextBoxEditor) - If Not editor Is Nothing Then - If (Not tbSubscribed) Then - tbSubscribed = True - Dim tbElement As RadTextBoxElement = CType(editor.EditorElement, RadTextBoxElement) - AddHandler tbElement.KeyDown, AddressOf tbElement_KeyDown - End If - End If -End Sub -Private Sub tbElement_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) - If e.Control Then - If e.KeyCode = Keys.D Then - CType(sender, RadTextBoxElement).Text = "Default text" - End If - End If -End Sub - -```` - -{{endregion}} + + + + ## Showing Images in PropertyGridDropDownListEditor @@ -92,62 +34,10 @@ If you need to show icons next to the popup items in **PropertyGridDropDownListE #### How to Handle Events -{{source=..\SamplesCS\PropertyGrid\Editors\PropertyGridHandlingEditorsEvents.cs region=ShowingIcons}} -{{source=..\SamplesVB\PropertyGrid\Editors\PropertyGridHandlingEditorsEvents.vb region=ShowingIcons}} - -````C# -private void EditorInitialized(object sender, PropertyGridItemEditorInitializedEventArgs e) -{ - PropertyGridDropDownListEditor editor = e.Editor as PropertyGridDropDownListEditor; - if (editor != null && e.Item.Name == "TextAlign") - { - BaseDropDownListEditorElement element = editor.EditorElement as BaseDropDownListEditorElement; - element.VisualItemFormatting -= element_VisualItemFormatting; - element.VisualItemFormatting += element_VisualItemFormatting; - } -} -private void element_VisualItemFormatting(object sender, VisualItemFormattingEventArgs args) -{ - args.VisualItem.Image = GetImageByText(args.VisualItem.Text); -} -private Image GetImageByText(string align) -{ - if (align == "Left") - { - return Properties.Resources.Format_Align_Left; - } - else if (align == "Right") - { - return Properties.Resources.Format_Align_Right; - } - return Properties.Resources.Format_Align_Center; -} - -```` -````VB.NET -Private Sub EditorInitialized(ByVal sender As Object, ByVal e As PropertyGridItemEditorInitializedEventArgs) - Dim editor As PropertyGridDropDownListEditor = TryCast(e.Editor, PropertyGridDropDownListEditor) - If editor IsNot Nothing AndAlso e.Item.Name = "TextAlign" Then - Dim element As BaseDropDownListEditorElement = TryCast(editor.EditorElement, BaseDropDownListEditorElement) - AddHandler element.VisualItemFormatting, AddressOf element_VisualItemFormatting - AddHandler element.VisualItemFormatting, AddressOf element_VisualItemFormatting - End If -End Sub -Private Sub element_VisualItemFormatting(ByVal sender As Object, ByVal args As VisualItemFormattingEventArgs) - args.VisualItem.Image = GetImageByText(args.VisualItem.Text) -End Sub -Private Function GetImageByText(ByVal align As String) As Image - If align = "Left" Then - Return My.Resources.Format_Align_Left - ElseIf align = "Right" Then - Return My.Resources.Format_Align_Right - End If - Return My.Resources.Format_Align_Center -End Function - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/propertygrid/editors/using-custom-editor.md b/controls/propertygrid/editors/using-custom-editor.md index 7cd3d0b44..5f685eb5f 100644 --- a/controls/propertygrid/editors/using-custom-editor.md +++ b/controls/propertygrid/editors/using-custom-editor.md @@ -21,135 +21,19 @@ All property grid editors inherit from __BaseInputEditor__. So, you have to inhe #### Creating Custom Editor -{{source=..\SamplesCS\PropertyGrid\Editors\PropertyGridUsingCustomEditor.cs region=CustomEditor}} -{{source=..\SamplesVB\PropertyGrid\Editors\PropertyGridUsingCustomEditor.vb region=CustomEditor}} - -````C# -public class PropertyGridTrackBarEditor : BaseInputEditor -{ - public override object Value - { - get - { - RadTrackBarElement editor = (RadTrackBarElement)this.EditorElement; - return editor.Value; - } - set - { - RadTrackBarElement editor = (RadTrackBarElement)this.EditorElement; - if (value != null && value != DBNull.Value) - { - editor.Value = Convert.ToInt32(value); - } - else - { - editor.Value = 0; - } - } - } - public override void BeginEdit() - { - base.BeginEdit(); - this.EditorElement.Focus(); - ((RadTrackBarElement)this.EditorElement).ValueChanged += new EventHandler(TrackBarEditor_ValueChanged); - } - void TrackBarEditor_ValueChanged(object sender, EventArgs e) - { - PropertyGridItemElement owner = this.OwnerElement as PropertyGridItemElement; - if (owner != null) - { - owner.PropertyTableElement.RaiseValueChanged(EventArgs.Empty); - } - } - public override bool EndEdit() - { - ((RadTrackBarElement)this.EditorElement).ValueChanged -= TrackBarEditor_ValueChanged; - return base.EndEdit(); - } - protected override RadElement CreateEditorElement() - { - return new RadTrackBarElement(); - } - public override Type DataType - { - get { return typeof(int); } - } -} - -```` -````VB.NET -Public Class PropertyGridTrackBarEditor - Inherits BaseInputEditor - Public Overrides Property Value() As Object - Get - Dim editor As RadTrackBarElement = CType(Me.EditorElement, RadTrackBarElement) - Return editor.Value - End Get - Set(ByVal value As Object) - Dim editor As RadTrackBarElement = CType(Me.EditorElement, RadTrackBarElement) - If Not value Is Nothing AndAlso Not value Is DBNull.Value Then - editor.Value = Convert.ToInt32(value) - Else - editor.Value = 0 - End If - End Set - End Property - Public Overrides Sub BeginEdit() - MyBase.BeginEdit() - Me.EditorElement.Focus() - AddHandler (CType(EditorElement, RadTrackBarElement)).ValueChanged, AddressOf TrackBarEditor_ValueChanged - End Sub - Private Sub TrackBarEditor_ValueChanged(ByVal sender As Object, ByVal e As EventArgs) - Dim owner As PropertyGridItemElement = TryCast(Me.OwnerElement, PropertyGridItemElement) - If owner IsNot Nothing Then - owner.PropertyTableElement.RaiseValueChanged(EventArgs.Empty) - End If - End Sub - Public Overrides Function EndEdit() As Boolean - RemoveHandler (CType(Me.EditorElement, RadTrackBarElement)).ValueChanged, AddressOf TrackBarEditor_ValueChanged - Return MyBase.EndEdit() - End Function - Protected Overrides Function CreateEditorElement() As RadElement - Return New RadTrackBarElement() - End Function - Public Overrides ReadOnly Property DataType() As Type - Get - Return GetType(Integer) - End Get - End Property -End Class - -```` - -{{endregion}} + + + + The __EditorRequired__ event is the correct place to replace the default editor: #### Replace Editor -{{source=..\SamplesCS\PropertyGrid\Editors\PropertyGridUsingCustomEditor.cs region=replaceEditor}} -{{source=..\SamplesVB\PropertyGrid\Editors\PropertyGridUsingCustomEditor.vb region=replaceEditor}} - -````C# -void radPropertyGrid1_EditorRequired(object sender, PropertyGridEditorRequiredEventArgs e) -{ - if (e.EditorType == typeof(PropertyGridSpinEditor)) - { - e.EditorType = typeof(PropertyGridTrackBarEditor); - } -} - -```` -````VB.NET -Private Sub radPropertyGrid1_EditorRequired(ByVal sender As Object, ByVal e As PropertyGridEditorRequiredEventArgs) - If e.EditorType Is GetType(PropertyGridSpinEditor) Then - e.EditorType = GetType(PropertyGridTrackBarEditor) - End If -End Sub - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/propertygrid/editors/validation.md b/controls/propertygrid/editors/validation.md index 0a5e64001..571d659e7 100644 --- a/controls/propertygrid/editors/validation.md +++ b/controls/propertygrid/editors/validation.md @@ -29,47 +29,10 @@ The code snippet below demonstrates simple data validation scenario. It is perfo #### Property validation -{{source=..\SamplesCS\PropertyGrid\Editors\PropertyGridValidation.cs region=PropertyValidating}} -{{source=..\SamplesVB\PropertyGrid\Editors\PropertyGridValidation.vb region=PropertyValidating}} + + -````C# -void radPropertyGrid1_PropertyValidating(object sender, PropertyValidatingEventArgs e) -{ - PropertyGridItem item = e.Item as PropertyGridItem; - if (item.PropertyType == typeof(string)) - { - if (string.IsNullOrEmpty(e.NewValue.ToString())) - { - item.ErrorMessage = "String value must not be an empty string!"; - e.Cancel = true; - } - } -} -void radPropertyGrid1_Edited(object sender, PropertyGridItemEditedEventArgs e) -{ - PropertyGridItem item = e.Item as PropertyGridItem; - item.ErrorMessage = ""; -} -```` -````VB.NET -Private Sub radPropertyGrid1_PropertyValidating(ByVal sender As Object, ByVal e As PropertyValidatingEventArgs) - Dim item As PropertyGridItem = TryCast(e.Item, PropertyGridItem) - If item.PropertyType Is GetType(String) Then - If String.IsNullOrEmpty(e.NewValue.ToString()) Then - item.ErrorMessage = "String value must not be an empty string!" - e.Cancel = True - End If - End If -End Sub -Private Sub radPropertyGrid1_Edited(ByVal sender As Object, ByVal e As PropertyGridItemEditedEventArgs) - Dim item As PropertyGridItem = TryCast(e.Item, PropertyGridItem) - item.ErrorMessage = "" -End Sub - -```` - -{{endregion}} # See Also diff --git a/controls/propertygrid/export-data/spread-export.md b/controls/propertygrid/export-data/spread-export.md index a08236b19..32e42d5f0 100644 --- a/controls/propertygrid/export-data/spread-export.md +++ b/controls/propertygrid/export-data/spread-export.md @@ -47,59 +47,18 @@ To use the spread export functionality, an instance of the __PropertyGridSpreadE You should pass an instance of a [SpreadExportRenderer]({%slug winforms/telerik-presentation-framework/export-renderers/spreadexportrenderer%}) to the export method as well. -{{source=..\SamplesCS\PropertyGrid\PropertyGridExportCode.cs region=Export}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridExportCode.vb region=Export}} + + -````C# -PropertyGridSpreadExport exporter = new PropertyGridSpreadExport(this.radPropertyGrid1); -SpreadExportRenderer renderer = new SpreadExportRenderer(); -exporter.RunExport(@"C:\ExportedFile.xlsx", renderer); -```` -````VB.NET -Dim exporter As New PropertyGridSpreadExport(Me.radPropertyGrid1) -Dim renderer As New SpreadExportRenderer() -exporter.RunExport("C:\ExportedFile.xlsx", renderer) - -```` - -{{endregion}} The __RunExport__ method has several overloads allowing the user to export using a stream as well: #### Running Export Synchronously Using a Stream -{{source=..\SamplesCS\PropertyGrid\PropertyGridExportCode.cs region=StreamRunExport}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridExportCode.vb region=StreamRunExport}} - -````C# -string exportFile = @"..\..\exportedData.xlsx"; -using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) -{ - Telerik.WinControls.Export.PropertyGridSpreadExport spreadExporter = new Telerik.WinControls.Export.PropertyGridSpreadExport(this.radPropertyGrid1); - Telerik.WinControls.Export.SpreadExportRenderer spreadRenderer = new Telerik.WinControls.Export.SpreadExportRenderer(); - spreadExporter.RunExport(ms, spreadRenderer); - using (System.IO.FileStream fileStream = new System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write)) - { - ms.WriteTo(fileStream); - } -} - -```` -````VB.NET -Dim exportFile As String = "..\..\exportedData.xlsx" -Using ms As New System.IO.MemoryStream() - Dim spreadExporter As New Telerik.WinControls.Export.PropertyGridSpreadExport(Me.radPropertyGrid1) - Dim spreadRenderer As New Telerik.WinControls.Export.SpreadExportRenderer() - spreadExporter.RunExport(ms, spreadRenderer) - Using fileStream As New System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write) - ms.WriteTo(fileStream) - End Using -End Using - -```` - -{{endregion}} + + + ## Properties @@ -138,26 +97,10 @@ End Using * __RowIndex__: The index of the currently exported row. Here is an example of formatting the exported TreeView: -{{source=..\SamplesCS\PropertyGrid\PropertyGridExportCode.cs region=Formatting}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridExportCode.vb region=Formatting}} + + -````C# -void exporter_CellFormatting(object sender, PropertyGridSpreadExportCellFormattingEventArgs e) -{ - e.ExportCell.BackColor = ColorTranslator.FromHtml("#F4FFEC"); - e.ExportCell.Font = new Font("Consolas", 10, FontStyle.Underline); -} -```` -````VB.NET -Private Sub exporter_CellFormatting(ByVal sender As Object, ByVal e As PropertyGridSpreadExportCellFormattingEventArgs) - e.ExportCell.BackColor = ColorTranslator.FromHtml("#F4FFEC") - e.ExportCell.Font = New Font("Consolas", 10, FontStyle.Underline) -End Sub - -```` - -{{endregion}} >caption Figure 2: Export Using Formating @@ -181,113 +124,26 @@ The following example will demonstrate how the async spread export feature can b 1\. The following code shows how you can subscribe to the notification events and start the async export operation. -{{source=..\SamplesCS\PropertyGrid\PropertyGridExportCode.cs region=AsyncExport}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridExportCode.vb region=AsyncExport}} - -````C# -private void btnExportAsync_Click(object sender, EventArgs e) -{ - PropertyGridSpreadExport spreadExporter = new PropertyGridSpreadExport(this.radPropertyGrid1); - spreadExporter.AsyncExportProgressChanged += spreadExporter_AsyncExportProgressChanged; - spreadExporter.AsyncExportCompleted += spreadExporter_AsyncExportCompleted; - SpreadExportRenderer exportRenderer = new SpreadExportRenderer(); - spreadExporter.RunExportAsync(@"..\..\ExportedFile.xlsx", exportRenderer); -} - -```` -````VB.NET -Private Sub btnExportAsync_Click(ByVal sender As Object, ByVal e As EventArgs) - Dim spreadExporter As New PropertyGridSpreadExport(Me.radPropertyGrid1) - AddHandler spreadExporter.AsyncExportProgressChanged, AddressOf spreadExporter_AsyncExportProgressChanged - AddHandler spreadExporter.AsyncExportCompleted, AddressOf spreadExporter_AsyncExportCompleted - Dim exportRenderer As New SpreadExportRenderer() - spreadExporter.RunExportAsync("..\..\ExportedFile.xlsx", exportRenderer) -End Sub - -```` - -{{endregion}} + + + + 2\. Handle the notification events and report progress. -{{source=..\SamplesCS\PropertyGrid\PropertyGridExportCode.cs region=ReportProgress}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridExportCode.vb region=ReportProgress}} - -````C# -private void spreadExporter_AsyncExportProgressChanged(object sender, ProgressChangedEventArgs e) -{ - this.radProgressBar1.Value1 = e.ProgressPercentage; -} -private void spreadExporter_AsyncExportCompleted(object sender, AsyncCompletedEventArgs e) -{ - RadMessageBox.Show("Async Spread Export Completed!"); - this.radProgressBar1.Value1 = 0; -} - -```` -````VB.NET -Private Sub spreadExporter_AsyncExportProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) - Me.radProgressBar1.Value1 = e.ProgressPercentage -End Sub -Private Sub spreadExporter_AsyncExportCompleted(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs) - RadMessageBox.Show("Async Spread Export Completed!") - Me.radProgressBar1.Value1 = 0 -End Sub - -```` - -{{endregion}} + + + + The __RunExportAsync__ method has several overloads allowing the user to export using a stream as well: #### Running Export Asynchronously Using a Stream -{{source=..\SamplesCS\PropertyGrid\PropertyGridExportCode.cs region=StreamRunExportAsync}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridExportCode.vb region=StreamRunExportAsync}} - -````C# -private void buttonRunExportAsync_Click(object sender, EventArgs e) -{ - System.IO.MemoryStream ms = new System.IO.MemoryStream(); - Telerik.WinControls.Export.PropertyGridSpreadExport spreadExporter = new Telerik.WinControls.Export.PropertyGridSpreadExport(this.radPropertyGrid1); - Telerik.WinControls.Export.SpreadExportRenderer spreadRenderer = new Telerik.WinControls.Export.SpreadExportRenderer(); - spreadExporter.AsyncExportCompleted += exporter_AsyncExportCompleted; - spreadExporter.RunExportAsync(ms, spreadRenderer); -} -private void exporter_AsyncExportCompleted(object sender, AsyncCompletedEventArgs e) -{ - RunWorkerCompletedEventArgs args = e as RunWorkerCompletedEventArgs; - string exportFile = @"..\..\exportedAsyncData.xlsx"; - using (System.IO.FileStream fileStream = new System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write)) - { - MemoryStream ms = args.Result as MemoryStream; - ms.WriteTo(fileStream); - ms.Close(); - } -} - -```` -````VB.NET -Private Sub buttonRunExportAsync_Click(sender As Object, e As EventArgs) - Dim ms As New System.IO.MemoryStream() - Dim spreadExporter As New Telerik.WinControls.Export.PropertyGridSpreadExport(Me.radPropertyGrid1) - Dim spreadRenderer As New Telerik.WinControls.Export.SpreadExportRenderer() - AddHandler spreadExporter.AsyncExportCompleted, AddressOf exporter_AsyncExportCompleted - spreadExporter.RunExportAsync(ms, spreadRenderer) -End Sub -Private Sub exporter_AsyncExportCompleted(sender As Object, e As AsyncCompletedEventArgs) - Dim args As RunWorkerCompletedEventArgs = TryCast(e, RunWorkerCompletedEventArgs) - Dim exportFile As String = "..\..\exportedAsyncData.xlsx" - Using fileStream As New System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write) - Dim ms As MemoryStream = TryCast(args.Result, MemoryStream) - ms.WriteTo(fileStream) - ms.Close() - End Using -End Sub - -```` - -{{endregion}} + + + + ## Async Export Methods and Events diff --git a/controls/propertygrid/features/custom-grouping.md b/controls/propertygrid/features/custom-grouping.md index 5c5fa4581..c2c657086 100644 --- a/controls/propertygrid/features/custom-grouping.md +++ b/controls/propertygrid/features/custom-grouping.md @@ -35,70 +35,10 @@ The following example demonstrates how to handle the __CustomGrouping__ event to #### Custom Grouping -{{source=..\SamplesCS\PropertyGrid\Features\PropertyGridCustomGrouping.cs region=CustomGrouping}} -{{source=..\SamplesVB\PropertyGrid\Features\PropertyGridCustomGrouping.vb region=CustomGrouping}} - -````C# -public PropertyGridCustomGrouping() -{ - InitializeComponent(); - radPropertyGrid1.SelectedObject = new RadButton(); - radPropertyGrid1.ToolbarVisible = true; - this.radPropertyGrid1.EnableCustomGrouping = true; - this.radPropertyGrid1.CustomGrouping += new PropertyGridCustomGroupingEventHandler(radPropertyGrid1_CustomGrouping); - radPropertyGrid1.ItemFormatting += new PropertyGridItemFormattingEventHandler(radPropertyGrid1_ItemFormatting); - GroupDescriptor descriptor = new GroupDescriptor("PropertyType"); - this.radPropertyGrid1.GroupDescriptors.Add(descriptor); -} -void radPropertyGrid1_ItemFormatting(object sender, PropertyGridItemFormattingEventArgs e) -{ - PropertyGridGroupItem groupItem = e.Item as PropertyGridGroupItem; - if (groupItem != null) - { - e.Item.Label = groupItem.Group.Key.ToString(); - } -} -private void radPropertyGrid1_CustomGrouping(object sender, PropertyGridCustomGroupingEventArgs e) -{ - Type propertyType = e.Item.PropertyType; - if (propertyType.IsClass) - { - e.GroupKey = "Reference type"; - } - else - { - e.GroupKey = "Value type"; - } -} - -```` -````VB.NET -Public Sub New() - InitializeComponent() - RadPropertyGrid1.SelectedObject = New RadButton() - RadPropertyGrid1.ToolbarVisible = True - Me.RadPropertyGrid1.EnableCustomGrouping = True - Dim descriptor As New GroupDescriptor("PropertyType") - Me.RadPropertyGrid1.GroupDescriptors.Add(descriptor) -End Sub -Private Sub RadPropertyGrid1_CustomGrouping(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.PropertyGridCustomGroupingEventArgs) Handles RadPropertyGrid1.CustomGrouping - Dim propertyType As Type = e.Item.PropertyType - If propertyType.IsClass Then - e.GroupKey = "Reference type" - Else - e.GroupKey = "Value type" - End If -End Sub -Private Sub RadPropertyGrid1_ItemFormatting(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.PropertyGridItemFormattingEventArgs) Handles RadPropertyGrid1.ItemFormatting - Dim groupItem As PropertyGridGroupItem = TryCast(e.Item, PropertyGridGroupItem) - If groupItem IsNot Nothing Then - e.Item.Label = groupItem.Group.Key.ToString() - End If -End Sub - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/propertygrid/features/filtering.md b/controls/propertygrid/features/filtering.md index 1e6e6618f..fa622f855 100644 --- a/controls/propertygrid/features/filtering.md +++ b/controls/propertygrid/features/filtering.md @@ -43,21 +43,10 @@ You can filter by the following criteria’s: #### Adding a Filter Descriptor -{{source=..\SamplesCS\PropertyGrid\Features\PropertyGridFiltering.cs region=Filtering}} -{{source=..\SamplesVB\PropertyGrid\Features\PropertyGridFiltering.vb region=Filtering}} + + -````C# -FilterDescriptor filter = new FilterDescriptor("Name", FilterOperator.Contains, "size"); -radPropertyGrid1.FilterDescriptors.Add(filter); -```` -````VB.NET -Dim filter = New FilterDescriptor("Name", FilterOperator.Contains, "size") -RadPropertyGrid1.FilterDescriptors.Add(filter) - -```` - -{{endregion}} # See Also diff --git a/controls/propertygrid/features/grouping.md b/controls/propertygrid/features/grouping.md index 0d749a421..2abb39799 100644 --- a/controls/propertygrid/features/grouping.md +++ b/controls/propertygrid/features/grouping.md @@ -27,21 +27,10 @@ Additionally, you can tune the sort order by setting the __SortOrder__ property. #### Setting Default Groups -{{source=..\SamplesCS\PropertyGrid\Features\PropertyGridGrouping.cs region=PropertySort}} -{{source=..\SamplesVB\PropertyGrid\Features\PropertyGridGrouping.vb region=PropertySort}} + + -````C# -radPropertyGrid1.PropertySort = PropertySort.CategorizedAlphabetical; -radPropertyGrid1.SortOrder = SortOrder.Descending; -```` -````VB.NET -RadPropertyGrid1.PropertySort = PropertySort.CategorizedAlphabetical -RadPropertyGrid1.SortOrder = SortOrder.Descending - -```` - -{{endregion}} To add your own groups programatically, make sure that the __EnableGrouping__ property is set to *true* and add the desired __GroupDescriptor__ to the __GroupDescriptors__ collection of the control. @@ -69,23 +58,10 @@ Here is an example of grouping by the formatted value: #### Adding a Group Descriptor -{{source=..\SamplesCS\PropertyGrid\Features\PropertyGridGrouping.cs region=GroupDescriptor}} -{{source=..\SamplesVB\PropertyGrid\Features\PropertyGridGrouping.vb region=GroupDescriptor}} - -````C# -radPropertyGrid1.EnableGrouping = true; -GroupDescriptor group = new GroupDescriptor(new SortDescriptor[] { new SortDescriptor("FormattedValue", ListSortDirection.Ascending) }); -radPropertyGrid1.GroupDescriptors.Add(group); - -```` -````VB.NET -RadPropertyGrid1.EnableGrouping = True -Dim group = New GroupDescriptor(New SortDescriptor() {New SortDescriptor("FormattedValue", ListSortDirection.Ascending)}) -RadPropertyGrid1.GroupDescriptors.Add(group) + + -```` -{{endregion}} # See Also diff --git a/controls/propertygrid/features/help-bar.md b/controls/propertygrid/features/help-bar.md index 4ddd157a5..6acc71a0c 100644 --- a/controls/propertygrid/features/help-bar.md +++ b/controls/propertygrid/features/help-bar.md @@ -19,19 +19,10 @@ previous_url: propertygrid-features-helpbar #### Enabling the Help Bar -{{source=..\SamplesCS\PropertyGrid\Features\PropertyGridHelpBar.cs region=helpVisible}} -{{source=..\SamplesVB\PropertyGrid\Features\PropertyGridHelpBar.vb region=helpVisible}} + + -````C# -radPropertyGrid1.HelpVisible = true; -```` -````VB.NET -RadPropertyGrid1.HelpVisible = True - -```` - -{{endregion}} By double clicking over the size grip above the help section, the help section is being collapsed or expanded. Additionally, by using the size grip, the end user can resize the help section. diff --git a/controls/propertygrid/features/sorting.md b/controls/propertygrid/features/sorting.md index c64f52899..4237e45d0 100644 --- a/controls/propertygrid/features/sorting.md +++ b/controls/propertygrid/features/sorting.md @@ -19,21 +19,10 @@ The sorting capabilities can be controlled either by using the predefined sortin #### Default Sorting -{{source=..\SamplesCS\PropertyGrid\Features\PropertyGridSorting.cs region=Sorting}} -{{source=..\SamplesVB\PropertyGrid\Features\PropertyGridSorting.vb region=Sorting}} + + -````C# -radPropertyGrid1.PropertySort = PropertySort.Alphabetical; -radPropertyGrid1.SortOrder = SortOrder.Descending; -```` -````VB.NET -RadPropertyGrid1.PropertySort = PropertySort.Alphabetical -RadPropertyGrid1.SortOrder = SortOrder.Descending - -```` - -{{endregion}} Another way to sort the items is to create a __SortDescriptor__ and add it to the __SortDescriptors__ collection of the control. Additionally, to enable sorting with sort descriptors, you have to set the __EnableSorting__ property to *true*. @@ -61,23 +50,10 @@ Here is an example of sorting the items by their value in ascending order. #### Sorting with SortDescriptors -{{source=..\SamplesCS\PropertyGrid\Features\PropertyGridSorting.cs region=SortDescriptor}} -{{source=..\SamplesVB\PropertyGrid\Features\PropertyGridSorting.vb region=SortDescriptor}} - -````C# -radPropertyGrid1.EnableSorting = true; -SortDescriptor sort = new SortDescriptor("FormattedValue", ListSortDirection.Ascending); -radPropertyGrid1.SortDescriptors.Add(sort); - -```` -````VB.NET -RadPropertyGrid1.EnableSorting = True -Dim sort = New SortDescriptor("FormattedValue", ListSortDirection.Ascending) -RadPropertyGrid1.SortDescriptors.Add(sort) + + -```` -{{endregion}} >important The user should clear programmatically the **SortDescriptors** collection first because there is a default sort order (*Ascending*) for the properties in the object. diff --git a/controls/propertygrid/features/toolbar.md b/controls/propertygrid/features/toolbar.md index 31ba50365..2384ba9cf 100644 --- a/controls/propertygrid/features/toolbar.md +++ b/controls/propertygrid/features/toolbar.md @@ -15,19 +15,10 @@ previous_url: propertygrid-features-toolbar #### Enabling the Toolbar -{{source=..\SamplesCS\PropertyGrid\Features\PropertyGridToolbar.cs region=ToolbarVisible}} -{{source=..\SamplesVB\PropertyGrid\Features\PropertyGridToolbar.vb region=ToolbarVisible}} + + -````C# -radPropertyGrid1.ToolbarVisible = true; -```` -````VB.NET -RadPropertyGrid1.ToolbarVisible = True - -```` - -{{endregion}} >caption Figure 1: Toolbar @@ -37,43 +28,19 @@ You can set the predefined filter operator and property by making use of the fol #### Customizing Default Filtering -{{source=..\SamplesCS\PropertyGrid\Features\PropertyGridToolbar.cs region=FilterProperties}} -{{source=..\SamplesVB\PropertyGrid\Features\PropertyGridToolbar.vb region=FilterProperties}} - -````C# -radPropertyGrid1.PropertyGridElement.ToolbarElement.FilterOperator = FilterOperator.Contains; -radPropertyGrid1.PropertyGridElement.ToolbarElement.FilterPropertyName = "Name"; - -```` -````VB.NET -RadPropertyGrid1.PropertyGridElement.ToolbarElement.FilterOperator = FilterOperator.Contains -RadPropertyGrid1.PropertyGridElement.ToolbarElement.FilterPropertyName = "Name" + + -```` -{{endregion}} The toolbar consists of a __StackLayoutPanel__, which allow you to easily add additional elements or modify the existing once. You can access the existing items as follows: #### Accessing Toolbar Elements -{{source=..\SamplesCS\PropertyGrid\Features\PropertyGridToolbar.cs region=accessingItems}} -{{source=..\SamplesVB\PropertyGrid\Features\PropertyGridToolbar.vb region=accessingItems}} + + -````C# -RadTextBoxElement filterTextBox = radPropertyGrid1.PropertyGridElement.ToolbarElement.SearchTextBoxElement; -RadToggleButtonElement sortButton = radPropertyGrid1.PropertyGridElement.ToolbarElement.AlphabeticalToggleButton; -RadToggleButtonElement groupButton = radPropertyGrid1.PropertyGridElement.ToolbarElement.CategorizedToggleButton; -```` -````VB.NET -Dim filterTextBox As RadTextBoxElement = RadPropertyGrid1.PropertyGridElement.ToolbarElement.SearchTextBoxElement -Dim sortButton As RadToggleButtonElement = RadPropertyGrid1.PropertyGridElement.ToolbarElement.AlphabeticalToggleButton -Dim groupButton As RadToggleButtonElement = RadPropertyGrid1.PropertyGridElement.ToolbarElement.CategorizedToggleButton - -```` - -{{endregion}} If you want to add a new element in the toolbar, just add it to the __Children__ collection of __ToolbarElement__: @@ -82,27 +49,10 @@ If you want to add a new element in the toolbar, just add it to the __Children__ >caption Figure 2: Add Element to Toolbar ![WinForms RadPropertyGrid Add Element to Toolbar](images/propertygrid-features-toolbar002.png) -{{source=..\SamplesCS\PropertyGrid\Features\PropertyGridToolbar.cs region=addElement}} -{{source=..\SamplesVB\PropertyGrid\Features\PropertyGridToolbar.vb region=addElement}} - -````C# -RadButtonElement clearFiltering = new RadButtonElement(); -clearFiltering.Text = "Clear"; -clearFiltering.MinSize = new System.Drawing.Size(25, 22); -clearFiltering.StretchHorizontally = false; -radPropertyGrid1.PropertyGridElement.ToolbarElement.Children.Add(clearFiltering); - -```` -````VB.NET -Dim clearFiltering As New RadButtonElement() -clearFiltering.Text = "Clear" -clearFiltering.MinSize = New System.Drawing.Size(25, 22) -clearFiltering.StretchHorizontally = False -RadPropertyGrid1.PropertyGridElement.ToolbarElement.Children.Add(clearFiltering) + + -```` -{{endregion}} # See Also diff --git a/controls/propertygrid/getting-started.md b/controls/propertygrid/getting-started.md index 125826f8c..e153a163e 100644 --- a/controls/propertygrid/getting-started.md +++ b/controls/propertygrid/getting-started.md @@ -42,19 +42,10 @@ The following example will demonstrate the basic functionalities of **RadPropert #### RadPropertyGrid`s SelectedObject -{{source=..\SamplesCS\PropertyGrid\PropertyGridGettingStarted.cs region=SelectedObject}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridGettingStarted.vb region=SelectedObject}} + + -````C# -this.radPropertyGrid1.SelectedObject = new PropertyGridElement(); -```` -````VB.NET -Me.RadPropertyGrid1.SelectedObject = New PropertyGridElement() - -```` - -{{endregion}} It is all set and **RadProperyGrid** reads all public properties of the given object and displays them: @@ -67,66 +58,26 @@ Next, we will add a predefined toolbox on the top of the control. This toolbox c #### ToolbarVisible -{{source=..\SamplesCS\PropertyGrid\PropertyGridGettingStarted.cs region=ToolBarVisible}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridGettingStarted.vb region=ToolBarVisible}} - -````C# -this.radPropertyGrid1.ToolbarVisible = true; + + -```` -````VB.NET -Me.RadPropertyGrid1.ToolbarVisible = True -```` - -{{endregion}} Additionally, since the toolbox consists of a __StackLayoutPanel__, is supports adding additional elements. Here is how to add a button that clears the filter text box: #### Add Element to Toolbox -{{source=..\SamplesCS\PropertyGrid\PropertyGridGettingStarted.cs region=AddElementToToolbox1}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridGettingStarted.vb region=AddElementToToolbox1}} - -````C# -RadButtonElement clearFiltering = new RadButtonElement(); -clearFiltering.Text = "Clear"; -clearFiltering.MinSize = new System.Drawing.Size(25, 22); -clearFiltering.StretchHorizontally = false; -clearFiltering.Click += new EventHandler(clearFiltering_Click); + + -```` -````VB.NET -Dim clearFiltering = New RadButtonElement() -clearFiltering.Text = "Clear" -clearFiltering.MinSize = New System.Drawing.Size(25, 22) -clearFiltering.StretchHorizontally = False -AddHandler clearFiltering.Click, AddressOf clearFiltering_Click -```` - -{{endregion}} #### Clear the Filter -{{source=..\SamplesCS\PropertyGrid\PropertyGridGettingStarted.cs region=AddElementToToolbox2}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridGettingStarted.vb region=AddElementToToolbox2}} - -````C# -void clearFiltering_Click(object sender, EventArgs e) -{ - this.radPropertyGrid1.PropertyGridElement.ToolbarElement.SearchTextBoxElement.Text = ""; -} + + -```` -````VB.NET -Private Sub clearFiltering_Click(ByVal sender As Object, ByVal e As EventArgs) - Me.RadPropertyGrid1.PropertyGridElement.ToolbarElement.SearchTextBoxElement.Text = "" -End Sub -```` - -{{endregion}} By default, opening the editor for editing is done by double clicking the editor. This behavior can be easily changed by selecting one of the predefined options of the __BeginEditMode__ property. The options to choose from are follows: @@ -138,19 +89,10 @@ By default, opening the editor for editing is done by double clicking the editor #### Begin Edit Mode -{{source=..\SamplesCS\PropertyGrid\PropertyGridGettingStarted.cs region=BeginEditMode}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridGettingStarted.vb region=BeginEditMode}} - -````C# -this.radPropertyGrid1.BeginEditMode = RadPropertyGridBeginEditModes.BeginEditOnClick; + + -```` -````VB.NET -Me.RadPropertyGrid1.BeginEditMode = RadPropertyGridBeginEditModes.BeginEditOnClick -```` - -{{endregion}} To set the default sorting or grouping of the properties, just set the **PropertySort** property, to one of the enumerated values: @@ -164,37 +106,19 @@ To set the default sorting or grouping of the properties, just set the **Propert #### Group by Categories -{{source=..\SamplesCS\PropertyGrid\PropertyGridGettingStarted.cs region=PropertySort}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridGettingStarted.vb region=PropertySort}} - -````C# -this.radPropertyGrid1.PropertySort = PropertySort.Categorized; + + -```` -````VB.NET -Me.RadPropertyGrid1.PropertySort = PropertySort.Categorized -```` - -{{endregion}} You can control the sort order, by setting the **SortOrder** property of the control. Possible values are *Ascending*, *Descending* and *None*: #### Setting the Sort Order -{{source=..\SamplesCS\PropertyGrid\PropertyGridGettingStarted.cs region=SortOrder}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridGettingStarted.vb region=SortOrder}} - -````C# -this.radPropertyGrid1.SortOrder = SortOrder.Ascending; + + -```` -````VB.NET -Me.RadPropertyGrid1.SortOrder = SortOrder.Ascending -```` - -{{endregion}} There are also four properties that allow you to control the expand/collapse image of the control. These are as follows: __CollapseImage__, __ExpandImage__, __HoveredCollapseImage__ and __HoveredExpandImage__. @@ -215,24 +139,10 @@ There are a few properties that you can set in order to change the item appearan #### Item Settings -{{source=..\SamplesCS\PropertyGrid\PropertyGridGettingStarted.cs region=ItemProperties}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridGettingStarted.vb region=ItemProperties}} -````C# -this.radPropertyGrid1.ItemHeight = 30; -this.radPropertyGrid1.ItemIndent = 25; -this.radPropertyGrid1.ItemSpacing = 1; - -```` -````VB.NET -Me.RadPropertyGrid1.ItemHeight = 30 -Me.RadPropertyGrid1.ItemIndent = 25 -Me.RadPropertyGrid1.ItemSpacing = 1 - -```` - + + -{{endregion}} >caption Figure 3: Selected Object ![WinForms RadPropertyGrid Selected Object](images/propertygrid-getting-started003.png) diff --git a/controls/propertygrid/how-to/custom-keyboard-handling.md b/controls/propertygrid/how-to/custom-keyboard-handling.md index 8aac89a7e..6f0e50af0 100644 --- a/controls/propertygrid/how-to/custom-keyboard-handling.md +++ b/controls/propertygrid/how-to/custom-keyboard-handling.md @@ -39,65 +39,10 @@ We need to create a custom **RadPropertyGrid** control so that we can override t #### Control`s Implementation -{{source=..\SamplesCS\PropertyGrid\PropertyGridCustomKeyboardNavigation.cs region=CustomRadPropertyGrid}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridCustomKeyboardNavigation.vb region=CustomRadPropertyGrid}} -````C# -public class CustomRadPropertyGrid : RadPropertyGrid -{ - public override string ThemeClassName - { - get - { - return typeof(RadPropertyGrid).FullName; - } - } - protected override PropertyGridElement CreatePropertyGridElement() - { - return new CuistomPropertyGridElement(); - } - protected override bool IsInputKey(Keys keyData) - { - PropertyGridTraverser traverser = new PropertyGridTraverser(this.PropertyGridElement.PropertyTableElement); - traverser.MoveTo(this.SelectedGridItem); - if (keyData == Keys.Tab && traverser.MoveNext()) - { - return true; - } - return base.IsInputKey(keyData); - } -} - -```` -````VB.NET -Public Class CustomRadPropertyGrid - Inherits RadPropertyGrid - Public Overrides Property ThemeClassName As String - Get - Return GetType(RadButton).FullName - End Get - Set(value As String) - MyBase.ThemeClassName = value - End Set - End Property - Protected Overrides Function CreatePropertyGridElement() As PropertyGridElement - Return New CuistomPropertyGridElement - End Function - Protected Overrides Function IsInputKey(ByVal keyData As Keys) As Boolean - Dim traverser As PropertyGridTraverser = New PropertyGridTraverser(Me.PropertyGridElement.PropertyTableElement) - traverser.MoveTo(Me.SelectedGridItem) - If ((keyData = Keys.Tab) _ - AndAlso traverser.MoveNext) Then - Return True - End If - Return MyBase.IsInputKey(keyData) - End Function -End Class - -```` - - - -{{endregion}} + + + + ## Custom Elements @@ -107,129 +52,10 @@ The various elements building the control are created in special virtual methods #### Elements` Implementation -{{source=..\SamplesCS\PropertyGrid\PropertyGridCustomKeyboardNavigation.cs region=CustomElements}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridCustomKeyboardNavigation.vb region=CustomElements}} -````C# -public class CuistomPropertyGridElement : PropertyGridElement -{ - protected override Type ThemeEffectiveType - { - get - { - return typeof(PropertyGridElement); - } - } - protected override PropertyGridSplitElement CreateSplitElement() - { - return new CustomPropertyGridSplitElement(); - } -} -public class CustomPropertyGridSplitElement : PropertyGridSplitElement -{ - protected override Type ThemeEffectiveType - { - get - { - return typeof(PropertyGridSplitElement); - } - } - protected override PropertyGridTableElement CreateTableElement() - { - return new CustomPropertyGridTableElement(); - } -} -public class CustomPropertyGridTableElement : PropertyGridTableElement -{ - protected override Type ThemeEffectiveType - { - get - { - return typeof(PropertyGridTableElement); - } - } - public override bool ProcessKeyDown(KeyEventArgs e) - { - if (e.KeyCode == Keys.Tab) - { - if (this.SelectedGridItem == null) - { - PropertyGridTraverser traverser = new PropertyGridTraverser(this); - if (traverser.MoveNext()) - { - this.ProcessSelection(traverser.Current, false); - } - } - else - { - PropertyGridTraverser traverser = new PropertyGridTraverser(this); - traverser.MoveTo(this.SelectedGridItem); - if (traverser.MoveNext()) - { - this.ProcessSelection(traverser.Current, false); - } - } - return true; - } - return base.ProcessKeyDown(e); - } -} - -```` -````VB.NET -Public Class CuistomPropertyGridElement - Inherits PropertyGridElement - Protected Overrides ReadOnly Property ThemeEffectiveType As Type - Get - Return GetType(PropertyGridElement) - End Get - End Property - Protected Overrides Function CreateSplitElement() As PropertyGridSplitElement - Return New CustomPropertyGridSplitElement - End Function -End Class -Public Class CustomPropertyGridSplitElement - Inherits PropertyGridSplitElement - Protected Overrides ReadOnly Property ThemeEffectiveType As Type - Get - Return GetType(PropertyGridSplitElement) - End Get - End Property - Protected Overrides Function CreateTableElement() As PropertyGridTableElement - Return New CustomPropertyGridTableElement - End Function -End Class -Public Class CustomPropertyGridTableElement - Inherits PropertyGridTableElement - Protected Overrides ReadOnly Property ThemeEffectiveType As Type - Get - Return GetType(PropertyGridTableElement) - End Get - End Property - Public Overrides Function ProcessKeyDown(ByVal e As KeyEventArgs) As Boolean - If (e.KeyCode = Keys.Tab) Then - If (Me.SelectedGridItem Is Nothing) Then - Dim traverser As PropertyGridTraverser = New PropertyGridTraverser(Me) - If traverser.MoveNext Then - Me.ProcessSelection(traverser.Current, False) - End If - Else - Dim traverser As PropertyGridTraverser = New PropertyGridTraverser(Me) - traverser.MoveTo(Me.SelectedGridItem) - If traverser.MoveNext Then - Me.ProcessSelection(traverser.Current, False) - End If - End If - Return True - End If - Return MyBase.ProcessKeyDown(e) - End Function -End Class - -```` - - - -{{endregion}} + + + + # See Also diff --git a/controls/propertygrid/keyboard-navigation.md b/controls/propertygrid/keyboard-navigation.md index f3be1f1f0..ea50ad0cc 100644 --- a/controls/propertygrid/keyboard-navigation.md +++ b/controls/propertygrid/keyboard-navigation.md @@ -19,37 +19,17 @@ __RadPropertyGrid__ allows navigation through its item by using keyboard. Two sc To enable this functionality a single property setting is needed: -{{source=..\SamplesCS\PropertyGrid\PropertyGridKeyboardNavigation.cs region=SetKeyboardSearchEnabled}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridKeyboardNavigation.vb region=SetKeyboardSearchEnabled}} -````C# -radPropertyGrid1.KeyboardSearchEnabled = true; + + -```` -````VB.NET -radPropertyGrid1.KeyboardSearchEnabled = True -```` - - - -{{endregion}} Another property of interest is the __KeyboardSearchResetInterval__. It is used to determine what time between keystrokes will be considered as typing. Consequent keystrokes with performed faster than the specified interval will be considered typing and once the time elapses, the matching item (if such) will be selected. Here is how to access this property to change the value of the timer: -{{source=..\SamplesCS\PropertyGrid\PropertyGridKeyboardNavigation.cs region=KeyboardSearchResetInterval}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridKeyboardNavigation.vb region=KeyboardSearchResetInterval}} -````C# -radPropertyGrid1.KeyboardSearchResetInterval = 200; - -```` -````VB.NET -radPropertyGrid1.KeyboardSearchResetInterval = 200 - -```` - + + -{{endregion}} # See Also diff --git a/controls/propertygrid/localization.md b/controls/propertygrid/localization.md index 81e1518db..d23d29e5d 100644 --- a/controls/propertygrid/localization.md +++ b/controls/propertygrid/localization.md @@ -23,86 +23,19 @@ Below is a sample implementation of an English localization provider: #### Creating English Localization Provider -{{source=..\SamplesCS\PropertyGrid\PropertyGridLocalization.cs region=localizationProvider}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridLocalization.vb region=localizationProvider}} - -````C# -public class MyEnglishPropertyGridLocalizationProvider : PropertyGridLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case PropertyGridStringId.ContextMenuReset: return "Reset"; - case PropertyGridStringId.ContextMenuEdit: return "Edit"; - case PropertyGridStringId.ContextMenuExpand: return "Expand"; - case PropertyGridStringId.ContextMenuCollapse: return "Collapse"; - case PropertyGridStringId.ContextMenuShowDescription: return "Show description"; - case PropertyGridStringId.ContextMenuShowToolbar: return "Show toolbar"; - case PropertyGridStringId.ContextMenuSort: return "Sorta"; - case PropertyGridStringId.ContextMenuNoSort: return "No Sort"; - case PropertyGridStringId.ContextMenuAlphabetical: return "Alphabetical"; - case PropertyGridStringId.ContextMenuCategorized: return "Categorized"; - case PropertyGridStringId.ContextMenuCategorizedAlphabetical: return "Categorized Alphabetical"; - } - return base.GetLocalizedString(id); - } -} - -```` -````VB.NET -Public Class MyEnglishPropertyGridLocalizationProvider - Inherits PropertyGridLocalizationProvider - Public Overrides Function GetLocalizedString(ByVal id As String) As String - Select Case id - Case PropertyGridStringId.ContextMenuReset - Return "Reset" - Case PropertyGridStringId.ContextMenuEdit - Return "Edit" - Case PropertyGridStringId.ContextMenuExpand - Return "Expand" - Case PropertyGridStringId.ContextMenuCollapse - Return "Collapse" - Case PropertyGridStringId.ContextMenuShowDescription - Return "Show description" - Case PropertyGridStringId.ContextMenuShowToolbar - Return "Show toolbar" - Case PropertyGridStringId.ContextMenuSort - Return "Sort" - Case PropertyGridStringId.ContextMenuNoSort - Return "No Sort" - Case PropertyGridStringId.ContextMenuAlphabetical - Return "Alphabetical" - Case PropertyGridStringId.ContextMenuCategorized - Return "Categorized" - Case PropertyGridStringId.ContextMenuCategorizedAlphabetical - Return "Categorized Alphabetical" - End Select - Return MyBase.GetLocalizedString(id) - End Function -End Class - -```` - -{{endregion}} + + -To apply the custom localization provider, instantiate and assign it to the current localization provider: -#### Changing the localization provider -{{source=..\SamplesCS\PropertyGrid\PropertyGridLocalization.cs region=changeLocalization}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridLocalization.vb region=changeLocalization}} +To apply the custom localization provider, instantiate and assign it to the current localization provider: -````C# -PropertyGridLocalizationProvider.CurrentProvider = new MyEnglishPropertyGridLocalizationProvider(); +#### Changing the localization provider -```` -````VB.NET -PropertyGridLocalizationProvider.CurrentProvider = New MyEnglishPropertyGridLocalizationProvider() + + -```` -{{endregion}} # See Also diff --git a/controls/propertygrid/populating-with-data/binding-to-multiple-objects.md b/controls/propertygrid/populating-with-data/binding-to-multiple-objects.md index 9d0afd043..eff80a397 100644 --- a/controls/propertygrid/populating-with-data/binding-to-multiple-objects.md +++ b/controls/propertygrid/populating-with-data/binding-to-multiple-objects.md @@ -21,21 +21,10 @@ Here is how to use this feature: #### SelectedObjects Property -{{source=..\SamplesCS\PropertyGrid\PropertyGridBindingToMultipleObjects.cs region=BindToMultipleObjects}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridBindingToMultipleObjects.vb region=BindToMultipleObjects}} + + -````C# -object[] objects = new object[] { this.radButton1, this.radTextBox1, this.radLabel1 }; -this.radPropertyGrid1.SelectedObjects = objects; -```` -````VB.NET -Dim objects As Object() = New Object() {Me.RadButton1, Me.RadTextBox1, Me.RadLabel1} -Me.RadPropertyGrid1.SelectedObjects = objects - -```` - -{{endregion}} # See Also diff --git a/controls/propertygrid/populating-with-data/radpropertystore-adding-custom-properties.md b/controls/propertygrid/populating-with-data/radpropertystore-adding-custom-properties.md index d1bdc9e31..9a5beeb0b 100644 --- a/controls/propertygrid/populating-with-data/radpropertystore-adding-custom-properties.md +++ b/controls/propertygrid/populating-with-data/radpropertystore-adding-custom-properties.md @@ -21,37 +21,10 @@ To get started with the **RadPropertyStore** follow these three steps: #### Using RadPropertyStore -{{source=..\SamplesCS\PropertyGrid\PropertyGridRadPropertyStore.cs region=RadPropertyStore}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridRadPropertyStore.vb region=RadPropertyStore}} - -````C# -PropertyStoreItem intItem = new PropertyStoreItem(typeof(int), "Integer", 1); -PropertyStoreItem floatItem = new PropertyStoreItem(typeof(float), "Float", 1f, "Property storing a floating point value."); -PropertyStoreItem stringItem = new PropertyStoreItem(typeof(string), "String", "telerik", "Property storing a string value", "Telerik"); -PropertyStoreItem dockItem = new PropertyStoreItem(typeof(DockStyle), "Dock", DockStyle.Top, "Property containing DockStyle value", "Layout", false); -RadPropertyStore store = new RadPropertyStore(); -store.Add(intItem); -store.Add(floatItem); -store.Add(stringItem); -store.Add(dockItem); -this.radPropertyGrid1.SelectedObject = store; - -```` -````VB.NET -Dim intItem As New PropertyStoreItem(GetType(Integer), "Integer", 1) -Dim floatItem As New PropertyStoreItem(GetType(Single), "Float", 1.0F, "Property storing a floating point value.") -Dim stringItem As New PropertyStoreItem(GetType(String), "String", "telerik", "Property storing a string value", "Telerik") -Dim dockItem As New PropertyStoreItem(GetType(DockStyle), "Dock", DockStyle.Top, "Property containing DockStyle value", "Layout", False) -Dim store As New RadPropertyStore -store.Add(intItem) -store.Add(floatItem) -store.Add(stringItem) -store.Add(dockItem) -Me.RadPropertyGrid1.SelectedObject = store - -```` - -{{endregion}} + + + + >caption Figure 1: RadPropertyStore @@ -61,25 +34,10 @@ You can then use the **RadPropertyGrid** to edit the **PropertyStoreItems** valu #### Add/Remove/Edit PropertyStoreItems -{{source=..\SamplesCS\PropertyGrid\PropertyGridRadPropertyStore.cs region=modifyStore}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridRadPropertyStore.vb region=modifyStore}} - -````C# -store["Integer"].Value = 100; -store["Dock"].Value = DockStyle.Fill; -store.RemoveAt(store.Count - 1); -store.Add(typeof(bool), "Boolean", true); - -```` -````VB.NET -store("Integer").Value = 100 -store("Dock").Value = DockStyle.Fill -store.RemoveAt(store.Count - 1) -store.Add(GetType(Boolean), "Boolean", True) + + -```` -{{endregion}} You have to provide a value of the same type as the PropertyStoreItem or a value that can be converted through the TypeConverter of the type of the property. Otherwise the value would not be stored in the item. diff --git a/controls/propertygrid/type-converters.md b/controls/propertygrid/type-converters.md index a4dc8d518..52e2f2ff4 100644 --- a/controls/propertygrid/type-converters.md +++ b/controls/propertygrid/type-converters.md @@ -26,147 +26,10 @@ Consider the __RadPropertyGrid__ is populated with a __Patient__ object contacti #### Bind RadPropertyGrid -{{source=..\SamplesCS\PropertyGrid\PropertyGridTypeConverters.cs region=PopulateData}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridTypeConverters.vb region=PopulateData}} - -````C# - -public PropertyGridTypeConverters() -{ - InitializeComponent(); - - Patient patient = new Patient(); - patient.BloodType = "O-"; - patient.BodyTemperature = new Temperature() { Value = 309.25, Unit = TemperatureUnit.Kelvin }; - patient.FirstName = "First"; - patient.LastName = "Last"; - patient.TotalLungCapacity = 5800d; - - this.radPropertyGrid1.SelectedObject = patient; -} - -public class Patient -{ - [Description("This property is here just to make the example more real-life like.")] - public string FirstName { get; set; } - - [Description("This property is here just to make the example more real-life like.")] - public string LastName { get; set; } - - public double TotalLungCapacity { get; set; } - - public string BloodType { get; set; } - - public Temperature BodyTemperature { get; set; } -} - -public class Temperature -{ - public double Value { get; set; } - - public TemperatureUnit Unit { get; set; } -} - -public enum TemperatureUnit -{ - Kelvin, - Celsius, - Fahrenheit -} - -```` -````VB.NET -Public Sub New() - InitializeComponent() - Dim patient As New Patient() - patient.BloodType = "O-" - patient.BodyTemperature = New Temperature() With { _ - .Value = 309.25, _ - .Unit = TemperatureUnit.Kelvin _ - } - patient.FirstName = "First" - patient.LastName = "Last" - patient.TotalLungCapacity = 5800.0 - Me.RadPropertyGrid1.SelectedObject = patient -End Sub -Public Class Patient - _ - Public Property FirstName() As String - Get - Return m_FirstName - End Get - Set(value As String) - m_FirstName = value - End Set - End Property - Private m_FirstName As String - _ - Public Property LastName() As String - Get - Return m_LastName - End Get - Set(value As String) - m_LastName = value - End Set - End Property - Private m_LastName As String - Public Property TotalLungCapacity() As Double - Get - Return m_TotalLungCapacity - End Get - Set(value As Double) - m_TotalLungCapacity = value - End Set - End Property - Private m_TotalLungCapacity As Double - Public Property BloodType() As String - Get - Return m_BloodType - End Get - Set(value As String) - m_BloodType = value - End Set - End Property - Private m_BloodType As String - Public Property BodyTemperature() As Temperature - Get - Return m_BodyTemperature - End Get - Set(value As Temperature) - m_BodyTemperature = value - End Set - End Property - Private m_BodyTemperature As Temperature -End Class -Public Class Temperature - Public Property Value() As Double - Get - Return m_Value - End Get - Set(value As Double) - m_Value = value - End Set - End Property - Private m_Value As Double - Public Property Unit() As TemperatureUnit - Get - Return m_Unit - End Get - Set(value As TemperatureUnit) - m_Unit = value - End Set - End Property - Private m_Unit As TemperatureUnit -End Class -Public Enum TemperatureUnit - Kelvin - Celsius - Fahrenheit -End Enum - -```` - -{{endregion}} + + + + You will notice that the __BodyTemperature__ property displays the property type: @@ -182,211 +45,19 @@ As the __BodyTemperature__ property is of complex type composed of two propertie #### TemperatureTypeConverter -{{source=..\SamplesCS\PropertyGrid\PropertyGridTypeConverters.cs region=TemperatureTypeConverter}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridTypeConverters.vb region=TemperatureTypeConverter}} - -````C# - -public class TemperatureTypeConverter : ExpandableObjectConverter -{ - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) - { - if (sourceType == typeof(string)) - { - return true; - } - - return base.CanConvertFrom(context, sourceType); - } - - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) - { - if (destinationType == typeof(string)) - { - return true; - } - - return base.CanConvertTo(context, destinationType); - } - - public override object ConvertTo(ITypeDescriptorContext context, - System.Globalization.CultureInfo culture, object value, Type destinationType) - { - if (destinationType != typeof(string)) - { - return base.ConvertTo(context, culture, value, destinationType); - } - - Temperature temp = value as Temperature; - - if (temp == null) - { - return string.Empty; - } - - return string.Format("{0} {1}", temp.Value, temp.Unit.ToString().Substring(0, 1)); - } - - public override object ConvertFrom(ITypeDescriptorContext context, - System.Globalization.CultureInfo culture, object value) - { - string stringValue = value as string; - - if (stringValue == null) - { - return base.ConvertFrom(context, culture, value); - } - - string number = ""; - - for (int i = 0; i < stringValue.Length; i++) - { - char c = stringValue[i]; - - if (char.IsNumber(c)) - { - number += stringValue[i]; - } - - if (c == ',' || c == '.') - { - number += culture.NumberFormat.NumberDecimalSeparator; - } - } - - TemperatureUnit unit = TemperatureUnit.Kelvin; - - if (stringValue.ToUpper().Contains("K")) - { - unit = TemperatureUnit.Kelvin; - } - else if (stringValue.ToUpper().Contains("F")) - { - unit = TemperatureUnit.Fahrenheit; - } - else if (stringValue.ToUpper().Contains("C")) - { - unit = TemperatureUnit.Celsius; - } - else - { - PropertyGridItem item = context as PropertyGridItem; - - if (item != null) - { - Temperature oldTemp = item.Value as Temperature; - - if (oldTemp != null) - { - unit = oldTemp.Unit; - } - } - } - - return new Temperature() { Value = double.Parse(number), Unit = unit }; - } -} - -```` -````VB.NET -Public Class TemperatureTypeConverter - Inherits ExpandableObjectConverter - Public Overrides Function CanConvertFrom(context As ITypeDescriptorContext, sourceType As Type) As Boolean - If sourceType = GetType(String) Then - Return True - End If - Return MyBase.CanConvertFrom(context, sourceType) - End Function - Public Overrides Function CanConvertTo(context As ITypeDescriptorContext, destinationType As Type) As Boolean - If destinationType = GetType(String) Then - Return True - End If - Return MyBase.CanConvertTo(context, destinationType) - End Function - Public Overrides Function ConvertTo(context As ITypeDescriptorContext, culture As System.Globalization.CultureInfo, value As Object, destinationType As Type) As Object - If destinationType <> GetType(String) Then - Return MyBase.ConvertTo(context, culture, value, destinationType) - End If - Dim temp As Temperature = TryCast(value, Temperature) - If temp Is Nothing Then - Return String.Empty - End If - Return String.Format("{0} {1}", temp.Value, temp.Unit.ToString().Substring(0, 1)) - End Function - Public Overrides Function ConvertFrom(context As ITypeDescriptorContext, culture As System.Globalization.CultureInfo, value As Object) As Object - Dim stringValue As String = TryCast(value, String) - If stringValue Is Nothing Then - Return MyBase.ConvertFrom(context, culture, value) - End If - Dim number As String = "" - For i As Integer = 0 To stringValue.Length - 1 - Dim c As Char = stringValue(i) - If Char.IsNumber(c) Then - number += stringValue(i) - End If - If c = ","c OrElse c = "."c Then - number += culture.NumberFormat.NumberDecimalSeparator - End If - Next - Dim unit As TemperatureUnit = TemperatureUnit.Kelvin - If stringValue.ToUpper().Contains("K") Then - unit = TemperatureUnit.Kelvin - ElseIf stringValue.ToUpper().Contains("F") Then - unit = TemperatureUnit.Fahrenheit - ElseIf stringValue.ToUpper().Contains("C") Then - unit = TemperatureUnit.Celsius - Else - Dim item As PropertyGridItem = TryCast(context, PropertyGridItem) - If item IsNot Nothing Then - Dim oldTemp As Temperature = TryCast(item.Value, Temperature) - If oldTemp IsNot Nothing Then - unit = oldTemp.Unit - End If - End If - End If - Return New Temperature() With { _ - .Value = Double.Parse(number), _ - .Unit = unit _ - } - End Function -End Class - -```` - -{{endregion}} + + + + Apply a __TypeConverterAttribute__ that indicates the type of your type converter. The result is illustrated on the screenshot below: #### BodyTemperature Property -{{source=..\SamplesCS\PropertyGrid\PropertyGridTypeConverters.cs region=ApplyTemparatureAttribute}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridTypeConverters.vb region=ApplyTemparatureAttribute}} - -````C# - -[Description("This is a property with a TypeConverter (TemperatureTypeConverter) set to the class defining the type of the property." + - "The converter allows the property to be expanded and individual properties of the class to be edited. " + - "Additionally the convert allows users to input temperature as string in Kelvin, Celsius and Fahrenheit.")] -[TypeConverter(typeof(TemperatureTypeConverter))] -public Temperature BodyTemperature { get; set; } - -```` -````VB.NET - _ - _ -Public Property BodyTemperature() As Temperature - Get - Return m_BodyTemperature - End Get - Set(value As Temperature) - m_BodyTemperature = value - End Set -End Property -Private m_BodyTemperature As Temperature - -```` - -{{endregion}} + + + + >caption Figure 2: RadPropertyGrid TypeConverterAttribute @@ -398,79 +69,19 @@ The __BloodType__ property is a string property which allows entering any string #### BloodTypeConverter -{{source=..\SamplesCS\PropertyGrid\PropertyGridTypeConverters.cs region=BloodTypeConverter}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridTypeConverters.vb region=BloodTypeConverter}} - -````C# - -public class BloodTypeConverter : TypeConverter -{ - public override bool GetStandardValuesSupported(ITypeDescriptorContext context) - { - return true; - } - - public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) - { - return true; - } - - public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) - { - return new StandardValuesCollection(new string[] { "O−", "O+", "A−", "A+", "B−", "B+", "AB−", "AB+" }); - } -} - -```` -````VB.NET -Public Class BloodTypeConverter - Inherits TypeConverter - Public Overrides Function GetStandardValuesSupported(context As ITypeDescriptorContext) As Boolean - Return True - End Function - Public Overrides Function GetStandardValuesExclusive(context As ITypeDescriptorContext) As Boolean - Return True - End Function - Public Overrides Function GetStandardValues(context As ITypeDescriptorContext) As StandardValuesCollection - Return New StandardValuesCollection(New String() {"O−", "O+", "A−", "A+", "B−", "B+", _ - "AB−", "AB+"}) - End Function -End Class - -```` - -{{endregion}} + + + + After applying the __TypeConverterAttribute__, when you try to modify the __BloodType__ property __RadPropertyGrid__ will display a drop down list editor with the predefined set of values: #### BloodType Property -{{source=..\SamplesCS\PropertyGrid\PropertyGridTypeConverters.cs region=ApplyBloodTypeAttribute}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridTypeConverters.vb region=ApplyBloodTypeAttribute}} - -````C# - -[TypeConverter(typeof(BloodTypeConverter)), -Description("This is a string property which has a standard values collection defined in its TypeConverter (BloodTypeConverter)." + - " The property grid uses this collection to build a list and provide it to the user for selection.")] -public string BloodType { get; set; } - -```` -````VB.NET - _ -Public Property BloodType() As String - Get - Return m_BloodType - End Get - Set(value As String) - m_BloodType = value - End Set -End Property -Private m_BloodType As String - -```` - -{{endregion}} + + + + >caption Figure 3: BloodTypeConverter @@ -482,165 +93,19 @@ This example demonstrates how to apply a culture aware __TypeConverter__ to the #### VolumeTypeConverter -{{source=..\SamplesCS\PropertyGrid\PropertyGridTypeConverters.cs region=VolumeTypeConverter}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridTypeConverters.vb region=VolumeTypeConverter}} - -````C# - -public class VolumeTypeConverter : TypeConverter -{ - private const double CubicInchesToCubicCentimeters = 16.387064d; - private const double CubicCentimetersToCubicInches = 0.0610237441d; - - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) - { - if (sourceType == typeof(string)) - { - return true; - } - - return base.CanConvertFrom(context, sourceType); - } - - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) - { - if (destinationType == typeof(string)) - { - return true; - } - - return base.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) - { - if (!(value is string)) - { - return base.ConvertFrom(context, culture, value); - } - - string val = (string)value; - - string measure = val.Substring(val.Length - 2, 2).ToLower(); - string dispValue = val.Substring(0, val.Length - 2); - double disp = double.Parse(dispValue); - - if (measure.ToLower() == "cc") - { - return disp; - } - else - { - return disp * CubicInchesToCubicCentimeters; - } - } - - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) - { - if (!(destinationType == typeof(string))) - { - return base.ConvertTo(context, culture, value, destinationType); - } - - RegionInfo regionInfo = new RegionInfo(culture.LCID); - bool metric = regionInfo.IsMetric; - - if (metric) - { - return string.Format("{0:F0}cc", value); - } - else - { - double cubicInches = (double)value * CubicCentimetersToCubicInches; - - return string.Format("{0:F0}ci", cubicInches); - } - } -} - -```` -````VB.NET -Public Class VolumeTypeConverter - Inherits TypeConverter - Private Const CubicInchesToCubicCentimeters As Double = 16.387064 - Private Const CubicCentimetersToCubicInches As Double = 0.0610237441 - Public Overrides Function CanConvertFrom(context As ITypeDescriptorContext, sourceType As Type) As Boolean - If sourceType = GetType(String) Then - Return True - End If - Return MyBase.CanConvertFrom(context, sourceType) - End Function - Public Overrides Function CanConvertTo(context As ITypeDescriptorContext, destinationType As Type) As Boolean - If destinationType = GetType(String) Then - Return True - End If - Return MyBase.CanConvertTo(context, destinationType) - End Function - Public Overrides Function ConvertFrom(context As ITypeDescriptorContext, culture As CultureInfo, value As Object) As Object - If Not (TypeOf value Is String) Then - Return MyBase.ConvertFrom(context, culture, value) - End If - Dim val As String = DirectCast(value, String) - Dim measure As String = val.Substring(val.Length - 2, 2).ToLower() - Dim dispValue As String = val.Substring(0, val.Length - 2) - Dim disp As Double = Double.Parse(dispValue) - If measure.ToLower() = "cc" Then - Return disp - Else - Return disp * CubicInchesToCubicCentimeters - End If - End Function - Public Overrides Function ConvertTo(context As ITypeDescriptorContext, culture As CultureInfo, value As Object, destinationType As Type) As Object - If Not (destinationType = GetType(String)) Then - Return MyBase.ConvertTo(context, culture, value, destinationType) - End If - Dim regionInfo As New RegionInfo(culture.LCID) - Dim metric As Boolean = regionInfo.IsMetric - If metric Then - Return String.Format("{0:F0}cc", value) - Else - Dim cubicInches As Double = CDbl(value) * CubicCentimetersToCubicInches - Return String.Format("{0:F0}ci", cubicInches) - End If - End Function -End Class - -```` - -{{endregion}} + + + + Do not forget to apply the __TypeConverterAttribute__. Additionally, we will specify the editor to be __PropertyGridTextBoxEditor__. #### ApplyVolumeTypeAttribute -{{source=..\SamplesCS\PropertyGrid\PropertyGridTypeConverters.cs region=ApplyVolumeTypeAttribute}} -{{source=..\SamplesVB\PropertyGrid\PropertyGridTypeConverters.vb region=ApplyVolumeTypeAttribute}} - -````C# - -[TypeConverter(typeof(VolumeTypeConverter)), -Editor(typeof(PropertyGridTextBoxEditor), typeof(BaseInputEditor)), -Description("This property has a culture aware TypeConverter (VolumeTypeConverter) which can convert input from Cubic Inches and" + - "Cubic Centimeters but when converting data for display it uses the current culture to determine" + - "which system of measurement to use (Imperial or Metric). Values is stored in Cubic Centimeters")] -public double TotalLungCapacity { get; set; } - -```` -````VB.NET - _ -Public Property TotalLungCapacity() As Double - Get - Return m_TotalLungCapacity - End Get - Set(value As Double) - m_TotalLungCapacity = value - End Set -End Property -Private m_TotalLungCapacity As Double - -```` - -{{endregion}} + + + + >caption Figure 4: TotalLungCapacity Property diff --git a/controls/rangeselector/customizing-radrangeselector.md b/controls/rangeselector/customizing-radrangeselector.md index 7056fb03e..4267e0de2 100644 --- a/controls/rangeselector/customizing-radrangeselector.md +++ b/controls/rangeselector/customizing-radrangeselector.md @@ -17,63 +17,19 @@ Each of the control's elements can be accessed and customized. Once you access t The following code snippet demonstrates how to access and customize the Range and Hover elements through element tree: -{{source=..\SamplesCS\RangeSelector\CustomizingRadRangeSelector.cs region=CustomizeHover}} -{{source=..\SamplesVB\RangeSelector\CustomizingRadRangeSelector.vb region=CustomizeHover}} - -````C# -this.radRangeSelector1.RangeSelectorElement.BodyElement.ViewContainer.TrackingElement.LeftHover.BackColor = Color.Yellow; -this.radRangeSelector1.RangeSelectorElement.BodyElement.ViewContainer.TrackingElement.LeftHover.GradientStyle = Telerik.WinControls.GradientStyles.Solid; -this.radRangeSelector1.RangeSelectorElement.BodyElement.ViewContainer.TrackingElement.LeftHover.Opacity = 0.5; -this.radRangeSelector1.RangeSelectorElement.BodyElement.ViewContainer.TrackingElement.RightHover.Opacity = 0.5; -this.radRangeSelector1.RangeSelectorElement.BodyElement.ViewContainer.TrackingElement.RightHover.BackColor = Color.Yellow; -this.radRangeSelector1.RangeSelectorElement.BodyElement.ViewContainer.TrackingElement.RightHover.GradientStyle = Telerik.WinControls.GradientStyles.Solid; -this.radRangeSelector1.RangeSelectorElement.BodyElement.ViewContainer.TrackingElement.Range.Opacity = 0.5; -this.radRangeSelector1.RangeSelectorElement.BodyElement.ViewContainer.TrackingElement.Range.BackColor = Color.Red; -this.radRangeSelector1.RangeSelectorElement.BodyElement.ViewContainer.TrackingElement.Range.GradientStyle = Telerik.WinControls.GradientStyles.Solid; - -```` -````VB.NET -Me.radRangeSelector1.RangeSelectorElement.BodyElement.ViewContainer.TrackingElement.LeftHover.BackColor = Color.Yellow -Me.radRangeSelector1.RangeSelectorElement.BodyElement.ViewContainer.TrackingElement.LeftHover.GradientStyle = Telerik.WinControls.GradientStyles.Solid -Me.radRangeSelector1.RangeSelectorElement.BodyElement.ViewContainer.TrackingElement.LeftHover.Opacity = 0.5 -Me.radRangeSelector1.RangeSelectorElement.BodyElement.ViewContainer.TrackingElement.RightHover.Opacity = 0.5 -Me.radRangeSelector1.RangeSelectorElement.BodyElement.ViewContainer.TrackingElement.RightHover.BackColor = Color.Yellow -Me.radRangeSelector1.RangeSelectorElement.BodyElement.ViewContainer.TrackingElement.RightHover.GradientStyle = Telerik.WinControls.GradientStyles.Solid -Me.radRangeSelector1.RangeSelectorElement.BodyElement.ViewContainer.TrackingElement.Range.Opacity = 0.5 -Me.radRangeSelector1.RangeSelectorElement.BodyElement.ViewContainer.TrackingElement.Range.BackColor = Color.Red -Me.radRangeSelector1.RangeSelectorElement.BodyElement.ViewContainer.TrackingElement.Range.GradientStyle = Telerik.WinControls.GradientStyles.Solid - -```` - -{{endregion}} + + -![WinForms RadRangeSelector Customize Hover Elements](images/rangeselector-customizing001.png) -## Customize Thumbs -{{source=..\SamplesCS\RangeSelector\CustomizingRadRangeSelector.cs region=CustomizeThumb}} -{{source=..\SamplesVB\RangeSelector\CustomizingRadRangeSelector.vb region=CustomizeThumb}} +![WinForms RadRangeSelector Customize Hover Elements](images/rangeselector-customizing001.png) -````C# -this.radRangeSelector1.RangeSelectorElement.BodyElement.ViewContainer.TrackingElement.LeftThumb.BackColor = Color.Green; -this.radRangeSelector1.RangeSelectorElement.BodyElement.ViewContainer.TrackingElement.LeftThumb.GradientStyle = Telerik.WinControls.GradientStyles.Solid; -this.radRangeSelector1.RangeSelectorElement.BodyElement.ViewContainer.TrackingElement.RightThumb.BackColor = Color.Green; -this.radRangeSelector1.RangeSelectorElement.BodyElement.ViewContainer.TrackingElement.RightThumb.GradientStyle = Telerik.WinControls.GradientStyles.Solid; -this.radRangeSelector1.RangeSelectorElement.BodyElement.ViewContainer.TrackingElement.LeftThumbLine.BackColor = Color.Green; -this.radRangeSelector1.RangeSelectorElement.BodyElement.ViewContainer.TrackingElement.RightThumbLine.BackColor = Color.Green; +## Customize Thumbs -```` -````VB.NET -Me.radRangeSelector1.RangeSelectorElement.BodyElement.ViewContainer.TrackingElement.LeftThumb.BackColor = Color.Green -Me.radRangeSelector1.RangeSelectorElement.BodyElement.ViewContainer.TrackingElement.LeftThumb.GradientStyle = Telerik.WinControls.GradientStyles.Solid -Me.radRangeSelector1.RangeSelectorElement.BodyElement.ViewContainer.TrackingElement.RightThumb.BackColor = Color.Green -Me.radRangeSelector1.RangeSelectorElement.BodyElement.ViewContainer.TrackingElement.RightThumb.GradientStyle = Telerik.WinControls.GradientStyles.Solid -Me.radRangeSelector1.RangeSelectorElement.BodyElement.ViewContainer.TrackingElement.LeftThumbLine.BackColor = Color.Green -Me.radRangeSelector1.RangeSelectorElement.BodyElement.ViewContainer.TrackingElement.RightThumbLine.BackColor = Color.Green + + -```` -{{endregion}} ![WinForms RadRangeSelector Customize Thumbs](images/rangeselector-customizing002.png) @@ -81,31 +37,10 @@ Me.radRangeSelector1.RangeSelectorElement.BodyElement.ViewContainer.TrackingElem This scroll element appears only when associated element implements IRangeSelectorElement interface. -{{source=..\SamplesCS\RangeSelector\CustomizingRadRangeSelector.cs region=CustomizeScroll}} -{{source=..\SamplesVB\RangeSelector\CustomizingRadRangeSelector.vb region=CustomizeScroll}} - -````C# -this.radRangeSelector1.RangeSelectorElement.ScrollSelectorElement.LeftTopThumb.BackColor = Color.Green; -this.radRangeSelector1.RangeSelectorElement.ScrollSelectorElement.LeftTopThumb.GradientStyle = Telerik.WinControls.GradientStyles.Solid; -this.radRangeSelector1.RangeSelectorElement.ScrollSelectorElement.BottomRightThumb.BackColor = Color.Green; -this.radRangeSelector1.RangeSelectorElement.ScrollSelectorElement.BottomRightThumb.GradientStyle = Telerik.WinControls.GradientStyles.Solid; -this.radRangeSelector1.RangeSelectorElement.ScrollSelectorElement.Range.BackColor = Color.Green; -this.radRangeSelector1.RangeSelectorElement.ScrollSelectorElement.Range.GradientStyle = Telerik.WinControls.GradientStyles.Solid; -this.radRangeSelector1.RangeSelectorElement.ScrollSelectorElement.SellectionRange.BackColor = Color.Red; - -```` -````VB.NET -Me.radRangeSelector1.RangeSelectorElement.ScrollSelectorElement.LeftTopThumb.BackColor = Color.Green -Me.radRangeSelector1.RangeSelectorElement.ScrollSelectorElement.LeftTopThumb.GradientStyle = Telerik.WinControls.GradientStyles.Solid -Me.radRangeSelector1.RangeSelectorElement.ScrollSelectorElement.BottomRightThumb.BackColor = Color.Green -Me.radRangeSelector1.RangeSelectorElement.ScrollSelectorElement.BottomRightThumb.GradientStyle = Telerik.WinControls.GradientStyles.Solid -Me.radRangeSelector1.RangeSelectorElement.ScrollSelectorElement.Range.BackColor = Color.Green -Me.radRangeSelector1.RangeSelectorElement.ScrollSelectorElement.Range.GradientStyle = Telerik.WinControls.GradientStyles.Solid -Me.radRangeSelector1.RangeSelectorElement.ScrollSelectorElement.SellectionRange.BackColor = Color.Red + + -```` -{{endregion}} ![WinForms RadRangeSelector Customize Scroll Event](images/rangeselector-customizing003.png) @@ -113,48 +48,15 @@ Me.radRangeSelector1.RangeSelectorElement.ScrollSelectorElement.SellectionRange. The scales are created dynamically according to the associated element and its look and feel can be customized through the __ScaleInitializing__ event. -{{source=..\SamplesCS\RangeSelector\CustomizingRadRangeSelector.cs region=CustomizeScales}} -{{source=..\SamplesVB\RangeSelector\CustomizingRadRangeSelector.vb region=CustomizeScales}} -````C# -this.radRangeSelector1.ScaleInitializing += new ScaleInitializingEventHandler(radRangeSelector1_ScaleInitializing); - -```` -````VB.NET -AddHandler Me.radRangeSelector1.ScaleInitializing, AddressOf radRangeSelector1_ScaleInitializing - -```` - - - -{{endregion}} + + -{{source=..\SamplesCS\RangeSelector\CustomizingRadRangeSelector.cs region=CustomizeScales1}} -{{source=..\SamplesVB\RangeSelector\CustomizingRadRangeSelector.vb region=CustomizeScales1}} -````C# -void radRangeSelector1_ScaleInitializing(object sender, ScaleInitializingEventArgs e) -{ - e.ScaleElement.BackColor = Color.Blue; - e.ScaleElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid; - e.ScaleElement.ForeColor = Color.White; - e.ScaleElement.ScalePostion = ViewPosition.TopLeft; -} + + -```` -````VB.NET -Private Sub radRangeSelector1_ScaleInitializing(sender As Object, e As ScaleInitializingEventArgs) - e.ScaleElement.BackColor = Color.Blue - e.ScaleElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid - e.ScaleElement.ForeColor = Color.White - e.ScaleElement.ScalePostion = ViewPosition.TopLeft -End Sub -```` - - - -{{endregion}} ![WinForms RadRangeSelector Customize Scales](images/rangeselector-customizing004.png) @@ -162,46 +64,15 @@ End Sub In order to customize the chart that is drawn into __RadRangeSelector__ when it is associated with __RadChartView__, the associated element should be accessed. The following code snippet demonstrates how this can be achieved. -{{source=..\SamplesCS\RangeSelector\CustomizingRadRangeSelector.cs region=CustomizeChartElement}} -{{source=..\SamplesVB\RangeSelector\CustomizingRadRangeSelector.vb region=CustomizeChartElement}} -````C# -RangeSelectorViewElement chartElement = this.radRangeSelector1.RangeSelectorElement.AssociatedElement as RangeSelectorViewElement; -chartElement.SeriesInitialized += new SeriesInitializedEventHandler(chartElement_SeriesInitialized); - -```` -````VB.NET -Dim chartElement As RangeSelectorViewElement = TryCast(Me.radRangeSelector1.RangeSelectorElement.AssociatedElement, RangeSelectorViewElement) -AddHandler chartElement.SeriesInitialized, AddressOf chartElement_SeriesInitialized - -```` - - - -{{endregion}} - - - -{{source=..\SamplesCS\RangeSelector\CustomizingRadRangeSelector.cs region=CustomizeChartElement1}} -{{source=..\SamplesVB\RangeSelector\CustomizingRadRangeSelector.vb region=CustomizeChartElement1}} -````C# -void chartElement_SeriesInitialized(object sender, SeriesInitializedEventArgs e) -{ - e.Series.BackColor = Color.Lime; - e.Series.BorderColor = Color.Red; -} + + -```` -````VB.NET -Private Sub chartElement_SeriesInitialized(sender As Object, e As SeriesInitializedEventArgs) - e.Series.BackColor = Color.Lime - e.Series.BorderColor = Color.Red -End Sub -```` + + -{{endregion}} ![WinForms RadRangeSelector Customize ChartElement](images/rangeselector-customizing005.png) diff --git a/controls/rangeselector/getting-started.md b/controls/rangeselector/getting-started.md index 6574660ea..420bf526f 100644 --- a/controls/rangeselector/getting-started.md +++ b/controls/rangeselector/getting-started.md @@ -44,19 +44,10 @@ This tutorial demonstrates how to use __RadRangeSelector__ to get a fine grain v * Set in code: -{{source=..\SamplesCS\RangeSelector\RangeSelectorGettingStarted.cs region=set associatedControl}} -{{source=..\SamplesVB\RangeSelector\RangeSelectorGettingStarted.vb region=set associatedControl}} + + -````C# -this.radRangeSelector1.AssociatedControl = this.radChartView1; -```` -````VB.NET -Me.radRangeSelector1.AssociatedControl = Me.radChartView1 - -```` - -{{endregion}} * Set in Property Builder at design time: diff --git a/controls/rangeselector/integration-with-radchartview.md b/controls/rangeselector/integration-with-radchartview.md index 16fe5a8c8..945c1da5d 100644 --- a/controls/rangeselector/integration-with-radchartview.md +++ b/controls/rangeselector/integration-with-radchartview.md @@ -24,42 +24,17 @@ Here is how to access the __RangeSelectorViewElement__ and change the series typ #### SeriesInitializing Event -{{source=..\SamplesCS\RangeSelector\RangeSelectorIntegrationWithChart.cs region=ScaleCustomization1}} -{{source=..\SamplesVB\RangeSelector\RangeSelectorIntegrationWithChart.vb region=ScaleCustomization1}} + + -````C# -RangeSelectorViewElement chartElement = this.radRangeSelector1.RangeSelectorElement.AssociatedElement as RangeSelectorViewElement; -chartElement.SeriesInitializing += new SeriesInitializingEventHandler(chartElement_SeriesInitializing); -```` -````VB.NET -Dim chartElement As RangeSelectorViewElement = TryCast(Me.radRangeSelector1.RangeSelectorElement.AssociatedElement, RangeSelectorViewElement) -AddHandler chartElement.SeriesInitializing, AddressOf chartElement_SeriesInitializing - -```` - -{{endregion}} #### Change Series Type -{{source=..\SamplesCS\RangeSelector\RangeSelectorIntegrationWithChart.cs region=ScaleCustomization2}} -{{source=..\SamplesVB\RangeSelector\RangeSelectorIntegrationWithChart.vb region=ScaleCustomization2}} - -````C# -void chartElement_SeriesInitializing(object sender, SeriesInitializingEventArgs e) -{ - e.SeriesType = typeof(BarSeries); -} + + -```` -````VB.NET -Private Sub chartElement_SeriesInitializing(sender As Object, e As SeriesInitializingEventArgs) - e.SeriesType = GetType(BarSeries) -End Sub -```` - -{{endregion}} >caption Figure 1: BarSeries ![WinForms RadRangeSelector BarSeries](images/rangeselector-integration-with-chartview001.png) @@ -72,58 +47,17 @@ Here is how to access and modify the labels in RadRangeSelector #### LabelInitializing Event -{{source=..\SamplesCS\RangeSelector\RangeSelectorIntegrationWithChart.cs region=LabelCustomization}} -{{source=..\SamplesVB\RangeSelector\RangeSelectorIntegrationWithChart.vb region=LabelCustomization}} + + -````C# -RangeSelectorViewElement chartElement = this.radRangeSelector1.RangeSelectorElement.AssociatedElement as RangeSelectorViewElement; -chartElement.LabelInitializing += new LabelInitializingEventHandler(chartElement_LabelInitializing); -```` -````VB.NET -Dim chartElement As RangeSelectorViewElement = TryCast(Me.radRangeSelector1.RangeSelectorElement.AssociatedElement, RangeSelectorViewElement) -AddHandler chartElement.LabelInitializing, AddressOf chartElement_LabelInitializing -```` +#### Change Labels -{{endregion}} + + -#### Change Labels -{{source=..\SamplesCS\RangeSelector\RangeSelectorIntegrationWithChart.cs region=LabelCustomization1}} -{{source=..\SamplesVB\RangeSelector\RangeSelectorIntegrationWithChart.vb region=LabelCustomization1}} - -````C# -Font f = new Font("Arial", 22); -void chartElement_LabelInitializing(object sender, LabelInitializingEventArgs e) -{ - e.LabelElement.Font = f; - if (e.LabelElement.Text == "C") - { - e.LabelElement.ForeColor = Color.Blue; - } - if (e.LabelElement.Text == "A") - { - e.LabelElement.ForeColor = Color.Red; - } -} - -```` -````VB.NET -Private f As New Font("Arial", 22) -Private Sub chartElement_LabelInitializing(sender As Object, e As LabelInitializingEventArgs) - e.LabelElement.Font = f - If e.LabelElement.Text = "C" Then - e.LabelElement.ForeColor = Color.Blue - End If - If e.LabelElement.Text = "A" Then - e.LabelElement.ForeColor = Color.Red - End If -End Sub - -```` - -{{endregion}} >caption Figure 2: Changed Chart Labels ![WinForms RadRangeSelector Changed Chart Labels](images/rangeselector-integration-with-chartview002.png) @@ -138,44 +72,17 @@ The easiest way to access these properties is in the __ScaleInitializing__ event #### ScaleInitializing Event -{{source=..\SamplesCS\RangeSelector\RangeSelectorIntegrationWithChart.cs region=LabelCustomization2}} -{{source=..\SamplesVB\RangeSelector\RangeSelectorIntegrationWithChart.vb region=LabelCustomization2}} + + -````C# -this.radRangeSelector1.ScaleInitializing += new ScaleInitializingEventHandler(radRangeSelector1_ScaleInitializing); -```` -````VB.NET -AddHandler Me.radRangeSelector1.ScaleInitializing, AddressOf radRangeSelector1_ScaleInitializing - -```` - -{{endregion}} #### Label Settings -{{source=..\SamplesCS\RangeSelector\RangeSelectorIntegrationWithChart.cs region=LabelCustomization3}} -{{source=..\SamplesVB\RangeSelector\RangeSelectorIntegrationWithChart.vb region=LabelCustomization3}} - -````C# -void radRangeSelector1_ScaleInitializing(object sender, ScaleInitializingEventArgs e) -{ - RangeSelectorChartScaleContainerElement chartScaleElement = e.ScaleElement as RangeSelectorChartScaleContainerElement; - chartScaleElement.LabelsOffset = 0; - chartScaleElement.ShowAllLabels = false; -} + + -```` -````VB.NET -Private Sub radRangeSelector1_ScaleInitializing(sender As Object, e As ScaleInitializingEventArgs) - Dim chartScaleElement As RangeSelectorChartScaleContainerElement = TryCast(e.ScaleElement, RangeSelectorChartScaleContainerElement) - chartScaleElement.LabelsOffset = 0 - chartScaleElement.ShowAllLabels = False -End Sub -```` - -{{endregion}} ## Pan and Zoom Synchronization @@ -183,19 +90,10 @@ There is two-way synchronization between the pan and zoom functionality of RadCh #### Disable Pan and Zoom Synchronization -{{source=..\SamplesCS\RangeSelector\RangeSelectorIntegrationWithChart.cs region=EnablePanAndZoomSynchronization}} -{{source=..\SamplesVB\RangeSelector\RangeSelectorIntegrationWithChart.vb region=EnablePanAndZoomSynchronization}} - -````C# -((RangeSelectorViewElement)this.radRangeSelector1.RangeSelectorElement.AssociatedElement).EnablePanAndZoomSynchronization = false; - -```` -````VB.NET -DirectCast(Me.radRangeSelector1.RangeSelectorElement.AssociatedElement, RangeSelectorViewElement).EnablePanAndZoomSynchronization = False + + -```` -{{endregion}} ## See Also diff --git a/controls/rangeselector/properties-and-events.md b/controls/rangeselector/properties-and-events.md index d6c2abdb4..a08d7399b 100644 --- a/controls/rangeselector/properties-and-events.md +++ b/controls/rangeselector/properties-and-events.md @@ -24,117 +24,56 @@ Here are the most important properties for changing the control appearance and b #### UpdateMode.Immediate -{{source=..\SamplesCS\RangeSelector\RangeSelectorPropertiesAndEvents.cs region=UpdateModeImmediate}} -{{source=..\SamplesVB\RangeSelector\RangeSelectorPropertiesAndEvents.vb region=UpdateModeImmediate}} -````C# -this.radRangeSelector1.UpdateMode = UpdateMode.Deferred; + + -```` -````VB.NET -Me.radRangeSelector1.UpdateMode = UpdateMode.Deferred -```` - - - -{{endregion}} >caption Figure 2: UpdateMode.Deferred ![WinForms RadRangeSelector UpdateMode Deferred](images/rangeselector-properties-and-events002.gif) #### UpdateMode.Defferred -{{source=..\SamplesCS\RangeSelector\RangeSelectorPropertiesAndEvents.cs region=UpdateModeDeferred}} -{{source=..\SamplesVB\RangeSelector\RangeSelectorPropertiesAndEvents.vb region=UpdateModeDeferred}} -````C# -this.radRangeSelector1.UpdateMode = UpdateMode.Deferred; - -```` -````VB.NET -Me.radRangeSelector1.UpdateMode = UpdateMode.Deferred - -```` - + + -{{endregion}} - * The __StartRange__ and __EndRange__ properties specify the range area. The values of these properties are from type double and should between 0 and 100. #### Start and End Range -{{source=..\SamplesCS\RangeSelector\RangeSelectorPropertiesAndEvents.cs region=StartEnd}} -{{source=..\SamplesVB\RangeSelector\RangeSelectorPropertiesAndEvents.vb region=StartEnd}} - -````C# -this.radRangeSelector1.StartRange = 20; -this.radRangeSelector1.EndRange = 50; - -```` -````VB.NET -Me.radRangeSelector1.StartRange = 20 -Me.radRangeSelector1.EndRange = 50 + + -```` -{{endregion}} * The __RangeSelectorViewZoomStart__ and __RangeSelectorViewZoomEnd__ define the start and end zoom factor of __RadRangeSelector__. These zoom is in percentages and can be controlled from track bar at the bottom of control. You can use these properties __only__ if associated element implements the __IRangeSelectorElement__ interface. The values of these properties are of type double and should between 0 and 100. #### Zoom Start and End -{{source=..\SamplesCS\RangeSelector\RangeSelectorPropertiesAndEvents.cs region=StartZoomEndZoom}} -{{source=..\SamplesVB\RangeSelector\RangeSelectorPropertiesAndEvents.vb region=StartZoomEndZoom}} - -````C# -this.radRangeSelector1.RangeSelectorViewZoomStart = 20; -this.radRangeSelector1.RangeSelectorViewZoomEnd = 50; - -```` -````VB.NET -Me.radRangeSelector1.RangeSelectorViewZoomStart = 20 -Me.radRangeSelector1.RangeSelectorViewZoomEnd = 50 + + -```` -{{endregion}} * The __ShowButtons__ property controls the visibility of the navigation buttons in RadRangeSelector. By default these buttons are displayed. To hide them, set the property to false. #### ShowButtons Property -{{source=..\SamplesCS\RangeSelector\RangeSelectorPropertiesAndEvents.cs region=hideButtons}} -{{source=..\SamplesVB\RangeSelector\RangeSelectorPropertiesAndEvents.vb region=hideButtons}} + + -````C# -this.radRangeSelector1.ShowButtons = false; -```` -````VB.NET -Me.radRangeSelector1.ShowButtons = False - -```` - -{{endregion}} * The __AssociatedControl__ is the most important property of __RadRangeSeletor__. This property establishes the connection between the __RadRangeSelector__ and the associated control. This property can accept every object that inherits __RadControl__ except __RadRangeSelector__. #### Associated Control -{{source=..\SamplesCS\RangeSelector\RangeSelectorGettingStarted.cs region=set associatedControl}} -{{source=..\SamplesVB\RangeSelector\RangeSelectorGettingStarted.vb region=set associatedControl}} - -````C# -this.radRangeSelector1.AssociatedControl = this.radChartView1; + + -```` -````VB.NET -Me.radRangeSelector1.AssociatedControl = Me.radChartView1 -```` - -{{endregion}} >note To take all advantages of __RadRangeSelector__ - like scales, track bar and controlling the associated control without any additional implementation, the element of associated control should implement the __IRangeSelectorElement__ interface. By design if the associated control implements the __IRangeSelectorControl__ the returned element should implement the __IRangeSelectorElement__ interface as well. For all controls that not implement the __IRangeSelectorControl__ interface the associated elements will be their RootElement. > @@ -143,19 +82,10 @@ If you want to associate only element without control you can use the following #### Associated Element -{{source=..\SamplesCS\RangeSelector\RangeSelectorPropertiesAndEvents.cs region=set associatedElement}} -{{source=..\SamplesVB\RangeSelector\RangeSelectorPropertiesAndEvents.vb region=set associatedElement}} - -````C# -this.radRangeSelector1.RangeSelectorElement.AssociatedElement = new RangeSelectorViewElement(new RadChartElement()); + + -```` -````VB.NET -Me.radRangeSelector1.RangeSelectorElement.AssociatedElement = New RangeSelectorViewElement(New RadChartElement()) -```` - -{{endregion}} ## Events @@ -177,44 +107,10 @@ There are several events that you will find useful in the context of RadRangeSel #### Initializing Scale -{{source=..\SamplesCS\RangeSelector\RangeSelectorPropertiesAndEvents.cs region=ScaleInitializing}} -{{source=..\SamplesVB\RangeSelector\RangeSelectorPropertiesAndEvents.vb region=ScaleInitializing}} - -````C# -void radRangeSelector1_ScaleInitializing(object sender, ScaleInitializingEventArgs e) -{ - RangeSelectorChartScaleContainerElement scaleElement = e.ScaleElement as RangeSelectorChartScaleContainerElement; - if (scaleElement == null) - { - return; - } - if (scaleElement.Title == "axe1") - { - e.Cancel = true; - } - else - { - scaleElement.ScalePostion = ViewPosition.TopLeft; - } -} - -```` -````VB.NET -Private Sub radRangeSelector1_ScaleInitializing(sender As Object, e As ScaleInitializingEventArgs) - Dim scaleElement As RangeSelectorChartScaleContainerElement = TryCast(e.ScaleElement, RangeSelectorChartScaleContainerElement) - If scaleElement Is Nothing Then - Return - End If - If scaleElement.Title = "axe1" Then - e.Cancel = True - Else - scaleElement.ScalePostion = ViewPosition.TopLeft - End If -End Sub - -```` - -{{endregion}} + + + + ## Custom Rendering @@ -223,63 +119,10 @@ End Sub >caption Figure 3: Custom Rendering ![WinForms RadRangeSelector Custom Rendering](images/rangeselector-properties-and-events003.gif) -{{source=..\SamplesCS\RangeSelector\RadRangeSelectorCustomRenderer.cs region=CustomRendering}} -{{source=..\SamplesVB\RangeSelector\RadRangeSelectorCustomRenderer.vb region=CustomRendering}} -````C# -public RadRangeSelectorCustomRenderer() -{ - InitializeComponent(); - this.radChartView1.CreateRenderer += OnCreateRenderer; - this.radChartView1.ShowPanZoom = true; - LineSeries series = new LineSeries(); - Random rnd = new Random(); - for (int i = 0; i < 30; i++) - { - series.DataPoints.Add(new CategoricalDataPoint(rnd.Next(0, 30), DateTime.Now.AddDays(i))); - } - this.radChartView1.Series.Add(series); - series.VerticalAxis.LabelFormat = "{0}°"; - series.HorizontalAxis.LabelFormat = "{0:M}"; - series.HorizontalAxis.LabelFitMode = AxisLabelFitMode.MultiLine; - this.radChartView1.ShowGrid = true; - this.radRangeSelector1.AssociatedControl = this.radChartView1; - RangeSelectorViewElement chartElement = this.radRangeSelector1.RangeSelectorElement.AssociatedElement as RangeSelectorViewElement; - chartElement.CreateRenderer += OnCreateRenderer; -} -private void OnCreateRenderer(object sender, ChartViewCreateRendererEventArgs e) -{ - e.Renderer = new CustomCartesianRenderer((CartesianArea)e.Area); -} - -```` -````VB.NET -Public Sub New() - InitializeComponent() - AddHandler Me.radChartView1.CreateRenderer, AddressOf OnCreateRenderer - Me.radChartView1.ShowPanZoom = True - Dim series As New LineSeries() - Dim rnd As New Random() - For i As Integer = 0 To 29 - series.DataPoints.Add(New CategoricalDataPoint(rnd.[Next](0, 30), DateTime.Now.AddDays(i))) - Next - Me.radChartView1.Series.Add(series) - series.VerticalAxis.LabelFormat = "{0}°" - series.HorizontalAxis.LabelFormat = "{0:M}" - series.HorizontalAxis.LabelFitMode = AxisLabelFitMode.MultiLine - Me.radChartView1.ShowGrid = True - Me.radRangeSelector1.AssociatedControl = Me.radChartView1 - Dim chartElement As RangeSelectorViewElement = TryCast(Me.radRangeSelector1.RangeSelectorElement.AssociatedElement, RangeSelectorViewElement) - AddHandler chartElement.CreateRenderer, AddressOf OnCreateRenderer -End Sub -Private Sub OnCreateRenderer(sender As Object, e As ChartViewCreateRendererEventArgs) - e.Renderer = New CustomCartesianRenderer(DirectCast(e.Area, CartesianArea)) -End Sub - -```` - - - -{{endregion}} + + + + >note The example above is using the the custom implementation as suggested [here]({%slug winforms/chartview-/customization/custom-rendering%}). diff --git a/controls/ribbonbar/backstage-view/customization.md b/controls/ribbonbar/backstage-view/customization.md index 3c038b188..358fd4d8d 100644 --- a/controls/ribbonbar/backstage-view/customization.md +++ b/controls/ribbonbar/backstage-view/customization.md @@ -35,50 +35,19 @@ Follows code snippet demonstrates how you can access the most used items in the #### Accessing BackstageView elements -{{source=..\SamplesCS\RibbonBar\BackstageView\RibbonBackstageView.cs region=accessElements}} -{{source=..\SamplesVB\RibbonBar\BackstageView\RibbonBackstageView.vb region=accessElements}} + + -````C# -BackstageViewElement backstageViewElemet = radRibbonBarBackstageView1.BackstageElement; - -BackstageItemsPanelElement itemsPanel = backstageViewElemet.ItemsPanelElement; -BackstageContentPanelElement contentPanel = backstageViewElemet.ContentElement; -```` -````VB.NET -Dim backstageViewElemet = CType(RadRibbonBarBackstageView1.BackstageElement, BackstageViewElement) -Dim itemsPanel = CType(backstageViewElemet.ItemsPanelElement, BackstageItemsPanelElement) -Dim contentPanel = CType(backstageViewElemet.ContentElement, BackstageContentPanelElement) - -```` - -{{endregion}} By accessing these elements, you can customize BackstageView. Here is an example on how to change the BackgroundImage of the content area: #### Customizing the content area -{{source=..\SamplesCS\RibbonBar\BackstageView\RibbonBackstageView.cs region=changeContentAreaImage}} -{{source=..\SamplesVB\RibbonBar\BackstageView\RibbonBackstageView.vb region=changeContentAreaImage}} - -````C# -RadImageShape imageShape = new RadImageShape(); -imageShape.Image = Image.FromFile(@"C:\MyFile.png"); -//the next line of code defines how to strech the image (if necessary) -imageShape.Margins = new System.Windows.Forms.Padding(10,10,10,10); -radRibbonBarBackstageView1.BackstageElement.ContentElement.BackgroundShape = imageShape; - -```` -````VB.NET -Dim imageShape As New RadImageShape() -imageShape.Image = Image.FromFile("C:\MyFile.png") -'the next line of code defines how to strech the image (if necessary) -imageShape.Margins = New System.Windows.Forms.Padding(10, 10, 10, 10) -RadRibbonBarBackstageView1.BackstageElement.ContentElement.BackgroundShape = imageShape + + -```` -{{endregion}} >note BackstageTabItems, BackstageItemsPanelElement and BackstageContentPanelElement use[RadImageShape]({%slug winforms/telerik-presentation-framework/primitives/imageshape%})for most of the predefinied themes. > diff --git a/controls/ribbonbar/backstage-view/overview.md b/controls/ribbonbar/backstage-view/overview.md index 35b5fac9f..9ce2e7ae0 100644 --- a/controls/ribbonbar/backstage-view/overview.md +++ b/controls/ribbonbar/backstage-view/overview.md @@ -15,19 +15,10 @@ Backstage View is the Office 2010 replacement of the Application Menu. It is a m #### Enabling Backstage view -{{source=..\SamplesCS\RibbonBar\BackstageView\RibbonBackstageView.cs region=ApplicationMenuStyle}} -{{source=..\SamplesVB\RibbonBar\BackstageView\RibbonBackstageView.vb region=ApplicationMenuStyle}} + + -````C# -radRibbonBar1.ApplicationMenuStyle = Telerik.WinControls.UI.ApplicationMenuStyle.BackstageView; -```` -````VB.NET -RadRibbonBar1.ApplicationMenuStyle = Telerik.WinControls.UI.ApplicationMenuStyle.BackstageView - -```` - -{{endregion}} ![WinForms RadRibbonBar Backstage Overview](images/ribbonbar-backstage-view-overview001.png) diff --git a/controls/ribbonbar/backstage-view/working-with-backstage-view.md b/controls/ribbonbar/backstage-view/working-with-backstage-view.md index 87070978d..0894c4d83 100644 --- a/controls/ribbonbar/backstage-view/working-with-backstage-view.md +++ b/controls/ribbonbar/backstage-view/working-with-backstage-view.md @@ -15,19 +15,10 @@ To enable the Backstage View in __RadRibbonBar__ change the __ApplicationMenuSty #### Enable Backstage View Mode -{{source=..\SamplesCS\RibbonBar\BackstageView\RibbonBackstageView.cs region=ApplicationMenuStyle}} -{{source=..\SamplesVB\RibbonBar\BackstageView\RibbonBackstageView.vb region=ApplicationMenuStyle}} + + -````C# -radRibbonBar1.ApplicationMenuStyle = Telerik.WinControls.UI.ApplicationMenuStyle.BackstageView; -```` -````VB.NET -RadRibbonBar1.ApplicationMenuStyle = Telerik.WinControls.UI.ApplicationMenuStyle.BackstageView - -```` - -{{endregion}} ![WinForms RadRibbonBar Backstage View Mode](images/ribbonbar-backstage-view-working-with-backstage-view001.png) @@ -67,23 +58,10 @@ You can also add these items as well as any other RadItem to the backstageview #### Adding items programatically -{{source=..\SamplesCS\RibbonBar\BackstageView\RibbonBackstageView.cs region=addingItems}} -{{source=..\SamplesVB\RibbonBar\BackstageView\RibbonBackstageView.vb region=addingItems}} - -````C# -radRibbonBarBackstageView1.Items.Add(new BackstageButtonItem("ButtonItem")); -radRibbonBarBackstageView1.Items.Add(new RadButtonElement("ButtonElement")); -radRibbonBarBackstageView1.Items.Add(new RadDropDownListElement()); - -```` -````VB.NET -RadRibbonBarBackstageView1.Items.Add(New BackstageButtonItem("ButtonItem")) -RadRibbonBarBackstageView1.Items.Add(New RadButtonElement("ButtonElement")) -RadRibbonBarBackstageView1.Items.Add(New RadDropDownListElement()) + + -```` -{{endregion}} ## Adding Controls to the Pages diff --git a/controls/ribbonbar/designing-radribbonbar/adding-screen-tips.md b/controls/ribbonbar/designing-radribbonbar/adding-screen-tips.md index 48dad6aed..137ad9c62 100644 --- a/controls/ribbonbar/designing-radribbonbar/adding-screen-tips.md +++ b/controls/ribbonbar/designing-radribbonbar/adding-screen-tips.md @@ -48,67 +48,19 @@ To completely customize the screen tips appearance, its size, text wrapping, etc ## Using ScreenTipNeeded -{{source=..\SamplesCS\RibbonBar\GettingStarted\AddingScreenTips.cs region=addingScreenTips}} -{{source=..\SamplesVB\RibbonBar\GettingStarted\AddingScreenTips.vb region=addingScreenTips}} - -````C# -private void radRibbonBar1_ScreenTipNeeded(object sender, ScreenTipNeededEventArgs e) -{ - RadButtonElement buttonElement = e.Item as RadButtonElement; - if (buttonElement != null && buttonElement.Text == "Button 1") - { - screenTip.CaptionLabel.Text = "Paste (Ctrl + V)"; - screenTip.MainTextLabel.Text = "Add content from the Clipboard to your document"; - buttonElement.ScreenTip = this.screenTip; - } -} - -```` -````VB.NET -Private Sub RadRibbonBar1_ScreenTipNeeded(sender As Object, e As ScreenTipNeededEventArgs) - Dim buttonElement As RadButtonElement = TryCast(e.Item, RadButtonElement) - If buttonElement IsNot Nothing AndAlso buttonElement.Text = "Button 1" Then - screenTip.CaptionLabel.Text = "Paste (Ctrl + V)" - screenTip.MainTextLabel.Text = "Add content from the Clipboard to your document" - buttonElement.ScreenTip = Me.screenTip - End If -End Sub - -```` - -{{endregion}} + + + + The code sample below adds screen tips to two button elements in the __RadRibbonBar__: #### Directly Acess Elements -{{source=..\SamplesCS\RibbonBar\GettingStarted\AddingScreenTips.cs region=addScreenTipsToButtonElements}} -{{source=..\SamplesVB\RibbonBar\GettingStarted\AddingScreenTips.vb region=addScreenTipsToButtonElements}} - -````C# -RadOffice2007ScreenTipElement tip1 = new RadOffice2007ScreenTipElement(); -tip1.CaptionLabel.Text = "Button1"; -tip1.MainTextLabel.Text = "My Text"; -RadOffice2007ScreenTipElement tip2 = new RadOffice2007ScreenTipElement(); -tip2.CaptionLabel.Text = "Button2"; -tip2.MainTextLabel.Text = "My Text"; -this.radButtonElement2.ScreenTip = tip1; -this.radButtonElement3.ScreenTip = tip2; - -```` -````VB.NET -Dim tip1 As New RadOffice2007ScreenTipElement() -tip1.CaptionLabel.Text = "Button1" -tip1.MainTextLabel.Text = "My Text" -Dim tip2 As New RadOffice2007ScreenTipElement() -tip2.CaptionLabel.Text = "Button2" -tip2.MainTextLabel.Text = "My Text" -Me.RadButtonElement2.ScreenTip = tip1 -Me.RadButtonElement3.ScreenTip = tip2 - -```` - -{{endregion}} + + + + ## See Also diff --git a/controls/ribbonbar/designing-radribbonbar/creating-a-gallery.md b/controls/ribbonbar/designing-radribbonbar/creating-a-gallery.md index 6f09c326f..c52782201 100644 --- a/controls/ribbonbar/designing-radribbonbar/creating-a-gallery.md +++ b/controls/ribbonbar/designing-radribbonbar/creating-a-gallery.md @@ -54,46 +54,10 @@ You can add items to the gallery at design-time using the following steps: Alternatively, you can add the items at run-time. Here is a sample snippet: -{{source=..\SamplesCS\RibbonBar\GettingStarted\CreatingAGallery.cs region=snippet1}} -{{source=..\SamplesVB\RibbonBar\GettingStarted\CreatingAGallery.vb region=snippet1}} - -````C# -RadGalleryItem blueItem1 = new RadGalleryItem("", Properties.Resources.RibbonBar_GettingStarted_CreatingAGallery001); -RadGalleryItem blueItem2 = new RadGalleryItem("", Properties.Resources.RibbonBar_GettingStarted_CreatingAGallery002); -RadGalleryItem blueItem3 = new RadGalleryItem("", Properties.Resources.RibbonBar_GettingStarted_CreatingAGallery003); -RadGalleryItem blueItem4 = new RadGalleryItem("", Properties.Resources.RibbonBar_GettingStarted_CreatingAGallery004); -RadGalleryItem purpleItem1 = new RadGalleryItem("", Properties.Resources.RibbonBar_GettingStarted_CreatingAGallery005); -RadGalleryItem purpleItem2 = new RadGalleryItem("", Properties.Resources.RibbonBar_GettingStarted_CreatingAGallery006); -RadGalleryItem purpleItem3 = new RadGalleryItem("", Properties.Resources.RibbonBar_GettingStarted_CreatingAGallery007); -RadGalleryItem purpleItem4 = new RadGalleryItem("", Properties.Resources.RibbonBar_GettingStarted_CreatingAGallery008); -RadGalleryItem greenItem1 = new RadGalleryItem("", Properties.Resources.RibbonBar_GettingStarted_CreatingAGallery009); -RadGalleryItem greenItem2 = new RadGalleryItem("", Properties.Resources.RibbonBar_GettingStarted_CreatingAGallery010); -RadGalleryItem greenItem3 = new RadGalleryItem("", Properties.Resources.RibbonBar_GettingStarted_CreatingAGallery011); -RadGalleryItem greenItem4 = new RadGalleryItem("", Properties.Resources.RibbonBar_GettingStarted_CreatingAGallery012); -this.radGalleryElement1.Items.AddRange( blueItem1, blueItem2, blueItem3, blueItem4, - greenItem1, greenItem2, greenItem3, greenItem4, - purpleItem1, purpleItem2, purpleItem3, purpleItem4); - -```` -````VB.NET -Dim blueItem1 As New RadGalleryItem("", My.Resources.RibbonBar_GettingStarted_CreatingAGallery001) -Dim blueItem2 As New RadGalleryItem("", My.Resources.RibbonBar_GettingStarted_CreatingAGallery002) -Dim blueItem3 As New RadGalleryItem("", My.Resources.RibbonBar_GettingStarted_CreatingAGallery003) -Dim blueItem4 As New RadGalleryItem("", My.Resources.RibbonBar_GettingStarted_CreatingAGallery004) -Dim purpleItem1 As New RadGalleryItem("", My.Resources.RibbonBar_GettingStarted_CreatingAGallery005) -Dim purpleItem2 As New RadGalleryItem("", My.Resources.RibbonBar_GettingStarted_CreatingAGallery006) -Dim purpleItem3 As New RadGalleryItem("", My.Resources.RibbonBar_GettingStarted_CreatingAGallery007) -Dim purpleItem4 As New RadGalleryItem("", My.Resources.RibbonBar_GettingStarted_CreatingAGallery008) -Dim greenItem1 As New RadGalleryItem("", My.Resources.RibbonBar_GettingStarted_CreatingAGallery009) -Dim greenItem2 As New RadGalleryItem("", My.Resources.RibbonBar_GettingStarted_CreatingAGallery010) -Dim greenItem3 As New RadGalleryItem("", My.Resources.RibbonBar_GettingStarted_CreatingAGallery011) -Dim greenItem4 As New RadGalleryItem("", My.Resources.RibbonBar_GettingStarted_CreatingAGallery012) -Me.RadGalleryElement1.Items.AddRange(blueItem1, blueItem2, blueItem3, blueItem4, greenItem1, greenItem2, _ - greenItem3, greenItem4, purpleItem1, purpleItem2, purpleItem3, purpleItem4) - -```` - -{{endregion}} + + + + ## Adding Groups @@ -119,41 +83,10 @@ To add a group at design-time, please follow these steps: Alternatively, you can add the items at run-time. Here is a sample snippet: -{{source=..\SamplesCS\RibbonBar\GettingStarted\CreatingAGallery.cs region=snippet2}} -{{source=..\SamplesVB\RibbonBar\GettingStarted\CreatingAGallery.vb region=snippet2}} - -````C# -RadGalleryGroupItem blueGroup = new RadGalleryGroupItem(); -blueGroup.Text = "Blue Items Group"; -blueGroup.Items.AddRange(blueItem1, blueItem2, blueItem3, blueItem4); -this.radGalleryElement1.Groups.Add(blueGroup); -RadGalleryGroupItem greenGroup = new RadGalleryGroupItem(); -greenGroup.Text = "Green Items Group"; -greenGroup.Items.AddRange(greenItem1, greenItem2, greenItem3, greenItem4); -this.radGalleryElement1.Groups.Add(greenGroup); -RadGalleryGroupItem purpleGroup = new RadGalleryGroupItem(); -purpleGroup.Text = "Purple Items Group"; -purpleGroup.Items.AddRange(purpleItem1, purpleItem2, purpleItem3, purpleItem4); -this.radGalleryElement1.Groups.Add(purpleGroup); - -```` -````VB.NET -Dim blueGroup As New RadGalleryGroupItem() -blueGroup.Text = "Blue Items Group" -blueGroup.Items.AddRange(blueItem1, blueItem2, blueItem3, blueItem4) -Me.RadGalleryElement1.Groups.Add(blueGroup) -Dim greenGroup As New RadGalleryGroupItem() -greenGroup.Text = "Green Items Group" -greenGroup.Items.AddRange(greenItem1, greenItem2, greenItem3, greenItem4) -Me.RadGalleryElement1.Groups.Add(greenGroup) -Dim purpleGroup As New RadGalleryGroupItem() -purpleGroup.Text = "Purple Items Group" -purpleGroup.Items.AddRange(purpleItem1, purpleItem2, purpleItem3, purpleItem4) -Me.RadGalleryElement1.Groups.Add(purpleGroup) - -```` - -{{endregion}} + + + + ## Creating Filters @@ -181,45 +114,10 @@ To create a filter, follow these steps: Alternatively, you can create a filter at run-time. Here is a sample snippet: -{{source=..\SamplesCS\RibbonBar\GettingStarted\CreatingAGallery.cs region=snippet3}} -{{source=..\SamplesVB\RibbonBar\GettingStarted\CreatingAGallery.vb region=snippet3}} - -````C# -RadGalleryGroupFilter all = new RadGalleryGroupFilter(); -all.Text = "All Groups"; -all.Items.AddRange(blueGroup, greenGroup, purpleGroup); -this.radGalleryElement1.Filters.Add(all); -RadGalleryGroupFilter blueGreenFilter = new RadGalleryGroupFilter(); -blueGreenFilter.Text = "Blue and Green Groups"; -blueGreenFilter.Items.Add(blueGroup); -blueGreenFilter.Items.Add(greenGroup); -this.radGalleryElement1.Filters.Add(blueGreenFilter); -RadGalleryGroupFilter greenPurpleFilter = new RadGalleryGroupFilter(); -greenPurpleFilter.Text = "Green and Purple Groups"; -greenPurpleFilter.Items.Add(greenGroup); -greenPurpleFilter.Items.Add(purpleGroup); -this.radGalleryElement1.Filters.Add(greenPurpleFilter); - -```` -````VB.NET -Dim all As New RadGalleryGroupFilter() -all.Text = "All Groups" -all.Items.AddRange(blueGroup, greenGroup, purpleGroup) -Me.RadGalleryElement1.Filters.Add(all) -Dim blueGreenFilter As New RadGalleryGroupFilter() -blueGreenFilter.Text = "Blue and Green Groups" -blueGreenFilter.Items.Add(blueGroup) -blueGreenFilter.Items.Add(greenGroup) -Me.RadGalleryElement1.Filters.Add(blueGreenFilter) -Dim greenPurpleFilter As New RadGalleryGroupFilter() -greenPurpleFilter.Text = "Green and Purple Groups" -greenPurpleFilter.Items.Add(greenGroup) -greenPurpleFilter.Items.Add(purpleGroup) -Me.RadGalleryElement1.Filters.Add(greenPurpleFilter) - -```` - -{{endregion}} + + + + ## Creating Tools @@ -239,21 +137,10 @@ To add a Tool at design-time please follow these steps: You can also create tools at run-time. Here is a sample snippet: -{{source=..\SamplesCS\RibbonBar\GettingStarted\CreatingAGallery.cs region=snippet4}} -{{source=..\SamplesVB\RibbonBar\GettingStarted\CreatingAGallery.vb region=snippet4}} - -````C# -RadMenuButtonItem buttonItem = new RadMenuButtonItem("Click me!"); -this.radGalleryElement1.Tools.Add(buttonItem); - -```` -````VB.NET -Dim buttonItem As New RadMenuButtonItem("Click me!") -Me.RadGalleryElement1.Tools.Add(buttonItem) + + -```` -{{endregion}} ## See Also diff --git a/controls/ribbonbar/designing-radribbonbar/creating-the-start-menu-quick-access-toolbar-and-shortcuts.md b/controls/ribbonbar/designing-radribbonbar/creating-the-start-menu-quick-access-toolbar-and-shortcuts.md index 014cd5ff3..dee25afe0 100644 --- a/controls/ribbonbar/designing-radribbonbar/creating-the-start-menu-quick-access-toolbar-and-shortcuts.md +++ b/controls/ribbonbar/designing-radribbonbar/creating-the-start-menu-quick-access-toolbar-and-shortcuts.md @@ -75,74 +75,10 @@ This tutorial is in three parts. First, you will create a Quick Access Toolbar #### Open a text file and make its text bold -{{source=..\SamplesCS\RibbonBar\GettingStarted\CreatingStartMenuQATAndShortcuts.cs region=OpenFileAndMakeTextBold}} -{{source=..\SamplesVB\RibbonBar\GettingStarted\CreatingStartMenuQATAndShortcuts.vb region=OpenFileAndMakeTextBold}} - -````C# -private void radButtonElement1_Click(object sender, EventArgs e) -{ - OpenFileDialog dlg = new OpenFileDialog(); - dlg.Filter = "*.txt,*.rtf|*.txt;*.rtf"; - dlg.ShowDialog(); - if (dlg.FileName != string.Empty) - { - OpenFile(dlg.FileName); - } -} -private void OpenFile(string fname) -{ - if (fname.EndsWith("txt")) - { - richTextBox1.LoadFile(fname, RichTextBoxStreamType.PlainText); - } - else - { - if (fname.EndsWith("rtf")) - { - richTextBox1.LoadFile(fname, RichTextBoxStreamType.RichText); - } - } -} -private void radButtonElement2_Click(object sender, EventArgs e) -{ - if (richTextBox1.SelectionFont.Bold) - { - richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, FontStyle.Regular); - } - else - { - richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, FontStyle.Bold); - } -} - -```` -````VB.NET -Private Sub RadButtonElement1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadButtonElement1.Click - Dim dlg As New OpenFileDialog - dlg.Filter = "*.txt,*.rtf|*.txt;*.rtf" - dlg.ShowDialog() - If dlg.FileName > "" Then - OpenFile(dlg.FileName) - End If -End Sub -Private Sub OpenFile(ByVal fname As String) - If fname.EndsWith("txt") Then - RichTextBox1.LoadFile(fname, RichTextBoxStreamType.PlainText) - ElseIf fname.EndsWith("rtf") Then - RichTextBox1.LoadFile(fname, RichTextBoxStreamType.RichText) - End If -End Sub -Private Sub RadButtonElement2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadButtonElement2.Click - If RichTextBox1.SelectionFont.Bold Then - RichTextBox1.SelectionFont = New Font(RichTextBox1.SelectionFont, RichTextBox1.SelectionFont.Style And Not FontStyle.Bold) - Else - RichTextBox1.SelectionFont = New Font(RichTextBox1.SelectionFont, RichTextBox1.SelectionFont.Style Or FontStyle.Bold) - End If -End Sub - -```` - -{{endregion}} + + + + In C#, it is necessary to connect the controls to the methods you have copied into the code: @@ -231,44 +167,10 @@ If you would like to learn more about Application Settings, follow the __Learn m #### Modify the OpenFile method -{{source=..\SamplesCS\RibbonBar\GettingStarted\CreatingStartMenuQATAndShortcuts.cs region=modifiedOpenFile}} -{{source=..\SamplesVB\RibbonBar\GettingStarted\CreatingStartMenuQATAndShortcuts.vb region=modifiedOpenFile}} - -````C# -private void ModifiedOpenFile(string fname) -{ - if (fname.EndsWith("txt")) - { - richTextBox1.LoadFile(fname, RichTextBoxStreamType.PlainText); - AddNewMostRecentFile(fname); - } - else - { - if (fname.EndsWith("rtf")) - { - richTextBox1.LoadFile(fname, RichTextBoxStreamType.RichText); - AddNewMostRecentFile(fname); - } - } -} - -```` -````VB.NET -Private Sub ModifiedOpenFile(ByVal fname As String) - If fname.EndsWith("txt") Then - RichTextBox1.LoadFile(fname, RichTextBoxStreamType.PlainText) - AddNewMostRecentFile(fname) - Else - If fname.EndsWith("rtf") Then - RichTextBox1.LoadFile(fname, RichTextBoxStreamType.RichText) - AddNewMostRecentFile(fname) - End If - End If -End Sub - -```` - -{{endregion}} + + + + 2\. Add the __Click__ event of the File Open button (__radMenuItem1__) on the Start Menu to the event handler that is being used for the File Open button (__radButtonElement1__) on the Quick Access Menu. @@ -288,79 +190,10 @@ Note that __OpenfromMRU__ method will respond to the user clicking any of the th #### Add most recent files functionality -{{source=..\SamplesCS\RibbonBar\GettingStarted\CreatingStartMenuQATAndShortcuts.cs region=addMostRecentOpenedFiles}} -{{source=..\SamplesVB\RibbonBar\GettingStarted\CreatingStartMenuQATAndShortcuts.vb region=addMostRecentOpenedFiles}} - -````C# -private void AddNewMostRecentFile(string newFile) -{ - //last three files are stored in appliation settings: "File1","File2","File3" with File1 being the newest - //replace 3 with 2 and 2 with 1 and then add new to 1 - Properties.Settings.Default.File3 = Properties.Settings.Default.File2; - Properties.Settings.Default.File2 = Properties.Settings.Default.File1; - Properties.Settings.Default.File1 = newFile; -} -private void radMenuItem1_Click(object sender, EventArgs e) -{ - OpenFileDialog dlg = new OpenFileDialog(); - dlg.Filter = "*.txt,*.rtf|*.txt;*.rtf"; - dlg.ShowDialog(); - if (dlg.FileName != string.Empty) - { - ModifiedOpenFile(dlg.FileName); - } -} -private void radMenuItem2_DropDownOpening(object sender, CancelEventArgs e) -{ - //dynamically populate MRU File list - //this example is not concerned about duplicates - radMenuItem3.Text = Properties.Settings.Default.File1; - radMenuItem4.Text = Properties.Settings.Default.File2; - radMenuItem5.Text = Properties.Settings.Default.File3; -} -private void OpenfromMRU(object sender, EventArgs e) -{ - Telerik.WinControls.UI.RadMenuItem filetoOpen = (Telerik.WinControls.UI.RadMenuItem)sender; - if (filetoOpen.Text != String.Empty) - { - ModifiedOpenFile(filetoOpen.Text); - } -} - -```` -````VB.NET -Private Sub AddNewMostRecentFile(ByVal newFile As String) - 'last three files are stored in appliation settings: "File1","File2","File3" with File1 being the newest - 'replace 3 with 2 and 2 with 1 and then add new to 1 - My.Settings.File3 = My.Settings.File2 - My.Settings.File2 = My.Settings.File1 - My.Settings.File1 = newFile -End Sub -Private Sub radMenuItem1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles RadMenuItem1.Click - Dim dlg As New OpenFileDialog() - dlg.Filter = "*.txt,*.rtf|*.txt;*.rtf" - dlg.ShowDialog() - If dlg.FileName <> String.Empty Then - ModifiedOpenFile(dlg.FileName) - End If -End Sub -Private Sub radMenuItem2_DropDownOpening(ByVal sender As Object, ByVal e As CancelEventArgs) Handles RadMenuItem2.DropDownOpening - 'dynamically populate MRU File list - 'this example is not concerned about duplicates - RadMenuItem3.Text = My.Settings.File1 - RadMenuItem4.Text = My.Settings.File2 - RadMenuItem5.Text = My.Settings.File3 -End Sub -Private Sub OpenfromMRU(ByVal sender As Object, ByVal e As EventArgs) Handles RadMenuItem5.Click, RadMenuItem4.Click, RadMenuItem3.Click - Dim filetoOpen As Telerik.WinControls.UI.RadMenuItem = DirectCast(sender, Telerik.WinControls.UI.RadMenuItem) - If filetoOpen.Text <> [String].Empty Then - ModifiedOpenFile(filetoOpen.Text) - End If -End Sub - -```` - -{{endregion}} + + + + In C#, it is necessary to connect these methods to the control events: @@ -386,21 +219,10 @@ The shorcut assignments is pretty simple. Just switch to the Code View of the fo #### Add most recent files functionality -{{source=..\SamplesCS\RibbonBar\GettingStarted\CreatingStartMenuQATAndShortcuts.cs region=shortcuts}} -{{source=..\SamplesVB\RibbonBar\GettingStarted\CreatingStartMenuQATAndShortcuts.vb region=shortcuts}} - -````C# -radMenuItem1.Shortcuts.Add(new Telerik.WinControls.RadShortcut(Keys.Control, Keys.O)); -radMenuItem2.Shortcuts.Add(new Telerik.WinControls.RadShortcut(Keys.Control, Keys.B)); - -```` -````VB.NET -RadMenuItem1.Shortcuts.Add(New Telerik.WinControls.RadShortcut(Keys.Control, Keys.O)) -RadMenuItem2.Shortcuts.Add(New Telerik.WinControls.RadShortcut(Keys.Control, Keys.B)) + + -```` -{{endregion}} ## Run the Form diff --git a/controls/ribbonbar/designing-radribbonbar/customizing-the-start-menu.md b/controls/ribbonbar/designing-radribbonbar/customizing-the-start-menu.md index 72cf15a34..7874082cc 100644 --- a/controls/ribbonbar/designing-radribbonbar/customizing-the-start-menu.md +++ b/controls/ribbonbar/designing-radribbonbar/customizing-the-start-menu.md @@ -76,19 +76,10 @@ You can easily set an Image to the __RadRibbonBar__ Start Menu by accessing the #### Set RibbonBar Start Button Image -{{source=..\SamplesCS\RibbonBar\GettingStarted\CustomizingTheStartMenu.cs region=StartButtonImage}} -{{source=..\SamplesVB\RibbonBar\GettingStarted\CustomizingTheStartMenu.vb region=StartButtonImage}} + + -````C# -this.radRibbonBar1.StartButtonImage = startMenuButtonImage; -```` -````VB.NET -Me.RadRibbonBar1.StartButtonImage = startMenuButtonImage - -```` - -{{endregion}} >note The size of the RadRibbonBar Start Button will be automatically adjusted to fit the size of the image set. Unappropriate image sizes might lead to undesired visual appearance of the button. > diff --git a/controls/ribbonbar/getting-started.md b/controls/ribbonbar/getting-started.md index b0d6a2566..915596f41 100644 --- a/controls/ribbonbar/getting-started.md +++ b/controls/ribbonbar/getting-started.md @@ -114,54 +114,10 @@ Having done that a __RadButtonElement__ is added to the *button group* that you #### Toggle Bold or Italic -{{source=..\SamplesCS\RibbonBar\GettingStarted\RibbonGettingStarted.cs region=BoldAndItalicText}} -{{source=..\SamplesVB\RibbonBar\GettingStarted\RibbonGettingStarted.vb region=BoldAndItalicText}} - -````C# -private void TextBold_Click(object sender, EventArgs e) -{ - if (richTextBox1.SelectionFont.Bold) - { - richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, richTextBox1.SelectionFont.Style & ~FontStyle.Bold); - } - else - { - richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, richTextBox1.SelectionFont.Style | FontStyle.Bold); - } -} - -private void TextItalic_Click(object sender, EventArgs e) -{ - if (richTextBox1.SelectionFont.Italic) - { - richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, richTextBox1.SelectionFont.Style & ~FontStyle.Italic); - } - else - { - richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, richTextBox1.SelectionFont.Style | FontStyle.Italic); - } -} - -```` -````VB.NET -Private Sub TextBold_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBold.Click - If RichTextBox1.SelectionFont.Bold Then - RichTextBox1.SelectionFont = New Font(RichTextBox1.SelectionFont, RichTextBox1.SelectionFont.Style And Not FontStyle.Bold) - Else - RichTextBox1.SelectionFont = New Font(RichTextBox1.SelectionFont, RichTextBox1.SelectionFont.Style Or FontStyle.Bold) - End If - End Sub -Private Sub TextItalic_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextItalic.Click - If RichTextBox1.SelectionFont.Italic Then - RichTextBox1.SelectionFont = New Font(RichTextBox1.SelectionFont, RichTextBox1.SelectionFont.Style And Not FontStyle.Italic) - Else - RichTextBox1.SelectionFont = New Font(RichTextBox1.SelectionFont, RichTextBox1.SelectionFont.Style Or FontStyle.Italic) - End If - End Sub - -```` - -{{endregion}} + + + + ## Additional Code Instructions diff --git a/controls/ribbonbar/how-to/set-radribbonbar-in-titlebar-mode.md b/controls/ribbonbar/how-to/set-radribbonbar-in-titlebar-mode.md index 0ef0355c6..607fc7d79 100644 --- a/controls/ribbonbar/how-to/set-radribbonbar-in-titlebar-mode.md +++ b/controls/ribbonbar/how-to/set-radribbonbar-in-titlebar-mode.md @@ -15,21 +15,10 @@ In order to remove the tabstrip part of RadRibbonBar and leave only the titlebar #### TitleBar Mode -{{source=..\SamplesCS\RibbonBar\HowTo\SetRadRibbonBarInTitleBarMode.cs region=setRadRibbonBarInTitleBarMode}} -{{source=..\SamplesVB\RibbonBar\HowTo\SetRadRibbonBarInTitleBarMode.vb region=setRadRibbonBarInTitleBarMode}} + + -````C# -this.radRibbonBar1.RibbonBarElement.TabStripElement.Visibility = Telerik.WinControls.ElementVisibility.Collapsed; -this.radRibbonBar1.StartButtonImage = new Bitmap(this.radRibbonBar1.StartButtonImage, new Size(15, 15)); -```` -````VB.NET -Me.RadRibbonBar1.RibbonBarElement.TabStripElement.Visibility = Telerik.WinControls.ElementVisibility.Collapsed -Me.RadRibbonBar1.StartButtonImage = New Bitmap(Me.RadRibbonBar1.StartButtonImage, New Size(15, 15)) - -```` - -{{endregion}} The result is shown on the screenshot below: diff --git a/controls/ribbonbar/localization/localization.md b/controls/ribbonbar/localization/localization.md index fae84dd10..12f8d7d08 100644 --- a/controls/ribbonbar/localization/localization.md +++ b/controls/ribbonbar/localization/localization.md @@ -13,43 +13,17 @@ previous_url: ribbonbar-localization-localization **RadRibbonBar** provides the possibility to localize the strings of the Options and Exit buttons that belong to the application menu. You just neet to set the __Text__ properties of the __OptionsButton__ and __ExitButton__: -{{source=..\SamplesCS\RibbonBar\GettingStarted\AddingScreenTips.cs region=localize}} -{{source=..\SamplesVB\RibbonBar\GettingStarted\AddingScreenTips.vb region=localize}} + + -````C# -radRibbonBar1.RibbonBarElement.OptionsButton.Text = "Options"; -radRibbonBar1.RibbonBarElement.ExitButton.Text = "Exit"; -```` -````VB.NET -RadRibbonBar1.RibbonBarElement.OptionsButton.Text = "Options" -RadRibbonBar1.RibbonBarElement.ExitButton.Text = "Exit" - -```` - -{{endregion}} Additionally, you can customize the text for the **LayoutMode**, __QuickAccessToolbar__, drop down menu, by setting the following properties of the __LocalizationSettings__ property of __RibbonBarElement__: -{{source=..\SamplesCS\RibbonBar\GettingStarted\AddingScreenTips.cs region=localize2}} -{{source=..\SamplesVB\RibbonBar\GettingStarted\AddingScreenTips.vb region=localize2}} - -````C# -radRibbonBar1.LocalizationSettings.ShowQuickAccessMenuBelowItemText = "ENG Show below the ribbon"; -radRibbonBar1.LocalizationSettings.MinimizeRibbonItemText = "ENG Minimize the ribbon"; -radRibbonBar1.LocalizationSettings.ShowQuickAccessMenuAboveItemText = "ENG Show above the ribbon"; -radRibbonBar1.LocalizationSettings.MaximizeRibbonItemText = "ENG Maximize the ribbon"; - -```` -````VB.NET -RadRibbonBar1.LocalizationSettings.ShowQuickAccessMenuBelowItemText = "ENG Show below the ribbon" -RadRibbonBar1.LocalizationSettings.MinimizeRibbonItemText = "ENG Minimize the ribbon" -RadRibbonBar1.LocalizationSettings.ShowQuickAccessMenuAboveItemText = "ENG Show above the ribbon" -RadRibbonBar1.LocalizationSettings.MaximizeRibbonItemText = "ENG Maximize the ribbon" + + -```` -{{endregion}} ## See Also diff --git a/controls/ribbonbar/localization/right-to-left-support.md b/controls/ribbonbar/localization/right-to-left-support.md index 7aa7d40df..3e3fe1c28 100644 --- a/controls/ribbonbar/localization/right-to-left-support.md +++ b/controls/ribbonbar/localization/right-to-left-support.md @@ -13,19 +13,10 @@ previous_url: ribbonbar-localization-rtl You can present the content of your ribbonbar instance in a right-to-left direction by setting the __RightToLeft__ property to *Yes*: -{{source=..\SamplesCS\RibbonBar\GettingStarted\AddingScreenTips.cs region=rtl}} -{{source=..\SamplesVB\RibbonBar\GettingStarted\AddingScreenTips.vb region=rtl}} + + -````C# -this.radRibbonBar1.RightToLeft = System.Windows.Forms.RightToLeft.Yes; -```` -````VB.NET -Me.RadRibbonBar1.RightToLeft = System.Windows.Forms.RightToLeft.Yes - -```` - -{{endregion}} >caption Figure 1: Right-to-left Ribbon UI ![WinForms RadRibbonBar Right-to-left Ribbon UI](images/ribbonbar-localization-rtl001.png) diff --git a/controls/ribbonbar/programming-radribbonbar/adding-and-removing-groups-and-buttons.md b/controls/ribbonbar/programming-radribbonbar/adding-and-removing-groups-and-buttons.md index aedd75a12..97dfc2f8f 100644 --- a/controls/ribbonbar/programming-radribbonbar/adding-and-removing-groups-and-buttons.md +++ b/controls/ribbonbar/programming-radribbonbar/adding-and-removing-groups-and-buttons.md @@ -19,49 +19,19 @@ To add a button to a RibbonBar group of __RadRibbonBar__, create a new __RadButt #### Add a button to RadRibbonBarGroup -{{source=..\SamplesCS\RibbonBar\ProgrammingRadRibbonBar\AddingAndRemovingGroupsAndButtons.cs region=addingAButton}} -{{source=..\SamplesVB\RibbonBar\ProgrammingRadRibbonBar\AddingAndRemovingGroupsAndButtons.vb region=addingAButton}} + + -````C# -RadButtonElement radButtonElement1 = new RadButtonElement(); -radButtonElement1.Text = "Button"; -radRibbonBarGroup1.Items.Add(radButtonElement1); -```` -````VB.NET -Dim RadButtonElement1 As RadButtonElement = New RadButtonElement() -RadButtonElement1.Text = "Button" -RadRibbonBarGroup1.Items.Add(RadButtonElement1) - -```` - -{{endregion}} Like the other collections, you can add multiple buttons in a single operation by using the appropriate __AddRange__ method: #### Add multiple buttons to RadRibbonBarGroup -{{source=..\SamplesCS\RibbonBar\ProgrammingRadRibbonBar\AddingAndRemovingGroupsAndButtons.cs region=addMultipleButtons}} -{{source=..\SamplesVB\RibbonBar\ProgrammingRadRibbonBar\AddingAndRemovingGroupsAndButtons.vb region=addMultipleButtons}} - -````C# -RadButtonElement radButtonElement2 = new RadButtonElement(); -RadButtonElement radButtonElement3 = new RadButtonElement(); -radButtonElement2.Text = "Second Button"; -radButtonElement3.Text = "Third Button"; -radRibbonBarGroup1.Items.AddRange(new RadItem[] { radButtonElement1, radButtonElement2 }); + + -```` -````VB.NET -Dim RadButtonElement2 As RadButtonElement = New RadButtonElement() -Dim RadButtonElement3 As RadButtonElement = New RadButtonElement() -RadButtonElement2.Text = "Second Button" -RadButtonElement3.Text = "Third Button" -RadRibbonBarGroup1.Items.AddRange(New RadItem() {RadButtonElement1, RadButtonElement2}) -```` - -{{endregion}} ## Removing a Button @@ -69,39 +39,19 @@ To remove a button, call the __Remove__ method of RadRibbonBarGroup.__Items__ co #### Remove a button from RadRibbonBarGroup -{{source=..\SamplesCS\RibbonBar\ProgrammingRadRibbonBar\AddingAndRemovingGroupsAndButtons.cs region=removeAButton}} -{{source=..\SamplesVB\RibbonBar\ProgrammingRadRibbonBar\AddingAndRemovingGroupsAndButtons.vb region=removeAButton}} - -````C# -RadButtonElement elementToRemove = (RadItem)radRibbonBarGroup1.Items[1] as RadButtonElement; -radRibbonBarGroup1.Items.Remove(elementToRemove); + + -```` -````VB.NET -Dim elementToRemove As RadButtonElement = RadRibbonBarGroup1.Items(1) -RadRibbonBarGroup1.Items.Remove(elementToRemove) -```` - -{{endregion}} To remove a button by index, you can use the __RemoveAt__ method: #### Remove a button from RadRibbonBarGroup by index -{{source=..\SamplesCS\RibbonBar\ProgrammingRadRibbonBar\AddingAndRemovingGroupsAndButtons.cs region=removeAButtonByIndex}} -{{source=..\SamplesVB\RibbonBar\ProgrammingRadRibbonBar\AddingAndRemovingGroupsAndButtons.vb region=removeAButtonByIndex}} - -````C# -radRibbonBarGroup1.Items.RemoveAt(1); - -```` -````VB.NET -RadRibbonBarGroup1.Items.RemoveAt(1) + + -```` -{{endregion}} ## Adding a Button Group with Buttons @@ -117,37 +67,10 @@ To add a new button group with buttons to a RibbonBar group of __RadRibbonBar__, #### Add button group with buttons -{{source=..\SamplesCS\RibbonBar\ProgrammingRadRibbonBar\AddingAndRemovingGroupsAndButtons.cs region=addingButtonGroupWithButtons}} -{{source=..\SamplesVB\RibbonBar\ProgrammingRadRibbonBar\AddingAndRemovingGroupsAndButtons.vb region=addingButtonGroupWithButtons}} - -````C# -RadRibbonBarButtonGroup radRibbonBarButtonGroup1 = new RadRibbonBarButtonGroup(); -radRibbonBarButtonGroup1.Orientation = System.Windows.Forms.Orientation.Horizontal; -radRibbonBarButtonGroup1.MinSize = new System.Drawing.Size(22, 22); -radRibbonBarButtonGroup1.ShowBorder = true; -RadButtonElement radButtonElement4 = new RadButtonElement(); -RadButtonElement radButtonElement5 = new RadButtonElement(); -radButtonElement4.Text = "Button One"; -radButtonElement5.Text = "Button Two"; -radRibbonBarButtonGroup1.Items.AddRange(new RadItem[] { radButtonElement1, radButtonElement2 }); -radRibbonBarGroup1.Items.Add(radRibbonBarButtonGroup1); - -```` -````VB.NET -Dim RadRibbonBarButtonGroup1 As RadRibbonBarButtonGroup = New RadRibbonBarButtonGroup() -RadRibbonBarButtonGroup1.Orientation = System.Windows.Forms.Orientation.Horizontal -RadRibbonBarButtonGroup1.MinSize = New System.Drawing.Size(22, 22) -RadRibbonBarButtonGroup1.ShowBorder = True -Dim RadButtonElement4 As RadButtonElement = New RadButtonElement() -Dim RadButtonElement5 As RadButtonElement = New RadButtonElement() -RadButtonElement4.Text = "Button One" -RadButtonElement5.Text = "Button Two" -RadRibbonBarButtonGroup1.Items.AddRange(New RadItem() {RadButtonElement4, RadButtonElement5}) -RadRibbonBarGroup1.Items.Add(RadRibbonBarButtonGroup1) - -```` - -{{endregion}} + + + + ## See Also diff --git a/controls/ribbonbar/programming-radribbonbar/adding-and-removing-tabs-and-ribbonbar-groups.md b/controls/ribbonbar/programming-radribbonbar/adding-and-removing-tabs-and-ribbonbar-groups.md index 77db6979f..b4b7dedc6 100644 --- a/controls/ribbonbar/programming-radribbonbar/adding-and-removing-tabs-and-ribbonbar-groups.md +++ b/controls/ribbonbar/programming-radribbonbar/adding-and-removing-tabs-and-ribbonbar-groups.md @@ -23,53 +23,19 @@ To add a tab to __RadRibbonBar__, follow the four steps below: #### Adding a tab to RadRibbonBar -{{source=..\SamplesCS\RibbonBar\ProgrammingRadRibbonBar\AddingAndRemovingTabsAndRibbonBarGroups.cs region=addingATab}} -{{source=..\SamplesVB\RibbonBar\ProgrammingRadRibbonBar\AddingAndRemovingTabsAndRibbonBarGroups.vb region=addingATab}} + + -````C# -RibbonTab tabItem1 = new RibbonTab(); -tabItem1.Text = "Manage"; -radRibbonBar1.CommandTabs.Add(tabItem1); -```` -````VB.NET -Dim TabItem1 As RibbonTab = New RibbonTab() -TabItem1.Text = "Manage" -RadRibbonBar1.CommandTabs.Add(TabItem1) - -```` - -{{endregion}} To add multiple tabs in a single operation, call __AddRange__ method of __RadRibbonBar.CommandTabs__ collection. #### Adding multiple tabs to RadRibbonBar -{{source=..\SamplesCS\RibbonBar\ProgrammingRadRibbonBar\AddingAndRemovingTabsAndRibbonBarGroups.cs region=addMultipleTabs}} -{{source=..\SamplesVB\RibbonBar\ProgrammingRadRibbonBar\AddingAndRemovingTabsAndRibbonBarGroups.vb region=addMultipleTabs}} - -````C# -RibbonTab tabItem2 = new RibbonTab(); -RibbonTab tabItem3 = new RibbonTab(); -RibbonTab tabItem4 = new RibbonTab(); -tabItem1.Text = "Write"; -tabItem2.Text = "Layout"; -tabItem3.Text = "Image"; -radRibbonBar1.CommandTabs.AddRange(new RibbonTab[] { tabItem2, tabItem3, tabItem4 }); - -```` -````VB.NET -Dim tabItem2 As New RibbonTab() -Dim tabItem3 As New RibbonTab() -Dim tabItem4 As New RibbonTab() -tabItem1.Text = "Write" -tabItem2.Text = "Layout" -tabItem3.Text = "Image" -RadRibbonBar1.CommandTabs.AddRange(New RibbonTab() {tabItem2, tabItem3, tabItem4}) + + -```` -{{endregion}} ## Removing a Tab @@ -77,39 +43,19 @@ To remove a tab, call the __Remove__ method of the __CommandTabs__ collection, s #### Remove a Tab from RadRibbonBar -{{source=..\SamplesCS\RibbonBar\ProgrammingRadRibbonBar\AddingAndRemovingTabsAndRibbonBarGroups.cs region=removingATab}} -{{source=..\SamplesVB\RibbonBar\ProgrammingRadRibbonBar\AddingAndRemovingTabsAndRibbonBarGroups.vb region=removingATab}} + + -````C# -RibbonTab ribbonTab2 = (RibbonTab)radRibbonBar1.CommandTabs[1]; -radRibbonBar1.CommandTabs.Remove(ribbonTab2); -```` -````VB.NET -Dim ribbonTab2 As RibbonTab = RadRibbonBar1.CommandTabs(1) -RadRibbonBar1.CommandTabs.Remove(ribbonTab2) - -```` - -{{endregion}} To remove a tab by index, you can use __RemoveAt__ method: #### Remove a Tab by Index -{{source=..\SamplesCS\RibbonBar\ProgrammingRadRibbonBar\AddingAndRemovingTabsAndRibbonBarGroups.cs region=removeATabByTabIndex}} -{{source=..\SamplesVB\RibbonBar\ProgrammingRadRibbonBar\AddingAndRemovingTabsAndRibbonBarGroups.vb region=removeATabByTabIndex}} - -````C# -radRibbonBar1.CommandTabs.RemoveAt(1); - -```` -````VB.NET -RadRibbonBar1.CommandTabs.RemoveAt(1) + + -```` -{{endregion}} ## Adding a RibbonBar Group @@ -122,55 +68,19 @@ To add a RibbonBar group to a tab, you follow the steps below: #### Create and Setup New RadRibbonBarGroup -{{source=..\SamplesCS\RibbonBar\ProgrammingRadRibbonBar\AddingAndRemovingTabsAndRibbonBarGroups.cs region=addingARibbonBarGroup}} -{{source=..\SamplesVB\RibbonBar\ProgrammingRadRibbonBar\AddingAndRemovingTabsAndRibbonBarGroups.vb region=addingARibbonBarGroup}} + + -````C# -RadRibbonBarGroup radRibbonBarGroup1 = new RadRibbonBarGroup(); -radRibbonBarGroup1.Text = "Options"; -((RibbonTab)radRibbonBar1.CommandTabs[0]).Items.Add(radRibbonBarGroup1); -```` -````VB.NET -Dim RadRibbonBarGroup1 As RadRibbonBarGroup = New RadRibbonBarGroup() -RadRibbonBarGroup1.Text = "Options" -DirectCast(Me.RadRibbonBar1.CommandTabs(0), RibbonTab).Items.Add(RadRibbonBarGroup1) - -```` - -{{endregion}} To add multiple RibbonBar groups in a single operation, call the __AddRange__ method of __RadRibbonBar.CommandTab.Items__ collection: #### Add Multiple RadRibbonBarGroups -{{source=..\SamplesCS\RibbonBar\ProgrammingRadRibbonBar\AddingAndRemovingTabsAndRibbonBarGroups.cs region=addingMultipleRibbonBarGroups}} -{{source=..\SamplesVB\RibbonBar\ProgrammingRadRibbonBar\AddingAndRemovingTabsAndRibbonBarGroups.vb region=addingMultipleRibbonBarGroups}} - -````C# -RadRibbonBarGroup radRibbonBarGroup2 = new RadRibbonBarGroup(); -RadRibbonBarGroup radRibbonBarGroup3 = new RadRibbonBarGroup(); -RadRibbonBarGroup radRibbonBarGroup4 = new RadRibbonBarGroup(); -radRibbonBarGroup2.Text = "Options"; -radRibbonBarGroup3.Text = "Text"; -radRibbonBarGroup4.Text = "Alignment"; -RibbonTab ribbonTab1 = (RibbonTab)radRibbonBar1.CommandTabs[0]; -ribbonTab1.Items.AddRange(new Telerik.WinControls.RadItem[] { radRibbonBarGroup2, radRibbonBarGroup3, radRibbonBarGroup4}); - -```` -````VB.NET -Dim RadRibbonBarGroup2 As RadRibbonBarGroup = New RadRibbonBarGroup() -Dim RadRibbonBarGroup3 As RadRibbonBarGroup = New RadRibbonBarGroup() -Dim RadRibbonBarGroup4 As RadRibbonBarGroup = New RadRibbonBarGroup() -RadRibbonBarGroup2.Text = "Options" -RadRibbonBarGroup3.Text = "Text" -RadRibbonBarGroup4.Text = "Alignment" -Dim RibbonTab1 As RibbonTab = RadRibbonBar1.CommandTabs(0) -RibbonTab1.Items.AddRange(New Telerik.WinControls.RadItem() {RadRibbonBarGroup2, RadRibbonBarGroup3, RadRibbonBarGroup4}) - -```` - -{{endregion}} + + + + ## Removing a RibbonBar Group @@ -178,37 +88,18 @@ To remove a group, call the __Remove__ method of the __CommandTab.Items__ collec #### Remove RadRibbonBarGroup -{{source=..\SamplesCS\RibbonBar\ProgrammingRadRibbonBar\AddingAndRemovingTabsAndRibbonBarGroups.cs region=removeARibbonBarGroup}} -{{source=..\SamplesVB\RibbonBar\ProgrammingRadRibbonBar\AddingAndRemovingTabsAndRibbonBarGroups.vb region=removeARibbonBarGroup}} + + -````C# -RadRibbonBarGroup groupToRemove = ((RadRibbonBarGroup)(((RibbonTab) radRibbonBar1.CommandTabs[0]).Items[0])); -((RibbonTab)radRibbonBar1.CommandTabs[0]).Items.Remove(groupToRemove); -```` -````VB.NET -Dim groupToRemove As RadRibbonBarGroup = DirectCast(RadRibbonBar1.CommandTabs(0), RibbonTab).Items(0) -DirectCast(RadRibbonBar1.CommandTabs(0), RibbonTab).Items.Remove(groupToRemove) - -```` -{{endregion}} To remove a group by index, you can use the __RemoveAt__ method: #### Remove RadRibbonBarGroup by Index -{{source=..\SamplesCS\RibbonBar\ProgrammingRadRibbonBar\AddingAndRemovingTabsAndRibbonBarGroups.cs region=removeAChunkByIndex}} -{{source=..\SamplesVB\RibbonBar\ProgrammingRadRibbonBar\AddingAndRemovingTabsAndRibbonBarGroups.vb region=removeAChunkByIndex}} - -````C# -((RibbonTab)radRibbonBar1.CommandTabs[0]).Items.RemoveAt(1); - -```` -````VB.NET -DirectCast(RadRibbonBar1.CommandTabs(0), RibbonTab).Items.RemoveAt(1) + + -```` -{{endregion}} ## See Also diff --git a/controls/ribbonbar/programming-radribbonbar/customizing-the-application-menu.md b/controls/ribbonbar/programming-radribbonbar/customizing-the-application-menu.md index 6bf15e966..c54a4ac61 100644 --- a/controls/ribbonbar/programming-radribbonbar/customizing-the-application-menu.md +++ b/controls/ribbonbar/programming-radribbonbar/customizing-the-application-menu.md @@ -24,19 +24,10 @@ __RadRibbonBar.StartButtonImage__ property defines the image used in the Applica #### Assign image to start button -{{source=..\SamplesCS\RibbonBar\ProgrammingRadRibbonBar\CustomizingTheApplicationMenu.cs region=assignImageToStartButton}} -{{source=..\SamplesVB\RibbonBar\ProgrammingRadRibbonBar\CustomizingTheApplicationMenu.vb region=assignImageToStartButton}} + + -````C# -radRibbonBar1.StartButtonImage = new Bitmap("..\\..\\DataSources\\star.png"); -```` -````VB.NET -RadRibbonBar1.StartButtonImage = New Bitmap("..\\..\\DataSources\\star.png") - -```` - -{{endregion}} ## Adding Items to the Application Menu @@ -54,46 +45,19 @@ For example to create a new RadMenuItem and add it to the application menu use t #### Creating and add new menu item -{{source=..\SamplesCS\RibbonBar\ProgrammingRadRibbonBar\CustomizingTheApplicationMenu.cs region=addingItemsToTheApplicationMenu1}} -{{source=..\SamplesVB\RibbonBar\ProgrammingRadRibbonBar\CustomizingTheApplicationMenu.vb region=addingItemsToTheApplicationMenu1}} - -````C# -RadMenuItem mnuNew = new RadMenuItem("New File"); -mnuNew.Click += new EventHandler(NewFile); -radRibbonBar1.StartMenuItems.Add(mnuNew); + + -```` -````VB.NET -Dim mnuNew As New RadMenuItem("New File") -AddHandler mnuNew.Click, AddressOf NewFile -RadRibbonBar1.StartMenuItems.Add(mnuNew) -```` - -{{endregion}} ## Below is the method that is referred to by the handler of the Click event. #### Handle the menu item click event -{{source=..\SamplesCS\RibbonBar\ProgrammingRadRibbonBar\CustomizingTheApplicationMenu.cs region=addingItemsToTheApplicationMenu2}} -{{source=..\SamplesVB\RibbonBar\ProgrammingRadRibbonBar\CustomizingTheApplicationMenu.vb region=addingItemsToTheApplicationMenu2}} - -````C# -void NewFile(object sender, EventArgs e) -{ - MessageBox.Show("New File code goes here"); -} + + -```` -````VB.NET -Private Sub NewFile(sender As Object, e As EventArgs) - MessageBox.Show("New File code goes here") -End Sub -```` - -{{endregion}} ## Adding Items to the Right Column @@ -101,24 +65,8 @@ To place items in the right column of the Application Menu use __RadRibbonBar.St #### Adding items to the right column -{{source=..\SamplesCS\RibbonBar\ProgrammingRadRibbonBar\CustomizingTheApplicationMenu.cs region=addingItemsToTheRightColumn}} -{{source=..\SamplesVB\RibbonBar\ProgrammingRadRibbonBar\CustomizingTheApplicationMenu.vb region=addingItemsToTheRightColumn}} - -````C# -RadMenuItem mnuRecentDocs = new RadMenuItem("Recent Documents"); -mnuRecentDocs.Enabled = false; -radRibbonBar1.StartMenuRightColumnItems.Add(mnuRecentDocs); - -```` -````VB.NET -Dim mnuRecentDocs As New RadMenuItem("Recent Documents") -mnuRecentDocs.Enabled = False -RadRibbonBar1.StartMenuRightColumnItems.Add(mnuRecentDocs) - -```` - -{{endregion}} - + + @@ -130,89 +78,28 @@ This code adds a new __RadMenuItem__, __mnuPrint__, to the Start Menu. Then an #### Adding menu items with sub items -{{source=..\SamplesCS\RibbonBar\ProgrammingRadRibbonBar\CustomizingTheApplicationMenu.cs region=addingItemsWithSubItems}} -{{source=..\SamplesVB\RibbonBar\ProgrammingRadRibbonBar\CustomizingTheApplicationMenu.vb region=addingItemsWithSubItems}} - -````C# -RadMenuItem mnuPrint = new RadMenuItem("Print"); -//add Print menu item to the Start Menu -radRibbonBar1.StartMenuItems.Add(mnuPrint); -//Create Sub-Menu Items with event handlers -RadMenuItem mnuPrintsubPrint = new RadMenuItem("Print"); -mnuPrintsubPrint.Click += new EventHandler(Print); -RadMenuItem mnuPrintsubQuickPrint = new RadMenuItem("Quick Print"); -mnuPrintsubQuickPrint.Click += new EventHandler(QuickPrint); -RadMenuItem mnuPrintsubPreview = new RadMenuItem("Print Preview"); -mnuPrintsubPreview.Click += new EventHandler(Preview); -//add sub-menu items to start menu -mnuPrint.Items.AddRange(new RadMenuItem[] {mnuPrintsubPrint, mnuPrintsubQuickPrint, mnuPrintsubPreview}); - -```` -````VB.NET -Dim mnuPrint As New RadMenuItem("Print") -'add Print menu item to the Start Menu -RadRibbonBar1.StartMenuItems.Add(mnuPrint) -'Create Sub-Menu Items with event handlers -Dim mnuPrintsubPrint As New RadMenuItem("Print") -AddHandler mnuPrintsubPrint.Click, AddressOf Print -Dim mnuPrintsubQuickPrint As New RadMenuItem("Quick Print") -AddHandler mnuPrintsubQuickPrint.Click, AddressOf QuickPrint -Dim mnuPrintsubPreview As New RadMenuItem("Print Preview") -AddHandler mnuPrintsubPreview.Click, AddressOf Preview -'Add sub-menu items to the Print menu item -mnuPrint.Items.AddRange(New RadMenuItem() {mnuPrintsubPrint, mnuPrintsubQuickPrint, mnuPrintsubPreview}) - -```` - -{{endregion}} + + -## Wrapping Items' Text -The ApplicationMenu of RadRibbonBar supports wrapping of the main and description texts of its items in the right column. To enable it, you should set the TextWrap property of the __Text__ and __Description__ parts of the menu items to true. In addition, you should set the MaxSize of these parts. Finally, you can set the width of the right column to an appropriate value by the ApplicationMenuRightColumnWidth property. Let's say that we have the following RadMenuItems in the right column: -{{source=..\SamplesCS\RibbonBar\ProgrammingRadRibbonBar\CustomizingTheApplicationMenu.cs region=menuItemsTexts}} -{{source=..\SamplesVB\RibbonBar\ProgrammingRadRibbonBar\CustomizingTheApplicationMenu.vb region=menuItemsTexts}} +## Wrapping Items' Text -````C# -this.LongNameFileMenuItem.Text = "This is a file with a veeeeeeeery veeeeery long name.png"; -this.UntitledFileMenuItem.DescriptionText = "C:\\Program Files (x86)\\Telerik\\RadControls for WinForms Q3 2012\\Resources\\Untitled.png"; -this.UntitledFileMenuItem.Text = "Untitled.png"; +The ApplicationMenu of RadRibbonBar supports wrapping of the main and description texts of its items in the right column. To enable it, you should set the TextWrap property of the __Text__ and __Description__ parts of the menu items to true. In addition, you should set the MaxSize of these parts. Finally, you can set the width of the right column to an appropriate value by the ApplicationMenuRightColumnWidth property. Let's say that we have the following RadMenuItems in the right column: -```` -````VB.NET -Me.LongNameFileMenuItem.Text = "This is a file with a veeeeeeeery veeeeery long name.png" -Me.UntitledFileMenuItem.DescriptionText = "C:\\Program Files (x86)\\Telerik\\RadControls for WinForms Q3 2012\\Resources\\Untitled.png" -Me.UntitledFileMenuItem.Text = "Untitled.png" + + -```` -{{endregion}} By default, the menu will look like this:
![WinForms RadRibbonBar No WordWrap](images/ribbonbar-programming-radribbonbar-customizing-the-application-menu002.png) So, as mentioned above, we should set the TextWrap and MaxSize properties of the Text and Description parts of the menu items: -{{source=..\SamplesCS\RibbonBar\ProgrammingRadRibbonBar\CustomizingTheApplicationMenu.cs region=settingUpSizes}} -{{source=..\SamplesVB\RibbonBar\ProgrammingRadRibbonBar\CustomizingTheApplicationMenu.vb region=settingUpSizes}} - -````C# -this.radRibbonBar1.RibbonBarElement.ApplicationMenuRightColumnWidth = 180; -this.LongNameFileMenuItem.Layout.Text.TextWrap = true; -this.LongNameFileMenuItem.Layout.Text.MaxSize = new Size(150, 0); -this.UntitledFileMenuItem.Layout.Description.TextWrap = true; -this.UntitledFileMenuItem.Layout.Description.MaxSize = new Size(150, 0); - -```` -````VB.NET -Me.RadRibbonBar1.RibbonBarElement.ApplicationMenuRightColumnWidth = 180 -Me.LongNameFileMenuItem.Layout.Text.TextWrap = True -Me.LongNameFileMenuItem.Layout.Text.MaxSize = New Size(150, 0) -Me.UntitledFileMenuItem.Layout.Description.TextWrap = True -Me.UntitledFileMenuItem.Layout.Description.MaxSize = New Size(150, 0) + + -```` -{{endregion}} The result in this case will be:
![WinForms RadRibbonBar With WordWrap](images/ribbonbar-programming-radribbonbar-customizing-the-application-menu001.png) diff --git a/controls/ribbonbar/programming-radribbonbar/customizing-the-key-tips.md b/controls/ribbonbar/programming-radribbonbar/customizing-the-key-tips.md index 85a035a27..f5cd69d55 100644 --- a/controls/ribbonbar/programming-radribbonbar/customizing-the-key-tips.md +++ b/controls/ribbonbar/programming-radribbonbar/customizing-the-key-tips.md @@ -36,51 +36,10 @@ The key tip`s location and styles can be modified in the event handler of the ** #### Handling the KeyTipShowing Event -{{source=..\SamplesCS\RibbonBar\ProgrammingRadRibbonBar\CustomizingTheKeyTips.cs region=KeyTipShowingEvent}} -{{source=..\SamplesVB\RibbonBar\ProgrammingRadRibbonBar\CustomizingTheKeyTips.vb region=KeyTipShowingEvent}} -````C# -Font f = new Font("Calibri", 12f, FontStyle.Regular); -private void RadRibbonBar1_KeyTipShowing(object sender, CancelEventArgs e) -{ - RadKeyTipShowingEventArgs args = e as RadKeyTipShowingEventArgs; - args.BackColor = Color.FromArgb(125, 173, 224, 0); - args.BorderColor = Color.LightBlue; - args.ForeColor = Color.Brown; - args.Font = f; - Point location = Point.Empty; - if (sender == this.coverPagesButton || sender == this.blankPageButton || sender == this.pageBreakButton) - { - location = new Point(args.CustomLocation.X + 15, args.CustomLocation.Y - 5); - } - else - { - location = new Point(args.CustomLocation.X, args.CustomLocation.Y + 15); - } - args.CustomLocation = location; -} - -```` -````VB.NET -Private Sub RadRibbonBar1_KeyTipShowing(ByVal sender As Object, ByVal e As CancelEventArgs) - Dim args As RadKeyTipShowingEventArgs = TryCast(e, RadKeyTipShowingEventArgs) - args.BackColor = Color.FromArgb(125, 173, 224, 0) - args.BorderColor = Color.LightBlue - args.ForeColor = Color.Brown - args.Font = f - Dim location As Point = Point.Empty - If sender Is Me.coverPagesButton OrElse sender Is Me.blankPageButton OrElse sender Is Me.pageBreakButton Then - location = New Point(args.CustomLocation.X + 15, args.CustomLocation.Y - 5) - Else - location = New Point(args.CustomLocation.X, args.CustomLocation.Y + 15) - End If - args.CustomLocation = location -End Sub - -```` - - - -{{endregion}} + + + + >note Key tips can also be displayed by the backstage view. The **KeyTipShowing** event needs to be subscribed on the **RadRibbonBarBackstageView** object. diff --git a/controls/ribbonbar/programming-radribbonbar/customizing-the-quick-access-menu.md b/controls/ribbonbar/programming-radribbonbar/customizing-the-quick-access-menu.md index e261a9c1e..dc137d459 100644 --- a/controls/ribbonbar/programming-radribbonbar/customizing-the-quick-access-menu.md +++ b/controls/ribbonbar/programming-radribbonbar/customizing-the-quick-access-menu.md @@ -28,33 +28,10 @@ In order to capture the click event of the items, add an event handler for anoth #### Adding items to QuickAccessToolbar -{{source=..\SamplesCS\RibbonBar\ProgrammingRadRibbonBar\CustomizingTheQuickAccessMenu.cs region=addingItemsToQuickAccessToolBar}} -{{source=..\SamplesVB\RibbonBar\ProgrammingRadRibbonBar\CustomizingTheQuickAccessMenu.vb region=addingItemsToQuickAccessToolBar}} - -````C# -RadMenuItem mnuQANew = new RadMenuItem(); -mnuQANew.Click += new EventHandler(NewFile); -mnuQANew.Text = "Menu item: New File"; -radRibbonBar1.QuickAccessToolBarItems.Add(mnuQANew); -RadButtonElement mnuQAPrint = new RadButtonElement(); -mnuQAPrint.Click += new EventHandler(QuickPrint); -mnuQAPrint.Text = "Menu item: Quick Print"; -radRibbonBar1.QuickAccessToolBarItems.Add(mnuQAPrint); - -```` -````VB.NET -Dim mnuQANew As New RadMenuItem -AddHandler mnuQANew.Click, AddressOf NewFile -mnuQANew.Text = "Menu item: New File" -RadRibbonBar1.QuickAccessToolBarItems.Add(mnuQANew) -Dim mnuQAPrint As New RadButtonElement -AddHandler mnuQAPrint.Click, AddressOf QuickPrint -mnuQAPrint.Text = "Menu item: Print" -RadRibbonBar1.QuickAccessToolBarItems.Add(mnuQAPrint) - -```` - -{{endregion}} + + + + >note The **RadQuickAccessToolBar** exposes the **SetItemVisibility** method which can be used at run-time to toggle the visible state of its items. diff --git a/controls/ribbonbar/programming-radribbonbar/managing-contextual-tab-groups.md b/controls/ribbonbar/programming-radribbonbar/managing-contextual-tab-groups.md index 7d220150a..d85acc181 100644 --- a/controls/ribbonbar/programming-radribbonbar/managing-contextual-tab-groups.md +++ b/controls/ribbonbar/programming-radribbonbar/managing-contextual-tab-groups.md @@ -39,79 +39,10 @@ The following code snippet shows how to add contextual tab groups and assign ta #### Creating ContextualTabGroups -{{source=..\SamplesCS\RibbonBar\ProgrammingRadRibbonBar\ManagingContextualTabGroups.cs region=managingContextualTabGroups}} -{{source=..\SamplesVB\RibbonBar\ProgrammingRadRibbonBar\ManagingContextualTabGroups.vb region=managingContextualTabGroups}} - -````C# -private Telerik.WinControls.UI.RibbonTab ribbonTab1; -private Telerik.WinControls.UI.RibbonTab ribbonTab2; -private Telerik.WinControls.UI.RibbonTab ribbonTab3; -private Telerik.WinControls.UI.RibbonTab ribbonTab4; -private Telerik.WinControls.UI.RibbonTab ribbonTab5; -private Telerik.WinControls.UI.ContextualTabGroup contextualTabGroup1; -private Telerik.WinControls.UI.ContextualTabGroup contextualTabGroup2; -void Form1_Load(object sender, EventArgs e) -{ - // The "this" variable refers to the form that contains the ribbonbar - // Declare variables for tabs and contextual tab groups - //Create the tabs - this.ribbonTab1 = new Telerik.WinControls.UI.RibbonTab(); - this.ribbonTab2 = new Telerik.WinControls.UI.RibbonTab(); - this.ribbonTab3 = new Telerik.WinControls.UI.RibbonTab(); - this.ribbonTab4 = new Telerik.WinControls.UI.RibbonTab(); - this.ribbonTab5 = new Telerik.WinControls.UI.RibbonTab(); - ribbonTab1.Text = "Tab one"; - ribbonTab2.Text = "Tab two"; - ribbonTab3.Text = "Tab three"; - ribbonTab4.Text = "Tab four"; - ribbonTab5.Text = "Tab five"; - // Create the contextual tab groups - this.contextualTabGroup1 = new Telerik.WinControls.UI.ContextualTabGroup(); - this.contextualTabGroup2 = new Telerik.WinControls.UI.ContextualTabGroup(); - // Add the command tabs to the ribbon bar's command tabs collection by accessing the - // ribbon bar's CommandTabs property and using its AddRange method - this.radRibbonBar1.CommandTabs.AddRange(new Telerik.WinControls.UI.RibbonTab[] { ribbonTab1, ribbonTab2, ribbonTab3, ribbonTab4, ribbonTab5 }); - // Add the contextual tab groups to the ribbon bar's contextual tab groups collection by - // accessing the ribbon bar's ContextualTabGroups property and using its AddRange method - this.radRibbonBar1.ContextualTabGroups.AddRange(new Telerik.WinControls.RadItem[] { this.contextualTabGroup1, this.contextualTabGroup2 }); - //Assign some tabs to the contextual tab groups. - this.contextualTabGroup1.TabItems.Add(this.ribbonTab1); - this.contextualTabGroup1.TabItems.Add(this.ribbonTab2); - this.contextualTabGroup2.TabItems.Add(this.ribbonTab3); - this.contextualTabGroup2.TabItems.Add(this.ribbonTab4); -} - -```` -````VB.NET -' The "Me" variable refers to the form that contains the RibbonBar -' Declare variables for tabs and contextual tab groups -Private RibbonTab1 As New Telerik.WinControls.UI.RibbonTab() -Private RibbonTab2 As New Telerik.WinControls.UI.RibbonTab() -Private RibbonTab3 As New Telerik.WinControls.UI.RibbonTab() -Private RibbonTab4 As New Telerik.WinControls.UI.RibbonTab() -Private RibbonTab5 As New Telerik.WinControls.UI.RibbonTab() -Private ContextualTabGroup1 As New Telerik.WinControls.UI.ContextualTabGroup() -Private ContextualTabGroup2 As New Telerik.WinControls.UI.ContextualTabGroup() -Private Sub ManagingContextualTabGroups_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load - RibbonTab1.Text = "Tab one" - RibbonTab2.Text = "Tab two" - RibbonTab3.Text = "Tab three" - RibbonTab4.Text = "Tab four" - RibbonTab5.Text = "Tab five" - 'Add the tabs to the ribbon bar - Me.RadRibbonBar1.CommandTabs.AddRange(New Telerik.WinControls.UI.RibbonTab() {Me.RibbonTab1, Me.RibbonTab2, Me.RibbonTab3, Me.RibbonTab4, Me.RibbonTab5}) - 'Add the contextual tab groups to the ribbon bar - Me.RadRibbonBar1.ContextualTabGroups.AddRange(New Telerik.WinControls.RadItem() {Me.ContextualTabGroup1, Me.ContextualTabGroup2}) - 'Associate the groups with some tabs - Me.ContextualTabGroup1.TabItems.Add(Me.RibbonTab1) - Me.ContextualTabGroup1.TabItems.Add(Me.RibbonTab2) - Me.ContextualTabGroup2.TabItems.Add(Me.RibbonTab3) - Me.ContextualTabGroup2.TabItems.Add(Me.RibbonTab4) -End Sub - -```` - -{{endregion}} + + + + ## See Also diff --git a/controls/ribbonbar/simplified-mode/customizing-simplified-layout.md b/controls/ribbonbar/simplified-mode/customizing-simplified-layout.md index 2e7a0acc9..eed34da9d 100644 --- a/controls/ribbonbar/simplified-mode/customizing-simplified-layout.md +++ b/controls/ribbonbar/simplified-mode/customizing-simplified-layout.md @@ -20,35 +20,9 @@ In this example, you will use the __ItemStyleChanging__ event to change the disp #### Using the ItemStyleChanging event -{{source=..\SamplesCS\RibbonBar\SimplifiedLayout\SimplifiedRibbonLayout.cs region=EventExample}} -{{source=..\SamplesVB\RibbonBar\SimplifiedLayout\SimplifiedRibbonLayout.vb region=EventExample}} - -````C# -private void RibbonBarElement_ItemStyleChanging(object sender, Telerik.WinControls.UI.ItemStyleChangingEventArgs args) -{ - if (args.Context == ItemStyleContext.DefaultToSimplified) - { - if (args.Element is RadGalleryItem && args.Property == RadButtonItem.DisplayStyleProperty) - { - args.NewValue = DisplayStyle.Image; - } - } -} - -```` -````VB.NET -Private Sub RibbonBarElement_ItemStyleChanging(ByVal sender As Object, ByVal args As Telerik.WinControls.UI.ItemStyleChangingEventArgs) - If args.Context = ItemStyleContext.DefaultToSimplified Then - If TypeOf args.Element Is RadGalleryItem AndAlso args.Property.Equals(RadButtonItem.DisplayStyleProperty) Then - args.NewValue = DisplayStyle.Image - End If - End If -End Sub - -```` - - -{{endregion}} + + + The bellow image shows the difference. diff --git a/controls/ribbonbar/simplified-mode/simplified-mode.md b/controls/ribbonbar/simplified-mode/simplified-mode.md index e37dfec35..ee9019ab9 100644 --- a/controls/ribbonbar/simplified-mode/simplified-mode.md +++ b/controls/ribbonbar/simplified-mode/simplified-mode.md @@ -19,35 +19,17 @@ When the simplified layout is switched on all elements in the RibbonBar are auto To enable the simplified mode set the __LayoutMode__ property: -{{source=..\SamplesCS\RibbonBar\SimplifiedLayout\SimplifiedRibbonLayout.cs region=EnableRibbon}} -{{source=..\SamplesVB\RibbonBar\SimplifiedLayout\SimplifiedRibbonLayout.vb region=EnableRibbon}} -````C# -radRibbonBar1.LayoutMode = RibbonLayout.Simplified; + + -```` -````VB.NET -radRibbonBar1.LayoutMode = RibbonLayout.Simplified -```` - - -{{endregion}} To allow the end user to change the LayoutMode ar runtime show the layout button: -{{source=..\SamplesCS\RibbonBar\SimplifiedLayout\SimplifiedRibbonLayout.cs region=LayoutButton}} -{{source=..\SamplesVB\RibbonBar\SimplifiedLayout\SimplifiedRibbonLayout.vb region=LayoutButton}} -````C# -radRibbonBar1.ShowLayoutModeButton = true; - -```` -````VB.NET -radRibbonBar1.ShowLayoutModeButton = True + + -```` - -{{endregion}} ![WinForms RadRibbonBar Simplified Mode Button](images/simplified-mode002.png) @@ -55,51 +37,24 @@ radRibbonBar1.ShowLayoutModeButton = True You are allowed to change the height of the ribbon when you are in the simplified mode: -{{source=..\SamplesCS\RibbonBar\SimplifiedLayout\SimplifiedRibbonLayout.cs region=LayoutHeight}} -{{source=..\SamplesVB\RibbonBar\SimplifiedLayout\SimplifiedRibbonLayout.vb region=LayoutHeight}} -````C# -this.radRibbonBar1.SimplifiedHeight = 100; - -```` -````VB.NET -Me.radRibbonBar1.SimplifiedHeight = 100 + + -```` - -{{endregion}} Access the simplified mode button: -{{source=..\SamplesCS\RibbonBar\SimplifiedLayout\SimplifiedRibbonLayout.cs region=LayoutButton}} -{{source=..\SamplesVB\RibbonBar\SimplifiedLayout\SimplifiedRibbonLayout.vb region=LayoutButton}} -````C# -radRibbonBar1.ShowLayoutModeButton = true; + + -```` -````VB.NET -radRibbonBar1.ShowLayoutModeButton = True -```` - - -{{endregion}} Access the simplified mode label. The following example shows how you can change the text of the label in the upper right corner: -{{source=..\SamplesCS\RibbonBar\SimplifiedLayout\SimplifiedRibbonLayout.cs region=SimplifiedLabel}} -{{source=..\SamplesVB\RibbonBar\SimplifiedLayout\SimplifiedRibbonLayout.vb region=SimplifiedLabel}} -````C# -this.radRibbonBar1.RibbonBarElement.LayoutModeTextElement.Text = "Compact Mode"; - -```` -````VB.NET -Me.radRibbonBar1.RibbonBarElement.LayoutModeTextElement.Text = "Compact Mode" + + -```` - -{{endregion}} ## Events diff --git a/controls/richtexteditor/document-elements/annotations/custom-annotations.md b/controls/richtexteditor/document-elements/annotations/custom-annotations.md index 7cee91694..fc829fa41 100644 --- a/controls/richtexteditor/document-elements/annotations/custom-annotations.md +++ b/controls/richtexteditor/document-elements/annotations/custom-annotations.md @@ -1,250 +1,95 @@ ---- -title: Custom Annotations -page_title: Custom Annotations - WinForms RichTextEditor Control -description: WinForms RadRichTextEditor offers custom annotation ranges which provide an approach for extending the document model to serve specific purposes such as persisting semantic information in the document. -slug: winforms/richtexteditor-/document-elements/annotations/custom-annotations -tags: custom,annotations -published: True -position: 2 -previous_url: richtexteditor-document-elements-annotations-custom-annotations ---- - -# Custom Annotations - -Custom annotation ranges provide an approach for extending the document model to serve specific purposes such as persisting semantic information in the document. This article will list the steps which should be followed in order to create a custom **AnnotationRange** with a specific behavior. - -For general information on **Annotations**, please refer to these articles: - -* [Annotations]({%slug winforms/richtexteditor-/document-elements/annotations%}) - -* [Manipulating Annotations]({%slug winforms/richtexteditor-/document-elements/annotations/manipulating-annotations%}) - -This topic explains: - -* [Creating Custom Annotation](#creating-a-custom-annotation) - -* [Customizing Annotations](#customizing-annotations) - -* [Serialization](#serialization) - -## Creating a Custom Annotation - -The most common scenarios for the use of custom annotations is for associating semantic data to a part of the document. In order to fulfill this task, you can implement custom annotation ranges. The steps to do so are: - -* Create two classes deriving from **AnnotationRangeStart** and **AnnotationRangeEnd** respectively. Depending on the behavior you would like to achieve, you can also inherit from some of the already implemented annotation ranges, such as **FieldRangeStart**/**FieldRangeEnd**. - -* Override the **CreateNewElementInstance** method and have it return an instance of your annotation range start/end in both classes. Override the required **CopyContentFromOverride** method as well. In most cases, it should be left empty. - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\CustomAnnotations.cs region=create}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\CustomAnnotations.vb region=create}} - -````C# +--- +title: Custom Annotations +page_title: Custom Annotations - WinForms RichTextEditor Control +description: WinForms RadRichTextEditor offers custom annotation ranges which provide an approach for extending the document model to serve specific purposes such as persisting semantic information in the document. +slug: winforms/richtexteditor-/document-elements/annotations/custom-annotations +tags: custom,annotations +published: True +position: 2 +previous_url: richtexteditor-document-elements-annotations-custom-annotations +--- + +# Custom Annotations + +Custom annotation ranges provide an approach for extending the document model to serve specific purposes such as persisting semantic information in the document. This article will list the steps which should be followed in order to create a custom **AnnotationRange** with a specific behavior. + +For general information on **Annotations**, please refer to these articles: + +* [Annotations]({%slug winforms/richtexteditor-/document-elements/annotations%}) + +* [Manipulating Annotations]({%slug winforms/richtexteditor-/document-elements/annotations/manipulating-annotations%}) + +This topic explains: + +* [Creating Custom Annotation](#creating-a-custom-annotation) + +* [Customizing Annotations](#customizing-annotations) + +* [Serialization](#serialization) + +## Creating a Custom Annotation + +The most common scenarios for the use of custom annotations is for associating semantic data to a part of the document. In order to fulfill this task, you can implement custom annotation ranges. The steps to do so are: + +* Create two classes deriving from **AnnotationRangeStart** and **AnnotationRangeEnd** respectively. Depending on the behavior you would like to achieve, you can also inherit from some of the already implemented annotation ranges, such as **FieldRangeStart**/**FieldRangeEnd**. + +* Override the **CreateNewElementInstance** method and have it return an instance of your annotation range start/end in both classes. Override the required **CopyContentFromOverride** method as well. In most cases, it should be left empty. + + + + + + +* Override the **CreateRangeStartInstance** in the **RangeEnd** class. + + + + + + +At this point, you will have the basic functionality working and can continue to customize the behavior of the ranges, i.e. if it will be possible to edit the content in them, what will be the behavior when you hit backspace or delete, if it will be possible to copy the ranges, etc. + +## Customizing Annotations + +The behavior of the annotations when edited, copied and deleted is determined by the following properties and methods which you can override: + +* __IsCopyable__ - specifies if the inline can be copied and pasted somewhere else in the document. The start and end must have the same value in order to have proper behavior. For example, **BookmarkRangeStart** and **End** are not copyable, while **CommentRangeStart** and **End** are copyable. + +* __CopyPropertiesFromOverride__ - this method should be used when you have custom properties you would like to have copied. This should be done as follows: + + + + + + +* __SkipPositionBefore__ - specifies where text will appear if you position the caret next to the range start/end. For example, if it returns *true* in the range start and *false* in the range end, the text you enter when you position the caret next to the start/end, will appear in the range. + +* __SkipPositionsInRange__ of **AnnotationRangeStart** - you can set this property to *false*, which will disable the option to edit the content of the range, i.e. it may be possible to delete the range altogether, but it will not be possible to position the caret in the range, select or edit only part of the range. + +* __DeleteBehavior, BackspaceBehavior, DeleteSelectedBehavior__ - you can customize these behaviors by choosing from the options in the enum **AnnotationMarkerDeleteBehavior**: **PreserveAnnotation**, **SelectAnnotation**, **RemoveAnnotation**, **SelectAnnotationMarker**. For example, hyperlinks keep the default settings in **FieldRangeStart** and **FieldRangeEnd**, which are: + +**HyperlinkRangeStart**: + + + + + + +**HyperlinkRangeEnd**: + + + + + + +* You can also define custom properties in your annotation range start/end. If you want to be able to serialize them, you can just mark them with the **XamlSerializable** attribute: + + + + + + +## Serialization + +Of the default document format providers, custom annotations are supported only in XAML. The other formats do not offer such extensibility. When exporting to XAML, the exporter will generate prefixes for each custom annotation namespace (custom1, custom2, etc.). Serialization is handled by **XamlFormatProvider** which looks for properties with the appropriate attributes: **XamlSerializable** (as inline properties) and **XamlCompositePropertySerializable** (as XAML composite properties). -protected override DocumentElement CreateNewElementInstance() -{ - return new CustomAnnotationRangeStart(); -} - -protected override void CopyContentFromOverride(DocumentElement fromElement) -{ -} - -```` -````VB.NET -Protected Overrides Function CreateNewElementInstance() As DocumentElement - Return New CustomAnnotationRangeStart() -End Function -Protected Overrides Sub CopyContentFromOverride(ByVal fromElement As DocumentElement) -End Sub - -```` - -{{endregion}} - -* Override the **CreateRangeStartInstance** in the **RangeEnd** class. - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\CustomAnnotations.cs region=instance}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\CustomAnnotations.vb region=instance}} - -````C# -protected override AnnotationRangeStart CreateRangeStartInstance() -{ - return new CustomAnnotationRangeStart(); -} - -```` -````VB.NET -Protected Overrides Function CreateRangeStartInstance() As AnnotationRangeStart - Return New CustomAnnotationRangeStart() -End Function - -```` - -{{endregion}} - -At this point, you will have the basic functionality working and can continue to customize the behavior of the ranges, i.e. if it will be possible to edit the content in them, what will be the behavior when you hit backspace or delete, if it will be possible to copy the ranges, etc. - -## Customizing Annotations - -The behavior of the annotations when edited, copied and deleted is determined by the following properties and methods which you can override: - -* __IsCopyable__ - specifies if the inline can be copied and pasted somewhere else in the document. The start and end must have the same value in order to have proper behavior. For example, **BookmarkRangeStart** and **End** are not copyable, while **CommentRangeStart** and **End** are copyable. - -* __CopyPropertiesFromOverride__ - this method should be used when you have custom properties you would like to have copied. This should be done as follows: - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\CustomAnnotations.cs region=copy}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\CustomAnnotations.vb region=copy}} - -````C# -protected override void CopyPropertiesFromOverride(DocumentElement fromElement) -{ - base.CopyPropertiesFromOverride(fromElement); - this.Name = ((CustomAnnotationRangeStart)fromElement).Name; -} - -```` -````VB.NET -Protected Overrides Sub CopyPropertiesFromOverride(ByVal fromElement As DocumentElement) - MyBase.CopyPropertiesFromOverride(fromElement) - Me.Name = CType(fromElement, CustomAnnotationRangeStart).Name -End Sub - -```` - -{{endregion}} - -* __SkipPositionBefore__ - specifies where text will appear if you position the caret next to the range start/end. For example, if it returns *true* in the range start and *false* in the range end, the text you enter when you position the caret next to the start/end, will appear in the range. - -* __SkipPositionsInRange__ of **AnnotationRangeStart** - you can set this property to *false*, which will disable the option to edit the content of the range, i.e. it may be possible to delete the range altogether, but it will not be possible to position the caret in the range, select or edit only part of the range. - -* __DeleteBehavior, BackspaceBehavior, DeleteSelectedBehavior__ - you can customize these behaviors by choosing from the options in the enum **AnnotationMarkerDeleteBehavior**: **PreserveAnnotation**, **SelectAnnotation**, **RemoveAnnotation**, **SelectAnnotationMarker**. For example, hyperlinks keep the default settings in **FieldRangeStart** and **FieldRangeEnd**, which are: - -**HyperlinkRangeStart**: - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\CustomAnnotations.cs region=delete}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\CustomAnnotations.vb region=delete}} - -````C# - -public override AnnotationMarkerDeleteBehavior DeleteBehavior -{ - get - { - return AnnotationMarkerDeleteBehavior.SelectAnnotation; - } -} - -public override AnnotationMarkerDeleteBehavior BackspaceBehavior -{ - get - { - return AnnotationMarkerDeleteBehavior.SelectAnnotation; - } -} - -public override AnnotationMarkerDeleteBehavior DeleteSelectedBehavior -{ - get - { - return AnnotationMarkerDeleteBehavior.RemoveAnnotation; - } -} - -```` -````VB.NET -Public Overrides ReadOnly Property DeleteBehavior() As AnnotationMarkerDeleteBehavior - Get - Return AnnotationMarkerDeleteBehavior.SelectAnnotation - End Get -End Property -Public Overrides ReadOnly Property BackspaceBehavior() As AnnotationMarkerDeleteBehavior - Get - Return AnnotationMarkerDeleteBehavior.SelectAnnotation - End Get -End Property -Public Overrides ReadOnly Property DeleteSelectedBehavior() As AnnotationMarkerDeleteBehavior - Get - Return AnnotationMarkerDeleteBehavior.RemoveAnnotation - End Get -End Property - -```` - -{{endregion}} - -**HyperlinkRangeEnd**: - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\CustomAnnotations.cs region=delete2}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\CustomAnnotations.vb region=delete2}} - -````C# - -public override AnnotationMarkerDeleteBehavior DeleteBehavior -{ - get - { - return AnnotationMarkerDeleteBehavior.PreserveAnnotation; - } -} - -public override AnnotationMarkerDeleteBehavior BackspaceBehavior -{ - get - { - return AnnotationMarkerDeleteBehavior.RemoveAnnotation; - } -} - -public override AnnotationMarkerDeleteBehavior DeleteSelectedBehavior -{ - get - { - return AnnotationMarkerDeleteBehavior.RemoveAnnotation; - } -} - -```` -````VB.NET -Public Overrides ReadOnly Property DeleteBehavior() As AnnotationMarkerDeleteBehavior - Get - Return AnnotationMarkerDeleteBehavior.PreserveAnnotation - End Get -End Property -Public Overrides ReadOnly Property BackspaceBehavior() As AnnotationMarkerDeleteBehavior - Get - Return AnnotationMarkerDeleteBehavior.RemoveAnnotation - End Get -End Property -Public Overrides ReadOnly Property DeleteSelectedBehavior() As AnnotationMarkerDeleteBehavior - Get - Return AnnotationMarkerDeleteBehavior.RemoveAnnotation - End Get -End Property - -```` - -{{endregion}} - -* You can also define custom properties in your annotation range start/end. If you want to be able to serialize them, you can just mark them with the **XamlSerializable** attribute: - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\CustomAnnotations.cs region=name}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\CustomAnnotations.vb region=name}} - -````C# - -[XamlSerializable] -public string Name { get; set; } - -```` -````VB.NET - -Public Property Name() As String - -```` - -{{endregion}} - -## Serialization - -Of the default document format providers, custom annotations are supported only in XAML. The other formats do not offer such extensibility. When exporting to XAML, the exporter will generate prefixes for each custom annotation namespace (custom1, custom2, etc.). Serialization is handled by **XamlFormatProvider** which looks for properties with the appropriate attributes: **XamlSerializable** (as inline properties) and **XamlCompositePropertySerializable** (as XAML composite properties). - diff --git a/controls/richtexteditor/document-elements/annotations/manipulating-annotations.md b/controls/richtexteditor/document-elements/annotations/manipulating-annotations.md index ac5cadb85..dd70e7be8 100644 --- a/controls/richtexteditor/document-elements/annotations/manipulating-annotations.md +++ b/controls/richtexteditor/document-elements/annotations/manipulating-annotations.md @@ -1,188 +1,104 @@ ---- -title: Manipulating Annotations -page_title: Manipulating Annotations - WinForms RadRichTextEditor Control -description: Learn which are the most commonly used manipulations with regard to Annotations in the WinForms RadRichTextEditor control. -slug: winforms/richtexteditor-/document-elements/annotations/manipulating-annotations -tags: manipulating,annotations -published: True -position: 1 -previous_url: richtexteditor-document-elements-annotations-manipulating-annotations ---- - -# Manipulating Annotations - -This article outlines the most commonly used manipulations with regard to **Annotations**. - -The types of manipulations that can be performed on annotations include: - -* Presentation in the document; - -* Retrieving annotations; - -* Inserting an annotation; - -* Deleting an annotation; - -* Splitting an annotation at a given position. - -## Presentation - -By default, all annotations are markup-only in the sense that they do not have any appearance. If you want to display a highlight, range brackets or anything else, you can use the UI layers feature of **RadRichTextEditor**. You can read more about them in [this article]({%slug winforms/richtexteditor-/how-to/customize-presentation-through-ui-layers%}). - -## Methods for Retrieving Annotations - -* **RadDocument** exposes the following general methods for retrieving annotation markers or checking if such exist in the document at all: - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\ManipulatingAnnotations.cs region=contains}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\ManipulatingAnnotations.vb region=contains}} - -````C# -bool containsBookamrks = this.radRichTextEditor1.Document.ContainsAnnotationMarkersOfType(); -IEnumerable markers = this.radRichTextEditor1.Document.GetAnnotationMarkersOfType(); - -```` -````VB.NET -Dim containsBookamrks As Boolean = Me.radRichTextEditor1.Document.ContainsAnnotationMarkersOfType(Of BookmarkRangeStart)() -Dim markers As IEnumerable(Of BookmarkRangeStart) = Me.radRichTextEditor1.Document.GetAnnotationMarkersOfType(Of BookmarkRangeStart)() - -```` - -{{endregion}} - -* Methods for retrieving the containing annotations around a particular inline. This is particularly convenient if you would like to perform checks against the position where the caret is at. First, you can obtain the current inline like this: - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\ManipulatingAnnotations.cs region=inline}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\ManipulatingAnnotations.vb region=inline}} - -````C# -Inline currentInline = this.radRichTextEditor1.Document.CaretPosition.GetCurrentInline(); - -```` -````VB.NET -Dim currentInline As Inline = Me.radRichTextEditor1.Document.CaretPosition.GetCurrentInline() - -```` - -{{endregion}} - -and then, check if this inline is contained in a range using one of the methods below: - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\ManipulatingAnnotations.cs region=inRange}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\ManipulatingAnnotations.vb region=inRange}} - -````C# -bool isInRange = this.radRichTextEditor1.Document.IsInAnnotationRange(inline); -IEnumerable ranges = this.radRichTextEditor1.Document.GetContainingAnnotationRanges(inline); - -```` -````VB.NET -Dim isInRange As Boolean = Me.radRichTextEditor1.Document.IsInAnnotationRange(Of BookmarkRangeStart)(inline) -Dim ranges As IEnumerable(Of BookmarkRangeStart) = Me.radRichTextEditor1.Document.GetContainingAnnotationRanges(Of BookmarkRangeStart)(inline) - -```` -{{endregion}} - -* More finely tuned methods that filter the annotation ranges at the time of their retrieval include: - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\ManipulatingAnnotations.cs region=inRange1}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\ManipulatingAnnotations.vb region=inRange1}} - -````C# -bool isInRange1 = this.radRichTextEditor1.Document.IsInAnnotationRange(inline, Filter, true); -IEnumerable ranges1 = this.radRichTextEditor1.Document.GetContainingAnnotationRanges(inline, Filter, true); - -```` -````VB.NET -Dim isInRange1 As Boolean = Me.radRichTextEditor1.Document.IsInAnnotationRange(Of BookmarkRangeStart)(inline, AddressOf Filter, True) -Dim ranges1 As IEnumerable(Of BookmarkRangeStart) = Me.radRichTextEditor1.Document.GetContainingAnnotationRanges(Of BookmarkRangeStart)(inline, AddressOf Filter, True) - -```` - -{{endregion}} - - -## Inserting Annotations - -Annotations can be inserted in the document using the following method of [RadDocumentEditor]({%slug winforms/richtexteditor-/features/raddocumenteditor%}). - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\ManipulatingAnnotations.cs region=insert}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\ManipulatingAnnotations.vb region=insert}} - -````C# -documentEditor.InsertAnnotationRange(new BookmarkRangeStart(), new BookmarkRangeEnd()); - -```` -````VB.NET -documentEditor.InsertAnnotationRange(New BookmarkRangeStart(), New BookmarkRangeEnd()) - -```` - -{{endregion}} - -There are also some methods that insert specific types of annotations for the commonly used types, such as Hyperlinks, Comments, etc. For more information, check the respective article. - -## Deleting Annotations - -In order to delete an annotation, you need to obtain a reference to its range start first. After that, you can use the following method of [RadDocumentEditor]({%slug winforms/richtexteditor-/features/raddocumenteditor%}) to remove it. - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\ManipulatingAnnotations.cs region=delete}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\ManipulatingAnnotations.vb region=delete}} - -````C# -documentEditor.DeleteAnnotationRange(start); - -```` -````VB.NET -documentEditor.DeleteAnnotationRange(start) - -```` - -{{endregion}} - -Note that this method will remove the annotation, but will keep its contents. In order to delete the contents as well, you can select it and use the **Delete** method of the editor: - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\ManipulatingAnnotations.cs region=delete1}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\ManipulatingAnnotations.vb region=delete1}} - -````C# -documentEditor.Document.Selection.SelectAnnotationRange(start); -documentEditor.Delete(false); - -```` -````VB.NET -documentEditor.Document.Selection.SelectAnnotationRange(start) -documentEditor.Delete(False) - -```` - -{{endregion}} - -There are also some methods that remove specific types of annotations for the commonly used types, such as **Hyperlinks**, **Comments**, etc. For more information, check the respective article. - -## Splitting Annotations - -Some user scenarios require that there would be an easy way to split annotation ranges. In such cases, one can use the following methods: - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\ManipulatingAnnotations.cs region=split}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\ManipulatingAnnotations.vb region=split}} - -````C# -documentEditor.SplitAnnotationRange(start); -//or -documentEditor.SplitAnnotationRange(start, documentPosition); - -```` -````VB.NET -documentEditor.SplitAnnotationRange(start) -'or -documentEditor.SplitAnnotationRange(start, documentPosition) - -```` - -{{endregion}} - -# See Also - - * [Annotations]({%slug winforms/richtexteditor-/document-elements/annotations%}) - - * [Custom Annotations]({%slug winforms/richtexteditor-/document-elements/annotations/custom-annotations%}) +--- +title: Manipulating Annotations +page_title: Manipulating Annotations - WinForms RadRichTextEditor Control +description: Learn which are the most commonly used manipulations with regard to Annotations in the WinForms RadRichTextEditor control. +slug: winforms/richtexteditor-/document-elements/annotations/manipulating-annotations +tags: manipulating,annotations +published: True +position: 1 +previous_url: richtexteditor-document-elements-annotations-manipulating-annotations +--- + +# Manipulating Annotations + +This article outlines the most commonly used manipulations with regard to **Annotations**. + +The types of manipulations that can be performed on annotations include: + +* Presentation in the document; + +* Retrieving annotations; + +* Inserting an annotation; + +* Deleting an annotation; + +* Splitting an annotation at a given position. + +## Presentation + +By default, all annotations are markup-only in the sense that they do not have any appearance. If you want to display a highlight, range brackets or anything else, you can use the UI layers feature of **RadRichTextEditor**. You can read more about them in [this article]({%slug winforms/richtexteditor-/how-to/customize-presentation-through-ui-layers%}). + +## Methods for Retrieving Annotations + +* **RadDocument** exposes the following general methods for retrieving annotation markers or checking if such exist in the document at all: + + + + + + +* Methods for retrieving the containing annotations around a particular inline. This is particularly convenient if you would like to perform checks against the position where the caret is at. First, you can obtain the current inline like this: + + + + + + +and then, check if this inline is contained in a range using one of the methods below: + + + + + + +* More finely tuned methods that filter the annotation ranges at the time of their retrieval include: + + + + + + +## Inserting Annotations + +Annotations can be inserted in the document using the following method of [RadDocumentEditor]({%slug winforms/richtexteditor-/features/raddocumenteditor%}). + + + + + + +There are also some methods that insert specific types of annotations for the commonly used types, such as Hyperlinks, Comments, etc. For more information, check the respective article. + +## Deleting Annotations + +In order to delete an annotation, you need to obtain a reference to its range start first. After that, you can use the following method of [RadDocumentEditor]({%slug winforms/richtexteditor-/features/raddocumenteditor%}) to remove it. + + + + + + +Note that this method will remove the annotation, but will keep its contents. In order to delete the contents as well, you can select it and use the **Delete** method of the editor: + + + + + + +There are also some methods that remove specific types of annotations for the commonly used types, such as **Hyperlinks**, **Comments**, etc. For more information, check the respective article. + +## Splitting Annotations + +Some user scenarios require that there would be an easy way to split annotation ranges. In such cases, one can use the following methods: + + + + + + +# See Also + + * [Annotations]({%slug winforms/richtexteditor-/document-elements/annotations%}) + + * [Custom Annotations]({%slug winforms/richtexteditor-/document-elements/annotations/custom-annotations%}) diff --git a/controls/richtexteditor/document-elements/break.md b/controls/richtexteditor/document-elements/break.md index 7df3cc6d0..7efec6ca7 100644 --- a/controls/richtexteditor/document-elements/break.md +++ b/controls/richtexteditor/document-elements/break.md @@ -1,72 +1,47 @@ ---- -title: Break -page_title: Break - WinForms RadRichTextEditor Control -description: Break element in the WinForms RadRichTextEditor control is an inline-level flow content element, which indicates that a break should be placed at the current position. -slug: winforms/richtextEditor/break -tags: properties,and,methods -published: True -position: 8 ---- - -# Break - -Break element is an inline-level flow content element, which indicates that a break should be placed at the current position. There are three types of breaks: - -* __Line Break__: Breaks the current line and starts a new one. - -* __Page Break__: Breaks the current page and starts a new one. - -* __Column Break__: Breaks the current [section column]({%slug winforms/richtextEditor/section-columns%}) and starts a new one. If the current section is not divided into columns, or the column break occurs in the last column on the current page, then the restart location for text will be the next page of the document. - -## Inserting a Break - -The Break elements can be used only in the context of a **Paragraph** element. The [Paragraph]({%slug winforms/richtexteditor-/document-elements/paragraph%}) exposes a collection of __Inlines__, to which the breaks can be added. __Example 1__ shows how to achieve this. - -#### Example 1: Insert a break - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\BreakCode.cs region=AddBreak}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\BreakCode.vb region=AddBreak}} -````C# -Section section = new Section(); -Paragraph paragraph = new Paragraph(); -Break br = new Break(BreakType.PageBreak); -paragraph.Inlines.Add(br); -section.Blocks.Add(paragraph); - -```` -````VB.NET -Dim section As New Section() -Dim paragraph As New Paragraph() -Dim br As New Break(BreakType.PageBreak) -paragraph.Inlines.Add(br) -section.Blocks.Add(paragraph) - -```` - -{{endregion}} - -## Modifying a Break - -The __Break__ element exposes a __BreakType__ property, which specifies the type of the break. __Example 2__ demonstrates how to change it. - -#### Example 2: Modify a break - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\BreakCode.cs region=ModifyBreak}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\BreakCode.vb region=ModifyBreak}} -````C# -br.BreakType = BreakType.LineBreak; - -```` -````VB.NET -br.BreakType = BreakType.LineBreak - -```` - -{{endregion}} - - -# See Also - - * [Elements Hierarchy]({%slug winforms/richtexteditor-/document-elements%}) - * [RadDocument]({%slug winforms/richtexteditor-/document-elements/raddocument%}) - * [Section]({%slug winforms/richtexteditor-/document-elements/section%}) +--- +title: Break +page_title: Break - WinForms RadRichTextEditor Control +description: Break element in the WinForms RadRichTextEditor control is an inline-level flow content element, which indicates that a break should be placed at the current position. +slug: winforms/richtextEditor/break +tags: properties,and,methods +published: True +position: 8 +--- + +# Break + +Break element is an inline-level flow content element, which indicates that a break should be placed at the current position. There are three types of breaks: + +* __Line Break__: Breaks the current line and starts a new one. + +* __Page Break__: Breaks the current page and starts a new one. + +* __Column Break__: Breaks the current [section column]({%slug winforms/richtextEditor/section-columns%}) and starts a new one. If the current section is not divided into columns, or the column break occurs in the last column on the current page, then the restart location for text will be the next page of the document. + +## Inserting a Break + +The Break elements can be used only in the context of a **Paragraph** element. The [Paragraph]({%slug winforms/richtexteditor-/document-elements/paragraph%}) exposes a collection of __Inlines__, to which the breaks can be added. __Example 1__ shows how to achieve this. + +#### Example 1: Insert a break + + + + + + +## Modifying a Break + +The __Break__ element exposes a __BreakType__ property, which specifies the type of the break. __Example 2__ demonstrates how to change it. + +#### Example 2: Modify a break + + + + + + +# See Also + + * [Elements Hierarchy]({%slug winforms/richtexteditor-/document-elements%}) + * [RadDocument]({%slug winforms/richtexteditor-/document-elements/raddocument%}) + * [Section]({%slug winforms/richtexteditor-/document-elements/section%}) diff --git a/controls/richtexteditor/document-elements/inline-image.md b/controls/richtexteditor/document-elements/inline-image.md index 645f40d58..d861b2c4e 100644 --- a/controls/richtexteditor/document-elements/inline-image.md +++ b/controls/richtexteditor/document-elements/inline-image.md @@ -1,113 +1,48 @@ ---- -title: Inline Image -page_title: Inline Image - WinForms RichTextEditor Control -description: Winforms RadRichTextEditor supports ImageInline that allows images to be displayed inside the document. -slug: winforms/richtexteditor-/document-elements/inline-image -tags: inline,image -published: True -position: 4 -previous_url: richtexteditor-document-elements-inline-image ---- - -# Inline Image - -The __ImageInline__ class allows images to be displayed inside the document. The __ImageInline__ can only be used in the context of a __Paragraph__ class. As it is an inline element, it gets placed after the previous inline element until the end of the line. If there is no space left, the element will be wrapped on the next line. - -This topic will explain you how to use the __ImageInline__ element. - -## Add in Code Behind - -Here is an example of how to add an __ImageInline__ element in the code behind. - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\InlineImageCode.cs region=image}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\InlineImageCode.vb region=image}} - -````C# - -Section section = new Section(); -Paragraph paragraph = new Paragraph(); -ImageInline image; -Telerik.WinControls.RichTextEditor.UI.Size size = new Telerik.WinControls.RichTextEditor.UI.Size(236, 50); -using (MemoryStream ms = new MemoryStream()) -{ - Image.FromFile(@"C:\logo.png").Save(ms, System.Drawing.Imaging.ImageFormat.Png); - image = new ImageInline(ms, size, "png"); -} - -paragraph.Inlines.Add(image); -section.Children.Add(paragraph); -this.radRichTextEditor1.Document.Sections.Add(section); - -```` -````VB.NET -Dim section As New Section() -Dim paragraph As New Paragraph() -Dim image As ImageInline -Dim my_size As New Telerik.WinControls.RichTextEditor.UI.Size(236, 50) -Using ms As New MemoryStream() - System.Drawing.Image.FromFile("C:\logo.png").Save(ms, System.Drawing.Imaging.ImageFormat.Png) - image = New ImageInline(ms, my_size, "png") -End Using -paragraph.Inlines.Add(image) -section.Children.Add(paragraph) -Me.radRichTextEditor1.Document.Sections.Add(section) - -```` - -{{endregion}} - -## Add via UI - -Here is an example of how to allow the user to select an image and add it to the document. For that purpose a __RadButton__ and an __OpenFileDialog__ are used. When the file stream from the __OpenFileDialog__ gets obtained, it's passed to the __InsertImage()__ API method of __RadRichTextEditor__. This method takes as an argument the extension of the image, which can be again obtained from the __FileInfo__ object. After calling the __InsertImage()__ method, the image will appear in the document with its default width and height. - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\InlineImageCode.cs region=insert}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\InlineImageCode.vb region=insert}} - -````C# - -private void ImageButton_Click(object sender, RoutedEventArgs e) -{ - OpenFileDialog openDialog = new OpenFileDialog(); - openDialog.Filter = "Images|*.jpg;*.png"; - openDialog.Multiselect = false; - DialogResult dialogResult = openDialog.ShowDialog(); - if (dialogResult == DialogResult.Yes) - { - Stream stream = openDialog.OpenFile(); - - string extension = Path.GetExtension(openDialog.FileName); - this.radRichTextEditor1.InsertImage(stream, extension); - } -} - -```` -````VB.NET -Private Sub ImageButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) - Dim openDialog As New OpenFileDialog() - openDialog.Filter = "Images|*.jpg;*.png" - openDialog.Multiselect = False - Dim myDialogResult As DialogResult = openDialog.ShowDialog() - If myDialogResult = System.Windows.Forms.DialogResult.Yes Then - Dim stream As Stream = openDialog.OpenFile() - Dim extension As String = Path.GetExtension(openDialog.FileName) - Me.radRichTextEditor1.InsertImage(stream, extension) - End If -End Sub - -```` - -{{endregion}} - -# See Also - - * [Document Elements]({%slug winforms/richtexteditor-/document-elements%}) - - * [Section]({%slug winforms/richtexteditor-/document-elements/section%}) - - * [Paragraph]({%slug winforms/richtexteditor-/document-elements/paragraph%}) - - * [Span]({%slug winforms/richtexteditor-/document-elements/span%}) - - * [Editing Images]({%slug winforms/richtexteditor-/ui-for-applying-rich-text-formatting/editing-images%}) - - * [Hyperlink]({%slug winforms/richtexteditor-/features/hyperlink%}) +--- +title: Inline Image +page_title: Inline Image - WinForms RichTextEditor Control +description: Winforms RadRichTextEditor supports ImageInline that allows images to be displayed inside the document. +slug: winforms/richtexteditor-/document-elements/inline-image +tags: inline,image +published: True +position: 4 +previous_url: richtexteditor-document-elements-inline-image +--- + +# Inline Image + +The __ImageInline__ class allows images to be displayed inside the document. The __ImageInline__ can only be used in the context of a __Paragraph__ class. As it is an inline element, it gets placed after the previous inline element until the end of the line. If there is no space left, the element will be wrapped on the next line. + +This topic will explain you how to use the __ImageInline__ element. + +## Add in Code Behind + +Here is an example of how to add an __ImageInline__ element in the code behind. + + + + + + +## Add via UI + +Here is an example of how to allow the user to select an image and add it to the document. For that purpose a __RadButton__ and an __OpenFileDialog__ are used. When the file stream from the __OpenFileDialog__ gets obtained, it's passed to the __InsertImage()__ API method of __RadRichTextEditor__. This method takes as an argument the extension of the image, which can be again obtained from the __FileInfo__ object. After calling the __InsertImage()__ method, the image will appear in the document with its default width and height. + + + + + + +# See Also + + * [Document Elements]({%slug winforms/richtexteditor-/document-elements%}) + + * [Section]({%slug winforms/richtexteditor-/document-elements/section%}) + + * [Paragraph]({%slug winforms/richtexteditor-/document-elements/paragraph%}) + + * [Span]({%slug winforms/richtexteditor-/document-elements/span%}) + + * [Editing Images]({%slug winforms/richtexteditor-/ui-for-applying-rich-text-formatting/editing-images%}) + + * [Hyperlink]({%slug winforms/richtexteditor-/features/hyperlink%}) diff --git a/controls/richtexteditor/document-elements/inlinieuicontainer.md b/controls/richtexteditor/document-elements/inlinieuicontainer.md index 9ff5eaa83..5f092d2c2 100644 --- a/controls/richtexteditor/document-elements/inlinieuicontainer.md +++ b/controls/richtexteditor/document-elements/inlinieuicontainer.md @@ -31,43 +31,10 @@ You can add any element that derives from the **RadElement** class inside the __ >note The following article contains more information about the element types which can be used inside the document: [Elements Overview]({%slug winforms/telerik-presentation-framework/elements/overview%}). > -{{source=..\SamplesCS\RichTextEditor\DocumentElements\UIContainerCode.cs region=add}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\UIContainerCode.vb region=add}} + + + -````C# - -RadButtonElement button = new RadButtonElement(); -button.Text = "My Button"; - -Section section = new Section(); -Paragraph paragraph = new Paragraph(); -InlineUIContainer container = new InlineUIContainer(); -RadElementUIContainer radContainer = new RadElementUIContainer(button); -container.UiElement = radContainer; -container.Height = 25; -container.Width = 70; -paragraph.Inlines.Add(container); -section.Blocks.Add(paragraph); -this.radRichTextEditor1.Document.Sections.Add(section); - -```` -````VB.NET -Dim button As New RadButtonElement() -button.Text = "My Button" -Dim section As New Section() -Dim paragraph As New Paragraph() -Dim container As New InlineUIContainer() -Dim radContainer As New RadElementUIContainer(button) -container.UiElement = radContainer -container.Height = 25 -container.Width = 70 -paragraph.Inlines.Add(container) -section.Blocks.Add(paragraph) -Me.radRichTextEditor1.Document.Sections.Add(section) - -```` - -{{endregion}} ## Specifics @@ -86,95 +53,10 @@ To enable copying of **InlineUIContainers** in your application, you can create #### Implement CopyableInlineUIContainer for a RadButtonElement as underlying UIElement -{{source=..\SamplesCS\RichTextEditor\DocumentElements\UIContainerCode.cs region=CopyableContainer}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\UIContainerCode.vb region=CopyableContainer}} - -````C# - - public class CopyableInlineUIContainer : InlineUIContainer - { - internal CopyableInlineUIContainer() - { - } - - public CopyableInlineUIContainer(Telerik.WinControls.RichTextEditor.UI.UIElement uiElement, - Telerik.WinControls.RichTextEditor.UI.Size size) : base(uiElement, size) - { - } - - public override bool IsCopyable - { - get - { - return true; - } - } - - protected override DocumentElement CreateNewElementInstance() - { - return new CopyableInlineUIContainer(); - } - - protected override void CopyPropertiesFromOverride(DocumentElement fromElement) - { - CopyableInlineUIContainer fromUIContainer = (CopyableInlineUIContainer)fromElement; - this.Width = fromUIContainer.Width; - this.Height = fromUIContainer.Height; - - RadElementUIContainer originalContainer = (RadElementUIContainer)fromUIContainer.UiElement; - RadButtonElement originalButton = originalContainer.Element as RadButtonElement; - - RadButtonElement newButton = new RadButtonElement(); - - newButton.Text = originalButton.Text; - Telerik.WinControls.RichTextEditor.UI.RadElementUIContainer newContainer = new RadElementUIContainer(newButton); - newContainer.Width = originalContainer.Width; - newContainer.Height = originalContainer.Height; - this.UiElement = newContainer; - } - } - -```` -````VB.NET - - Public Class CopyableInlineUIContainer - Inherits InlineUIContainer - - Friend Sub New() - End Sub - - Public Sub New(ByVal uiElement As Telerik.WinControls.RichTextEditor.UI.UIElement, ByVal size As Telerik.WinControls.RichTextEditor.UI.Size) - MyBase.New(uiElement, size) - End Sub - - Public Overrides ReadOnly Property IsCopyable As Boolean - Get - Return True - End Get - End Property - - Protected Overrides Function CreateNewElementInstance() As DocumentElement - Return New CopyableInlineUIContainer() - End Function - - Protected Overrides Sub CopyPropertiesFromOverride(ByVal fromElement As DocumentElement) - Dim fromUIContainer As CopyableInlineUIContainer = CType(fromElement, CopyableInlineUIContainer) - Me.Width = fromUIContainer.Width - Me.Height = fromUIContainer.Height - Dim originalContainer As RadElementUIContainer = CType(fromUIContainer.UiElement, RadElementUIContainer) - Dim originalButton As RadButtonElement = TryCast(originalContainer.Element, RadButtonElement) - Dim newButton As RadButtonElement = New RadButtonElement() - newButton.Text = originalButton.Text - Dim newContainer As Telerik.WinControls.RichTextEditor.UI.RadElementUIContainer = New RadElementUIContainer(newButton) - newContainer.Width = originalContainer.Width - newContainer.Height = originalContainer.Height - Me.UiElement = newContainer - End Sub - End Class - -```` - -{{endregion}} + + + + ## Import Export InlineUIContainers diff --git a/controls/richtexteditor/document-elements/paragraph.md b/controls/richtexteditor/document-elements/paragraph.md index 1cb6959b8..e64fff3d2 100644 --- a/controls/richtexteditor/document-elements/paragraph.md +++ b/controls/richtexteditor/document-elements/paragraph.md @@ -1,127 +1,81 @@ ---- -title: Paragraph -page_title: Paragraph - WinForms RichTextEditor Control -description: Get familiar with the the paragraph class in WinForms RichTextEditor that allows you to separate the content into paragraphs. -slug: winforms/richtexteditor-/document-elements/paragraph -tags: paragraph -published: True -position: 2 -previous_url: richtexteditor-document-elements-paragraph ---- - -# Paragraph - -The paragraph class allows you to separate the content into paragraphs. It is responsible for displaying inline elements such as __Span__, __HyperlinkRangeStart__ and __End__, __InlineImage__ etc. You are also able to configure the appearance of the paragraph by modifying its parameters. - -This topic will explain you how to: - -* [Use Paragraphs](#use-paragraphs) - -* [Add inline elements to a Paragraph](#add-inline-elements-to-a-paragraph) - -* [Customize the Paragraph](#customize-the-paragraph) - -## Use Paragraphs - -The __Paragraph__ can be used only in the context of a [Section]({%slug winforms/richtexteditor-/document-elements/section%}) or a **TableCell** element. The section exposes a collection of **Blocks**, to which the paragraphs can be added. - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\ParagraphCode.cs region=section}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\ParagraphCode.vb region=section}} - -````C# +--- +title: Paragraph +page_title: Paragraph - WinForms RichTextEditor Control +description: Get familiar with the the paragraph class in WinForms RichTextEditor that allows you to separate the content into paragraphs. +slug: winforms/richtexteditor-/document-elements/paragraph +tags: paragraph +published: True +position: 2 +previous_url: richtexteditor-document-elements-paragraph +--- + +# Paragraph + +The paragraph class allows you to separate the content into paragraphs. It is responsible for displaying inline elements such as __Span__, __HyperlinkRangeStart__ and __End__, __InlineImage__ etc. You are also able to configure the appearance of the paragraph by modifying its parameters. + +This topic will explain you how to: + +* [Use Paragraphs](#use-paragraphs) + +* [Add inline elements to a Paragraph](#add-inline-elements-to-a-paragraph) + +* [Customize the Paragraph](#customize-the-paragraph) + +## Use Paragraphs + +The __Paragraph__ can be used only in the context of a [Section]({%slug winforms/richtexteditor-/document-elements/section%}) or a **TableCell** element. The section exposes a collection of **Blocks**, to which the paragraphs can be added. + + + + + + +## Add inline elements to a Paragraph + +To add inline elements such as **Span**, **HyperlinkRangeStart** and **End**, or **InlineImage** you have to use the **Inlines** collection of the **Paragraph**. + + + + + + +## Customize the Paragraph + +The __Paragraph__ exposes several properties that allow you to customize the layout of the elements placed underneath it. Here is a list of them: + +* __FontSize__ - represents the font size of the text inside the __Paragraph__. If not explicitly set to its child elements, they inherit its value. + +* __LineSpacing__ - specifies the value for the space between the lines. + +* __LineSpacingType - specifies the type of spacing:__ + + * __AtLeast -__ the space between the lines should be equal or greater than the value of the __LineSpacing__ property. + + * __Auto -__ the space between the lines is determined automatically. + + * __Exact -__ the space between the lines should be equal to the value of the __LineSpacing__ property. + +* __LeftIndent -__ represents the size of the indent to the left size of the __Paragraph__. The indent gets applied together with the respective margins to the layout. + +* __RightIndent__ - represents the size of the indent to the right size of the __Paragraph__. The indent gets applied together with the respective margins to the layout. + +* __SpacingAfter__ - represents the size of the empty space after the __Paragraph__. + +* __SpacingBefore__ - represents the size of the empty space before the __Paragraph__. + +* __TextAlignment__ - represents the alignment of the text inside the __Paragraph__. -Section section = new Section(); -Paragraph paragraph = new Paragraph(); -section.Blocks.Add(paragraph); -RadDocument document = new RadDocument(); -document.Sections.Add(section); - -this.radRichTextEditor1.Document = document; - -```` -````VB.NET -Dim section As New Section() -Dim paragraph As New Paragraph() -section.Blocks.Add(paragraph) -Dim document As New RadDocument() -document.Sections.Add(section) -Me.radRichTextEditor1.Document = document - -```` - -{{endregion}} - -## Add inline elements to a Paragraph - -To add inline elements such as **Span**, **HyperlinkRangeStart** and **End**, or **InlineImage** you have to use the **Inlines** collection of the **Paragraph**. - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\ParagraphCode.cs region=inline}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\ParagraphCode.vb region=inline}} - -````C# - -Section section = new Section(); -Paragraph paragraph = new Paragraph(); -Span span = new Span("Span declared in code-behind"); -paragraph.Inlines.Add(span); -section.Blocks.Add(paragraph); -RadDocument document = new RadDocument(); -document.Sections.Add(section); - -this.radRichTextEditor1.Document = document; - -```` -````VB.NET -Dim section As New Section() -Dim paragraph As New Paragraph() -Dim span As New Span("Span declared in code-behind") -paragraph.Inlines.Add(span) -section.Blocks.Add(paragraph) -Dim document As New RadDocument() -document.Sections.Add(section) -Me.radRichTextEditor1.Document = document - -```` - -{{endregion}} - -## Customize the Paragraph - -The __Paragraph__ exposes several properties that allow you to customize the layout of the elements placed underneath it. Here is a list of them: - -* __FontSize__ - represents the font size of the text inside the __Paragraph__. If not explicitly set to its child elements, they inherit its value. - -* __LineSpacing__ - specifies the value for the space between the lines. - -* __LineSpacingType - specifies the type of spacing:__ - - * __AtLeast -__ the space between the lines should be equal or greater than the value of the __LineSpacing__ property. - - * __Auto -__ the space between the lines is determined automatically. - - * __Exact -__ the space between the lines should be equal to the value of the __LineSpacing__ property. - -* __LeftIndent -__ represents the size of the indent to the left size of the __Paragraph__. The indent gets applied together with the respective margins to the layout. - -* __RightIndent__ - represents the size of the indent to the right size of the __Paragraph__. The indent gets applied together with the respective margins to the layout. - -* __SpacingAfter__ - represents the size of the empty space after the __Paragraph__. - -* __SpacingBefore__ - represents the size of the empty space before the __Paragraph__. - -* __TextAlignment__ - represents the alignment of the text inside the __Paragraph__. - - -# See Also - - * [Document Elements]({%slug winforms/richtexteditor-/document-elements%}) - - * [RadDocument]({%slug winforms/richtexteditor-/document-elements/raddocument%}) - - * [Section]({%slug winforms/richtexteditor-/document-elements/section%}) - - * [Span]({%slug winforms/richtexteditor-/document-elements/span%}) - - * [Inline Image]({%slug winforms/richtexteditor-/document-elements/inline-image%}) - - * [Hyperlink]({%slug winforms/richtexteditor-/features/hyperlink%}) + +# See Also + + * [Document Elements]({%slug winforms/richtexteditor-/document-elements%}) + + * [RadDocument]({%slug winforms/richtexteditor-/document-elements/raddocument%}) + + * [Section]({%slug winforms/richtexteditor-/document-elements/section%}) + + * [Span]({%slug winforms/richtexteditor-/document-elements/span%}) + + * [Inline Image]({%slug winforms/richtexteditor-/document-elements/inline-image%}) + + * [Hyperlink]({%slug winforms/richtexteditor-/features/hyperlink%}) diff --git a/controls/richtexteditor/document-elements/raddocument.md b/controls/richtexteditor/document-elements/raddocument.md index 0ede3c77c..f4cbbcc6e 100644 --- a/controls/richtexteditor/document-elements/raddocument.md +++ b/controls/richtexteditor/document-elements/raddocument.md @@ -1,127 +1,105 @@ ---- -title: RadDocument -page_title: RadDocument - WinForms RichTextEditor Control -description: RadDocument is the root element for WinForms RadRichTextEditor's content. It holds the collection of Sections defined for the RadRichTextEditor's content. -slug: winforms/richtexteditor-/document-elements/raddocument -tags: raddocument -published: True -position: 1 -previous_url: richtexteditor-document-elements-raddocument ---- - -# RadDocument - -__RadDocument__ is the root element for __RadRichTextEditor's__ content. It holds the collection of __Sections__ defined for the __RadRichTextEditor__ content. It also allows you to configure the appearance of its child elements. - -This topic will explain how you can customize the contents of the **RadDocument**. - -* [Customizing a RadDocument](#customize-the-contents-of-raddocument) - -* [Specifics](#specifics) - -* [Adding Sections to a RadDocument](#adding-sections-to-raddocument) - -## Customize the contents of RadDocument - -__RadDocument__ exposes several properties that allow you to customize the layout of the elements placed underneath it. Here is a list of them: - -* __LayoutMode__ - specifies whether the page should be in *Paged*, *Flow* or *FlowNoWrap* layout mode. To learn more about layout modes read [here]({%slug winforms/richtexteditor-/getting-started/layout-modes%}). - -* __DefaultPageLayoutSettings__ - this property is of type __PageLayoutSettings__. The __PageLayoutSettings__ class exposes the following properties: - - * __Height__ - represents the height of the page. - - * __Width__ - represents the width of the page. - ->note The __DefaultPageLayoutSettings__ get applied only when Paged layout mode is used. -> - - -* __SectionDefaultPageMargin__ - defines the default margin for each of the sections in the **RadDocument**. To assign different margins for each of the sections use the respective property of the __Section__ class. - -* __ParagraphDefaultSpacingAfter__ - defines the default spacing after for each of the paragraphs in the __RadDocument__. To assign different spacing after for each of the paragraphs use the respective property of the __Paragraph__ class. - -* __ParagraphDefaultSpacingBefore__ - defines the default spacing before for each of the paragraphs in the __RadDocument__. To assign different spacing before for each of the paragraphs use the respective property of the __Paragraph__ class. - -* __LineSpacing__ - specifies the value for the space between the lines. - -* __LineSpacingType - specifies the type of spacing:__ - - * __AtLeast -__ the space between the lines should be equal or greater than the value of the __LineSpacing__ property. - - * __Auto -__ the space between the lines is determined automatically. - - * __Exact -__ the space between the lines should be equal to the value of the __LineSpacing__ property. - -* __ShowFormattingSymbols__ - indicates whether the formatting symbols should be displayed or not. - -## Specifics - -The first time a __RadDocument__ is shown inside a __RadRichTextEditor__ in the Visual Tree, it is measured by the framework and arranges its children. This is the moment when the layout cycle is completed, each of the document elements calculates its size and arranges its children. - -As the two states of the document - measured and not measured are too different, distinct methods for manipulating the content of the document should be used before the document is measured and after the first time that it is shown in the editor. - -## Adding Sections to RadDocument - -As explained in the previous section, the state of the document is essential for the methods that can be used on it. - -For example, you can build a **RadDocument** from scratch and add **Sections** to it in the following way: - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\RadDocumentCode.cs region=section}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\RadDocumentCode.vb region=section}} - -````C# +--- +title: RadDocument +page_title: RadDocument - WinForms RichTextEditor Control +description: RadDocument is the root element for WinForms RadRichTextEditor's content. It holds the collection of Sections defined for the RadRichTextEditor's content. +slug: winforms/richtexteditor-/document-elements/raddocument +tags: raddocument +published: True +position: 1 +previous_url: richtexteditor-document-elements-raddocument +--- + +# RadDocument + +__RadDocument__ is the root element for __RadRichTextEditor's__ content. It holds the collection of __Sections__ defined for the __RadRichTextEditor__ content. It also allows you to configure the appearance of its child elements. + +This topic will explain how you can customize the contents of the **RadDocument**. + +* [Customizing a RadDocument](#customize-the-contents-of-raddocument) + +* [Specifics](#specifics) + +* [Adding Sections to a RadDocument](#adding-sections-to-raddocument) + +## Customize the contents of RadDocument + +__RadDocument__ exposes several properties that allow you to customize the layout of the elements placed underneath it. Here is a list of them: + +* __LayoutMode__ - specifies whether the page should be in *Paged*, *Flow* or *FlowNoWrap* layout mode. To learn more about layout modes read [here]({%slug winforms/richtexteditor-/getting-started/layout-modes%}). + +* __DefaultPageLayoutSettings__ - this property is of type __PageLayoutSettings__. The __PageLayoutSettings__ class exposes the following properties: -Section section = new Section(); -this.radRichTextEditor1.Document.Sections.Add(section); - -```` -````VB.NET -Dim section As New Section() -Me.radRichTextEditor1.Document.Sections.Add(section) - -```` - -{{endregion}} - -Splitting an already measured document into two sections at the current caret position, on the other hand, can be done by inserting a section break: - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\RadDocumentCode.cs region=break}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\RadDocumentCode.vb region=break}} - -````C# + * __Height__ - represents the height of the page. + + * __Width__ - represents the width of the page. + +>note The __DefaultPageLayoutSettings__ get applied only when Paged layout mode is used. +> + + +* __SectionDefaultPageMargin__ - defines the default margin for each of the sections in the **RadDocument**. To assign different margins for each of the sections use the respective property of the __Section__ class. -this.radRichTextEditor1.InsertSectionBreak(SectionBreakType.NextPage); - -```` -````VB.NET -Me.radRichTextEditor1.InsertSectionBreak(SectionBreakType.NextPage) - -```` - -{{endregion}} - -The method accept a parameter of type **SectionBreakType**. The possible values are: - -* SectionBreakType.*NextPage* - the default value. The next section will start on the next page. - -* SectionBreakType.*OddPage* - the next section will start on the next odd page. - -* SectionBreakType.*EvenPage* - analogically, the next section will start on the next even page. - ->note The distribution of the document content in sections is only visible when the document is in *Paged* layout mode. Furthermore, the sections and section breaks can be persisted in XAML, docx and RTF. If you export the document to HTML or plain text, the section breaks will be lost. -> - -# See Also - - * [Document Elements]({%slug winforms/richtexteditor-/document-elements%}) - - * [Section]({%slug winforms/richtexteditor-/document-elements/section%}) - - * [Paragraph]({%slug winforms/richtexteditor-/document-elements/paragraph%}) - - * [Span]({%slug winforms/richtexteditor-/document-elements/span%}) - - * [Inline Image]({%slug winforms/richtexteditor-/document-elements/inline-image%}) - - * [Hyperlink]({%slug winforms/richtexteditor-/features/hyperlink%}) +* __ParagraphDefaultSpacingAfter__ - defines the default spacing after for each of the paragraphs in the __RadDocument__. To assign different spacing after for each of the paragraphs use the respective property of the __Paragraph__ class. + +* __ParagraphDefaultSpacingBefore__ - defines the default spacing before for each of the paragraphs in the __RadDocument__. To assign different spacing before for each of the paragraphs use the respective property of the __Paragraph__ class. + +* __LineSpacing__ - specifies the value for the space between the lines. + +* __LineSpacingType - specifies the type of spacing:__ + + * __AtLeast -__ the space between the lines should be equal or greater than the value of the __LineSpacing__ property. + + * __Auto -__ the space between the lines is determined automatically. + + * __Exact -__ the space between the lines should be equal to the value of the __LineSpacing__ property. + +* __ShowFormattingSymbols__ - indicates whether the formatting symbols should be displayed or not. + +## Specifics + +The first time a __RadDocument__ is shown inside a __RadRichTextEditor__ in the Visual Tree, it is measured by the framework and arranges its children. This is the moment when the layout cycle is completed, each of the document elements calculates its size and arranges its children. + +As the two states of the document - measured and not measured are too different, distinct methods for manipulating the content of the document should be used before the document is measured and after the first time that it is shown in the editor. + +## Adding Sections to RadDocument + +As explained in the previous section, the state of the document is essential for the methods that can be used on it. + +For example, you can build a **RadDocument** from scratch and add **Sections** to it in the following way: + + + + + + +Splitting an already measured document into two sections at the current caret position, on the other hand, can be done by inserting a section break: + + + + + + +The method accept a parameter of type **SectionBreakType**. The possible values are: + +* SectionBreakType.*NextPage* - the default value. The next section will start on the next page. + +* SectionBreakType.*OddPage* - the next section will start on the next odd page. + +* SectionBreakType.*EvenPage* - analogically, the next section will start on the next even page. + +>note The distribution of the document content in sections is only visible when the document is in *Paged* layout mode. Furthermore, the sections and section breaks can be persisted in XAML, docx and RTF. If you export the document to HTML or plain text, the section breaks will be lost. +> + +# See Also + + * [Document Elements]({%slug winforms/richtexteditor-/document-elements%}) + + * [Section]({%slug winforms/richtexteditor-/document-elements/section%}) + + * [Paragraph]({%slug winforms/richtexteditor-/document-elements/paragraph%}) + + * [Span]({%slug winforms/richtexteditor-/document-elements/span%}) + + * [Inline Image]({%slug winforms/richtexteditor-/document-elements/inline-image%}) + + * [Hyperlink]({%slug winforms/richtexteditor-/features/hyperlink%}) diff --git a/controls/richtexteditor/document-elements/section.md b/controls/richtexteditor/document-elements/section.md index 6dccca8b2..6483fe94c 100644 --- a/controls/richtexteditor/document-elements/section.md +++ b/controls/richtexteditor/document-elements/section.md @@ -1,260 +1,137 @@ ---- -title: Section -page_title: Section - WinForms RichTextEditor Control -description: Section class in WinForms RichTextEditor allows you to separate the content into sections. Sections are chunks of the document that can be displayed on one or several pages. -slug: winforms/richtexteditor-/document-elements/section -tags: section -published: True -position: 1 -previous_url: richtexteditor-document-elements-section ---- - -# Section - -The __Section__ class allows you to separate the content into sections. __Sections__ are chunks of the document that can be displayed on one or several pages. - -A __Section__ can contain only __Paragraph__ and __Table__ elements. You are also able to customize the section layout by setting its properties. - -This topic will explain you how to: - -* [Create and Add a Section to RadDocument](#create-and-add-a-section-to-raddocument) - -* [Customize a Section](#customize-a-section) - -* [Add Paragraphs to a Section](#adding-paragraphs-to-a-section) - -## Create and add a Section to RadDocument - -As explained in the previous section, the state of the document is essential for the methods that can be used on it. - -For example, you can build a **RadDocument** from scratch and add **Sections** to it in the following way: - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\SectionCode.cs region=init}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\SectionCode.vb region=init}} - -````C# - -Telerik.WinForms.Documents.Model.Section section = new Telerik.WinForms.Documents.Model.Section(); -this.radRichTextEditor1.Document.Sections.Add(section); - -```` -````VB.NET -Dim section As New Telerik.WinForms.Documents.Model.Section() -Me.radRichTextEditor1.Document.Sections.Add(section) - -```` - -{{endregion}} - -Splitting an already measured document into two sections at the current caret position, on the other hand, can be done by inserting a section break: - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\SectionCode.cs region=break}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\SectionCode.vb region=break}} - -````C# - -this.radRichTextEditor1.InsertSectionBreak(SectionBreakType.NextPage); - -```` -````VB.NET -Me.radRichTextEditor1.InsertSectionBreak(SectionBreakType.NextPage) - -```` - -{{endregion}} - -The method accept a parameter of type **SectionBreakType**. The possible values are: - -* SectionBreakType.*NextPage* - the default value. The next section will start on the next page. - -* SectionBreakType.*OddPage* - the next section will start on the next odd page. - -* SectionBreakType.*EvenPage* - analogically, the next section will start on the next even page. - ->note The distribution of the document content in sections is only visible when the document is in *Paged* layout mode. Furthermore, the sections and section breaks can be persisted in XAML, docx and RTF. If you export the document to HTML or plain text, the section breaks will be lost. -> - -## Customize a Section - -The __Section__ exposes several properties that allow you to customize the layout of the elements placed underneath it. These properties can be set directly to the section when the document is created programmatically. If the changes should be applied to the document after it has been loaded in the editor, the respective methods and commands should be used. - -Here is a list of these properties: - -* __PageMargin__ - represents the margin towards the edges of the page when in *Paged* mode. - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\SectionCode.cs region=margin}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\SectionCode.vb region=margin}} - -````C# - -section.PageMargin = new Telerik.WinForms.Documents.Layout.Padding(40, 40, 30, 30); - -//When the section has already been added to the document -this.radRichTextEditor1.ChangeSectionPageMargin(new Telerik.WinForms.Documents.Layout.Padding(40, 40, 30, 30)); - -```` -````VB.NET -section.PageMargin = New Telerik.WinForms.Documents.Layout.Padding(40, 40, 30, 30) -'When the section has already been added to the document -Me.radRichTextEditor1.ChangeSectionPageMargin(New Telerik.WinForms.Documents.Layout.Padding(40, 40, 30, 30)) - -```` - -{{endregion}} - - -* __PageOrientation__ - specifies if the pages in the section should be in *Portrait* or *Landscape* mode. - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\SectionCode.cs region=orientation}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\SectionCode.vb region=orientation}} - -````C# - -//When creating a Section programmatically -section.PageOrientation = PageOrientation.Landscape; - -//When the section has already been added to the document -this.radRichTextEditor1.ChangeSectionPageOrientation(PageOrientation.Landscape); - -```` -````VB.NET -'When creating a Section programmatically -section.PageOrientation = PageOrientation.Landscape -'When the section has already been added to the document -Me.radRichTextEditor1.ChangeSectionPageOrientation(PageOrientation.Landscape) - -```` - -{{endregion}} - -* __PageSize__ - specifies the size of the pages in the section. The **PapertTypeConverter** class and the enum **PaperTypes** provide a convenient API and predefined sizes out of the box. - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\SectionCode.cs region=page}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\SectionCode.vb region=page}} - -````C# - -//When creating a Section programmatically -section.PageSize = PaperTypeConverter.ToSize(PaperTypes.A4); - -//When the section has already been added to the document -this.radRichTextEditor1.ChangeSectionPageSize(PaperTypeConverter.ToSize(PaperTypes.A4)); - -```` -````VB.NET -'When creating a Section programmatically -section.PageSize = PaperTypeConverter.ToSize(PaperTypes.A4) -'When the section has already been added to the document -Me.radRichTextEditor1.ChangeSectionPageSize(PaperTypeConverter.ToSize(PaperTypes.A4)) - -```` - -{{endregion}} - -* Add headers and footers to a **Section**. Each section has the following types of **Headers** and **Footers** - *Default* (used all through the section), *First* (used on the first page of the section) and *Even* (to be used on every even page; if set, overrides the default header/footer on all even pages of the section). Here is how you can create a **Header**: - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\SectionCode.cs region=body}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\SectionCode.vb region=body}} - -````C# -Telerik.WinForms.Documents.Model.Header header = new Telerik.WinForms.Documents.Model.Header() { Body = radDocument, IsLinkedToPrevious = false }; - -```` -````VB.NET -Dim header As New Telerik.WinForms.Documents.Model.Header() With {.Body = radDocument, .IsLinkedToPrevious = False} - -```` - -{{endregion}} - -All header/footer types are set identically. - -* In a non-measured document: - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\SectionCode.cs region=header1}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\SectionCode.vb region=header1}} - -````C# -section.Headers.First = header; - -```` -````VB.NET -section.Headers.First = header - -```` - -{{endregion}} - - -* In a measured document: - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\SectionCode.cs region=header2}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\SectionCode.vb region=header2}} - -````C# -this.radRichTextEditor1.UpdateHeader(this.radRichTextEditor1.Document.Sections.First, Telerik.WinForms.Documents.Model.HeaderFooterType.First, header); - -```` -````VB.NET -Me.radRichTextEditor1.UpdateHeader(Me.radRichTextEditor1.Document.Sections.First, Telerik.WinForms.Documents.Model.HeaderFooterType.First, header) - -```` - -{{endregion}} - -Setting the **Footers** can be done in the same way. - -## Adding Paragraphs to a Section - -Paragraphs can be added to a section in the following ways: - -In a non-measured document: - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\SectionCode.cs region=add1}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\SectionCode.vb region=add1}} - -````C# - -Section section1 = new Section(); -Paragraph paragraph = new Paragraph(); -section1.Blocks.Add(paragraph); - -```` -````VB.NET -Dim section1 As New Section() -Dim paragraph As New Paragraph() -section1.Blocks.Add(paragraph) - -```` - -{{endregion}} - -In a measured document: - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\SectionCode.cs region=add2}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\SectionCode.vb region=add2}} - -````C# -this.radRichTextEditor1.Insert(FormattingSymbolLayoutBox.ENTER); - -```` -````VB.NET -Me.radRichTextEditor1.Insert(FormattingSymbolLayoutBox.ENTER) - -```` - -{{endregion}} - -# See Also - - * [Document Elements]({%slug winforms/richtexteditor-/document-elements%}) - - * [Section]({%slug winforms/richtexteditor-/document-elements/section%}) - - * [Paragraph]({%slug winforms/richtexteditor-/document-elements/paragraph%}) - - * [Span]({%slug winforms/richtexteditor-/document-elements/span%}) - - * [Inline Image]({%slug winforms/richtexteditor-/document-elements/inline-image%}) - - * [Hyperlink]({%slug winforms/richtexteditor-/features/hyperlink%}) +--- +title: Section +page_title: Section - WinForms RichTextEditor Control +description: Section class in WinForms RichTextEditor allows you to separate the content into sections. Sections are chunks of the document that can be displayed on one or several pages. +slug: winforms/richtexteditor-/document-elements/section +tags: section +published: True +position: 1 +previous_url: richtexteditor-document-elements-section +--- + +# Section + +The __Section__ class allows you to separate the content into sections. __Sections__ are chunks of the document that can be displayed on one or several pages. + +A __Section__ can contain only __Paragraph__ and __Table__ elements. You are also able to customize the section layout by setting its properties. + +This topic will explain you how to: + +* [Create and Add a Section to RadDocument](#create-and-add-a-section-to-raddocument) + +* [Customize a Section](#customize-a-section) + +* [Add Paragraphs to a Section](#adding-paragraphs-to-a-section) + +## Create and add a Section to RadDocument + +As explained in the previous section, the state of the document is essential for the methods that can be used on it. + +For example, you can build a **RadDocument** from scratch and add **Sections** to it in the following way: + + + + + + +Splitting an already measured document into two sections at the current caret position, on the other hand, can be done by inserting a section break: + + + + + + +The method accept a parameter of type **SectionBreakType**. The possible values are: + +* SectionBreakType.*NextPage* - the default value. The next section will start on the next page. + +* SectionBreakType.*OddPage* - the next section will start on the next odd page. + +* SectionBreakType.*EvenPage* - analogically, the next section will start on the next even page. + +>note The distribution of the document content in sections is only visible when the document is in *Paged* layout mode. Furthermore, the sections and section breaks can be persisted in XAML, docx and RTF. If you export the document to HTML or plain text, the section breaks will be lost. +> + +## Customize a Section + +The __Section__ exposes several properties that allow you to customize the layout of the elements placed underneath it. These properties can be set directly to the section when the document is created programmatically. If the changes should be applied to the document after it has been loaded in the editor, the respective methods and commands should be used. + +Here is a list of these properties: + +* __PageMargin__ - represents the margin towards the edges of the page when in *Paged* mode. + + + + + + +* __PageOrientation__ - specifies if the pages in the section should be in *Portrait* or *Landscape* mode. + + + + + + +* __PageSize__ - specifies the size of the pages in the section. The **PapertTypeConverter** class and the enum **PaperTypes** provide a convenient API and predefined sizes out of the box. + + + + + + +* Add headers and footers to a **Section**. Each section has the following types of **Headers** and **Footers** - *Default* (used all through the section), *First* (used on the first page of the section) and *Even* (to be used on every even page; if set, overrides the default header/footer on all even pages of the section). Here is how you can create a **Header**: + + + + + + +All header/footer types are set identically. + +* In a non-measured document: + + + + + + +* In a measured document: + + + + + + +Setting the **Footers** can be done in the same way. + +## Adding Paragraphs to a Section + +Paragraphs can be added to a section in the following ways: + +In a non-measured document: + + + + + + +In a measured document: + + + + + + +# See Also + + * [Document Elements]({%slug winforms/richtexteditor-/document-elements%}) + + * [Section]({%slug winforms/richtexteditor-/document-elements/section%}) + + * [Paragraph]({%slug winforms/richtexteditor-/document-elements/paragraph%}) + + * [Span]({%slug winforms/richtexteditor-/document-elements/span%}) + + * [Inline Image]({%slug winforms/richtexteditor-/document-elements/inline-image%}) + + * [Hyperlink]({%slug winforms/richtexteditor-/features/hyperlink%}) diff --git a/controls/richtexteditor/document-elements/span.md b/controls/richtexteditor/document-elements/span.md index 077a8aa10..0d471498d 100644 --- a/controls/richtexteditor/document-elements/span.md +++ b/controls/richtexteditor/document-elements/span.md @@ -1,119 +1,79 @@ ---- -title: Span -page_title: Span - WinForms RichTextEditor Control -description: Span class represents an inline object that allows you to display formatted text. A Span can only be used in the context of a Paragraph in WinForms RichTextEditor. -slug: winforms/richtexteditor-/document-elements/span -tags: span -published: True -position: 3 -previous_url: richtexteditor-document-elements-span ---- - -# Span - -The __Span__ class represents an inline object that allows you to display formatted text. A __Span__ can only be used in the context of a __Paragraph__. As the spans are inline elements they get placed one after another and the text inside them gets wrapped to the next line if the space is insufficient. - -This topic will explain you how to: - -* [Use Spans](#use-spans) - -* [Add Text to a Span](#add-text-to-a-span) - -* [Customize a Span](#customize-a-span) - -## Use Spans - -The __Spans__ can be used only in the context of the [Paragraph]({%slug winforms/richtexteditor-/document-elements/paragraph%}) element. The __Paragraph__ exposes a collection of **Inlines**, to which the spans can be added. - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\SpanCode.cs region=span}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\SpanCode.vb region=span}} - -````C# +--- +title: Span +page_title: Span - WinForms RichTextEditor Control +description: Span class represents an inline object that allows you to display formatted text. A Span can only be used in the context of a Paragraph in WinForms RichTextEditor. +slug: winforms/richtexteditor-/document-elements/span +tags: span +published: True +position: 3 +previous_url: richtexteditor-document-elements-span +--- + +# Span + +The __Span__ class represents an inline object that allows you to display formatted text. A __Span__ can only be used in the context of a __Paragraph__. As the spans are inline elements they get placed one after another and the text inside them gets wrapped to the next line if the space is insufficient. + +This topic will explain you how to: + +* [Use Spans](#use-spans) + +* [Add Text to a Span](#add-text-to-a-span) + +* [Customize a Span](#customize-a-span) + +## Use Spans + +The __Spans__ can be used only in the context of the [Paragraph]({%slug winforms/richtexteditor-/document-elements/paragraph%}) element. The __Paragraph__ exposes a collection of **Inlines**, to which the spans can be added. + + + + + + +## Add Text to a Span + +To specify the text in the __Span__ you can use its __Text__ property. + + + + + + +>caution The **Text** property of a **Span** cannot be set to an empty string, as spans that do not contain any text are considered invalid. If you add an empty span in the document programmatically, an exception will be thrown. +> + +## Customize a Span + +The __Span__ class exposes several properties that allow you to customize the layout of the elements placed underneath it. Here is a list of them: + +* __BaselineAlignment__ - indicates whether the text is __Baseline__, __Subscript__ or __Superscript__. -Section section = new Section(); -Paragraph paragraph = new Paragraph(); -Span span = new Span("Span declared in code-behind"); -paragraph.Inlines.Add(span); -section.Blocks.Add(paragraph); -this.radRichTextEditor1.Document.Sections.Add(section); - -```` -````VB.NET -Dim section As New Section() -Dim paragraph As New Paragraph() -Dim span As New Span("Span declared in code-behind") -paragraph.Inlines.Add(span) -section.Blocks.Add(paragraph) -Me.radRichTextEditor1.Document.Sections.Add(section) - -```` - -{{endregion}} - -## Add Text to a Span - -To specify the text in the __Span__ you can use its __Text__ property. - -{{source=..\SamplesCS\RichTextEditor\DocumentElements\SpanCode.cs region=span}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\SpanCode.vb region=span}} - -````C# +* __FontFamily__ - represents the name of the text's font. -Section section = new Section(); -Paragraph paragraph = new Paragraph(); -Span span = new Span("Span declared in code-behind"); -paragraph.Inlines.Add(span); -section.Blocks.Add(paragraph); -this.radRichTextEditor1.Document.Sections.Add(section); - -```` -````VB.NET -Dim section As New Section() -Dim paragraph As New Paragraph() -Dim span As New Span("Span declared in code-behind") -paragraph.Inlines.Add(span) -section.Blocks.Add(paragraph) -Me.radRichTextEditor1.Document.Sections.Add(section) - -```` - -{{endregion}} - ->caution The **Text** property of a **Span** cannot be set to an empty string, as spans that do not contain any text are considered invalid. If you add an empty span in the document programmatically, an exception will be thrown. -> - -## Customize a Span - -The __Span__ class exposes several properties that allow you to customize the layout of the elements placed underneath it. Here is a list of them: - -* __BaselineAlignment__ - indicates whether the text is __Baseline__, __Subscript__ or __Superscript__. - -* __FontFamily__ - represents the name of the text's font. - -* __FontSize__ - represent the size of the text. - -* __FontStyle__ - indicates whether the text should have its style set to italic or to normal. - -* __FontWeight__ - represents the value for the text's weight. - -* __ForeColor__ - represents the foreground color for the text. - -* __HighlightColor__ - represents the background color for the text. - -* __Strikethrough__ - indicates whether the text should be stroke through. - -* __UnderlineDecoration__ - indicates whether the text should be underlined. - -# See Also - - * [Document Elements]({%slug winforms/richtexteditor-/document-elements%}) - - * [Section]({%slug winforms/richtexteditor-/document-elements/section%}) - - * [Paragraph]({%slug winforms/richtexteditor-/document-elements/paragraph%}) - - * [RadDocument]({%slug winforms/richtexteditor-/document-elements/raddocument%}) - - * [Inline Image]({%slug winforms/richtexteditor-/document-elements/inline-image%}) - - * [Hyperlink]({%slug winforms/richtexteditor-/features/hyperlink%}) +* __FontSize__ - represent the size of the text. + +* __FontStyle__ - indicates whether the text should have its style set to italic or to normal. + +* __FontWeight__ - represents the value for the text's weight. + +* __ForeColor__ - represents the foreground color for the text. + +* __HighlightColor__ - represents the background color for the text. + +* __Strikethrough__ - indicates whether the text should be stroke through. + +* __UnderlineDecoration__ - indicates whether the text should be underlined. + +# See Also + + * [Document Elements]({%slug winforms/richtexteditor-/document-elements%}) + + * [Section]({%slug winforms/richtexteditor-/document-elements/section%}) + + * [Paragraph]({%slug winforms/richtexteditor-/document-elements/paragraph%}) + + * [RadDocument]({%slug winforms/richtexteditor-/document-elements/raddocument%}) + + * [Inline Image]({%slug winforms/richtexteditor-/document-elements/inline-image%}) + + * [Hyperlink]({%slug winforms/richtexteditor-/features/hyperlink%}) diff --git a/controls/richtexteditor/document-elements/table.md b/controls/richtexteditor/document-elements/table.md index c23db3ef3..6c55eee89 100644 --- a/controls/richtexteditor/document-elements/table.md +++ b/controls/richtexteditor/document-elements/table.md @@ -32,94 +32,9 @@ __RadRichTextEditor__ exposes a rich API, which allows you to use various method Here is an example done in the code-behind. -{{source=..\SamplesCS\RichTextEditor\DocumentElements\TableCode.cs region=add}} -{{source=..\SamplesVB\RichTextEditor\DocumentElements\TableCode.vb region=add}} - -````C# - -RadDocument document = new RadDocument(); -Section section = new Section(); - -Table table = new Table(); -table.StyleName = RadDocumentDefaultStyles.DefaultTableGridStyleName; -TableRow row1 = new TableRow(); - -TableCell cell1 = new TableCell(); -Paragraph p1 = new Paragraph(); -Span s1 = new Span(); -s1.Text = "Cell 1"; -p1.Inlines.Add(s1); -cell1.Blocks.Add(p1); -row1.Cells.Add(cell1); - -TableCell cell2 = new TableCell(); -Paragraph p2 = new Paragraph(); -Span s2 = new Span(); -s2.Text = "Cell 2"; -p2.Inlines.Add(s2); -cell2.Blocks.Add(p2); -row1.Cells.Add(cell2); -table.Rows.Add(row1); -TableRow row2 = new TableRow(); - -TableCell cell3 = new TableCell(); -cell3.ColumnSpan = 2; -Paragraph p3 = new Paragraph(); -Span s3 = new Span(); -s3.Text = "Cell 3"; -p3.Inlines.Add(s3); -cell3.Blocks.Add(p3); -row2.Cells.Add(cell3); -table.Rows.Add(row2); - -section.Blocks.Add(new Paragraph()); -section.Blocks.Add(table); -section.Blocks.Add(new Paragraph()); -document.Sections.Add(section); - -this.radRichTextEditor1.Document = document; - -```` -````VB.NET -Dim document As New RadDocument() -Dim section As New Section() -Dim table As New Table() -table.StyleName = RadDocumentDefaultStyles.DefaultTableGridStyleName -Dim row1 As New TableRow() -Dim cell1 As New TableCell() -Dim p1 As New Paragraph() -Dim s1 As New Span() -s1.Text = "Cell 1" -p1.Inlines.Add(s1) -cell1.Blocks.Add(p1) -row1.Cells.Add(cell1) -Dim cell2 As New TableCell() -Dim p2 As New Paragraph() -Dim s2 As New Span() -s2.Text = "Cell 2" -p2.Inlines.Add(s2) -cell2.Blocks.Add(p2) -row1.Cells.Add(cell2) -table.Rows.Add(row1) -Dim row2 As New TableRow() -Dim cell3 As New TableCell() -cell3.ColumnSpan = 2 -Dim p3 As New Paragraph() -Dim s3 As New Span() -s3.Text = "Cell 3" -p3.Inlines.Add(s3) -cell3.Blocks.Add(p3) -row2.Cells.Add(cell3) -table.Rows.Add(row2) -section.Blocks.Add(New Paragraph()) -section.Blocks.Add(table) -section.Blocks.Add(New Paragraph()) -document.Sections.Add(section) -Me.radRichTextEditor1.Document = document - -```` - -{{endregion}} + + + Here is a snapshot of the result. diff --git a/controls/richtexteditor/features/bookmarks.md b/controls/richtexteditor/features/bookmarks.md index c42fdfa8f..387202687 100644 --- a/controls/richtexteditor/features/bookmarks.md +++ b/controls/richtexteditor/features/bookmarks.md @@ -39,138 +39,22 @@ The document elements that encapsulate the bookmarks functionality are __Bookmar You can also add bookmarks in a document you are creating manually. As both __BookmarkRangeStart__ and __BookMarkRangeEnd__ inherit from __Inline__, they can be added to the **Inlines** property of a **Paragraph**, just like any other **Inline**. You can also have document positions go to the start or end of the bookmark and perform non-standard operations. -{{source=..\SamplesCS\RichTextEditor\Features\Bookmarks.cs region=BookmarkRunTime}} -{{source=..\SamplesVB\RichTextEditor\Features\Bookmarks.vb region=BookmarkRunTime}} -````C# -private void GenerateBookmarksDocument() -{ - RadDocument document = new RadDocument(); - - Section bmSection = new Section(); - Paragraph bmParagraph = new Paragraph(); - Span bmSpan = new Span("Content prior bookmark["); - Span bmSpan2 = new Span("]Content after bookmark"); - Span bmContent = new Span("Content in Bookmark"); - - BookmarkRangeEnd bmRangeEnd = new BookmarkRangeEnd(); - BookmarkRangeStart bmRangeStart = (BookmarkRangeStart)bmRangeEnd.CreatePairedStart(); - bmRangeStart.Name = System.Guid.NewGuid().ToString(); - - bmParagraph.Inlines.Add(bmSpan); - bmParagraph.Inlines.Add(bmRangeStart); - bmParagraph.Inlines.Add(bmContent); - bmParagraph.Inlines.Add(bmRangeEnd); - bmParagraph.Inlines.Add(bmSpan2); - - bmSection.Blocks.Add(bmParagraph); - document.Sections.Add(bmSection); - - this.radRichTextEditor1.Document = document; -} - -```` -````VB.NET -Private Sub GenerateBookmarksDocument() - Dim document As New RadDocument() - Dim bmSection As New Section() - Dim bmParagraph As New Paragraph() - Dim bmSpan As New Span("Content prior bookmark[") - Dim bmSpan2 As New Span("]Content after bookmark") - Dim bmContent As New Span("Content in Bookmark") - Dim bmRangeEnd As New BookmarkRangeEnd() - Dim bmRangeStart = DirectCast(bmRangeEnd.CreatePairedStart(), BookmarkRangeStart) - bmRangeStart.Name = System.Guid.NewGuid().ToString() - bmParagraph.Inlines.Add(bmSpan) - bmParagraph.Inlines.Add(bmRangeStart) - bmParagraph.Inlines.Add(bmContent) - bmParagraph.Inlines.Add(bmRangeEnd) - bmParagraph.Inlines.Add(bmSpan2) - bmSection.Blocks.Add(bmParagraph) - document.Sections.Add(bmSection) - Me.radRichTextEditor1.Document = document -End Sub - -```` - -{{endregion}} - -For example, you can keep a **Dictionary** mapping each bookmark name to another string and substitute a bookmark with the corresponding text using the following method: - -{{source=..\SamplesCS\RichTextEditor\Features\Bookmarks.cs region=replace}} -{{source=..\SamplesVB\RichTextEditor\Features\Bookmarks.vb region=replace}} + + -````C# -private void ReplaceContentOfBookmark(string bookmarkName) -{ - BookmarkRangeStart bookmark = this.radRichTextEditor1.Document.GetBookmarkByName(bookmarkName); - this.radRichTextEditor1.Document.Selection.SelectAnnotationRange(bookmark); - this.radRichTextEditor1.Delete(false); - this.radRichTextEditor1.Insert("new text"); -} -```` -````VB.NET -Private Sub ReplaceContentOfBookmark(ByVal bookmarkName As String) - Dim bookmark As BookmarkRangeStart = Me.radRichTextEditor1.Document.GetBookmarkByName(bookmarkName) - Me.radRichTextEditor1.Document.Selection.SelectAnnotationRange(bookmark) - Me.radRichTextEditor1.Delete(False) - Me.radRichTextEditor1.Insert("new text") -End Sub -```` +For example, you can keep a **Dictionary** mapping each bookmark name to another string and substitute a bookmark with the corresponding text using the following method: -{{endregion}} + + -If you want to preserve the bookmarks in the document and only change the text between the **BookmarkRangeStart** and **BookmarkRangeEnd** document elements, you can do so like this: -{{source=..\SamplesCS\RichTextEditor\Features\Bookmarks.cs region=change}} -{{source=..\SamplesVB\RichTextEditor\Features\Bookmarks.vb region=change}} - -````C# -private void ChangeAllBookmarks(RadRichTextEditor radRichTextEditor) -{ - BookmarkRangeStart[] bookmarks = radRichTextEditor.Document.GetAllBookmarks().ToArray(); - DocumentPosition start = new DocumentPosition(radRichTextEditor.Document); - DocumentPosition end = new DocumentPosition(radRichTextEditor.Document); - foreach (BookmarkRangeStart item in bookmarks) - { - radRichTextEditor.Document.GoToBookmark(item); - - start.MoveToInline(item.FirstLayoutBox as InlineLayoutBox, 0); - end.MoveToInline(item.End.FirstLayoutBox as InlineLayoutBox, 0); - start.MoveToNextInline(); - radRichTextEditor.Document.Selection.SetSelectionStart(start); - radRichTextEditor.Document.Selection.AddSelectionEnd(end); - - radRichTextEditor.Delete(false); - - radRichTextEditor.Insert("new text"); - } -} - -```` -````VB.NET -Private Sub ChangeAllBookmarks(ByVal radRichTextEditor As RadRichTextEditor) - Dim bookmarks() As BookmarkRangeStart = radRichTextEditor.Document.GetAllBookmarks().ToArray() - Dim start As New DocumentPosition(radRichTextEditor.Document) - Dim [end] As New DocumentPosition(radRichTextEditor.Document) - For Each item As BookmarkRangeStart In bookmarks - radRichTextEditor.Document.GoToBookmark(item) - start.MoveToInline(TryCast(item.FirstLayoutBox, InlineLayoutBox), 0) - [end].MoveToInline(TryCast(item.End.FirstLayoutBox, InlineLayoutBox), 0) - start.MoveToNextInline() - radRichTextEditor.Document.Selection.SetSelectionStart(start) - radRichTextEditor.Document.Selection.AddSelectionEnd([end]) - radRichTextEditor.Delete(False) - radRichTextEditor.Insert("new text") - Next item -End Sub - -```` - -{{endregion}} +If you want to preserve the bookmarks in the document and only change the text between the **BookmarkRangeStart** and **BookmarkRangeEnd** document elements, you can do so like this: + + diff --git a/controls/richtexteditor/features/clipboard-support.md b/controls/richtexteditor/features/clipboard-support.md index 18f27ce89..d5804d173 100644 --- a/controls/richtexteditor/features/clipboard-support.md +++ b/controls/richtexteditor/features/clipboard-support.md @@ -1,92 +1,59 @@ ---- -title: Clipboard Support -page_title: Clipboard Support - WinForms RichTextEditor Control -description: WinForms RichTextEditor takes advantage of the clipboard support. Learn what are the supported formats and how to choose which input to use and further customize the way the text will look when pasted. -slug: winforms/richtexteditor-/features/clipboard-support -tags: clipboard,support -published: True -position: 9 -previous_url: richtexteditor-features-clipboard-support ---- - -# Clipboard Support - -__RadRichTextEditor__ takes advantage of the clipboard support in Win Forms. As the clipboard keeps content in several formats, it is possible to choose which input to use and further customize the way the text will look when pasted. - -## Methods and Commands - -__RadRichTextEditor's__ API exposes a method and a command for each of the three actions that can be performed against the clipboard: Cut, Copy and Paste. They can be invoked as follows: - -{{source=..\SamplesCS\RichTextEditor\Features\ClipboardSupport.cs region=clipboard}} -{{source=..\SamplesVB\RichTextEditor\Features\ClipboardSupport.vb region=clipboard}} - -````C# - -this.radRichTextEditor1.Copy(); -this.radRichTextEditor1.Cut(); -this.radRichTextEditor1.Paste(); - -```` -````VB.NET -Me.radRichTextEditor1.Copy() -Me.radRichTextEditor1.Cut() -Me.radRichTextEditor1.Paste() - -```` - -{{endregion}} - -## Settings - -By default, the __PasteCommand__ of the editor uses its __RtfFormatProvider__ and __HtmlFormatProvider__ in order to create a **RadDocument** out of the document in the clipboard and insert it in the current document.The **PasteCommand** tries to create a document out of the RTF content of the clipboard. If it fails for some reason (e.g. the RTF is invalid or not supported by **RtfFormatProvider**), the paste falls back to HTML. In case **HtmlFormatProvider** cannot handle the clipboard content as well, the plain text from the clipboard will be inserted in the document. - -You can customize this behavior by removing or reordering the clipboard handlers for the different formats. - -Each Clipboard Handler contains the following properties: - -* __DocumentFormatProvider__ – the format provider used to import the data in the clipboard, e.g. **HtmlFormatProvider** or **RtfFormatProvider**; - -* __ClipboardDataFormat__ – the format of the data (DataFormats.*Html* or DataFormats.*Rtf*); - -* __ClipboardStringFilter__ – a filter used to preprocess the data if needed. For example, the HTML that Word puts in the clipboard contains some headings which should be stripped in order to acquire the clean HTML content before passing it to a format provider. Such a filter is ClipboardEx.*StripHtmlClipboardFormatHeaders*, but you can also pass any **Func**. - -For instance, here is how you can clear the default clipboard handlers and add only a handler which uses __TxtFormatProvider__. In this way only plain text will be pasted when you copy from a source such as another rich text editor or a browser. - -{{source=..\SamplesCS\RichTextEditor\Features\ClipboardSupport.cs region=ex}} -{{source=..\SamplesVB\RichTextEditor\Features\ClipboardSupport.vb region=ex}} - -````C# - -ClipboardEx.ClipboardHandlers.Clear(); -ClipboardHandler clipboardHandler = new ClipboardHandler(); -clipboardHandler.ClipboardDataFormat = DataFormats.Text; -clipboardHandler.DocumentFormatProvider = new TxtFormatProvider(); - -ClipboardEx.ClipboardHandlers.Add(clipboardHandler); - -```` -````VB.NET -ClipboardEx.ClipboardHandlers.Clear() -Dim clipboardHandler As New ClipboardHandler() -clipboardHandler.ClipboardDataFormat = DataFormats.Text -clipboardHandler.DocumentFormatProvider = New TxtFormatProvider() -ClipboardEx.ClipboardHandlers.Add(clipboardHandler) - -```` - -{{endregion}} - -You can also reorder the clipboard handlers to use first HTML paste and fallback to RTF instead of the other way around, or attach to different events of the format providers. - -## Key Bindings - ->tip In order to copy, paste or cut, the standard keyboard shortcuts can also be used - `Ctrl` + `C` , `Ctrl` + `V` , `Ctrl` + `X` . -> - -To learn more about the default key-bindings of the editor and ways to override them, you can refer to this article: [Keyboard Support]({%slug winforms/richtexteditor-/keyboard-support%}) - -# See Also - - * [Formatting API]({%slug winforms/richtexteditor-/getting-started/formatting-api%}) - - * [Layout Modes]({%slug winforms/richtexteditor-/getting-started/layout-modes%}) +--- +title: Clipboard Support +page_title: Clipboard Support - WinForms RichTextEditor Control +description: WinForms RichTextEditor takes advantage of the clipboard support. Learn what are the supported formats and how to choose which input to use and further customize the way the text will look when pasted. +slug: winforms/richtexteditor-/features/clipboard-support +tags: clipboard,support +published: True +position: 9 +previous_url: richtexteditor-features-clipboard-support +--- + +# Clipboard Support + +__RadRichTextEditor__ takes advantage of the clipboard support in Win Forms. As the clipboard keeps content in several formats, it is possible to choose which input to use and further customize the way the text will look when pasted. + +## Methods and Commands + +__RadRichTextEditor's__ API exposes a method and a command for each of the three actions that can be performed against the clipboard: Cut, Copy and Paste. They can be invoked as follows: + + + + + + +## Settings + +By default, the __PasteCommand__ of the editor uses its __RtfFormatProvider__ and __HtmlFormatProvider__ in order to create a **RadDocument** out of the document in the clipboard and insert it in the current document.The **PasteCommand** tries to create a document out of the RTF content of the clipboard. If it fails for some reason (e.g. the RTF is invalid or not supported by **RtfFormatProvider**), the paste falls back to HTML. In case **HtmlFormatProvider** cannot handle the clipboard content as well, the plain text from the clipboard will be inserted in the document. + +You can customize this behavior by removing or reordering the clipboard handlers for the different formats. + +Each Clipboard Handler contains the following properties: + +* __DocumentFormatProvider__ – the format provider used to import the data in the clipboard, e.g. **HtmlFormatProvider** or **RtfFormatProvider**; + +* __ClipboardDataFormat__ – the format of the data (DataFormats.*Html* or DataFormats.*Rtf*); + +* __ClipboardStringFilter__ – a filter used to preprocess the data if needed. For example, the HTML that Word puts in the clipboard contains some headings which should be stripped in order to acquire the clean HTML content before passing it to a format provider. Such a filter is ClipboardEx.*StripHtmlClipboardFormatHeaders*, but you can also pass any **Func**. + +For instance, here is how you can clear the default clipboard handlers and add only a handler which uses __TxtFormatProvider__. In this way only plain text will be pasted when you copy from a source such as another rich text editor or a browser. + + + + + + +You can also reorder the clipboard handlers to use first HTML paste and fallback to RTF instead of the other way around, or attach to different events of the format providers. + +## Key Bindings + +>tip In order to copy, paste or cut, the standard keyboard shortcuts can also be used - `Ctrl` + `C` , `Ctrl` + `V` , `Ctrl` + `X` . +> + +To learn more about the default key-bindings of the editor and ways to override them, you can refer to this article: [Keyboard Support]({%slug winforms/richtexteditor-/keyboard-support%}) + +# See Also + + * [Formatting API]({%slug winforms/richtexteditor-/getting-started/formatting-api%}) + + * [Layout Modes]({%slug winforms/richtexteditor-/getting-started/layout-modes%}) diff --git a/controls/richtexteditor/features/code-block.md b/controls/richtexteditor/features/code-block.md index 9e0dc60fa..667a844ca 100644 --- a/controls/richtexteditor/features/code-block.md +++ b/controls/richtexteditor/features/code-block.md @@ -42,29 +42,10 @@ The constructor of __CodeFormattingSettings__ requires a code language to be spe Additionally, you can enable the display of line numbers and the alternating lines options. -{{source=..\SamplesCS\RichTextEditor\Features\CodeBlock.cs region=insert}} -{{source=..\SamplesVB\RichTextEditor\Features\CodeBlock.vb region=insert}} - -````C# - -string code = "this.IsCodeBlock = true;\nthis.IsCodeBlock = false;\nthis.IsCodeBlock = true;"; -CodeFormattingSettings formattingSettings = new CodeFormattingSettings(CodeLanguages.CSharp); -formattingSettings.IsLineNumberingEnabled = true; -formattingSettings.IsAlternatingLinesEnabled = true; - -this.radRichTextEditor1.InsertCodeBlock(code, formattingSettings); - -```` -````VB.NET -Dim code As String = "this.IsCodeBlock = true;" & ControlChars.Lf & "this.IsCodeBlock = false;" & ControlChars.Lf & "this.IsCodeBlock = true;" -Dim formattingSettings As New CodeFormattingSettings(CodeLanguages.CSharp) -formattingSettings.IsLineNumberingEnabled = True -formattingSettings.IsAlternatingLinesEnabled = True -Me.radRichTextEditor1.InsertCodeBlock(code, formattingSettings) - -```` - -{{endregion}} + + + + The inner representation of the code block in the document is achieved by surrounding the content with __CodeAnnotationRangeStart__ and __CodeAnnotationRangeEnd__. @@ -72,22 +53,10 @@ The inner representation of the code block in the document is achieved by surrou To remove the code block you can use the __DeleteCodeBlock()__ method of __RadRichTextEditor__ accepting __CodeAnnotationRangeStart__ as parameter: -{{source=..\SamplesCS\RichTextEditor\Features\CodeBlock.cs region=delete}} -{{source=..\SamplesVB\RichTextEditor\Features\CodeBlock.vb region=delete}} - -````C# - -IEnumerable markers = this.radRichTextEditor1.Document.GetAnnotationMarkersOfType(); -this.radRichTextEditor1.DeleteCodeBlock(markers.First()); - -```` -````VB.NET -Dim markers As IEnumerable(Of CodeAnnotationRangeStart) = Me.radRichTextEditor1.Document.GetAnnotationMarkersOfType(Of CodeAnnotationRangeStart)() -Me.radRichTextEditor1.DeleteCodeBlock(markers.First()) + + -```` -{{endregion}} The contents of a code block can be selected and copied, but cannot be edited. However, existing code blocks can be modified with the code block dialog. @@ -102,28 +71,8 @@ the language will be visible in the __InsertCodeBlock__ dialog. You can also register or change which style will be used for which classification types in which language in the __CodeFormatter__ class. Here is how to change the color for all comments when formatting JavaScript: -{{source=..\SamplesCS\RichTextEditor\Features\CodeBlock.cs region=js}} -{{source=..\SamplesVB\RichTextEditor\Features\CodeBlock.vb region=js}} - -````C# - -StyleDefinition commentJS = new StyleDefinition("CommentJS", StyleType.Character); -commentJS.SpanProperties.ForeColor = Colors.Gray; -commentJS.IsCustom = false; -commentJS.IsPrimary = false; -this.radRichTextEditor1.Document.CodeFormatter.RegisterClassificationType(ClassificationTypes.Comment, CodeLanguages.JavaScript, commentJS); - -```` -````VB.NET -Dim commentJS As New StyleDefinition("CommentJS", StyleType.Character) -commentJS.SpanProperties.ForeColor = Colors.Gray -commentJS.IsCustom = False -commentJS.IsPrimary = False -Me.radRichTextEditor1.Document.CodeFormatter.RegisterClassificationType(ClassificationTypes.Comment, CodeLanguages.JavaScript, commentJS) - -```` - -{{endregion}} + + diff --git a/controls/richtexteditor/features/commands.md b/controls/richtexteditor/features/commands.md index db44332ef..56cda5c38 100644 --- a/controls/richtexteditor/features/commands.md +++ b/controls/richtexteditor/features/commands.md @@ -204,76 +204,17 @@ The following list shows all available __RadRichTextEditor__ commands. Here is an example with a __RadToggleButton__ control. -{{source=..\SamplesCS\RichTextEditor\Features\Commands.cs region=init}} -{{source=..\SamplesVB\RichTextEditor\Features\Commands.vb region=init}} + + -````C# - -private RadToggleButton boldButton; - -public Commands() -{ - this.InitializeComponent(); - this.boldButton = new RadToggleButton(); - this.boldButton.Text = "Bold"; - this.boldButton.Click += this.boldButton_Click; - this.boldButton.Location = new Point(10, 10); - this.Controls.Add(this.boldButton); -} - -private void boldButton_Click(object sender, EventArgs e) -{ - this.radRichTextEditor1.Commands.ToggleBoldCommand.Execute(); -} -```` -````VB.NET -Private boldButton As RadToggleButton -Public Sub New() - Me.InitializeComponent() - Me.boldButton = New RadToggleButton() - Me.boldButton.Text = "Bold" - AddHandler Me.boldButton.Click, AddressOf Me.boldButton_Click - Me.boldButton.Location = New Point(10, 10) - Me.Controls.Add(Me.boldButton) -End Sub -Private Sub boldButton_Click(ByVal sender As Object, ByVal e As EventArgs) - Me.radRichTextEditor1.Commands.ToggleBoldCommand.Execute() -End Sub - -```` - -{{endregion}} Now, every time the button is clicked it will toggle the boldness of the current selection. The thing it won't do is to response to the current state of the selection. For example, if the context of the caret is a bold text, the button won't get automatically toggled. In order to implement this behavior you have to handle the __ToggleStateChanged__ event of the __ToggleBoldCommand__. Here is an example. -{{source=..\SamplesCS\RichTextEditor\Features\Commands.cs region=event}} -{{source=..\SamplesVB\RichTextEditor\Features\Commands.vb region=event}} - -````C# - -private void Commands_Load(object sender, EventArgs e) -{ - this.radRichTextEditor1.Commands.ToggleBoldCommand.ToggleStateChanged += this.ToggleBoldCommand_ToggleStateChanged; -} - -public void ToggleBoldCommand_ToggleStateChanged(object sender, StylePropertyChangedEventArgs e) -{ - this.boldButton.IsChecked = e.NewValue; -} - -```` -````VB.NET -Private Sub Commands_Load(ByVal sender As Object, ByVal e As EventArgs) - AddHandler Me.radRichTextEditor1.Commands.ToggleBoldCommand.ToggleStateChanged, AddressOf Me.ToggleBoldCommand_ToggleStateChanged -End Sub -Public Sub ToggleBoldCommand_ToggleStateChanged(ByVal sender As Object, ByVal e As StylePropertyChangedEventArgs(Of Boolean)) - Me.boldButton.IsChecked = e.NewValue -End Sub + + -```` -{{endregion}} Now, the button will respond to the current state of the selection. diff --git a/controls/richtexteditor/features/comments.md b/controls/richtexteditor/features/comments.md index 6337b2e70..e12525af2 100644 --- a/controls/richtexteditor/features/comments.md +++ b/controls/richtexteditor/features/comments.md @@ -74,44 +74,10 @@ There are also __GoToNextComment()__ and __GoToPreviousComment()__ methods avail You can customize the looks of the comments by attaching to the __CommentShowing__ event of __RadRichTextEditor__. Inside the event handler you can access the __Comment__ and modify the __AppearanceSettings__ that are used to visualize the comment. Here is an example: -{{source=..\SamplesCS\RichTextEditor\Features\Comments.cs region=event}} -{{source=..\SamplesVB\RichTextEditor\Features\Comments.vb region=event}} + + + -````C# - -private void radRichTextEditor1_CommentShowing(object sender, Telerik.WinForms.Documents.UI.CommentShowingEventArgs e) -{ - if (e.Comment.Author == "Boss") - { - e.AppearanceSettings.BorderBrush = System.Drawing.Brushes.Red; - e.AppearanceSettings.BackgroundBrush = System.Drawing.Brushes.Orange; - e.AppearanceSettings.HighlightColor = Telerik.WinControls.RichTextEditor.UI.Colors.Orange; - } - else - { - e.AppearanceSettings.BorderBrush = System.Drawing.Brushes.Green; - e.AppearanceSettings.BackgroundBrush = System.Drawing.Brushes.LightGray; - e.AppearanceSettings.HighlightColor = Telerik.WinControls.RichTextEditor.UI.Colors.LightGray; - } -} - -```` -````VB.NET -Private Sub radRichTextEditor1_CommentShowing(ByVal sender As Object, ByVal e As Telerik.WinForms.Documents.UI.CommentShowingEventArgs) - If e.Comment.Author = "Boss" Then - e.AppearanceSettings.BorderBrush = System.Drawing.Brushes.Red - e.AppearanceSettings.BackgroundBrush = System.Drawing.Brushes.Orange - e.AppearanceSettings.HighlightColor = Telerik.WinControls.RichTextEditor.UI.Colors.Orange - Else - e.AppearanceSettings.BorderBrush = System.Drawing.Brushes.Green - e.AppearanceSettings.BackgroundBrush = System.Drawing.Brushes.LightGray - e.AppearanceSettings.HighlightColor = Telerik.WinControls.RichTextEditor.UI.Colors.LightGray - End If -End Sub - -```` - -{{endregion}} And the result looks like this: diff --git a/controls/richtexteditor/features/content-controls/content-controls.md b/controls/richtexteditor/features/content-controls/content-controls.md index 4eeeebaf0..877c01a94 100644 --- a/controls/richtexteditor/features/content-controls/content-controls.md +++ b/controls/richtexteditor/features/content-controls/content-controls.md @@ -73,39 +73,10 @@ The __CheckBox__ content control exposes two properties __CheckedState__ and __U #### Example 1: Setting CheckBox properties -{{source=..\SamplesCS\RichTextEditor\Features\ContentControls.cs region=CheckBoxProperties}} -{{source=..\SamplesCS\RichTextEditor\Features\ContentControls.vb region=CheckBoxProperties}} + + -````C# -SdtCheckBoxState checkedBoxState = new SdtCheckBoxState(); -checkedBoxState.Font = new Telerik.WinControls.RichTextEditor.UI.FontFamily("Arial"); -checkedBoxState.CharacterCode = 0040; -SdtCheckBoxState uncheckedBoxState = new SdtCheckBoxState(); -uncheckedBoxState.Font = new Telerik.WinControls.RichTextEditor.UI.FontFamily("Arial"); -uncheckedBoxState.CharacterCode = 0024; - -CheckBoxProperties properties = new CheckBoxProperties(); -properties.CheckedState = checkedBoxState; -properties.UncheckedState = uncheckedBoxState; -properties.Checked = true; - -```` -````VB.NET -Dim checkedBoxState = New SdtCheckBoxState() -checkedBoxState.Font = New Telerik.WinControls.RichTextEditor.UI.FontFamily("Arial") -checkedBoxState.CharacterCode = 40 - -Dim uncheckedBoxState = New SdtCheckBoxState() -uncheckedBoxState.Font = New Telerik.WinControls.RichTextEditor.UI.FontFamily("Arial") -uncheckedBoxState.CharacterCode = 24 - -Dim properties = New CheckBoxProperties() -properties.CheckedState = checkedBoxState -properties.UncheckedState = uncheckedBoxState -properties.Checked = True - -```` ### ComboBox and DropDownList @@ -118,31 +89,10 @@ The __ComboBox__ and __DropDownList__ provider the user with options to choose f #### Example 2: Setting ComboBox properties -{{source=..\SamplesCS\RichTextEditor\Features\ContentControls.cs region=ComboBoxProperties}} -{{source=..\SamplesCS\RichTextEditor\Features\ContentControls.vb region=ComboBoxProperties}} - -````C# -List items = new List(); -items.Add(new ListItem() { DisplayText = "Choice 1", Value = "a" }); -items.Add(new ListItem() { DisplayText = "Choice 2", Value = "b" }); + + -ComboBoxProperties properties = new ComboBoxProperties(); -properties.Items = items; -properties.SelectedItem = items.Where(li => li.Value == "a").FirstOrDefault(); -```` -````VB.NET -Dim items As List(Of ListItem) = New List(Of ListItem)() -items.Add(New ListItem() With { - .DisplayText = "Choice 1", - .Value = "a" -}) -items.Add(New ListItem() With { - .DisplayText = "Choice 2", - .Value = "b" -}) - -```` ### Date @@ -155,27 +105,10 @@ The __Date__ content control allows you to enter a date by using a calendar. The #### Example 3: Setting Date properties -{{source=..\SamplesCS\RichTextEditor\Features\ContentControls.cs region=DateProperties}} -{{source=..\SamplesCS\RichTextEditor\Features\ContentControls.vb region=DateProperties}} - -````C# -DateProperties properties = new DateProperties(); -properties.DateFormat = "MM/dd/yyyy H:mm"; -properties.Language = new CultureInfo("bg-BG"); -properties.FullDate = DateTime.Now; -properties.Calendar = SdtCalendar.Gregorian; -properties.DateMappingType = DateMappingType.DateTime; + + -```` -````VB.NET -Dim properties As DateProperties = New DateProperties() -properties.DateFormat = "MM/dd/yyyy H:mm" -properties.Language = New CultureInfo("bg-BG") -properties.FullDate = DateTime.Now -properties.Calendar = SdtCalendar.Gregorian -properties.DateMappingType = DateMappingType.DateTime -```` ### Text @@ -184,19 +117,10 @@ The __Text__ content control allows you to enter plain text. The text content co #### Example 4: Setting Text properties -{{source=..\SamplesCS\RichTextEditor\Features\ContentControls.cs region=TextProperties}} -{{source=..\SamplesCS\RichTextEditor\Features\ContentControls.vb region=TextProperties}} - -````C# -TextProperties properties = new TextProperties(); -properties.IsMultiline = true; + + -```` -````VB.NET -Dim properties As TextProperties = New TextProperties() -properties.IsMultiline = True -```` ### RepeatingSection @@ -206,21 +130,9 @@ The __RepeatingSection__ content control repeats the content contained within it #### Example 5: Setting RepeatingSection properties -{{source=..\SamplesCS\RichTextEditor\Features\ContentControls.cs region=RepeatingSectionProperties}} -{{source=..\SamplesCS\RichTextEditor\Features\ContentControls.vb region=RepeatingSectionProperties}} - -````C# -RepeatingSectionProperties properties = new RepeatingSectionProperties(); -properties.SectionTitle = "Title"; -properties.AllowInsertAndDeleteSections = true; - -```` -````VB.NET -Dim properties As RepeatingSectionProperties = New RepeatingSectionProperties() -properties.SectionTitle = "Title" -properties.AllowInsertAndDeleteSections = True + + -```` # See Also diff --git a/controls/richtexteditor/features/content-controls/working-wirh-content-controls-ui.md b/controls/richtexteditor/features/content-controls/working-wirh-content-controls-ui.md index e048329ab..43fa1b1e1 100644 --- a/controls/richtexteditor/features/content-controls/working-wirh-content-controls-ui.md +++ b/controls/richtexteditor/features/content-controls/working-wirh-content-controls-ui.md @@ -39,41 +39,16 @@ In order to successfully execute the __InsertStructuredDocumentTagCommand__ you #### Example 1: Execute InsertStructuredDocumentTagCommand -{{source=..\SamplesCS\RichTextEditor\Features\ContentControls.cs region=ExecuteInsertStructuredDocumentTag}} -{{source=..\SamplesVB\RichTextEditor\Features\ContentControls.vb region=ExecuteInsertStructuredDocumentTag}} + + -````C# -this.radRichTextEditor1.InsertStructuredDocumentTag(SdtType.Picture); -```` -````VB.NET -Me.RadRichTextEditor1.InsertStructuredDocumentTag(SdtType.Picture) - -```` - -{{endregion}} Another way is to create a new instance of the __InsertStructuredDocumentTagCommand__ and specify the SdtType in the __Execute__ method: -{{source=..\SamplesCS\RichTextEditor\Features\ContentControls.cs region=CreateNewInsertStructuredDocumentTag}} -{{source=..\SamplesVB\RichTextEditor\Features\ContentControls.vb region=CreateNewInsertStructuredDocumentTag}} - -````C# -InsertStructuredDocumentTagCommand command = new InsertStructuredDocumentTagCommand(this.radRichTextEditor1.RichTextBoxElement); -command.Execute("Picture"); -//OR -this.radRichTextEditor1.Commands.InsertSdtCommand.Execute("Picture"); - -```` -````VB.NET -Dim command As InsertStructuredDocumentTagCommand = New InsertStructuredDocumentTagCommand(Me.RadRichTextEditor1.RichTextBoxElement) -command.Execute("Picture") -'OR -Me.RadRichTextEditor1.Commands.InsertSdtCommand.Execute("Picture") + + -```` - -{{endregion}} * __ShowContentControlPropertiesDialogCommand__ @@ -82,25 +57,10 @@ In order to execute the __ShowContentControlPropertiesDialogCommand__ you can cr #### Example 2: Execute ShowContentControlPropertiesDialogCommand -{{source=..\SamplesCS\RichTextEditor\Features\ContentControls.cs region=ShowContentControlPropertiesDialogCommand}} -{{source=..\SamplesVB\RichTextEditor\Features\ContentControls.vb region=ShowContentControlPropertiesDialogCommand}} - -````C# -ShowContentControlPropertiesDialogCommand command = new ShowContentControlPropertiesDialogCommand(this.radRichTextEditor1.RichTextBoxElement); -command.Execute("Text"); -//OR -this.radRichTextEditor1.Commands.ShowContentControlPropertiesDialogCommand.Execute("Text"); - -```` -````VB.NET -Dim command As ShowContentControlPropertiesDialogCommand = New ShowContentControlPropertiesDialogCommand(Me.RadRichTextEditor1.RichTextBoxElement) -command.Execute("Text") -'OR -Me.RadRichTextEditor1.Commands.ShowContentControlPropertiesDialogCommand.Execute("Text") + + -```` -{{endregion}} >note In order to learn more about commands and how to use them refer to [Commands](https://docs.telerik.com/devtools/winforms/controls/richtexteditor/features/commands) help article. diff --git a/controls/richtexteditor/features/content-controls/working-with-content-controls.md b/controls/richtexteditor/features/content-controls/working-with-content-controls.md index 28bd5a858..526c01bac 100644 --- a/controls/richtexteditor/features/content-controls/working-with-content-controls.md +++ b/controls/richtexteditor/features/content-controls/working-with-content-controls.md @@ -20,27 +20,10 @@ The content controls can be retrieved by using the __GetAnnotationMarkersOfType_ #### Example 1: Get all Content Controls -{{source=..\SamplesCS\RichTextEditor\Features\ContentControls.cs region=IterateContentControls}} -{{source=..\SamplesVB\RichTextEditor\Features\ContentControls.vb region=IterateContentControls}} + + -````C# -IEnumerable content_controls = this.radRichTextEditor1.Document.GetAnnotationMarkersOfType(); -foreach (var item in content_controls) -{ - Console.WriteLine("Type: {0} ID:{1}", item.SdtProperties.Type, item.SdtProperties.ID); -} -```` -````VB.NET -Dim content_controls As IEnumerable(Of SdtRangeStart) = Me.RadRichTextEditor1.Document.GetAnnotationMarkersOfType(Of SdtRangeStart)() -For Each item In content_controls - Console.WriteLine("Type: {0} ID:{1}", item.SdtProperties.Type, item.SdtProperties.ID) -Next - -```` - -{{endregion}} - ### Set content controls properties. @@ -48,35 +31,9 @@ This example shows how you can iterate the items and add an item to a existing C #### Example 2: Adding items to a ComboBox or a DropDownList -{{source=..\SamplesCS\RichTextEditor\Features\ContentControls.cs region=AddItemsToCombo}} -{{source=..\SamplesVB\RichTextEditor\Features\ContentControls.vb region=AddItemsToCombo}} - -````C# -foreach (var item in content_controls) -{ - if (item.SdtProperties.Type == SdtType.ComboBox) - { - ComboBoxProperties properties = item.SdtProperties as ComboBoxProperties; - ListItem newItem = new System.Windows.Documents.ListItem(); - newItem.DisplayText = "New Item Text"; - properties.Items.Add(newItem); - } -} - -```` -````VB.NET -For Each item In content_controls - If item.SdtProperties.Type = SdtType.ComboBox Then - Dim properties As ComboBoxProperties = TryCast(item.SdtProperties, ComboBoxProperties) - Dim newItem As New ListItem() - newItem.DisplayText = "New Item Text" - properties.Items.Add(newItem) - End If -Next - -```` - -{{endregion}} + + + ## Insert new content controls @@ -85,80 +42,23 @@ New content controls can be inserted trough one of the overloads of the __Insert #### Example 3: Inserting a content control -{{source=..\SamplesCS\RichTextEditor\Features\ContentControls.cs region=InsertContentControl}} -{{source=..\SamplesVB\RichTextEditor\Features\ContentControls.vb region=InsertContentControl}} - -````C# -this.radRichTextEditor1.InsertStructuredDocumentTag(); -// OR -RadDocumentEditor editor = new RadDocumentEditor(this.radRichTextEditor1.Document); -editor.InsertStructuredDocumentTag(); - -```` -````VB.NET -Me.RadRichTextEditor1.InsertStructuredDocumentTag() -'OR -Dim editor As RadDocumentEditor = New RadDocumentEditor(Me.RadRichTextEditor1.Document) -editor.InsertStructuredDocumentTag() + + -```` - -{{endregion}} #### Example 4: Inserting a content control using content control type -{{source=..\SamplesCS\RichTextEditor\Features\ContentControls.cs region=InsertContentControlUsingType}} -{{source=..\SamplesVB\RichTextEditor\Features\ContentControls.vb region=InsertContentControlUsingType}} - -````C# -this.radRichTextEditor1.InsertStructuredDocumentTag(SdtType.CheckBox); -// OR -RadDocumentEditor editor = new RadDocumentEditor(this.radRichTextEditor1.Document); -editor.InsertStructuredDocumentTag(SdtType.CheckBox); - -```` -````VB.NET -Me.RadRichTextEditor1.InsertStructuredDocumentTag(SdtType.CheckBox) -'OR -Dim editor As RadDocumentEditor = New RadDocumentEditor(Me.RadRichTextEditor1.Document) -editor.InsertStructuredDocumentTag(SdtType.CheckBox) + + -```` - -{{endregion}} #### Example 5: Inserting a content control using content control properties -{{source=..\SamplesCS\RichTextEditor\Features\ContentControls.cs region=InsertContentControlUsingProperties}} -{{source=..\SamplesVB\RichTextEditor\Features\ContentControls.vb region=InsertContentControlUsingProperties}} - -````C# -SdtProperties sdtProperties = new SdtProperties(SdtType.RichText) -{ - Alias = "AliasName", - Lock = Lock.SdtContentLocked, -}; -this.radRichTextEditor1.InsertStructuredDocumentTag(sdtProperties); -// OR -RadDocumentEditor editor = new RadDocumentEditor(this.radRichTextEditor1.Document); -editor.InsertStructuredDocumentTag(sdtProperties); - -```` -````VB.NET -Dim sdtProperties As SdtProperties = New SdtProperties(SdtType.RichText) With { -Alias = "AliasName", -Lock = Lock.SdtContentLocked -} -Me.RadRichTextEditor1.InsertStructuredDocumentTag(sdtProperties) -'OR -Dim editor As RadDocumentEditor = New RadDocumentEditor(Me.RadRichTextEditor1.Document) -editor.InsertStructuredDocumentTag(sdtProperties) - -```` - -{{endregion}} + + + # See Also diff --git a/controls/richtexteditor/features/custom-fonts.md b/controls/richtexteditor/features/custom-fonts.md index f3b976582..653cf8b51 100644 --- a/controls/richtexteditor/features/custom-fonts.md +++ b/controls/richtexteditor/features/custom-fonts.md @@ -22,34 +22,10 @@ In order to utilize this functionality, one needs to load the font carried with #### Custom Fonts -{{source=..\SamplesCS\RichTextEditor\Features\CustomFonts.cs region=CustomFontLoading}} -{{source=..\SamplesVB\RichTextEditor\Features\CustomFonts.vb region=CustomFontLoading}} -````C# -public CustomFonts() -{ - using (Stream stream = System.Reflection.Assembly.GetAssembly(this.GetType()).GetManifestResourceStream("SamplesCS.RichTextEditor.Features.HelveticaLt.ttf")) - { - ThemeResolutionService.LoadFont(stream); - Telerik.WinForms.Documents.Layout.FontManager.RegisterFont(new Telerik.WinControls.RichTextEditor.UI.FontFamily("Helvetica-Light")); - } - InitializeComponent(); -} - -```` -````VB.NET -Public Sub New() - Using stream As Stream = System.Reflection.Assembly.GetAssembly(Me.[GetType]()).GetManifestResourceStream("SamplesVB.HelveticaLt.ttf") - ThemeResolutionService.LoadFont(stream) - Telerik.WinForms.Documents.Layout.FontManager.RegisterFont(New Telerik.WinControls.RichTextEditor.UI.FontFamily("Helvetica-Light")) - End Using - InitializeComponent() -End Sub - -```` - - - -{{endregion}} + + + + # See Also diff --git a/controls/richtexteditor/features/document-protection.md b/controls/richtexteditor/features/document-protection.md index b239cb5fc..34d2544c9 100644 --- a/controls/richtexteditor/features/document-protection.md +++ b/controls/richtexteditor/features/document-protection.md @@ -1,263 +1,126 @@ ---- -title: Document Protection -page_title: Document Protection - WinForms RichTextEditor Control -description: Document Protection in WinForms RichTextEditor allows defining and enforcing different editing restrictions in the document for a set of users and groups. -slug: winforms/richtexteditor-/features/document-protection -tags: document,protection -published: True -position: 9 -previous_url: richtexteditor-features-document-protection ---- - -# Document Protection - -__Document Protection__ allows defining and enforcing different editing restrictions in the document for a set of users and groups. - -This article describes how this feature can be used in terms of UI and API of __RadRichTextEditor__. - -* [Defining Users](#defining-the-users) - -* [Changing the Current User](#changing-the-current-user) - -* [Toggling Document Protection](#toggling-document-protection) - -* [Creating And Modifying Document Protection Regions](#creating-and-modifying-document-protection-regions) - -## Defining the Users - -The editing restrictions can be used with a set of users or groups. When document protection is enforced, each user will be able to edit only the parts of the document he/she has rights for and the parts that are editable by the group he/she belongs to. - -The users that will be able to edit the document and the groups they are in can be declared like this: - -{{source=..\SamplesCS\RichTextEditor\Features\DocumentProtection.cs region=users}} -{{source=..\SamplesVB\RichTextEditor\Features\DocumentProtection.vb region=users}} - -````C# - -this.radRichTextEditor1.Users = new PermissionInfoCollection() -{ - PermissionInfo.CreateEveryonePermissionInfo(), - new PermissionInfo("jmiller", PermissionType.Individual, "James Miller"), - new PermissionInfo("jsmith", PermissionType.Individual, "John Smith"), - new PermissionInfo("rbrown", PermissionType.Individual, "Robert Brown"), - new PermissionInfo("Administrators", PermissionType.Group, "Administrators"), -}; - -```` -````VB.NET -Me.radRichTextEditor1.Users = New PermissionInfoCollection() From {PermissionInfo.CreateEveryonePermissionInfo(), New PermissionInfo("jmiller", PermissionType.Individual, "James Miller"), New PermissionInfo("jsmith", PermissionType.Individual, "John Smith"), New PermissionInfo("rbrown", PermissionType.Individual, "Robert Brown"), New PermissionInfo("Administrators", PermissionType.Group, "Administrators")} - -```` - -{{endregion}} - -This code determines 3 users and two groups but does not specify the relationship between the users and the groups. This is so because users have the potential to change their groups. - -The collection kept in the **Users** property of __RadRichTextEditor__ is also used in the default __ChangeEditingPermissionsDialog__ which creates the **PermissionRangeInfos** to be inserted in the document. - -## Changing the Current User - -The current user of the document is set using the __CurrentUser__ property of the editor. It is of type **UserInfo** - here in addition to the name of the user, the group that the user belongs to can also be passed. - -{{source=..\SamplesCS\RichTextEditor\Features\DocumentProtection.cs region=current}} -{{source=..\SamplesVB\RichTextEditor\Features\DocumentProtection.vb region=current}} - -````C# - -this.radRichTextEditor1.CurrentUser = new UserInfo("Users", "James Miller", "jmiller", "jmiller@example.com"); - -```` -````VB.NET -Me.radRichTextEditor1.CurrentUser = New UserInfo("Users", "James Miller", "jmiller", "jmiller@example.com") - -```` - -{{endregion}} - -You can also create a collection with the **UserInfos** that will be interacting with the document and wire it with some UI of yours. For example, if you set-up the collection as follows: - -{{source=..\SamplesCS\RichTextEditor\Features\DocumentProtection.cs region=usersList}} -{{source=..\SamplesVB\RichTextEditor\Features\DocumentProtection.vb region=usersList}} - -````C# - -List CurrentUsers = new List() -{ - new UserInfo("Users", "James Miller", "jmiller", "jmiller@example.com"), - new UserInfo("Administrators", "John Smith", "jsmith", "jsmith@example.com"), - new UserInfo("Administrators", "Robert Brown", "rbrown", "rbrown@example.com"), -}; - -```` -````VB.NET -Dim CurrentUsers As New List(Of UserInfo)() From { - New UserInfo("Users", "James Miller", "jmiller", "jmiller@example.com"), - New UserInfo("Administrators", "John Smith", "jsmith", "jsmith@example.com"), - New UserInfo("Administrators", "Robert Brown", "rbrown", "rbrown@example.com") -} - -```` - -{{endregion}} - -You can declare a __RadDropDownList__ which will be used to change the current user in the following way: - -{{source=..\SamplesCS\RichTextEditor\Features\DocumentProtection.cs region=combo1}} -{{source=..\SamplesVB\RichTextEditor\Features\DocumentProtection.vb region=combo1}} - -````C# - -RadDropDownList dropdown1 = new RadDropDownList(); -dropdown1.Location = new Point(10, 10); -this.Controls.Add(dropdown1); -dropdown1.SelectedIndexChanged += this.dropdown1_SelectedIndexChanged; - -```` -````VB.NET -Dim dropdown1 As New RadDropDownList() -dropdown1.Location = New Point(10, 10) -Me.Controls.Add(dropdown1) -AddHandler dropdown1.SelectedIndexChanged, AddressOf Me.dropdown1_SelectedIndexChanged - -```` - -{{endregion}} - -and populate it like this: - -{{source=..\SamplesCS\RichTextEditor\Features\DocumentProtection.cs region=combo2}} -{{source=..\SamplesVB\RichTextEditor\Features\DocumentProtection.vb region=combo2}} - -````C# - -dropdown1.DataSource = CurrentUsers; -dropdown1.DisplayMember = "Username"; - -```` -````VB.NET -dropdown1.DataSource = CurrentUsers -dropdown1.DisplayMember = "Username" - -```` - -{{endregion}} - -Then, when the selected item of the combo changes, the **CurrentUser** of the editor will be updated: - -{{source=..\SamplesCS\RichTextEditor\Features\DocumentProtection.cs region=combo3}} -{{source=..\SamplesVB\RichTextEditor\Features\DocumentProtection.vb region=combo3}} - -````C# -private void dropdown1_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e) -{ - this.radRichTextEditor1.CurrentUser = ((RadDropDownList)sender).SelectedValue as UserInfo; -} - -```` -````VB.NET -Private Sub dropdown1_SelectedIndexChanged(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.Data.PositionChangedEventArgs) - Me.radRichTextEditor1.CurrentUser = TryCast(DirectCast(sender, RadDropDownList).SelectedValue, UserInfo) -End Sub - -```` - -{{endregion}} - -## Toggling Document Protection - -When document protection is enforced, the current user can modify the rights for editing the part of the document that he/she is entitled to editing. When the protection is disabled, the editing rights for the document can be freely modified by all users. - -The protection of the document can be turned on and off using the __ToggleDocumentProtectionCommand__ command of **RadRichTextEditor**. - -The command opens a dialog that allows you to enter a password. By clicking OK, the document protection starts to be enforced. - -It is also possible to toggle document protection in code-behind, without showing a dialog: - -{{source=..\SamplesCS\RichTextEditor\Features\DocumentProtection.cs region=password}} -{{source=..\SamplesVB\RichTextEditor\Features\DocumentProtection.vb region=password}} - -````C# - -this.radRichTextEditor1.Document.ProtectDocument(DocumentProtectionMode.ReadOnly, "password"); - -```` -````VB.NET -Me.radRichTextEditor1.Document.ProtectDocument(DocumentProtectionMode.ReadOnly, "password") - -```` - -{{endregion}} - -The reverse operations can be executed like this: - -{{source=..\SamplesCS\RichTextEditor\Features\DocumentProtection.cs region=unprotect}} -{{source=..\SamplesVB\RichTextEditor\Features\DocumentProtection.vb region=unprotect}} - -````C# +--- +title: Document Protection +page_title: Document Protection - WinForms RichTextEditor Control +description: Document Protection in WinForms RichTextEditor allows defining and enforcing different editing restrictions in the document for a set of users and groups. +slug: winforms/richtexteditor-/features/document-protection +tags: document,protection +published: True +position: 9 +previous_url: richtexteditor-features-document-protection +--- + +# Document Protection + +__Document Protection__ allows defining and enforcing different editing restrictions in the document for a set of users and groups. + +This article describes how this feature can be used in terms of UI and API of __RadRichTextEditor__. + +* [Defining Users](#defining-the-users) + +* [Changing the Current User](#changing-the-current-user) + +* [Toggling Document Protection](#toggling-document-protection) + +* [Creating And Modifying Document Protection Regions](#creating-and-modifying-document-protection-regions) + +## Defining the Users + +The editing restrictions can be used with a set of users or groups. When document protection is enforced, each user will be able to edit only the parts of the document he/she has rights for and the parts that are editable by the group he/she belongs to. + +The users that will be able to edit the document and the groups they are in can be declared like this: + + + + + + +This code determines 3 users and two groups but does not specify the relationship between the users and the groups. This is so because users have the potential to change their groups. + +The collection kept in the **Users** property of __RadRichTextEditor__ is also used in the default __ChangeEditingPermissionsDialog__ which creates the **PermissionRangeInfos** to be inserted in the document. + +## Changing the Current User + +The current user of the document is set using the __CurrentUser__ property of the editor. It is of type **UserInfo** - here in addition to the name of the user, the group that the user belongs to can also be passed. + + + + + + +You can also create a collection with the **UserInfos** that will be interacting with the document and wire it with some UI of yours. For example, if you set-up the collection as follows: + + + + + + +You can declare a __RadDropDownList__ which will be used to change the current user in the following way: + + + + + + +and populate it like this: + + + + + + +Then, when the selected item of the combo changes, the **CurrentUser** of the editor will be updated: + + + + + + +## Toggling Document Protection + +When document protection is enforced, the current user can modify the rights for editing the part of the document that he/she is entitled to editing. When the protection is disabled, the editing rights for the document can be freely modified by all users. -this.radRichTextEditor1.Document.UnprotectDocument("password"); - -```` -````VB.NET -Me.radRichTextEditor1.Document.UnprotectDocument("password") - -```` - -{{endregion}} - -Note that the **UnprotectDocument** method will succeed only if the password you have passed as parameter matches the one used to protect the document. - -## Creating and Modifying Document Protection Regions - -**DocumentProtection** regions can be most easily created and modified through the **ChangeEditingPermissionsDialog** which can be invoked through the __ShowChangeEditingPermissionsDialogCommand__ of __RadRichTextEditor__. They can also be edited in code-behind, using the API of **RadRichTextEditor** and **RadDocument**. - -Here is an example: - -{{source=..\SamplesCS\RichTextEditor\Features\DocumentProtection.cs region=permissions}} -{{source=..\SamplesVB\RichTextEditor\Features\DocumentProtection.vb region=permissions}} - -````C# -PermissionRangeInfo info = new PermissionRangeInfo(); -info.Type = PermissionType.Individual; -info.Name = this.radRichTextEditor1.CurrentUser.Username; -List infos = new List() { info }; -this.radRichTextEditor1.InsertPermissionRange(infos); - -```` -````VB.NET -Dim info As New PermissionRangeInfo() -info.Type = PermissionType.Individual -info.Name = Me.radRichTextEditor1.CurrentUser.Username -Dim infos As New List(Of PermissionRangeInfo)() From {info} -Me.radRichTextEditor1.InsertPermissionRange(infos) - -```` - -{{endregion}} - -This code will insert a permission range around the current selection in the document. The type of the permission is *Individual* - meaning that only the **CurrentUser** will be able to edit the region. - -To change the highlight color of the permission range, we can use the __EnforcedPermissionRangeBrush__ property. - -{{source=..\SamplesCS\RichTextEditor\Features\DocumentProtection.cs region=color_permissions}} -{{source=..\SamplesVB\RichTextEditor\Features\DocumentProtection.vb region=color_permissions}} - -````C# - -this.radRichTextEditor1.RichTextBoxElement.EnforcedPermissionRangeBrush = new SolidBrush(System.Drawing.Color.Red); - - -```` -````VB.NET - -Me.radRichTextEditor1.RichTextBoxElement.EnforcedPermissionRangeBrush = New SolidBrush(System.Drawing.Color.Red) - - -```` - - -# See Also - - * [Positioning]({%slug winforms/richtexteditor-/features/positioning%}) - - * [Selection]({%slug winforms/richtexteditor-/features/selection%}) +The protection of the document can be turned on and off using the __ToggleDocumentProtectionCommand__ command of **RadRichTextEditor**. + +The command opens a dialog that allows you to enter a password. By clicking OK, the document protection starts to be enforced. + +It is also possible to toggle document protection in code-behind, without showing a dialog: + + + + + + +The reverse operations can be executed like this: + + + + + + +Note that the **UnprotectDocument** method will succeed only if the password you have passed as parameter matches the one used to protect the document. + +## Creating and Modifying Document Protection Regions + +**DocumentProtection** regions can be most easily created and modified through the **ChangeEditingPermissionsDialog** which can be invoked through the __ShowChangeEditingPermissionsDialogCommand__ of __RadRichTextEditor__. They can also be edited in code-behind, using the API of **RadRichTextEditor** and **RadDocument**. + +Here is an example: + + + + + + +This code will insert a permission range around the current selection in the document. The type of the permission is *Individual* - meaning that only the **CurrentUser** will be able to edit the region. + +To change the highlight color of the permission range, we can use the __EnforcedPermissionRangeBrush__ property. + + + + + + +# See Also + + * [Positioning]({%slug winforms/richtexteditor-/features/positioning%}) + + * [Selection]({%slug winforms/richtexteditor-/features/selection%}) diff --git a/controls/richtexteditor/features/fields-and-document-variables/custom-fields.md b/controls/richtexteditor/features/fields-and-document-variables/custom-fields.md index 051f16901..012f24ac6 100644 --- a/controls/richtexteditor/features/fields-and-document-variables/custom-fields.md +++ b/controls/richtexteditor/features/fields-and-document-variables/custom-fields.md @@ -1,336 +1,129 @@ ---- -title: Custom Fields -page_title: Custom Fields - WinForms RichTextEditor Control -description: Fields In WinForms RichTextEditor are a convenient way to show non-static data in the document. It is possible to present different data to the end-user without actually changing the document content. -slug: winforms/richtexteditor-/features/fields-and-document-variables/custom-fields -tags: custom,fields -published: True -position: 2 -previous_url: richtexteditor-features-fields-and-document-variables-custom-fields ---- - -# Custom Fields - -Fields are a convenient way to show non-static data in the document. In this way, you could present different data to the end-user without actually changing the document content. - -For a description of the supported out of the box field types, please refer to [this article]({%slug winforms/richtexteditor-/features/fields-and-document-variables/fields%}). - -This topic will explain how custom fields can be created in order to suit application-specific purposes. It contains the following sections: - -* [Creating a Custom Field](#create-custom-field) - -* [Adding Properties](#adding-properties) - -## Create Custom Field - -In some cases, it is convenient to extend the currently available fields to suit application-specific scenarios. This can be done by inheriting from __CodeBasedField__ or (if the functionality of the new field will be closely connected to Mail Merge) from __MergeField__. - -This topic will list the steps for creating such a custom field. - -1\. Have your class inherit from **MergeField** or **CodeBasedField**: - -{{source=..\SamplesCS\RichTextEditor\Features\CustomFields.cs region=define}} -{{source=..\SamplesVB\RichTextEditor\Features\CustomFields.vb region=define}} - -````C# -public class CustomField : CodeBasedField - -```` -````VB.NET -Public Class CustomField -Inherits CodeBasedField - -```` - -{{endregion}} - -2\. Give a **FieldTypeName** to instances of your field: - -{{source=..\SamplesCS\RichTextEditor\Features\CustomFields.cs region=TypeName}} -{{source=..\SamplesVB\RichTextEditor\Features\CustomFields.vb region=TypeName}} - -````C# - -private static readonly string FieldType = "CUSTOMFIELD"; - -public override string FieldTypeName -{ - get - { - return CustomField.FieldType; - } -} - -```` -````VB.NET -Private Shared ReadOnly FieldType As String = "CUSTOMFIELD" -Public Overrides ReadOnly Property FieldTypeName() As String - Get - Return CustomField.FieldType - End Get -End Property - -```` - -{{endregion}} - -The field type is shown when the field is in code mode, just after the opening curly bracket. If you toggle the field to Code mode and modify this first word, the type of the field will also change. That is why it is important to give a meaningful name to the field. - -3\. Register your custom field type in the factory that **RadDocument** uses. It is convenient to use the static constructor of the class for that purpose: - -{{source=..\SamplesCS\RichTextEditor\Features\CustomFields.cs region=ctor}} -{{source=..\SamplesVB\RichTextEditor\Features\CustomFields.vb region=ctor}} - -````C# - -static CustomField() -{ - CodeBasedFieldFactory.RegisterFieldType(CustomField.FieldType, () => new CustomField()); -} - -```` -````VB.NET -Shared Sub New() - CodeBasedFieldFactory.RegisterFieldType(CustomField.FieldType, Function() New CustomField()) -End Sub - -```` - -{{endregion}} - -The function passed as a second parameter essentially tells the document how it could create a new instance of the field. This is required because fields have to be created internally when you copy/paste or even when you toggle field modes. - -4\. Override the **CreateInstance()** method to return a new instance of your custom field: - -{{source=..\SamplesCS\RichTextEditor\Features\CustomFields.cs region=create}} -{{source=..\SamplesVB\RichTextEditor\Features\CustomFields.vb region=create}} - -````C# - -public override Field CreateInstance() -{ - return new CustomField(); -} - -```` -````VB.NET -Public Overrides Function CreateInstance() As Field - Return New CustomField() -End Function - -```` - -{{endregion}} - -5\. If you have inherited from **CodeBasedField** or you would like to customize the way the field appears in the document in *ResultMode*, override the __GetResultFragment__ method. In short, it will return a **DocumentFragment** with the content that should be shown when the field is updated and its mode is changed to *Result*. - -That is all that needs to be done in order to be able to get your custom field working, insert it in documents, serialize and deserialize it. - -## Adding Properties - -If you would like to add some properties to this field, similar to the **PropertyPath** field of **MergeFields**, you can do so following the steps bellow: - -1\. Create a read-only **FieldProperty**: - -{{source=..\SamplesCS\RichTextEditor\Features\CustomFields.cs region=field}} -{{source=..\SamplesVB\RichTextEditor\Features\CustomFields.vb region=field}} - -````C# - -private readonly FieldProperty myProperty; - -```` -````VB.NET -Private ReadOnly _myProperty As FieldProperty - -```` - -{{endregion}} - -2\. Add a public CLR property. Properties of type string can be set and retrieved from the **FieldProperty** directly. No other types are accepted, as it would not be possible to convert them correctly to text for the purpose of field evaluation when inserted in the document. Therefore, if you would like to have non-string properties, you would have to make the conversion to/from string yourself: - -{{source=..\SamplesCS\RichTextEditor\Features\CustomFields.cs region=property}} -{{source=..\SamplesVB\RichTextEditor\Features\CustomFields.vb region=property}} - -````C# - -[XamlSerializable] -public string MyProperty -{ - get - { - return this.myProperty.GetValue(); - } - set - { - if (!this.myProperty.IsNestedField && this.myProperty.GetValue() == value) - { - return; - } - - this.myProperty.SetValue(value); - this.InvalidateCode(); - } -} - -```` -````VB.NET - -Public Property MyProperty() As String - Get - Return Me._myProperty.GetValue() - End Get - Set(ByVal value As String) - If (Not Me._myProperty.IsNestedField) AndAlso Me._myProperty.GetValue() = value Then - Return - End If - Me._myProperty.SetValue(value) - Me.InvalidateCode() - End Set -End Property - -```` - -{{endregion}} - -The **XamlSerializable** attribute ensures that this property will be exported and imported to/from XAML when **XamlFormatProvider** is used. The other part of the code ensures that the field will be reset only if the new value is different and that the code will be invalidated, so as to be correctly updated on the next pass. - -3\. Declare a static **FieldPropertyDefinition** wired to your property: - -{{source=..\SamplesCS\RichTextEditor\Features\CustomFields.cs region=static}} -{{source=..\SamplesVB\RichTextEditor\Features\CustomFields.vb region=static}} - -````C# - -public static readonly FieldPropertyDefinition MyPropertyProperty = new FieldPropertyDefinition("MyProperty"); - -```` -````VB.NET -Public Shared ReadOnly MyPropertyProperty As New FieldPropertyDefinition("MyProperty") - -```` - -{{endregion}} - -4\. Make sure to initialize the **FieldProperty** in the constructor of your field: - -{{source=..\SamplesCS\RichTextEditor\Features\CustomFields.cs region=ctor2}} -{{source=..\SamplesVB\RichTextEditor\Features\CustomFields.vb region=ctor2}} - -````C# - -public CustomField() -{ - this.myProperty = new FieldProperty(this, CustomField.MyPropertyProperty); -} - -```` -````VB.NET -Public Sub New() - Me._myProperty = New FieldProperty(Me, CustomField.MyPropertyProperty) -End Sub - -```` - -{{endregion}} - -5\. Ensure that your custom property is copied along with the other field properties: - -{{source=..\SamplesCS\RichTextEditor\Features\CustomFields.cs region=codeExpression}} -{{source=..\SamplesVB\RichTextEditor\Features\CustomFields.vb region=codeExpression}} - -````C# - -protected override void CopyPropertiesFromCodeExpression(FieldCodeExpression fieldCodeExpression) -{ - base.CopyPropertiesFromCodeExpression(fieldCodeExpression); - this.myProperty.SetValue(fieldCodeExpression.FieldArgumentNode); -} - -```` -````VB.NET -Protected Overrides Sub CopyPropertiesFromCodeExpression(ByVal fieldCodeExpression As FieldCodeExpression) - MyBase.CopyPropertiesFromCodeExpression(fieldCodeExpression) - Me._myProperty.SetValue(fieldCodeExpression.FieldArgumentNode) -End Sub - -```` - -{{endregion}} - -This method is used when a field is created from field fragment. This happens when you update a field and is what enables changing the property path of a merge field by typing in the editor or even changing a **PageField** to a **DateField**. As the type of the new field is inferred from the text in the document, it is required that the field be created anew and the respective properties must be copied as well. - -{{source=..\SamplesCS\RichTextEditor\Features\CustomFields.cs region=build}} -{{source=..\SamplesVB\RichTextEditor\Features\CustomFields.vb region=build}} - -````C# - -protected override void BuildCodeOverride() -{ - base.BuildCodeOverride(); - this.CodeBuilder.SetFieldArgument(this.myProperty); -} - -```` -````VB.NET -Protected Overrides Sub BuildCodeOverride() - MyBase.BuildCodeOverride() - Me.CodeBuilder.SetFieldArgument(Me._myProperty) -End Sub - -```` - -{{endregion}} - -This method is invoked when the **CodeFragment** of the field is requested. In it, the field arguments and switches must be added, so that they are properly included in the field. - -{{source=..\SamplesCS\RichTextEditor\Features\CustomFields.cs region=copy}} -{{source=..\SamplesVB\RichTextEditor\Features\CustomFields.vb region=copy}} - -````C# - -public override void CopyPropertiesFrom(Field fromField) -{ - base.CopyPropertiesFrom(fromField); - CustomField customField = (CustomField)fromField; - this.myProperty.CopyPropertiesFrom(customField.myProperty); -} - -```` -````VB.NET -Public Overrides Sub CopyPropertiesFrom(ByVal fromField As Field) - MyBase.CopyPropertiesFrom(fromField) - Dim _customField As CustomField = CType(fromField, CustomField) - Me._myProperty.CopyPropertiesFrom(_customField._myProperty) -End Sub - -```` - -{{endregion}} - -As field ranges are copyable, this method must be overridden in order to ensure that the added properties will also be copied. - -6\. If you like, you can also customize the fragment that is returned when the **ResultFragment** is requested. This is done by overriding the __GetResultFragment__ method. Here is an example: - -{{source=..\SamplesCS\RichTextEditor\Features\CustomFields.cs region=fragment}} -{{source=..\SamplesVB\RichTextEditor\Features\CustomFields.vb region=fragment}} - -````C# - -protected override DocumentFragment GetResultFragment() -{ - return DocumentFragment.CreateFromInline(new Span(this.MyProperty)); -} - -```` -````VB.NET -Protected Overrides Function GetResultFragment() As DocumentFragment - Return DocumentFragment.CreateFromInline(New Span(Me.MyProperty)) -End Function - -```` - -{{endregion}} - - - +--- +title: Custom Fields +page_title: Custom Fields - WinForms RichTextEditor Control +description: Fields In WinForms RichTextEditor are a convenient way to show non-static data in the document. It is possible to present different data to the end-user without actually changing the document content. +slug: winforms/richtexteditor-/features/fields-and-document-variables/custom-fields +tags: custom,fields +published: True +position: 2 +previous_url: richtexteditor-features-fields-and-document-variables-custom-fields +--- + +# Custom Fields + +Fields are a convenient way to show non-static data in the document. In this way, you could present different data to the end-user without actually changing the document content. + +For a description of the supported out of the box field types, please refer to [this article]({%slug winforms/richtexteditor-/features/fields-and-document-variables/fields%}). + +This topic will explain how custom fields can be created in order to suit application-specific purposes. It contains the following sections: + +* [Creating a Custom Field](#create-custom-field) + +* [Adding Properties](#adding-properties) + +## Create Custom Field + +In some cases, it is convenient to extend the currently available fields to suit application-specific scenarios. This can be done by inheriting from __CodeBasedField__ or (if the functionality of the new field will be closely connected to Mail Merge) from __MergeField__. + +This topic will list the steps for creating such a custom field. + +1\. Have your class inherit from **MergeField** or **CodeBasedField**: + + + + + + +2\. Give a **FieldTypeName** to instances of your field: + + + + + + +The field type is shown when the field is in code mode, just after the opening curly bracket. If you toggle the field to Code mode and modify this first word, the type of the field will also change. That is why it is important to give a meaningful name to the field. + +3\. Register your custom field type in the factory that **RadDocument** uses. It is convenient to use the static constructor of the class for that purpose: + + + + + + +The function passed as a second parameter essentially tells the document how it could create a new instance of the field. This is required because fields have to be created internally when you copy/paste or even when you toggle field modes. + +4\. Override the **CreateInstance()** method to return a new instance of your custom field: + + + + + + +5\. If you have inherited from **CodeBasedField** or you would like to customize the way the field appears in the document in *ResultMode*, override the __GetResultFragment__ method. In short, it will return a **DocumentFragment** with the content that should be shown when the field is updated and its mode is changed to *Result*. + +That is all that needs to be done in order to be able to get your custom field working, insert it in documents, serialize and deserialize it. + +## Adding Properties + +If you would like to add some properties to this field, similar to the **PropertyPath** field of **MergeFields**, you can do so following the steps bellow: + +1\. Create a read-only **FieldProperty**: + + + + + + +2\. Add a public CLR property. Properties of type string can be set and retrieved from the **FieldProperty** directly. No other types are accepted, as it would not be possible to convert them correctly to text for the purpose of field evaluation when inserted in the document. Therefore, if you would like to have non-string properties, you would have to make the conversion to/from string yourself: + + + + + + +The **XamlSerializable** attribute ensures that this property will be exported and imported to/from XAML when **XamlFormatProvider** is used. The other part of the code ensures that the field will be reset only if the new value is different and that the code will be invalidated, so as to be correctly updated on the next pass. + +3\. Declare a static **FieldPropertyDefinition** wired to your property: + + + + + + +4\. Make sure to initialize the **FieldProperty** in the constructor of your field: + + + + + + +5\. Ensure that your custom property is copied along with the other field properties: + + + + + + +This method is used when a field is created from field fragment. This happens when you update a field and is what enables changing the property path of a merge field by typing in the editor or even changing a **PageField** to a **DateField**. As the type of the new field is inferred from the text in the document, it is required that the field be created anew and the respective properties must be copied as well. + + + + + + +This method is invoked when the **CodeFragment** of the field is requested. In it, the field arguments and switches must be added, so that they are properly included in the field. + + + + + + +As field ranges are copyable, this method must be overridden in order to ensure that the added properties will also be copied. + +6\. If you like, you can also customize the fragment that is returned when the **ResultFragment** is requested. This is done by overriding the __GetResultFragment__ method. Here is an example: + + + + + + diff --git a/controls/richtexteditor/features/fields-and-document-variables/document-variables.md b/controls/richtexteditor/features/fields-and-document-variables/document-variables.md index 60c85ab68..ebbf23067 100644 --- a/controls/richtexteditor/features/fields-and-document-variables/document-variables.md +++ b/controls/richtexteditor/features/fields-and-document-variables/document-variables.md @@ -1,89 +1,45 @@ ---- -title: Document Variables -page_title: Document Variables - WinForms RichTextEditor Control -description: Document variables in WinForms RichTextEditor provide a mechanism to store information in the document. It is possible to define nested fields and can be used as the backbone of master-detail mail merge. -slug: winforms/richtexteditor-/features/fields-and-document-variables/document-variables -tags: document,variables -published: True -position: 1 -previous_url: richtexteditor-features-fields-and-document-variables-document-variables ---- - -# Document Variables - -Document variables provide a mechanism to store information in the document. They also provide a convenient way to define more complicated field constructions (nested fields) and can be used as the backbone of master-detail mail merge. - -Each **RadDocument** instance has a dictionary of variables exposed by the __DocumentVariables__ property: - -{{source=..\SamplesCS\RichTextEditor\Features\DocumentVariables.cs region=get}} -{{source=..\SamplesVB\RichTextEditor\Features\DocumentVariables.vb region=get}} - -````C# - -Telerik.WinForms.Documents.Model.DocumentVariableCollection variables = this.radRichTextEditor1.Document.DocumentVariables; - -```` -````VB.NET -Dim variables As Telerik.WinForms.Documents.Model.DocumentVariableCollection = Me.radRichTextEditor1.Document.DocumentVariables - -```` - -{{endregion}} - -This collection maps string keys to object values (most often strings). The values of the fields most often are strings again and contain the text that will be inserted in the document when the variable is inserted in the document and is evaluated. Variables can be added to this collection in one of the following ways: - -{{source=..\SamplesCS\RichTextEditor\Features\DocumentVariables.cs region=add}} -{{source=..\SamplesVB\RichTextEditor\Features\DocumentVariables.vb region=add}} - -````C# -this.radRichTextEditor1.Document.DocumentVariables.Add("Name", "Andrew Fuller"); -this.radRichTextEditor1.Document.DocumentVariables["Job"] = "Software Engineer"; - -```` -````VB.NET -Me.radRichTextEditor1.Document.DocumentVariables.Add("Name", "Andrew Fuller") -Me.radRichTextEditor1.Document.DocumentVariables("Job") = "Software Engineer" - -```` - -{{endregion}} - -This code will add two variables to the document – "**Name**", which will be evaluated to "*Andrew Fuller*" and "**Job**" with a value "*Software Engineer*". The second syntax can also be used to modify the value of a variable that has already been added to the collection. - -Removing variables from the collection can be done like this: - -{{source=..\SamplesCS\RichTextEditor\Features\DocumentVariables.cs region=remove}} -{{source=..\SamplesVB\RichTextEditor\Features\DocumentVariables.vb region=remove}} - -````C# - -this.radRichTextEditor1.Document.DocumentVariables.Remove("Name"); - -```` -````VB.NET -Me.radRichTextEditor1.Document.DocumentVariables.Remove("Name") - -```` - -{{endregion}} - -Document variables can be inserted in the document using **DocumentVariableField**. Here is an example how the above created **Name** variable can be inserted in the current document of the editor: - -{{source=..\SamplesCS\RichTextEditor\Features\DocumentVariables.cs region=field}} -{{source=..\SamplesVB\RichTextEditor\Features\DocumentVariables.vb region=field}} - -````C# -Telerik.WinForms.Documents.Model.DocumentVariableField docVariable = new Telerik.WinForms.Documents.Model.DocumentVariableField() { VariableName = "Name" }; -this.radRichTextEditor1.InsertField(docVariable); - -```` -````VB.NET -Dim docVariable As New Telerik.WinForms.Documents.Model.DocumentVariableField() With {.VariableName = "Name"} -Me.radRichTextEditor1.InsertField(docVariable) - -```` - -{{endregion}} - - - +--- +title: Document Variables +page_title: Document Variables - WinForms RichTextEditor Control +description: Document variables in WinForms RichTextEditor provide a mechanism to store information in the document. It is possible to define nested fields and can be used as the backbone of master-detail mail merge. +slug: winforms/richtexteditor-/features/fields-and-document-variables/document-variables +tags: document,variables +published: True +position: 1 +previous_url: richtexteditor-features-fields-and-document-variables-document-variables +--- + +# Document Variables + +Document variables provide a mechanism to store information in the document. They also provide a convenient way to define more complicated field constructions (nested fields) and can be used as the backbone of master-detail mail merge. + +Each **RadDocument** instance has a dictionary of variables exposed by the __DocumentVariables__ property: + + + + + + +This collection maps string keys to object values (most often strings). The values of the fields most often are strings again and contain the text that will be inserted in the document when the variable is inserted in the document and is evaluated. Variables can be added to this collection in one of the following ways: + + + + + + +This code will add two variables to the document – "**Name**", which will be evaluated to "*Andrew Fuller*" and "**Job**" with a value "*Software Engineer*". The second syntax can also be used to modify the value of a variable that has already been added to the collection. + +Removing variables from the collection can be done like this: + + + + + + +Document variables can be inserted in the document using **DocumentVariableField**. Here is an example how the above created **Name** variable can be inserted in the current document of the editor: + + + + + + diff --git a/controls/richtexteditor/features/fields-and-document-variables/fields.md b/controls/richtexteditor/features/fields-and-document-variables/fields.md index dfdfc58d8..0a3504c10 100644 --- a/controls/richtexteditor/features/fields-and-document-variables/fields.md +++ b/controls/richtexteditor/features/fields-and-document-variables/fields.md @@ -74,38 +74,19 @@ Inserting any type of field in the document of an editor can be done with the __ #### Insert a page field: -{{source=..\SamplesCS\RichTextEditor\Features\Fields.cs region=insert}} -{{source=..\SamplesVB\RichTextEditor\Features\Fields.vb region=insert}} + + -````C# -this.radRichTextEditor1.InsertField(new PageField()); -```` -````VB.NET -Me.radRichTextEditor1.InsertField(New PageField()) - -```` - -{{endregion}} Update of a field can be triggered from the context menu or using the __UpdateField()__ method of **RadRichTextEditor** by passing the **FieldRangeStart** of the field as a parameter. #### Update a field: -{{source=..\SamplesCS\RichTextEditor\Features\Fields.cs region=update}} -{{source=..\SamplesVB\RichTextEditor\Features\Fields.vb region=update}} - -````C# -this.radRichTextEditor1.UpdateField(new FieldRangeStart()); - -```` -````VB.NET -Me.radRichTextEditor1.UpdateField(New FieldRangeStart()) + + -```` - -{{endregion}} You can also update all fields in the current document with the __UpdateAllFields()__ method of **RadRichTextEditor**. @@ -116,19 +97,10 @@ All field types in the context of **RadDocument** have an update priority which Priority can be specified through the __FieldsUpdateManager__ static class. The following code snippet shows how to set higher priority for a specific field type, causing all fields of this type to be updated before the rest of the fields when calling **UpdateAllField()**: -{{source=..\SamplesCS\RichTextEditor\Features\Fields.cs region=register}} -{{source=..\SamplesVB\RichTextEditor\Features\Fields.vb region=register}} - -````C# -FieldsUpdateManager.RegisterFieldUpdateInfo(typeof(ReferenceField), new FieldTypeUpdateInfo() { Priority = 1000 }); - -```` -````VB.NET -FieldsUpdateManager.RegisterFieldUpdateInfo(GetType(ReferenceField), New FieldTypeUpdateInfo() With {.Priority = 1000}) + + -```` -{{endregion}} >warning Having many different values for field priory is not recommended and may lead to performance degradation of the **UpdateAllFields()** method. The reason for this is that all fields with the same priority are updated in a batch update. Having more priority groups leads to execution of more batch updates. > diff --git a/controls/richtexteditor/features/format-painter.md b/controls/richtexteditor/features/format-painter.md index 853dd2d67..f468a0ba2 100644 --- a/controls/richtexteditor/features/format-painter.md +++ b/controls/richtexteditor/features/format-painter.md @@ -53,36 +53,10 @@ Note, that these methods work with the current position and selection in the doc #### Copying and Pasting Formatting -{{source=..\SamplesCS\RichTextEditor\Features\FormatPainter.cs region=FormatPainter}} -{{source=..\SamplesVB\RichTextEditor\Features\FormatPainter.vb region=FormatPainter}} -````C# -this.radRichTextEditor1.RichTextBoxElement.CopyFormatting(); - -DocumentPosition start = new DocumentPosition(this.radRichTextEditor1.Document.CaretPosition); -DocumentPosition end = new DocumentPosition(start); - -start.MoveToFirstPositionInDocument(); -end.MoveToEndOfDocumentElement(start.GetCurrentParagraphBox().AssociatedParagraph); - -this.radRichTextEditor1.Document.Selection.SetSelectionStart(start); -this.radRichTextEditor1.Document.Selection.AddSelectionEnd(end); - -this.radRichTextEditor1.RichTextBoxElement.PasteFormatting(); - -```` -````VB.NET -Me.radRichTextEditor1.RichTextBoxElement.CopyFormatting() -Dim start As DocumentPosition = New DocumentPosition(Me.radRichTextEditor1.Document.CaretPosition) -Dim [end] As DocumentPosition = New DocumentPosition(start) -start.MoveToFirstPositionInDocument() -[end].MoveToEndOfDocumentElement(start.GetCurrentParagraphBox().AssociatedParagraph) -Me.radRichTextEditor1.Document.Selection.SetSelectionStart(start) -Me.radRichTextEditor1.Document.Selection.AddSelectionEnd([end]) -Me.radRichTextEditor1.RichTextBoxElement.PasteFormatting() - -```` - -{{endregion}} + + + + The example uses the **DocumentPosition** and **DocumentSelection** APIs to create different positions and select content. More information about these APIs is available in the [Positioning]({%slug winforms/richtexteditor-/features/positioning%}) and [Selection]({%slug winforms/richtexteditor-/features/selection%}) topics. diff --git a/controls/richtexteditor/features/headers-and-footers.md b/controls/richtexteditor/features/headers-and-footers.md index e7bb4dece..a7edc958b 100644 --- a/controls/richtexteditor/features/headers-and-footers.md +++ b/controls/richtexteditor/features/headers-and-footers.md @@ -1,224 +1,117 @@ ---- -title: Headers and Footers -page_title: Headers and Footers - WinForms RichTextEditor Control -description: WinForms RichTextEditor supports Headers and Footers in its document when in Paged layout mode. -slug: winforms/richtexteditor-/features/headers-and-footers -tags: headers,and,footers -published: True -position: 9 -previous_url: richtexteditor-features-headers-and-footers ---- - -# Headers and Footers - -__RadRichTextEditor__ supports **Headers** and **Footers** in its document when in *Paged* [layout mode]({%slug winforms/richtexteditor-/document-elements/raddocument%}). - ->note Note that **Headers** and **Footers** are not persisted when exporting with **HtmlFormatProvider**. You can read more about this [here](https://docs.telerik.com/devtools/winforms/controls/richtexteditor/import-export/overview) -> - -The topic contains the following sections: - -* [Header Footer Types](#header-footer-types) - -* [Customizing Headers And Footers](#customizing-headers-and-footers) - -* [Disabling Headers and Footers](#disabling-headers-and-footers) - -## Header Footer Types - -The **Headers** and **Footers** are properties of a **Section** and each section in the document can have the following types of Headers and Footers: - -* __Default__ - used all through the section; - -* __First__ - used on the first page of the section only; - -* __Even__ - to be used on every even page. - -## Customizing Headers And Footers - -Here is an example how you can create a **Header**: - -{{source=..\SamplesCS\RichTextEditor\Features\HeadersAndFooters.cs region=header}} -{{source=..\SamplesVB\RichTextEditor\Features\HeadersAndFooters.vb region=header}} - -````C# -Header header = new Header() { Body = radDocument, IsLinkedToPrevious = false }; //radDocument is an instance of RadDocument, representing the content of a Header, -//typically contains a few paragraphs - -```` -````VB.NET -Dim header As New Header() With {.Body = radDocument, .IsLinkedToPrevious = False} 'radDocument is an instance of RadDocument, representing the content of a Header, -'typically contains a few paragraphs - -```` - -{{endregion}} - -When it comes to using a **Header** created in this manner, this depends on the state of the document - if it has been measured or not. - -* In a non-measured document, which you are building in code-behind, you can set the Default page **Header** of a section in the following way: - -{{source=..\SamplesCS\RichTextEditor\Features\HeadersAndFooters.cs region=section}} -{{source=..\SamplesVB\RichTextEditor\Features\HeadersAndFooters.vb region=section}} - -````C# -section.Headers.Default = header; - -```` -````VB.NET -section.Headers.Default = header - -```` - -{{endregion}} - - -* In a measured document (a document that has been previewed in the editor), you can change the *Default* page header of the first section like this: - -{{source=..\SamplesCS\RichTextEditor\Features\HeadersAndFooters.cs region=editor}} -{{source=..\SamplesVB\RichTextEditor\Features\HeadersAndFooters.vb region=editor}} - -````C# -this.radRichTextEditor1.UpdateHeader(this.radRichTextEditor1.Document.Sections.First, HeaderFooterType.Default, header); - -```` -````VB.NET -Me.radRichTextEditor1.UpdateHeader(Me.radRichTextEditor1.Document.Sections.First, HeaderFooterType.Default, header) - -```` - -{{endregion}} - -All header/footer types - *Default*, *First* and *Even* are set identically. The only thing you should add when you set the *First* or *Even* **Header**/**Footer** of the document, is to set the property of the section that notifies the document to use different **Header**/**Footer** than the default one using one of the following properties: - -{{source=..\SamplesCS\RichTextEditor\Features\HeadersAndFooters.cs region=first}} -{{source=..\SamplesVB\RichTextEditor\Features\HeadersAndFooters.vb region=first}} - -````C# -this.radRichTextEditor1.Document.Sections.First.HasDifferentFirstPageHeaderFooter = true; -//or -this.radRichTextEditor1.Document.HasDifferentEvenAndOddHeadersFooters = true; - -```` -````VB.NET -Me.radRichTextEditor1.Document.Sections.First.HasDifferentFirstPageHeaderFooter = True -'or -Me.radRichTextEditor1.Document.HasDifferentEvenAndOddHeadersFooters = True - -```` - -{{endregion}} - -Setting the **Footers** can be done in the same way. Here is the respective code for footers: - -* Creating a Footer: - -{{source=..\SamplesCS\RichTextEditor\Features\HeadersAndFooters.cs region=footer}} -{{source=..\SamplesVB\RichTextEditor\Features\HeadersAndFooters.vb region=footer}} - -````C# -Footer footer = new Footer() { Body = radDocument, IsLinkedToPrevious = false }; //radDocument is an instance of RadDocument, representing the content of the footer - -```` -````VB.NET -Dim footer As New Footer() With {.Body = radDocument, .IsLinkedToPrevious = False} 'radDocument is an instance of RadDocument, representing the content of the footer - -```` - -{{endregion}} - - -* Setting the **Footer** to be used in a particular section: - -* In a non-measured document: - -{{source=..\SamplesCS\RichTextEditor\Features\HeadersAndFooters.cs region=footersection}} -{{source=..\SamplesVB\RichTextEditor\Features\HeadersAndFooters.vb region=footersection}} - -````C# -section.Footers.Default = footer; - -```` -````VB.NET -section.Footers.Default = footer - -```` - -{{endregion}} - -* In a measured document: - -{{source=..\SamplesCS\RichTextEditor\Features\HeadersAndFooters.cs region=update}} -{{source=..\SamplesVB\RichTextEditor\Features\HeadersAndFooters.vb region=update}} - -````C# -this.radRichTextEditor1.UpdateFooter(this.radRichTextEditor1.Document.Sections.First, HeaderFooterType.Default, footer); - -```` -````VB.NET -Me.radRichTextEditor1.UpdateFooter(Me.radRichTextEditor1.Document.Sections.First, HeaderFooterType.Default, footer) - -```` - -{{endregion}} - -As for setting different footers for the first page or the even page, this is done by passing the respective parameter to the **UpdateFooter** method - **HeaderFooterType**. *First* or HeaderFooterType.*Even* and setting the corresponding property of the document/editor: - -{{source=..\SamplesCS\RichTextEditor\Features\HeadersAndFooters.cs region=even}} -{{source=..\SamplesVB\RichTextEditor\Features\HeadersAndFooters.vb region=even}} - -````C# -this.radRichTextEditor1.Document.Sections.First.HasDifferentFirstPageHeaderFooter = true; -//or -this.radRichTextEditor1.Document.HasDifferentEvenAndOddHeadersFooters = true; - -```` -````VB.NET -Me.radRichTextEditor1.Document.Sections.First.HasDifferentFirstPageHeaderFooter = True -'or -Me.radRichTextEditor1.Document.HasDifferentEvenAndOddHeadersFooters = True - -```` - -{{endregion}} - -## Disabling Headers and Footers - -**Headers** and **Footers** are only present in *Paged* layout mode, so the easiest way to remove them is to change the layout mode. In case you wish to show documents in paged mode and still disable headers and footers, you can do so by removing the UI layer responsible for their visualization - __HeaderFooterLayer__. - ->tip The concept of UI layers and their usage are explained in [this article](https://docs.telerik.com/devtools/winforms/controls/richtexteditor/how-to/customize-presentation-through-ui-layers). -> - -{{source=..\SamplesCS\RichTextEditor\Features\HeadersAndFooters.cs region=custom}} -{{source=..\SamplesVB\RichTextEditor\Features\HeadersAndFooters.vb region=custom}} - -````C# -class CustomUILayerBuilder : UILayersBuilder -{ - protected override void BuildUILayersOverride(IUILayerContainer uiLayerContainer) - { - base.BuildUILayersOverride(uiLayerContainer); - uiLayerContainer.UILayers.Remove(DefaultUILayers.HeaderFooterLayer); - } -} - -```` -````VB.NET -Friend Class CustomUILayerBuilder - Inherits UILayersBuilder - Protected Overrides Sub BuildUILayersOverride(ByVal uiLayerContainer As IUILayerContainer) - Me.BuildUILayersOverride(uiLayerContainer) - uiLayerContainer.UILayers.Remove(DefaultUILayers.HeaderFooterLayer) - End Sub -End Class - -```` - -{{endregion}} - - -# See Also - - * [RadDocument]({%slug winforms/richtexteditor-/document-elements/raddocument%}) - - * [Selection]({%slug winforms/richtexteditor-/features/selection%}) +--- +title: Headers and Footers +page_title: Headers and Footers - WinForms RichTextEditor Control +description: WinForms RichTextEditor supports Headers and Footers in its document when in Paged layout mode. +slug: winforms/richtexteditor-/features/headers-and-footers +tags: headers,and,footers +published: True +position: 9 +previous_url: richtexteditor-features-headers-and-footers +--- + +# Headers and Footers + +__RadRichTextEditor__ supports **Headers** and **Footers** in its document when in *Paged* [layout mode]({%slug winforms/richtexteditor-/document-elements/raddocument%}). + +>note Note that **Headers** and **Footers** are not persisted when exporting with **HtmlFormatProvider**. You can read more about this [here](https://docs.telerik.com/devtools/winforms/controls/richtexteditor/import-export/overview) +> + +The topic contains the following sections: + +* [Header Footer Types](#header-footer-types) + +* [Customizing Headers And Footers](#customizing-headers-and-footers) + +* [Disabling Headers and Footers](#disabling-headers-and-footers) + +## Header Footer Types + +The **Headers** and **Footers** are properties of a **Section** and each section in the document can have the following types of Headers and Footers: + +* __Default__ - used all through the section; + +* __First__ - used on the first page of the section only; + +* __Even__ - to be used on every even page. + +## Customizing Headers And Footers + +Here is an example how you can create a **Header**: + + + + + + +When it comes to using a **Header** created in this manner, this depends on the state of the document - if it has been measured or not. + +* In a non-measured document, which you are building in code-behind, you can set the Default page **Header** of a section in the following way: + + + + + + +* In a measured document (a document that has been previewed in the editor), you can change the *Default* page header of the first section like this: + + + + + + +All header/footer types - *Default*, *First* and *Even* are set identically. The only thing you should add when you set the *First* or *Even* **Header**/**Footer** of the document, is to set the property of the section that notifies the document to use different **Header**/**Footer** than the default one using one of the following properties: + + + + + + +Setting the **Footers** can be done in the same way. Here is the respective code for footers: + +* Creating a Footer: + + + + + + +* Setting the **Footer** to be used in a particular section: + +* In a non-measured document: + + + + + + +* In a measured document: + + + + + + +As for setting different footers for the first page or the even page, this is done by passing the respective parameter to the **UpdateFooter** method - **HeaderFooterType**. *First* or HeaderFooterType.*Even* and setting the corresponding property of the document/editor: + + + + + + +## Disabling Headers and Footers + +**Headers** and **Footers** are only present in *Paged* layout mode, so the easiest way to remove them is to change the layout mode. In case you wish to show documents in paged mode and still disable headers and footers, you can do so by removing the UI layer responsible for their visualization - __HeaderFooterLayer__. + +>tip The concept of UI layers and their usage are explained in [this article](https://docs.telerik.com/devtools/winforms/controls/richtexteditor/how-to/customize-presentation-through-ui-layers). +> + + + + + + +# See Also + + * [RadDocument]({%slug winforms/richtexteditor-/document-elements/raddocument%}) + + * [Selection]({%slug winforms/richtexteditor-/features/selection%}) diff --git a/controls/richtexteditor/features/history.md b/controls/richtexteditor/features/history.md index 2ec32c557..55f730de4 100644 --- a/controls/richtexteditor/features/history.md +++ b/controls/richtexteditor/features/history.md @@ -29,90 +29,37 @@ This topic will explain you how to: You can enable or disable the history for the __RadDocument__ via the __Enabled__ property of the __DocumentHistory__. -{{source=..\SamplesCS\RichTextEditor\Features\HistoryCode.cs region=enabled}} -{{source=..\SamplesVB\RichTextEditor\Features\HistoryCode.vb region=enabled}} + + -````C# - -this.radRichTextEditor1.Document.History.IsEnabled = false; - -```` -````VB.NET -Me.radRichTextEditor1.Document.History.IsEnabled = False - -```` - -{{endregion}} ## Clear History To clear the history you just have to call the __Clear()__ method of the __DocumentHistory__ class. -{{source=..\SamplesCS\RichTextEditor\Features\HistoryCode.cs region=clear}} -{{source=..\SamplesVB\RichTextEditor\Features\HistoryCode.vb region=clear}} - -````C# - -this.radRichTextEditor1.Document.History.Clear(); - -```` -````VB.NET -Me.radRichTextEditor1.Document.History.Clear() + + -```` -{{endregion}} ## Undo/Redo Actions To undo and redo some actions, you can call the __Undo()__ and __Redo()__ methods of the __RadRichTextEditor__. -{{source=..\SamplesCS\RichTextEditor\Features\HistoryCode.cs region=undo}} -{{source=..\SamplesVB\RichTextEditor\Features\HistoryCode.vb region=undo}} + + + -````C# - -private void UndoAction() -{ - this.radRichTextEditor1.Undo(); -} -private void RedoAction() -{ - this.radRichTextEditor1.Redo(); -} - -```` -````VB.NET -Private Sub UndoAction() - Me.radRichTextEditor1.Undo() -End Sub -Private Sub RedoAction() - Me.radRichTextEditor1.Redo() -End Sub - -```` - -{{endregion}} ## Change History Depth To change the history capacity you have to set the desired value of the __Depth__ property of the __DocumentHistory__. The default one is __1000__. -{{source=..\SamplesCS\RichTextEditor\Features\HistoryCode.cs region=depth}} -{{source=..\SamplesVB\RichTextEditor\Features\HistoryCode.vb region=depth}} - -````C# - -this.radRichTextEditor1.Document.History.Depth = 500; - -```` -````VB.NET -Me.radRichTextEditor1.Document.History.Depth = 500 + + -```` -{{endregion}} ## Preserve History Using RadDocumentEditor diff --git a/controls/richtexteditor/features/hyperlink.md b/controls/richtexteditor/features/hyperlink.md index 360353419..554c1ca40 100644 --- a/controls/richtexteditor/features/hyperlink.md +++ b/controls/richtexteditor/features/hyperlink.md @@ -35,43 +35,17 @@ More often than not, you would only need to use objects of type **HyperlinkInfo* For example, a link to our site can be inserted in the document programmatically as follows: -{{source=..\SamplesCS\RichTextEditor\Features\HyperlinkCode.cs region=insert}} -{{source=..\SamplesVB\RichTextEditor\Features\HyperlinkCode.vb region=insert}} + + -````C# -HyperlinkInfo info = new HyperlinkInfo() -{ - NavigateUri = "http://www.telerik.com", - Target = HyperlinkTargets.Blank, - IsAnchor = false -}; -this.radRichTextEditor1.InsertHyperlink(info, "RichTextBox demo"); - -```` -````VB.NET -Dim info As New HyperlinkInfo() With {.NavigateUri = "http://www.telerik.com", .Target = HyperlinkTargets.Blank, .IsAnchor = False} -Me.radRichTextEditor1.InsertHyperlink(info, "RichTextBox demo") - -```` - -{{endregion}} A link to a bookmark is inserted by specifying the bookmark's name as **NavigateUri** and setting the **IsAnchor** property to *true*: -{{source=..\SamplesCS\RichTextEditor\Features\HyperlinkCode.cs region=remove}} -{{source=..\SamplesVB\RichTextEditor\Features\HyperlinkCode.vb region=remove}} - -````C# -this.radRichTextEditor1.RemoveHyperlink(); + + -```` -````VB.NET -Me.radRichTextEditor1.RemoveHyperlink() -```` - -{{endregion}} You can also use the overloaded methods for inserting a hyperlink: @@ -85,19 +59,10 @@ You can also use the overloaded methods for inserting a hyperlink: Removing a hyperlink (and keeping the part of the document that the hyperlink spanned) can be done by positioning the caret in the hyperlink and invoking: -{{source=..\SamplesCS\RichTextEditor\Features\HyperlinkCode.cs region=remove}} -{{source=..\SamplesVB\RichTextEditor\Features\HyperlinkCode.vb region=remove}} - -````C# -this.radRichTextEditor1.RemoveHyperlink(); + + -```` -````VB.NET -Me.radRichTextEditor1.RemoveHyperlink() -```` - -{{endregion}} ## HyperlinkRangeStart and HyperlinkRangeEnd @@ -105,70 +70,10 @@ Me.radRichTextEditor1.RemoveHyperlink() Here is an example that creates a document with a hyperlink spanning several paragraphs, including an image in one of the paragraphs: -{{source=..\SamplesCS\RichTextEditor\Features\HyperlinkCode.cs region=startend}} -{{source=..\SamplesVB\RichTextEditor\Features\HyperlinkCode.vb region=startend}} - -````C# -HyperlinkRangeStart hyperlinkStart = new HyperlinkRangeStart(); -HyperlinkRangeEnd hyperlinkEnd = new HyperlinkRangeEnd(); -hyperlinkEnd.PairWithStart(hyperlinkStart); -HyperlinkInfo hyperlinkInfo = new HyperlinkInfo() { NavigateUri = "http://telerik.com", Target = HyperlinkTargets.Blank }; -hyperlinkStart.HyperlinkInfo = hyperlinkInfo; -RadDocument document = new RadDocument(); -Section section = new Section(); -Paragraph paragraph = new Paragraph(); -Span spanBefore = new Span("Text before the image "); -ImageInline image; -using (MemoryStream ms = new MemoryStream()) -{ - System.Drawing.Image.FromFile(@"C:\logo.png").Save(ms, System.Drawing.Imaging.ImageFormat.Png); - image = new ImageInline(ms, new Telerik.WinControls.RichTextEditor.UI.Size(25, 25), "png"); -} -Span spanAfter = new Span(" and some text after the image"); -paragraph.Inlines.Add(hyperlinkStart); -paragraph.Inlines.Add(spanBefore); -paragraph.Inlines.Add(image); -paragraph.Inlines.Add(spanAfter); -section.Blocks.Add(paragraph); -Paragraph anotherParagraph = new Paragraph(); -anotherParagraph.Inlines.Add(new Span("Another paragraph here and still in hyperlink")); -anotherParagraph.Inlines.Add(hyperlinkEnd); -section.Blocks.Add(anotherParagraph); -document.Sections.Add(section); -this.radRichTextEditor1.Document = document; - -```` -````VB.NET -Dim hyperlinkStart As New HyperlinkRangeStart() -Dim hyperlinkEnd As New HyperlinkRangeEnd() -hyperlinkEnd.PairWithStart(hyperlinkStart) -Dim hyperlinkInfo As New HyperlinkInfo() With {.NavigateUri = "http://telerik.com", .Target = HyperlinkTargets.Blank} -hyperlinkStart.HyperlinkInfo = hyperlinkInfo -Dim document As New RadDocument() -Dim section As New Section() -Dim paragraph As New Paragraph() -Dim spanBefore As New Span("Text before the image ") -Dim image As ImageInline -Using ms As New MemoryStream() - System.Drawing.Image.FromFile("C:\logo.png").Save(ms, System.Drawing.Imaging.ImageFormat.Png) - image = New ImageInline(ms, New Telerik.WinControls.RichTextEditor.UI.Size(25, 25), "png") -End Using -Dim spanAfter As New Span(" and some text after the image") -paragraph.Inlines.Add(hyperlinkStart) -paragraph.Inlines.Add(spanBefore) -paragraph.Inlines.Add(image) -paragraph.Inlines.Add(spanAfter) -section.Blocks.Add(paragraph) -Dim anotherParagraph As New Paragraph() -anotherParagraph.Inlines.Add(New Span("Another paragraph here and still in hyperlink")) -anotherParagraph.Inlines.Add(hyperlinkEnd) -section.Blocks.Add(anotherParagraph) -document.Sections.Add(section) -Me.radRichTextEditor1.Document = document - -```` - -{{endregion}} + + + + The result (`Ctrl` + `Click` to follow): @@ -178,32 +83,10 @@ You will also need to use **HyperlinkRangeStart** and **HyperlinkRangeEnd**, if For instance, here is how you can delete all hyperlinks in the document and replace them with some text: -{{source=..\SamplesCS\RichTextEditor\Features\HyperlinkCode.cs region=delete}} -{{source=..\SamplesVB\RichTextEditor\Features\HyperlinkCode.vb region=delete}} - -````C# -IEnumerable links = this.radRichTextEditor1.Document.EnumerateChildrenOfType(); -foreach (HyperlinkRangeStart link in links) -{ - this.radRichTextEditor1.Document.CaretPosition.MoveToInline(link.FirstLayoutBox as Telerik.WinForms.Documents.Layout.InlineLayoutBox, 0); - this.radRichTextEditor1.Document.Selection.SelectAnnotationRange(link); - this.radRichTextEditor1.Delete(false); - this.radRichTextEditor1.Insert("Removed hyperlink"); -} - -```` -````VB.NET -Dim links As IEnumerable(Of HyperlinkRangeStart) = Me.radRichTextEditor1.Document.EnumerateChildrenOfType(Of HyperlinkRangeStart)() -For Each link As HyperlinkRangeStart In links - Me.radRichTextEditor1.Document.CaretPosition.MoveToInline(TryCast(link.FirstLayoutBox, Telerik.WinForms.Documents.Layout.InlineLayoutBox), 0) - Me.radRichTextEditor1.Document.Selection.SelectAnnotationRange(link) - Me.radRichTextEditor1.Delete(False) - Me.radRichTextEditor1.Insert("Removed hyperlink") -Next link - -```` - -{{endregion}} + + + + ## Other Customization Options @@ -224,49 +107,9 @@ With the 2024 Q3 (2024.3.924), the default navigation behavior of the hyperlinks Here is an example of using the HyperlinkClicked event prompting that the clicked hyperlink might be unsafe and allows to cancel the navigation process upon receiving the end user confirmation: -{{source=..\SamplesCS\RichTextEditor\Features\HyperlinkCode.cs region=HyperlinkClickedEvent}} -{{source=..\SamplesVB\RichTextEditor\Features\HyperlinkCode.vb region=HyperlinkClickedEvent}} - -````C# -void radRichTextEditor1_HyperlinkClicked(object sender, HyperlinkClickedEventArgs e) -{ - var link = e.URL; - if (link.EndsWith("exe")) - { - e.Handled = true; MessageBoxResult Result = System.Windows.MessageBox.Show("You are about to open an executable file. Do you want to proceed", "Possible unsafe link", MessageBoxButton.YesNo, MessageBoxImage.Question); - if (Result == MessageBoxResult.Yes) - { - Process.Start(new ProcessStartInfo() - { - FileName = link, - UseShellExecute = true - }); - } - } -} - - -```` -````VB.NET -Private Sub radRichTextEditor1_HyperlinkClicked(ByVal sender As Object, ByVal e As HyperlinkClickedEventArgs) - Dim link = e.URL - - If link.EndsWith("exe") Then - e.Handled = True - Dim Result As MessageBoxResult = System.Windows.MessageBox.Show("You are about to open an executable file. Do you want to proceed", "Possible unsafe link", MessageBoxButton.YesNo, MessageBoxImage.Question) - If Result = MessageBoxResult.Yes Then - Process.Start(New ProcessStartInfo() With { - .FileName = link, - .UseShellExecute = True - }) - End If - End If -End Sub - - -```` - -{{endregion}} + + + ### HyperlinkNavigationMode @@ -278,20 +121,9 @@ The __HyperlinkNavigationMode__ allows you to control what action should trigger Below is demonstrated how to change the default hyperlink navigation mode: -{{source=..\SamplesCS\RichTextEditor\Features\HyperlinkCode.cs region=HyperlinkMode}} -{{source=..\SamplesVB\RichTextEditor\Features\HyperlinkCode.vb region=HyperlinkMode}} - -````C# - -this.radRichTextEditor1.HyperlinkNavigationMode = Telerik.WinForms.Documents.UI.HyperlinkNavigationMode.Click; - -```` -````VB.NET -Me.radRichTextEditor1.HyperlinkNavigationMode = Telerik.WinForms.Documents.UI.HyperlinkNavigationMode.Click - -```` + + -{{endregion}} ## See Also diff --git a/controls/richtexteditor/features/line-numbering.md b/controls/richtexteditor/features/line-numbering.md index c2387e45e..ce70ea93e 100644 --- a/controls/richtexteditor/features/line-numbering.md +++ b/controls/richtexteditor/features/line-numbering.md @@ -53,26 +53,10 @@ The line numbering functionality can be programmatically used through the follow #### Example 1: Create and apply line numbering for the whole document -{{source=..\SamplesCS\RichTextEditor\Features\LineNumberingCode.cs region=SetLineNumbering}} -{{source=..\SamplesVB\RichTextEditor\Features\LineNumberingCode.vb region=SetLineNumbering}} + + -````C# -LineNumbering numbering = new LineNumbering(10,20,2,LineNumberingRestartType.Continuous); -this.radRichTextEditor1.Document.Selection.SelectAll(); -this.radRichTextEditor1.RichTextBoxElement.ChangeSectionLineNumbering(numbering); - -```` -````VB.NET - -Dim numbering As LineNumbering = New LineNumbering(10, 20, 2, LineNumberingRestartType.Continuous) -Me.radRichTextEditor1.Document.Selection.SelectAll() -Me.radRichTextEditor1.RichTextBoxElement.ChangeSectionLineNumbering(numbering) - - -```` - -{{endregion}} You can also directly control the line numbering settings for a specific Section object through its **LineNumbering** property and suppress the numbering for a specific Paragraph using **SuppressLineNumbers**. diff --git a/controls/richtexteditor/features/mail-merge/insert-new-line-in-merge-field.md b/controls/richtexteditor/features/mail-merge/insert-new-line-in-merge-field.md index 97eb22704..59fb133a4 100644 --- a/controls/richtexteditor/features/mail-merge/insert-new-line-in-merge-field.md +++ b/controls/richtexteditor/features/mail-merge/insert-new-line-in-merge-field.md @@ -30,19 +30,10 @@ The [RadDocumentEditor class]({%slug winforms/richtexteditor-/features/raddocume #### Example 1: Insert vertical tab through RadDocumentEditor -{{source=..\SamplesCS\RichTextEditor\Features\MailMergeCode.cs region=radrichtexteditor-features-mail-merge-Insert-new-line-in-merge-field_0}} -{{source=..\SamplesVB\RichTextEditor\Features\MailMergeCode.vb region=radrichtexteditor-features-mail-merge-Insert-new-line-in-merge-field_0}} + + -````C# -radDocumentEditor.Insert("\v"); -```` -````VB.NET -radDocumentEditor.Insert(vbVerticalTab) - -```` - -{{endregion}} Another option is to create a [Span]({%slug winforms/richtexteditor-/document-elements/span%}) and assign the vertical tab character to it. @@ -50,21 +41,11 @@ Another option is to create a [Span]({%slug winforms/richtexteditor-/document-el #### Example 2: Create vertical tab through document model -{{source=..\SamplesCS\RichTextEditor\Features\MailMergeCode.cs region=radrichtexteditor-features-mail-merge-Insert-new-line-in-merge-field_2}} -{{source=..\SamplesVB\RichTextEditor\Features\MailMergeCode.vb region=radrichtexteditor-features-mail-merge-Insert-new-line-in-merge-field_2}} - -````C# -Span span = new Span("\v"); - -```` -````VB.NET -Dim span As New Span(vbVerticalTab) + + -```` -{{endregion}} - When the vertical tab symbol is inserted in a document, it is replaced with a Break element of type **LineBreak**. ## Insert a Line Break Before/After a Merge Field If the Field Result Isn't Empty @@ -87,24 +68,11 @@ You could handle a similar scenario using the vertical tab symbol in the **TextA #### Example 3: Insert vertical tab in the switch of a merge field -{{source=..\SamplesCS\RichTextEditor\Features\MailMergeCode.cs region=radrichtexteditor-features-mail-merge-Insert-new-line-in-merge-field_4}} -{{source=..\SamplesVB\RichTextEditor\Features\MailMergeCode.vb region=radrichtexteditor-features-mail-merge-Insert-new-line-in-merge-field_4}} - -````C# -MergeField mergeField = new MergeField() { PropertyPath = "JobTitle", TextAfterIfNotEmpty = "\v" }; + + -```` -````VB.NET -Dim mergeField As New MergeField() With { _ - .PropertyPath = "JobTitle", _ - .TextAfterIfNotEmpty = vbVerticalTab _ -} -```` -{{endregion}} - - >caption Figure 3: Result fragment of mail merge, when one of the fields has applied a switch using vertical tab and has no value ![WinForms RadRichTextEditor Result fragment of mail merge](images/radrichtexteditor-MailMerge-InsertANewLineInMergeField_03.png) @@ -115,24 +83,11 @@ You could also use the *“\r\n”* in the **TextBeforeIfNotEmpty** or **TextAft #### Example 4: Insert \r\n in the switch of a merge field -{{source=..\SamplesCS\RichTextEditor\Features\MailMergeCode.cs region=radrichtexteditor-features-mail-merge-Insert-new-line-in-merge-field_6}} -{{source=..\SamplesVB\RichTextEditor\Features\MailMergeCode.vb region=radrichtexteditor-features-mail-merge-Insert-new-line-in-merge-field_6}} + + -````C# -MergeField mergeField = new MergeField() { PropertyPath = "FirstName", TextAfterIfNotEmpty = "\r\n" }; -```` -````VB.NET -Dim mergeField As New MergeField() With { _ - .PropertyPath = "FirstName", _ - .TextAfterIfNotEmpty = vbCr & vbLf _ -} -```` - -{{endregion}} - - >important The vertical tab is serialized only when it is used as a value for a document variable. In all other cases, it is not included in the document content on export. ## Using the Vertical Tab in a DocumentVariableField @@ -141,36 +96,11 @@ The suggested approach in scenarios that include export is to use a [document va #### Example 5: Insert the vertical tab in the switch of a merge field -{{source=..\SamplesCS\RichTextEditor\Features\MailMergeCode.cs region=radrichtexteditor-features-mail-merge-Insert-new-line-in-merge-field_8}} -{{source=..\SamplesVB\RichTextEditor\Features\MailMergeCode.vb region=radrichtexteditor-features-mail-merge-Insert-new-line-in-merge-field_8}} - -````C# -string verticalTabSymbol = "\v"; -string verticalTabKey = "verticalTab"; -radRichTextEditor.Document.DocumentVariables.Add(verticalTabKey, verticalTabSymbol); -DocumentVariableField documentVariableField = new DocumentVariableField(); -documentVariableField.VariableName = verticalTabKey; -var mergeField = new MergeField() { PropertyPath = "FirstName" }; -mergeField.SetPropertyValue(MergeField.TextAfterIfNotEmptyProperty, documentVariableField); -radRichTextEditor.InsertField(mergeField, FieldDisplayMode.Result); - -```` -````VB.NET -Dim verticalTabSymbol As String = vbVerticalTab -Dim verticalTabKey As String = "verticalTab" -radRichTextEditor.Document.DocumentVariables.Add(verticalTabKey, verticalTabSymbol) -Dim documentVariableField As New DocumentVariableField() -documentVariableField.VariableName = verticalTabKey -Dim mergeField__1 = New MergeField() With { _ - .PropertyPath = "FirstName" _ -} -mergeField__1.SetPropertyValue(MergeField.TextAfterIfNotEmptyProperty, documentVariableField) -radRichTextEditor.InsertField(mergeField__1, FieldDisplayMode.Result) - -```` - -{{endregion}} - + + + + + As a value of the document variable, you could also insert the "\r\n". Keep in mind that this value is exported to DOCX files only. # See Also diff --git a/controls/richtexteditor/features/mail-merge/mail-merge.md b/controls/richtexteditor/features/mail-merge/mail-merge.md index acadbf351..775fe66b4 100644 --- a/controls/richtexteditor/features/mail-merge/mail-merge.md +++ b/controls/richtexteditor/features/mail-merge/mail-merge.md @@ -17,95 +17,17 @@ The general use of mail merge is the creation of a document serving as a templat The first thing you need to do is assign a value to the __ItemsSource__ property of the __MailMergeDataSource__ of the document. For example, if you will be writing letters to Employees of a company, you can have a context that keeps a list of Employees, each Employee having a FirstName, LastName, and JobTitle. -{{source=..\SamplesCS\RichTextEditor\Features\MailMergeCode.cs region=data}} -{{source=..\SamplesVB\RichTextEditor\Features\MailMergeCode.vb region=data}} - -````C# -public class ExamplesDataContext -{ - private List employees = new List() - { - new Employee() - { - FirstName = "Andrew", - LastName = "Fuller", - JobTitle = "Director - Finance", - }, - new Employee() - { - FirstName = "Nancy", - LastName = "Davolio", - JobTitle = "Director - Human Resources", - }, - new Employee() - { - FirstName = "Robert", - LastName = "King", - JobTitle = "Engineering Design Manager", - }, - new Employee() - { - FirstName = "Margaret", - LastName = "Peacock", - JobTitle = "Finance & Investments Officer", - } - }; - public List Employees - { - get - { - return this.employees; - } - } -} -public class Employee -{ - public string FirstName { get; set; } - public string LastName { get; set; } - public string JobTitle { get; set; } -} - -```` -````VB.NET -Public Class ExamplesDataContext - Private _employees As New List(Of Employee)() From { - New Employee() With {.FirstName = "Andrew", .LastName = "Fuller", .JobTitle = "Director - Finance"}, - New Employee() With {.FirstName = "Nancy", .LastName = "Davolio", .JobTitle = "Director - Human Resources"}, - New Employee() With {.FirstName = "Robert", .LastName = "King", .JobTitle = "Engineering Design Manager"}, - New Employee() With {.FirstName = "Margaret", .LastName = "Peacock", .JobTitle = "Finance & Investments Officer"} - } - Public ReadOnly Property Employees() As List(Of Employee) - Get - Return Me._employees - End Get - End Property -End Class -Public Class Employee - Public Property FirstName() As String - Public Property LastName() As String - Public Property JobTitle() As String -End Class - -```` - -{{endregion}} + + -All that is left is to add the following line: - -{{source=..\SamplesCS\RichTextEditor\Features\MailMergeCode.cs region=source}} -{{source=..\SamplesVB\RichTextEditor\Features\MailMergeCode.vb region=source}} -````C# -this.radRichTextEditor1.Document.MailMergeDataSource.ItemsSource = new ExamplesDataContext().Employees; +All that is left is to add the following line: -```` -````VB.NET -Me.radRichTextEditor1.Document.MailMergeDataSource.ItemsSource = (New ExamplesDataContext()).Employees + + -```` -{{endregion}} ## Performing Mail Merge @@ -134,110 +56,39 @@ The same scenario can be carried out programmatically just as easily. The method ### Creating a MergeField: -{{source=..\SamplesCS\RichTextEditor\Features\MailMergeCode.cs region=field}} -{{source=..\SamplesVB\RichTextEditor\Features\MailMergeCode.vb region=field}} + + -````C# -MergeField field = new MergeField() { PropertyPath = "FirstName" }; -```` -````VB.NET -Dim field As New MergeField() With {.PropertyPath = "FirstName"} - -```` - -{{endregion}} This fields will look for the value of the **FirstName** property of the Employee objects. ### Changing the display mode of merge fields: -{{source=..\SamplesCS\RichTextEditor\Features\MailMergeCode.cs region=mode}} -{{source=..\SamplesVB\RichTextEditor\Features\MailMergeCode.vb region=mode}} - -````C# -field.DisplayMode = FieldDisplayMode.Result; -this.radRichTextEditor1.ChangeFieldDisplayMode(field.FieldStart, FieldDisplayMode.Result); -this.radRichTextEditor1.ChangeAllFieldsDisplayMode(FieldDisplayMode.Result); + + -```` -````VB.NET -field.DisplayMode = FieldDisplayMode.Result -Me.radRichTextEditor1.ChangeFieldDisplayMode(field.FieldStart, FieldDisplayMode.Result) -Me.radRichTextEditor1.ChangeAllFieldsDisplayMode(FieldDisplayMode.Result) -```` - -{{endregion}} ### Inserting a MergeField at the current position of the caret: -{{source=..\SamplesCS\RichTextEditor\Features\MailMergeCode.cs region=insert}} -{{source=..\SamplesVB\RichTextEditor\Features\MailMergeCode.vb region=insert}} - -````C# -this.radRichTextEditor1.InsertField(field); -this.radRichTextEditor1.InsertField(field, FieldDisplayMode.DisplayName); - -```` -````VB.NET -Me.radRichTextEditor1.InsertField(field) -Me.radRichTextEditor1.InsertField(field, FieldDisplayMode.DisplayName) + + -```` -{{endregion}} ### Previewing the results of Mail Merge: -{{source=..\SamplesCS\RichTextEditor\Features\MailMergeCode.cs region=preview}} -{{source=..\SamplesVB\RichTextEditor\Features\MailMergeCode.vb region=preview}} + + -````C# -this.radRichTextEditor1.PreviewFirstMailMergeDataRecord(); -this.radRichTextEditor1.PreviewLastMailMergeDataRecord(); -this.radRichTextEditor1.PreviewMailMergeDataRecordAtIndex(0); -this.radRichTextEditor1.PreviewNextMailMergeDataRecord(); -this.radRichTextEditor1.PreviewPreviousMailMergeDataRecord(); -```` -````VB.NET -Me.radRichTextEditor1.PreviewFirstMailMergeDataRecord() -Me.radRichTextEditor1.PreviewLastMailMergeDataRecord() -Me.radRichTextEditor1.PreviewMailMergeDataRecordAtIndex(0) -Me.radRichTextEditor1.PreviewNextMailMergeDataRecord() -Me.radRichTextEditor1.PreviewPreviousMailMergeDataRecord() -```` +### Performing MailMerge: -{{endregion}} + + -### Performing MailMerge: -{{source=..\SamplesCS\RichTextEditor\Features\MailMergeCode.cs region=perform}} -{{source=..\SamplesVB\RichTextEditor\Features\MailMergeCode.vb region=perform}} - -````C# -this.radRichTextEditor1.MailMergeCurrentRecord(); // returns a RadDocument that is the result of substituting the merge fields with the data from the current record. The current record can be specified through the MailMergeSource API: -this.radRichTextEditor1.Document.MailMergeDataSource.MoveToFirst(); -this.radRichTextEditor1.Document.MailMergeDataSource.MoveToLast(); -this.radRichTextEditor1.Document.MailMergeDataSource.MoveToNext(); -this.radRichTextEditor1.Document.MailMergeDataSource.MoveToPrevious(); -this.radRichTextEditor1.Document.MailMergeDataSource.MoveToIndex(index); -this.radRichTextEditor1.MailMerge(false); // returns a RadDocument that is the result of Mail Merging all records. The parameter specifies if a page break should be inserted between the records (default value is true). - -```` -````VB.NET -Me.radRichTextEditor1.MailMergeCurrentRecord() ' returns a RadDocument that is the result of substituting the merge fields with the data from the current record. The current record can be specified through the MailMergeSource API: -Me.radRichTextEditor1.Document.MailMergeDataSource.MoveToFirst() -Me.radRichTextEditor1.Document.MailMergeDataSource.MoveToLast() -Me.radRichTextEditor1.Document.MailMergeDataSource.MoveToNext() -Me.radRichTextEditor1.Document.MailMergeDataSource.MoveToPrevious() -Me.radRichTextEditor1.Document.MailMergeDataSource.MoveToIndex(index) -Me.radRichTextEditor1.MailMerge(False) ' returns a RadDocument that is the result of Mail Merging all records. The parameter specifies if a page break should be inserted between the records (default value is true). - -```` - -{{endregion}} You can further choose what you wish to do with the resulting **RadDocument** – assign it to a **RadRichTextEditor**’s Document property, export it, etc. diff --git a/controls/richtexteditor/features/mentions/mentions-custom-provider.md b/controls/richtexteditor/features/mentions/mentions-custom-provider.md index ed89807fe..8eb6f5cfc 100644 --- a/controls/richtexteditor/features/mentions/mentions-custom-provider.md +++ b/controls/richtexteditor/features/mentions/mentions-custom-provider.md @@ -18,116 +18,10 @@ This object should implement **INotifyPropertyChanged** so it can be later used #### Example 1: Custom mention item -{{source=..\SamplesCS\RichTextEditor\Features\Mentions.cs region=MentionItem}} -{{source=..\SamplesVB\RichTextEditor\Features\Mentions.vb region=MentionItem}} - -````C# - -public class OrganizationInfo : INotifyPropertyChanged -{ - private string name; - private string abbreviation; - - public string Name - { - get - { - return this.name; - } - set - { - if (this.name != value) - { - this.name = value; - this.OnPropertyChanged("Name"); - } - } - } - - public string Abbreviation - { - get - { - return this.abbreviation; - } - set - { - if (this.abbreviation != value) - { - this.abbreviation = value; - this.OnPropertyChanged("Abbreviation"); - } - } - } - - public override string ToString() - { - return this.Name; - } - - /// - /// Occurs when a property value changes. - /// - public event PropertyChangedEventHandler PropertyChanged; - - private void OnPropertyChanged(string propertyName) - { - if (this.PropertyChanged != null) - { - this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); - } - } -} - -```` -````VB.NET - -Public Class OrganizationInfo - Implements INotifyPropertyChanged - - Private _name As String - Private _abbreviation As String - - Public Property Name As String - Get - Return Me._name - End Get - Set(ByVal value As String) - - If Me._name <> value Then - Me._name = value - Me.OnPropertyChanged("Name") - End If - End Set - End Property - - Public Property Abbreviation As String - Get - Return Me._abbreviation - End Get - Set(ByVal value As String) - - If Me._abbreviation <> value Then - Me._abbreviation = value - Me.OnPropertyChanged("Abbreviation") - End If - End Set - End Property - - Public Overrides Function ToString() As String - Return Me.Name - End Function - - Public Event PropertyChanged As PropertyChangedEventHandler Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged - - Private Sub OnPropertyChanged(ByVal propertyName As String) - RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName)) - End Sub -End Class - -```` - -{{endregion}} + + + + 2\. Implement a custom mention provider @@ -135,69 +29,10 @@ End Class This is done by inheriting the **MentionProviderBase<T>** class where **T** is the mention item. You should implement the **InsertItem** and **DetermineItemVisibility** methods. For more information about them, check the Customize the Insert Action and Customize the Filtering sections. -{{source=..\SamplesCS\RichTextEditor\Features\Mentions.cs region=OrganizationProvider}} -{{source=..\SamplesVB\RichTextEditor\Features\Mentions.vb region=OrganizationProvider}} - -````C# - -public class OrganizationMentionProvider : MentionProviderBase -{ - public override bool DetermineItemVisibility(OrganizationInfo item, string currentMentionText) - { - if (string.IsNullOrEmpty(currentMentionText)) - { - return true; - } - else if (item == null || string.IsNullOrEmpty(item.Name)) - { - return false; - } - else - { - string text = currentMentionText.ToUpperInvariant(); - return item.Name.ToUpperInvariant().Contains(text) || - item.Abbreviation.ToUpperInvariant().StartsWith(text); - } - } - - public override void InsertItem(RadDocument document, OrganizationInfo item) - { - if (item != null) - { - RadDocumentEditor editor = new RadDocumentEditor(document); - editor.Insert(item.Name); - } - } -} - -```` -````VB.NET - -Public Class OrganizationMentionProvider - Inherits MentionProviderBase(Of OrganizationInfo) - - Public Overrides Function DetermineItemVisibility(ByVal item As OrganizationInfo, ByVal currentMentionText As String) As Boolean - If String.IsNullOrEmpty(currentMentionText) Then - Return True - ElseIf item Is Nothing OrElse String.IsNullOrEmpty(item.Name) Then - Return False - Else - Dim text As String = currentMentionText.ToUpperInvariant() - Return item.Name.ToUpperInvariant().Contains(text) OrElse item.Abbreviation.ToUpperInvariant().StartsWith(text) - End If - End Function - - Public Overrides Sub InsertItem(ByVal document As RadDocument, ByVal item As OrganizationInfo) - If item IsNot Nothing Then - Dim editor As RadDocumentEditor = New RadDocumentEditor(document) - editor.Insert(item.Name) - End If - End Sub -End Class - -```` - -{{endregion}} + + + + 3\. Implement a data template for the custom mention provider @@ -209,135 +44,10 @@ The mentions dialog internally uses a **RadListControl**. Hence, you can constru #### Example 3: DataTemplate for the custom mention item -{{source=..\SamplesCS\RichTextEditor\Features\Mentions.cs region=VisualMentionItem}} -{{source=..\SamplesVB\RichTextEditor\Features\Mentions.vb region=VisualMentionItem}} - -````C# -public class OrganizationInfoVisualItem : RadListVisualItem -{ - private StackLayoutElement verticalStackLayout; - private LightVisualElement nameElement; - private Font nameFont = new Font("Segoe UI", 9, FontStyle.Bold); - private LightVisualElement abbreviationElement; - private Font abbreviationFont = new Font("Segoe UI", 9, FontStyle.Regular); - - protected override Type ThemeEffectiveType - { - get - { - return typeof(RadListVisualItem); - } - } - - protected override void CreateChildElements() - { - base.CreateChildElements(); - - this.verticalStackLayout = new StackLayoutElement(); - this.verticalStackLayout.Orientation = Orientation.Vertical; - this.verticalStackLayout.StretchHorizontally = true; - this.verticalStackLayout.StretchVertically = false; - this.verticalStackLayout.ShouldHandleMouseInput = false; - this.Children.Add(this.verticalStackLayout); - - this.nameElement = new LightVisualElement(); - this.nameElement.StretchVertically = false; - this.nameElement.TextAlignment = ContentAlignment.MiddleLeft; - this.nameElement.NotifyParentOnMouseInput = true; - this.nameElement.TextWrap = true; - this.nameElement.ShouldHandleMouseInput = false; - this.verticalStackLayout.Children.Add(this.nameElement); - - this.abbreviationElement = new LightVisualElement(); - this.abbreviationElement.StretchVertically = false; - this.abbreviationElement.TextAlignment = ContentAlignment.MiddleLeft; - this.abbreviationElement.NotifyParentOnMouseInput = true; - this.abbreviationElement.TextWrap = true; - this.abbreviationElement.ShouldHandleMouseInput = false; - this.verticalStackLayout.Children.Add(this.abbreviationElement); - } - - protected override void SynchronizeProperties() - { - base.SynchronizeProperties(); - - this.DrawText = false; - - OrganizationInfo infoItem = this.Data.DataBoundItem as OrganizationInfo; - if (infoItem == null) - { - return; - } - - this.nameElement.Text = infoItem.Name; - this.nameElement.Font = this.nameFont; - - this.abbreviationElement.Text = $"({infoItem.Abbreviation})"; - this.abbreviationElement.Font = this.abbreviationFont; - } -} - -```` -````VB.NET - -Public Class OrganizationInfoVisualItem - Inherits RadListVisualItem - - Private verticalStackLayout As StackLayoutElement - Private nameElement As LightVisualElement - Private nameFont As Font = New Font("Segoe UI", 9, FontStyle.Bold) - Private abbreviationElement As LightVisualElement - Private abbreviationFont As Font = New Font("Segoe UI", 9, FontStyle.Regular) - - Protected Overrides ReadOnly Property ThemeEffectiveType As Type - Get - Return GetType(RadListVisualItem) - End Get - End Property - - Protected Overrides Sub CreateChildElements() - MyBase.CreateChildElements() - Me.verticalStackLayout = New StackLayoutElement() - Me.verticalStackLayout.Orientation = Orientation.Vertical - Me.verticalStackLayout.StretchHorizontally = True - Me.verticalStackLayout.StretchVertically = False - Me.verticalStackLayout.ShouldHandleMouseInput = False - Me.Children.Add(Me.verticalStackLayout) - Me.nameElement = New LightVisualElement() - Me.nameElement.StretchVertically = False - Me.nameElement.TextAlignment = ContentAlignment.MiddleLeft - Me.nameElement.NotifyParentOnMouseInput = True - Me.nameElement.TextWrap = True - Me.nameElement.ShouldHandleMouseInput = False - Me.verticalStackLayout.Children.Add(Me.nameElement) - Me.abbreviationElement = New LightVisualElement() - Me.abbreviationElement.StretchVertically = False - Me.abbreviationElement.TextAlignment = ContentAlignment.MiddleLeft - Me.abbreviationElement.NotifyParentOnMouseInput = True - Me.abbreviationElement.TextWrap = True - Me.abbreviationElement.ShouldHandleMouseInput = False - Me.verticalStackLayout.Children.Add(Me.abbreviationElement) - End Sub - - Protected Overrides Sub SynchronizeProperties() - MyBase.SynchronizeProperties() - Me.DrawText = False - Dim infoItem As OrganizationInfo = TryCast(Me.Data.DataBoundItem, OrganizationInfo) - - If infoItem Is Nothing Then - Return - End If - - Me.nameElement.Text = infoItem.Name - Me.nameElement.Font = Me.nameFont - Me.abbreviationElement.Text = $"({infoItem.Abbreviation})" - Me.abbreviationElement.Font = Me.abbreviationFont - End Sub -End Class - -```` - -{{endregion}} + + + + 4\. Register the mention provider with its mention character and the new data template @@ -345,64 +55,10 @@ After the prerequisites are completed, you should set the new members to the **M #### Add the provider and the data template to the MentionContext -{{source=..\SamplesCS\RichTextEditor\Features\Mentions.cs region=ApplyProvider}} -{{source=..\SamplesVB\RichTextEditor\Features\Mentions.vb region=ApplyProvider}} - -````C# -OrganizationMentionProvider organizationMentionProvider = new OrganizationMentionProvider(); -organizationMentionProvider.MentionCharacter = '#'; - -List organizations = new List() -{ - new OrganizationInfo(){ Name="United Nations Organization" , Abbreviation="UN"}, - new OrganizationInfo(){ Name="United Nations Children’s Fund" , Abbreviation="UNICEF"}, - new OrganizationInfo(){ Name="World Health Organization" , Abbreviation="WHO"}, - new OrganizationInfo(){ Name="United Nations Education Scientific & Cultural Organization" , Abbreviation="UNESCO"}, - new OrganizationInfo(){ Name="World Wide Fund for Nature" , Abbreviation="WWF"} -}; - -organizationMentionProvider.ItemsSource = organizations; -this.radRichTextEditor1.RichTextBoxElement.MentionContext.Providers.Add(organizationMentionProvider); - -DataTemplate template = new DataTemplate(visualType: typeof(OrganizationInfoVisualItem), - dataType: typeof(OrganizationInfo)); -this.radRichTextEditor1.RichTextBoxElement.MentionContext.Templates.Add(template); - -```` -````VB.NET - -Dim organizationMentionProvider As OrganizationMentionProvider = New OrganizationMentionProvider() -organizationMentionProvider.MentionCharacter = "#"c -Dim organizations As List(Of OrganizationInfo) = New List(Of OrganizationInfo)() From { - New OrganizationInfo() With { - .Name = "United Nations Organization", - .Abbreviation = "UN" - }, - New OrganizationInfo() With { - .Name = "United Nations Children’s Fund", - .Abbreviation = "UNICEF" - }, - New OrganizationInfo() With { - .Name = "World Health Organization", - .Abbreviation = "WHO" - }, - New OrganizationInfo() With { - .Name = "United Nations Education Scientific & Cultural Organization", - .Abbreviation = "UNESCO" - }, - New OrganizationInfo() With { - .Name = "World Wide Fund for Nature", - .Abbreviation = "WWF" - } -} -organizationMentionProvider.ItemsSource = organizations -Me.radRichTextEditor1.RichTextBoxElement.MentionContext.Providers.Add(organizationMentionProvider) -Dim template As DataTemplate = New DataTemplate(visualType:=GetType(OrganizationInfoVisualItem), dataType:=GetType(OrganizationInfo)) -Me.radRichTextEditor1.RichTextBoxElement.MentionContext.Templates.Add(template) - -```` - -{{endregion}} + + + + #### Custom Mentions @@ -414,38 +70,10 @@ You can implement your own logic determining what and how it is being inserted i #### Custom insert action -{{source=..\SamplesCS\RichTextEditor\Features\Mentions.cs region=CustomInsert}} -{{source=..\SamplesVB\RichTextEditor\Features\Mentions.vb region=CustomInsert}} - -````C# -public class CustomPersonMentionProvider : PersonMentionProvider -{ - public override void InsertItem(RadDocument document, PersonMentionItem item) - { - if (item != null) - { - RadDocumentEditor editor = new RadDocumentEditor(document); - editor.Insert(item.Name); - } - } -} - -```` -````VB.NET -Public Class CustomPersonMentionProvider - Inherits PersonMentionProvider - - Public Overrides Sub InsertItem(ByVal document As RadDocument, ByVal item As PersonMentionItem) - If item IsNot Nothing Then - Dim editor As RadDocumentEditor = New RadDocumentEditor(document) - editor.Insert(item.Name) - End If - End Sub -End Class - -```` - -{{endregion}} + + + + ![WinForms RadRichTextEditor Customize Insert Action](images/richtexteditor-features-mentions-custom-provider002.gif) @@ -457,51 +85,10 @@ The example shows how to implement filtering that matches only the items that st #### Custom Filtering -{{source=..\SamplesCS\RichTextEditor\Features\Mentions.cs region=Filtering}} -{{source=..\SamplesVB\RichTextEditor\Features\Mentions.vb region=Filtering}} - -````C# - -public class MyFilterPersonMentionProvider : PersonMentionProvider -{ - public override bool DetermineItemVisibility(PersonMentionItem item, string currentMentionText) - { - if (string.IsNullOrEmpty(currentMentionText)) - { - return true; - } - else if (item == null || string.IsNullOrEmpty(item.Name)) - { - return false; - } - else - { - return item.Name.ToUpperInvariant().StartsWith(currentMentionText.ToUpperInvariant()); - } - } -} - - -```` -````VB.NET - -Public Class MyFilterPersonMentionProvider - Inherits PersonMentionProvider - - Public Overrides Function DetermineItemVisibility(ByVal item As PersonMentionItem, ByVal currentMentionText As String) As Boolean - If String.IsNullOrEmpty(currentMentionText) Then - Return True - ElseIf item Is Nothing OrElse String.IsNullOrEmpty(item.Name) Then - Return False - Else - Return item.Name.ToUpperInvariant().StartsWith(currentMentionText.ToUpperInvariant()) - End If - End Function -End Class - -```` - -{{endregion}} + + + + ![WinForms RadRichTextEditor Custom Filtering](images/richtexteditor-features-mentions-custom-provider003.gif) diff --git a/controls/richtexteditor/features/mentions/mentions-overview.md b/controls/richtexteditor/features/mentions/mentions-overview.md index 07df1c03d..edc620b29 100644 --- a/controls/richtexteditor/features/mentions/mentions-overview.md +++ b/controls/richtexteditor/features/mentions/mentions-overview.md @@ -41,60 +41,10 @@ For your convenience, RadRichTextEditor comes with a default implementation of a #### Example 1: Using PersonMentionProvider -{{source=..\SamplesCS\RichTextEditor\Features\Mentions.cs region=SetupDefaultProvider}} -{{source=..\SamplesVB\RichTextEditor\Features\Mentions.vb region=SetupDefaultProvider}} - -````C# - -this.radRichTextEditor1.RichTextBoxElement.MentionContext.Providers.Clear(); -this.radRichTextEditor1.RichTextBoxElement.MentionContext.Templates.Clear(); - -List personMentionItems = new List() -{ - new PersonMentionItem() { Name = "Nancy Anders", Mail = "mailto:nanders@somecompany.com", - Image = Properties.Resources.nancy}, - - new PersonMentionItem() { Name = "Andrew Taquería", Mail = "mailto:ataqueria@somecompany.com", - Image = Properties.Resources.Andrew}, - - new PersonMentionItem() { Name = "Janet Hardy", Mail = "mailto:jhardy@somecompany.com", - Image = Properties.Resources.Janet} -}; - -PersonMentionProvider personMentionProvider = new PersonMentionProvider(); -personMentionProvider.ItemsSource = personMentionItems; - -this.radRichTextEditor1.MentionContext.Providers.Add(personMentionProvider); - -```` -````VB.NET - -Me.radRichTextEditor1.RichTextBoxElement.MentionContext.Providers.Clear() -Me.radRichTextEditor1.RichTextBoxElement.MentionContext.Templates.Clear() -Dim personMentionItems As List(Of Telerik.WinForms.Documents.UI.Mentions.PersonMentionItem) = New List(Of PersonMentionItem)() From { - New PersonMentionItem() With { - .Name = "Nancy Anders", - .Mail = "mailto:nanders@somecompany.com", - .Image = My.Resources.nancy - }, - New PersonMentionItem() With { - .Name = "Andrew Taquería", - .Mail = "mailto:ataqueria@somecompany.com", - .Image = My.Resources.Andrew - }, - New PersonMentionItem() With { - .Name = "Janet Hardy", - .Mail = "mailto:jhardy@somecompany.com", - .Image = My.Resources.Janet - } -} -Dim personMentionProvider As PersonMentionProvider = New PersonMentionProvider() -personMentionProvider.ItemsSource = personMentionItems -Me.radRichTextEditor1.MentionContext.Providers.Add(personMentionProvider) - -```` - -{{endregion}} + + + + Figure 2 shows how the result of Example 1 would look like in RadRichTextEditor. @@ -106,21 +56,10 @@ Figure 2 shows how the result of Example 1 would look like in RadRichTextEditor. The mention character is the character that triggers the visibility of the drop-down with suggestions when found at the start of a span. Each mention provider must be associated with a unique mention character. The character for the default mention provider is **@**. If you need to change the default character for a provider, you can use its **MentionCharacter** property. -{{source=..\SamplesCS\RichTextEditor\Features\Mentions.cs region=ChangeCharacter}} -{{source=..\SamplesVB\RichTextEditor\Features\Mentions.vb region=ChangeCharacter}} - -````C# - -personMentionProvider.MentionCharacter = '#'; - -```` -````VB.NET - -personMentionProvider.MentionCharacter = "#"c + + -```` -{{endregion}} >note If the mention character applied to a mention provider is already used by another provider, an InvalidOperationException is thrown. diff --git a/controls/richtexteditor/features/merge-documents/append.md b/controls/richtexteditor/features/merge-documents/append.md index 1a75fd3f8..5218dac17 100644 --- a/controls/richtexteditor/features/merge-documents/append.md +++ b/controls/richtexteditor/features/merge-documents/append.md @@ -42,27 +42,10 @@ The overloads of the __AppendDocument()__ method allow you to pass a parameter o #### **Example 1: Using the AppendDocument() method** -{{source=..\SamplesCS\RichTextEditor\GettingStarted\Main.cs region=cs-radrichtextbox-features-merge-append-documents_1}} -{{source=..\SamplesVB\RichTextEditor\GettingStarted\Main.vb region=cs-radrichtextbox-features-merge-append-documents_1}} - -````C# -Telerik.WinForms.Documents.Model.Merging.RadDocumentMerger documentMerger = new RadDocumentMerger(targetDocument); -Telerik.WinForms.Documents.Model.Merging.AppendDocumentOptions options = new AppendDocumentOptions(); -options.ConflictingStylesResolutionMode = ConflictingStylesResolutionMode.UseTargetStyle; -options.FirstSourceSectionPropertiesResolutionMode = SectionPropertiesResolutionMode.Target; -documentMerger.AppendDocument(sourceDocument, options); - -```` -````VB.NET -Dim documentMerger As Telerik.WinForms.Documents.Model.Merging.RadDocumentMerger = New RadDocumentMerger(targetDocument) -Dim options As Telerik.WinForms.Documents.Model.Merging.AppendDocumentOptions = New AppendDocumentOptions() -options.ConflictingStylesResolutionMode = ConflictingStylesResolutionMode.UseTargetStyle -options.FirstSourceSectionPropertiesResolutionMode = SectionPropertiesResolutionMode.Target -documentMerger.AppendDocument(sourceDocument, options) - -```` - -{{endregion}} + + + + There is another overload of **AppendDocument()** that takes only a **RadDocument** instance. When you use this overload, the default values of **AppendDocumentOptions** are used when merging documents. diff --git a/controls/richtexteditor/features/merge-documents/merge.md b/controls/richtexteditor/features/merge-documents/merge.md index 24fda6f59..8f539daf3 100644 --- a/controls/richtexteditor/features/merge-documents/merge.md +++ b/controls/richtexteditor/features/merge-documents/merge.md @@ -24,25 +24,10 @@ Along with the [RadDocument]({%slug winforms/richtexteditor-/document-elements/r #### Merge documents with InsertDocumentOptions -{{source=..\SamplesCS\RichTextEditor\GettingStarted\Main.cs region=radrichtextbox-features-raddocumentmerger_1}} -{{source=..\SamplesVB\RichTextEditor\GettingStarted\Main.vb region=radrichtextbox-features-raddocumentmerger_1}} + + -````C# -InsertDocumentOptions insertOptions = new InsertDocumentOptions(); -insertOptions.ConflictingStylesResolutionMode = ConflictingStylesResolutionMode.UseTargetStyle; -insertOptions.InsertLastParagraphMarker = false; -merger.InsertDocument(sourceDocument, insertOptions); -```` -````VB.NET -Dim insertOptions As New InsertDocumentOptions() -insertOptions.ConflictingStylesResolutionMode = ConflictingStylesResolutionMode.UseTargetStyle -insertOptions.InsertLastParagraphMarker = False -merger.InsertDocument(sourceDocument, insertOptions) - -```` - -{{endregion}} There is another overload of **InsertDocument()** that takes only a [RadDocument]({%slug winforms/richtexteditor-/document-elements/raddocument%}) instance. When you use this overload, the default values of **InsertDocumentOptions** are used when merging documents. diff --git a/controls/richtexteditor/features/merge-documents/raddocumentmerger.md b/controls/richtexteditor/features/merge-documents/raddocumentmerger.md index fe40825fd..0477c8ed6 100644 --- a/controls/richtexteditor/features/merge-documents/raddocumentmerger.md +++ b/controls/richtexteditor/features/merge-documents/raddocumentmerger.md @@ -18,19 +18,10 @@ When instantiating the **RadDocumentMerger** class, you should pass to its const #### Example 1: Create a RadDocumentMerger -{{source=..\SamplesCS\RichTextEditor\GettingStarted\Main.cs region=DocumentMerger}} -{{source=..\SamplesVB\RichTextEditor\GettingStarted\Main.vb region=DocumentMerger}} + + -````C# -Telerik.WinForms.Documents.Model.Merging.RadDocumentMerger merger = new RadDocumentMerger(targetDocument); -```` -````VB.NET -Dim merger As Telerik.WinForms.Documents.Model.Merging.RadDocumentMerger = New RadDocumentMerger(targetDocument) - -```` - -{{endregion}} The document passed to the constructor can be obtained through the **Document** property of the __RadDocumentMerger__ instance. diff --git a/controls/richtexteditor/features/paste-options.md b/controls/richtexteditor/features/paste-options.md index 4b50ea4ed..391adb07d 100644 --- a/controls/richtexteditor/features/paste-options.md +++ b/controls/richtexteditor/features/paste-options.md @@ -71,21 +71,9 @@ You can invoke the paste with specific options through the RadRichTextEditor/Rad #### [C#] Example 1: Paste with Specific Settings -{{source=..\SamplesCS\RichTextEditor\Features\ClipboardSupport.cs region=PasteAsOptions}} -{{source=..\SamplesVB\RichTextEditor\Features\ClipboardSupport.vb region=PasteAsOptions}} + + -````C# - -this.radRichTextEditor1.Paste(Telerik.WinForms.Documents.Model.PasteOption.MergeFormatting); - -```` -````VB.NET - -Me.radRichTextEditor1.Paste(Telerik.WinForms.Documents.Model.PasteOption.MergeFormatting) - -```` - -{{endregion}} ## Executing Paste through UI diff --git a/controls/richtexteditor/features/positioning.md b/controls/richtexteditor/features/positioning.md index 4d876a6f6..930cc804e 100644 --- a/controls/richtexteditor/features/positioning.md +++ b/controls/richtexteditor/features/positioning.md @@ -1,275 +1,158 @@ ---- -title: Positioning -page_title: Positioning - WinForms RichTextEditor Control -description: The positioning feature in the WinForms RichTextEditor is used to navigate through document's content and to get information about the document's elements at a specific position. -slug: winforms/richtexteditor-/features/positioning -tags: positioning -published: True -position: 9 -previous_url: richtexteditor-features-positioning ---- - -# Positioning - -The positioning feature in the __RadRichTextEditor__ is used to navigate through document's content and to get information about the document's elements at a specific position. The __RadDocument__ uses the positioning to track the movement of the caret and to control the selection. - -The positioning is implemented via the __DocumentPosition__ class. This class can be used by the developer to programmatically control the positioning or the selection. __DocumentPosition__ offers methods, such as __MoveToNextWord()__, __MoveToPreviousWord()__, __MoveToCurrentLineStart/End()__ and so on, which will navigate to the given document element. In order to get information about the element at a given position you can use several methods such as __GetCurrentSpanBox()__, __GetCurrentParagraphBox()__, __GetCurrentSectionBox()__ and so on which will return the LayoutBox of an element. Another option is to use directly the methods returning the specific document element - **GetCurrentSpan()**, **GetCurrentParagraph()**, **GetCurrentTable()** etc. - -__DocumentPosition__ also redefines equality and comparison operators for more convenience, when you should find whether the __DocumentPosition__ is before or after another position in the natural flow of the document. By default, __RadRichTextEditor__ moves __Document.CaretPosition__ using arrow keys or on mouse click. __DocumentPosition__ can also be obtained by giving the coordinates of a point in the document using the method __DocumentPosition.SetPosition__. - -You can manage the caret position for a specific __RadDocument__ by either accessing its __CaretPosition__ property, which is of type __DocumentPosition__, or by creating a new instance of the __DocumentPosition__ class and associating it with the desired __RadDocument__. - ->note When using the __CaretPosition__ property you are directly managing the caret position in the __RadDocument__. By using the __DocumentPosition__ class you can create instances of several positions inside the document without changing the current caret position. -> - -## CaretPosition property - -This property enables you to manage the position of the caret inside the document and to obtain information about its location and the elements it currently resides at. Here is an example of how to use the **CaretPosition** property to get the current word. - -{{source=..\SamplesCS\RichTextEditor\Features\PositioningCode.cs region=caret}} -{{source=..\SamplesVB\RichTextEditor\Features\PositioningCode.vb region=caret}} - -````C# - -string currentSpanText = this.radRichTextEditor1.Document.CaretPosition.GetCurrentSpanBox().Text; - -```` -````VB.NET -Dim currentSpanText As String = Me.radRichTextEditor1.Document.CaretPosition.GetCurrentSpanBox().Text - -```` - -{{endregion}} - - -## DocumentPosition class - -An alternative of using the __CaretPosition__ property is to create an instance of the __DocumentPosition__ class. Here is the same example from the previous chapter done with an instance of the __DocumentPosition__ class. - ->note When instantiated in such a way, the position will be at the start of the document, so the result will be the first word in the text. The position of the instance won't be affected by the UI. To change it, you have to use the [API of the DocumentPosition class](https://docs.telerik.com/devtools/winforms/api/telerik.winforms.documents.documentposition). - -{{source=..\SamplesCS\RichTextEditor\Features\PositioningCode.cs region=position}} -{{source=..\SamplesVB\RichTextEditor\Features\PositioningCode.vb region=position}} - -````C# - -Telerik.WinForms.Documents.DocumentPosition position = new Telerik.WinForms.Documents.DocumentPosition(this.radRichTextEditor1.Document); -string currentSpanText1 = position.GetCurrentSpanBox().Text; - -```` -````VB.NET -Dim position As New Telerik.WinForms.Documents.DocumentPosition(Me.radRichTextEditor1.Document) -Dim currentSpanText1 As String = position.GetCurrentSpanBox().Text - -```` - -{{endregion}} - -### Tracking Positions - -When you need to ensure that the position is kept between the same characters, no matter the modifications users can do on the document content, you can instantiate the **DocumentPosition** object using one of the constructors accepting a boolean value. This boolean value indicates whether the position should track the changes in the document and move accordingly so it can be located on the same position in the word. - -**DocumentPosition** created with any of the constructors accepting the boolean *trackDocumentChangeEvents* parameter set to *true* moves automatically when the document is edited before the position (just like the caret position). - ->note Positions created in such a way could be explicitly disposed to avoid preserving them too much in memory. - -## Determine The Type of Element The Position Is At - -The **DocumentPosition** class offers different properties allowing you to determine where the position is located. For example, you can check whether the position is at the start of the document or at its end. Similarly, you can obtain information whether the position is inside table. Here is a list of these properties: - -* **IsPositionAtDocumentEnd** -* **IsPositionAtDocumentStart** -* **IsPositionAtParagraphEnd** -* **IsPositionAtParagraphStart** -* **IsPositionAtTableCellEnd** -* **IsPositionAtTableCellStart** -* **IsPositionAtTableRowStart** +--- +title: Positioning +page_title: Positioning - WinForms RichTextEditor Control +description: The positioning feature in the WinForms RichTextEditor is used to navigate through document's content and to get information about the document's elements at a specific position. +slug: winforms/richtexteditor-/features/positioning +tags: positioning +published: True +position: 9 +previous_url: richtexteditor-features-positioning +--- + +# Positioning + +The positioning feature in the __RadRichTextEditor__ is used to navigate through document's content and to get information about the document's elements at a specific position. The __RadDocument__ uses the positioning to track the movement of the caret and to control the selection. + +The positioning is implemented via the __DocumentPosition__ class. This class can be used by the developer to programmatically control the positioning or the selection. __DocumentPosition__ offers methods, such as __MoveToNextWord()__, __MoveToPreviousWord()__, __MoveToCurrentLineStart/End()__ and so on, which will navigate to the given document element. In order to get information about the element at a given position you can use several methods such as __GetCurrentSpanBox()__, __GetCurrentParagraphBox()__, __GetCurrentSectionBox()__ and so on which will return the LayoutBox of an element. Another option is to use directly the methods returning the specific document element - **GetCurrentSpan()**, **GetCurrentParagraph()**, **GetCurrentTable()** etc. + +__DocumentPosition__ also redefines equality and comparison operators for more convenience, when you should find whether the __DocumentPosition__ is before or after another position in the natural flow of the document. By default, __RadRichTextEditor__ moves __Document.CaretPosition__ using arrow keys or on mouse click. __DocumentPosition__ can also be obtained by giving the coordinates of a point in the document using the method __DocumentPosition.SetPosition__. + +You can manage the caret position for a specific __RadDocument__ by either accessing its __CaretPosition__ property, which is of type __DocumentPosition__, or by creating a new instance of the __DocumentPosition__ class and associating it with the desired __RadDocument__. + +>note When using the __CaretPosition__ property you are directly managing the caret position in the __RadDocument__. By using the __DocumentPosition__ class you can create instances of several positions inside the document without changing the current caret position. +> + +## CaretPosition property + +This property enables you to manage the position of the caret inside the document and to obtain information about its location and the elements it currently resides at. Here is an example of how to use the **CaretPosition** property to get the current word. + + + + + + +## DocumentPosition class + +An alternative of using the __CaretPosition__ property is to create an instance of the __DocumentPosition__ class. Here is the same example from the previous chapter done with an instance of the __DocumentPosition__ class. + +>note When instantiated in such a way, the position will be at the start of the document, so the result will be the first word in the text. The position of the instance won't be affected by the UI. To change it, you have to use the [API of the DocumentPosition class](https://docs.telerik.com/devtools/winforms/api/telerik.winforms.documents.documentposition). + + + + + + +### Tracking Positions + +When you need to ensure that the position is kept between the same characters, no matter the modifications users can do on the document content, you can instantiate the **DocumentPosition** object using one of the constructors accepting a boolean value. This boolean value indicates whether the position should track the changes in the document and move accordingly so it can be located on the same position in the word. + +**DocumentPosition** created with any of the constructors accepting the boolean *trackDocumentChangeEvents* parameter set to *true* moves automatically when the document is edited before the position (just like the caret position). + +>note Positions created in such a way could be explicitly disposed to avoid preserving them too much in memory. + +## Determine The Type of Element The Position Is At + +The **DocumentPosition** class offers different properties allowing you to determine where the position is located. For example, you can check whether the position is at the start of the document or at its end. Similarly, you can obtain information whether the position is inside table. Here is a list of these properties: + +* **IsPositionAtDocumentEnd** +* **IsPositionAtDocumentStart** +* **IsPositionAtParagraphEnd** +* **IsPositionAtParagraphStart** +* **IsPositionAtTableCellEnd** +* **IsPositionAtTableCellStart** +* **IsPositionAtTableRowStart** * **IsPositionInsideTable** - -There is also a **Location** property holding information about where in the layout the position is situated. - -## Access Document Element from Caret Position - -You can use the methods of the **DocumentPosition** class to get the document element at the specific position. The following list shows the methods which can be used. - -* **GetCurrentInline()** -* **GetCurrentParagraph()** -* **GetCurrentSpan()** -* **GetCurrentTable()** -* **GetCurrentTableCell()** -* **GetCurrentTableRow()** -* **GetNextInline()** -* **GetNextSpan()** + +There is also a **Location** property holding information about where in the layout the position is situated. + +## Access Document Element from Caret Position + +You can use the methods of the **DocumentPosition** class to get the document element at the specific position. The following list shows the methods which can be used. + +* **GetCurrentInline()** +* **GetCurrentParagraph()** +* **GetCurrentSpan()** +* **GetCurrentTable()** +* **GetCurrentTableCell()** +* **GetCurrentTableRow()** +* **GetNextInline()** +* **GetNextSpan()** * **GetPreviousInline()** -In addition to the above-mentioned methods, **DocumentPosition** exposes also **GetCurrent[document element]Box** methods returning objects of type **LayoutBox**, which can be used to get the relevant layout information about a document element. To get the element from the layout box, you can use the **AssociatedDocumentElement** property. - -In the different implementations of the **LayoutBox** class (examples: **ParagraphLayoutBox**, **SectionLayoutBox**, etc.) there are also more specific properties that allow you to easily get the associated document element without casting it from the base **DocumentElement** class. For example, the **GetCurrentParagraphBox()** method returns an object of type **ParagraphLayoutBox** which has **AssociatedParagraph** property. And the **GetCurrentSectionBox()** returns **SectionLayoutBox** which has **AssociatedSection** property. This rule applies to all **LayoutBox** elements (also **TableLayoutBox**, **SpanLayoutBox**, etc.). - -#### Getting the Paragraph on the caret position - -{{source=..\SamplesCS\RichTextEditor\Features\PositioningCode.cs region=Paragraph}} -{{source=..\SamplesVB\RichTextEditor\Features\PositioningCode.vb region=Paragraph}} - - -````C# - - DocumentPosition documentPosition = this.radRichTextEditor1.Document.CaretPosition; - Paragraph paragraph = documentPosition.GetCurrentParagraph(); - -```` -````VB.NET - Dim documentPosition As DocumentPosition = Me.radRichTextEditor1.Document.CaretPosition() - Dim paragraph As Paragraph = documentPosition.GetCurrentParagraph() - -```` - -{{endregion}} - -#### Getting the Inline on the caret position - -{{source=..\SamplesCS\RichTextEditor\Features\PositioningCode.cs region=Inline}} -{{source=..\SamplesVB\RichTextEditor\Features\PositioningCode.vb region=Inline}} - - -````C# - documentPosition = this.radRichTextEditor1.Document.CaretPosition; - Inline inline = documentPosition.GetCurrentInline(); - - -```` -````VB.NET - - documentPosition = Me.radRichTextEditor1.Document.CaretPosition - Dim inline As Inline = documentPosition.GetCurrentInline() - -```` - -{{endregion}} - -To get the word on the document position, you can use the **GetCurrentWord()** method. - -#### Getting the word on the caret position - - -{{source=..\SamplesCS\RichTextEditor\Features\PositioningCode.cs region=Word}} -{{source=..\SamplesVB\RichTextEditor\Features\PositioningCode.vb region=Word}} - - -````C# - - documentPosition = this.radRichTextEditor1.Document.CaretPosition; - string word = documentPosition.GetCurrentWord(); - - -```` -````VB.NET - documentPosition = Me.radRichTextEditor1.Document.CaretPosition - Dim word As String = documentPosition.GetCurrentWord() - - - -```` - -{{endregion}} - -If the searched document element (paragraph, span, table, etc.) cannot be found on the caret position, the corresponding method will return null. - -## Convert Between DocumentPosition And Screen Position - -You can use the **ActiveEditorPresenter** of **RadRichTextEditor** to convert a screen position to **DocumentPosition** and vice versa. The **ActiveEditorPresenter** exposes a couple of methods which can be used. - +In addition to the above-mentioned methods, **DocumentPosition** exposes also **GetCurrent[document element]Box** methods returning objects of type **LayoutBox**, which can be used to get the relevant layout information about a document element. To get the element from the layout box, you can use the **AssociatedDocumentElement** property. + +In the different implementations of the **LayoutBox** class (examples: **ParagraphLayoutBox**, **SectionLayoutBox**, etc.) there are also more specific properties that allow you to easily get the associated document element without casting it from the base **DocumentElement** class. For example, the **GetCurrentParagraphBox()** method returns an object of type **ParagraphLayoutBox** which has **AssociatedParagraph** property. And the **GetCurrentSectionBox()** returns **SectionLayoutBox** which has **AssociatedSection** property. This rule applies to all **LayoutBox** elements (also **TableLayoutBox**, **SpanLayoutBox**, etc.). + +#### Getting the Paragraph on the caret position + + + + + + +#### Getting the Inline on the caret position + + + + + + +To get the word on the document position, you can use the **GetCurrentWord()** method. + +#### Getting the word on the caret position + + + + + + + +If the searched document element (paragraph, span, table, etc.) cannot be found on the caret position, the corresponding method will return null. + +## Convert Between DocumentPosition And Screen Position + +You can use the **ActiveEditorPresenter** of **RadRichTextEditor** to convert a screen position to **DocumentPosition** and vice versa. The **ActiveEditorPresenter** exposes a couple of methods which can be used. + * **GetDocumentPositionFromViewPoint()**: The method accepts an argument of type System.Windows.Point and returns an instance of type DocumentPosition. -#### Screen position to DocumentPosition conversion - -{{source=..\SamplesCS\RichTextEditor\Features\PositioningCode.cs region=DocumentPosition}} -{{source=..\SamplesVB\RichTextEditor\Features\PositioningCode.vb region=DocumentPosition}} - - -````C# - Point position = GetMousePosition(); - DocumentPosition documentPosition = this.radRichTextEditor1.RichTextBoxElement.ActiveEditorPresenter.GetDocumentPositionFromViewPoint(position); - -```` -````VB.NET - - Dim position As Point = GetMousePosition() - Dim documentPosition As DocumentPosition = Me.radRichTextEditor1.RichTextBoxElement.ActiveEditorPresenter.GetDocumentPositionFromViewPoint(position) - - -```` - -{{endregion}} - +#### Screen position to DocumentPosition conversion + + + + + + * **GetViewPointFromDocumentPosition()**: The method accepts an argument of type DocumentPosition and returns an instance of type System.Windows.Point -#### DocumentPosition to screen position conversion - -{{source=..\SamplesCS\RichTextEditor\Features\PositioningCode.cs region=Point}} -{{source=..\SamplesVB\RichTextEditor\Features\PositioningCode.vb region=Point}} - - -````C# - documentPosition = this.radRichTextEditor1.Document.CaretPosition; - position = this.radRichTextEditor1.RichTextBoxElement.ActiveEditorPresenter.GetViewPointFromDocumentPosition(documentPosition); - -```` -````VB.NET - - documentPosition = Me.radRichTextEditor1.Document.CaretPosition - position = Me.radRichTextEditor1.RichTextBoxElement.ActiveEditorPresenter.GetViewPointFromDocumentPosition(documentPosition) - - -```` - -{{endregion}} - -## Events - -There are several events that you can use to track changes in the position. - -* **LocationChanging**: Occurs before changing the coordinates of a position. For the caret position, this can be also achieved by typing, using the arrows keys or by clicking somewhere in the document. -LocationChanged: Occurs when changing the coordinates of a position. For the caret position, this can be also achieved by typing, using the arrows keys or by clicking somewhere in the document. - -* **PositionChanging**: Occurs before the position is moved. For the caret position, this can be also achieved using the arrows keys or by clicking somewhere in the document. - +#### DocumentPosition to screen position conversion + + + + + + +## Events + +There are several events that you can use to track changes in the position. + +* **LocationChanging**: Occurs before changing the coordinates of a position. For the caret position, this can be also achieved by typing, using the arrows keys or by clicking somewhere in the document. +LocationChanged: Occurs when changing the coordinates of a position. For the caret position, this can be also achieved by typing, using the arrows keys or by clicking somewhere in the document. + +* **PositionChanging**: Occurs before the position is moved. For the caret position, this can be also achieved using the arrows keys or by clicking somewhere in the document. + * **PositionChanged**: Occurs when the position is moved. For the caret position, this can be also achieved using the arrows keys or by clicking somewhere in the document. -The following example shows how you can change the background of a Table object once the caret is positioned inside a Table. - -#### Using DocumentPosition events - -{{source=..\SamplesCS\RichTextEditor\Features\PositioningCode.cs region=Events}} -{{source=..\SamplesVB\RichTextEditor\Features\PositioningCode.vb region=Events}} - - -````C# - private void CaretPosition_LocationChanged(object sender, EventArgs e) - { - if (this.radRichTextEditor1.Document.CaretPosition.IsPositionInsideTable) - { - Table table = this.radRichTextEditor1.Document.CaretPosition.GetCurrentTable(); - table.Background = Colors.Red; - } - } - -```` -````VB.NET - - Private Sub CaretPosition_LocationChanged(ByVal sender As Object, ByVal e As EventArgs) - If Me.radRichTextBox.Document.CaretPosition.IsPositionInsideTable Then - Dim table As Table = Me.radRichTextBox.Document.CaretPosition.GetCurrentTable() - table.Background = Colors.Red - End If -End Sub - -```` - -{{endregion}} - -# See Also - - * [Section]({%slug winforms/richtexteditor-/document-elements/section%}) - - * [History]({%slug winforms/richtexteditor-/features/history%}) +The following example shows how you can change the background of a Table object once the caret is positioned inside a Table. + +#### Using DocumentPosition events + + + + + + +# See Also + + * [Section]({%slug winforms/richtexteditor-/document-elements/section%}) + + * [History]({%slug winforms/richtexteditor-/features/history%}) diff --git a/controls/richtexteditor/features/raddocumenteditor.md b/controls/richtexteditor/features/raddocumenteditor.md index 54727dc3b..58fdd005e 100644 --- a/controls/richtexteditor/features/raddocumenteditor.md +++ b/controls/richtexteditor/features/raddocumenteditor.md @@ -1,114 +1,53 @@ ---- -title: RadDocumentEditor -page_title: RadDocumentEditor - WinForms RichTextEditor Control -description: RadDocument is the main document unit in WinForms RichTextEditor. It has API of its own for adding and removing Blocks and Inlines from the document. -slug: winforms/richtexteditor-/features/raddocumenteditor -tags: raddocumenteditor -published: True -position: 9 -previous_url: richtexteditor-features-raddocumenteditor ---- - -# RadDocumentEditor - -__RadDocument__ has API of its own, but using it has a set of limitations. First of all, adding and removing **Blocks** and **Inlines** from the document can be done only before the document has been measured – a procedure that calculates the desired size of the spans, paragraphs and the document altogether in order to calculate its layout. These operations are usually invoked by the framework when the document in shown in a __RadRichTextEditor__. However, some of the methods of __RadDocument__ and __RadRichTextEditor__ require that the document is measured before their execution, so if such a method is invoked, the document will be measured. Then, adding **Paragraphs**, **Tables**, **Sections** and **Spans** will break the structure of the document. - -Another issue that the use of the methods of __RadDocument__ causes is due to the fact that they are not registered in the undo/redo stack. Thus, once such a method is used, the history stack is cleared and users will no longer be able to undo and redo their previous changes. - -## What is RadDocumentEditor - -On the other hand, __RadRichTextEditor__ provides a much richer API for editing the __RadDocument__ instance in it. All respective methods from that API are located in the __IDocumentEditor__ interface which defines all method that edit fields, annotation ranges, document elements, history, headers and footers and so on and is inherited from __RadRichTextEditor__. In that regard, if you are modifying the document in a class that knows of the existence of __RadRichTextEditor__, you can use the methods of __RadRichTextEditor__ in order to manipulate the document in a way transparent to the end user. - -The appropriate API, however, should be available in cases when you want to modify a document from code without having a __RadRichTextEditor__. For this purpose, a __RadDocumentEditor__ class has been introduced. It also implements the __IDocumentEditor__ interface and includes all relevant methods of __RadRichTextEditor__ for manipulating the document programmatically. - -## How to use RadDocumentEditor - -When a __RadDocument__ instance was for some reason created from code – built using the elements hierarchy or imported, it can be passed to a __RadDocumentEditor__ like this: - -{{source=..\SamplesCS\RichTextEditor\Features\DocumentEditorCode.cs region=init}} -{{source=..\SamplesVB\RichTextEditor\Features\DocumentEditorCode.vb region=init}} - -````C# - -RadDocumentEditor documentEditor = new RadDocumentEditor(this.radRichTextEditor1.Document); - -```` -````VB.NET -Dim documentEditor As New RadDocumentEditor(Me.radRichTextEditor1.Document) - -```` - -{{endregion}} - -The newly created *documentEditor* instance now provides all capabilities that a __RadRichTextEditor__ provides. Moreover, you can group several methods so that they are added to the Undo/Redo stack as a single item. This can be achieved like this: - -{{source=..\SamplesCS\RichTextEditor\Features\DocumentEditorCode.cs region=insert}} -{{source=..\SamplesVB\RichTextEditor\Features\DocumentEditorCode.vb region=insert}} - -````C# - -documentEditor.BeginUndoGroup(); - -if (documentEditor.Document.CaretPosition.IsPositionInsideTable) -{ - documentEditor.InsertTableRow(); - documentEditor.InsertTableRow(); - documentEditor.InsertTableRow(); - documentEditor.Document.Selection.Clear(); -} -documentEditor.EndUndoGroup("Insert three table rows"); - -```` -````VB.NET -documentEditor.BeginUndoGroup() -If documentEditor.Document.CaretPosition.IsPositionInsideTable Then - documentEditor.InsertTableRow() - documentEditor.InsertTableRow() - documentEditor.InsertTableRow() - documentEditor.Document.Selection.Clear() -End If -documentEditor.EndUndoGroup("Insert three table rows") - -```` - -{{endregion}} - -You can also cancel the execution of the undo group, and it won't be recorded in the history: - -{{source=..\SamplesCS\RichTextEditor\Features\DocumentEditorCode.cs region=cancel}} -{{source=..\SamplesVB\RichTextEditor\Features\DocumentEditorCode.vb region=cancel}} - -````C# - -documentEditor.BeginUndoGroup(); -if (documentEditor.Document.CaretPosition.IsPositionInsideTable) -{ - documentEditor.InsertTableRow(); - documentEditor.InsertTableRow(); - documentEditor.InsertTableRow(); - documentEditor.Document.Selection.Clear(); -} -documentEditor.CancelUndoGroup(); - -```` -````VB.NET -documentEditor.BeginUndoGroup() -If documentEditor.Document.CaretPosition.IsPositionInsideTable Then - documentEditor.InsertTableRow() - documentEditor.InsertTableRow() - documentEditor.InsertTableRow() - documentEditor.Document.Selection.Clear() -End If -documentEditor.CancelUndoGroup() - -```` - -{{endregion}} - -One thing to note here is that it is not possible to remove some actions from the undo history altogether, i.e. you cannot perform an action without it getting registered in the Undo/Redo stack. In most cases, however, this is sufficient, as you can group the operations that you do not want to name and show explicitly to the end user with the ones that have been user-initiated and are expected by the person modifying the content of __RadRichTextEditor__. - -# See Also - - * [History]({%slug winforms/richtexteditor-/features/history%}) - - * [Using RadRichTextEditor's formatting API ]({%slug winforms/richtexteditor-/getting-started/formatting-api%}) +--- +title: RadDocumentEditor +page_title: RadDocumentEditor - WinForms RichTextEditor Control +description: RadDocument is the main document unit in WinForms RichTextEditor. It has API of its own for adding and removing Blocks and Inlines from the document. +slug: winforms/richtexteditor-/features/raddocumenteditor +tags: raddocumenteditor +published: True +position: 9 +previous_url: richtexteditor-features-raddocumenteditor +--- + +# RadDocumentEditor + +__RadDocument__ has API of its own, but using it has a set of limitations. First of all, adding and removing **Blocks** and **Inlines** from the document can be done only before the document has been measured – a procedure that calculates the desired size of the spans, paragraphs and the document altogether in order to calculate its layout. These operations are usually invoked by the framework when the document in shown in a __RadRichTextEditor__. However, some of the methods of __RadDocument__ and __RadRichTextEditor__ require that the document is measured before their execution, so if such a method is invoked, the document will be measured. Then, adding **Paragraphs**, **Tables**, **Sections** and **Spans** will break the structure of the document. + +Another issue that the use of the methods of __RadDocument__ causes is due to the fact that they are not registered in the undo/redo stack. Thus, once such a method is used, the history stack is cleared and users will no longer be able to undo and redo their previous changes. + +## What is RadDocumentEditor + +On the other hand, __RadRichTextEditor__ provides a much richer API for editing the __RadDocument__ instance in it. All respective methods from that API are located in the __IDocumentEditor__ interface which defines all method that edit fields, annotation ranges, document elements, history, headers and footers and so on and is inherited from __RadRichTextEditor__. In that regard, if you are modifying the document in a class that knows of the existence of __RadRichTextEditor__, you can use the methods of __RadRichTextEditor__ in order to manipulate the document in a way transparent to the end user. + +The appropriate API, however, should be available in cases when you want to modify a document from code without having a __RadRichTextEditor__. For this purpose, a __RadDocumentEditor__ class has been introduced. It also implements the __IDocumentEditor__ interface and includes all relevant methods of __RadRichTextEditor__ for manipulating the document programmatically. + +## How to use RadDocumentEditor + +When a __RadDocument__ instance was for some reason created from code – built using the elements hierarchy or imported, it can be passed to a __RadDocumentEditor__ like this: + + + + + + +The newly created *documentEditor* instance now provides all capabilities that a __RadRichTextEditor__ provides. Moreover, you can group several methods so that they are added to the Undo/Redo stack as a single item. This can be achieved like this: + + + + + + +You can also cancel the execution of the undo group, and it won't be recorded in the history: + + + + + + +One thing to note here is that it is not possible to remove some actions from the undo history altogether, i.e. you cannot perform an action without it getting registered in the Undo/Redo stack. In most cases, however, this is sufficient, as you can group the operations that you do not want to name and show explicitly to the end user with the ones that have been user-initiated and are expected by the person modifying the content of __RadRichTextEditor__. + +# See Also + + * [History]({%slug winforms/richtexteditor-/features/history%}) + + * [Using RadRichTextEditor's formatting API ]({%slug winforms/richtexteditor-/getting-started/formatting-api%}) diff --git a/controls/richtexteditor/features/read-only-ranges.md b/controls/richtexteditor/features/read-only-ranges.md index c456650b8..6573ad334 100644 --- a/controls/richtexteditor/features/read-only-ranges.md +++ b/controls/richtexteditor/features/read-only-ranges.md @@ -33,20 +33,10 @@ __Insert in Measured Document__ When the document is measured (for example, shown in a __RadRichTextEditor__), you can select the part of the document which you want to make read-only and use the __InsertReadOnlyRange()__ method of __RadRichTextEditor__ (or [RadDocumentEditor]({%slug winforms/richtexteditor-/features/raddocumenteditor%}) respectively): -{{source=..\SamplesCS\RichTextEditor\Features\ReadOnlyRanges.cs region=insert}} -{{source=..\SamplesVB\RichTextEditor\Features\ReadOnlyRanges.vb region=insert}} + + -````C# - -this.radRichTextEditor1.InsertReadOnlyRange(); -```` -````VB.NET -Me.radRichTextEditor1.InsertReadOnlyRange() - -```` - -{{endregion}} Generally, editing the content of a read only range is not possible through the UI and through __RadRichTextEditor__'s API. However, when manipulating a document using __RadDocumentEditor__ you can set the __RespectReadOnlyRanges__ property of __RadDocumentEditor__ to *false* and read only ranges will be ignored. @@ -54,97 +44,27 @@ __Insert in Non-measured Document__ As opposed to when inserting with one of the methods of __RadRichTextEditor__, when building a document from code you have to make sure that the annotations in it are explicitly paired. This can be achieved with the __PairWithStart()__ method of __AnnotationRangeEnd__. Here is an example which builds a __RadDocument__ with a read only range in it. -{{source=..\SamplesCS\RichTextEditor\Features\ReadOnlyRanges.cs region=add}} -{{source=..\SamplesVB\RichTextEditor\Features\ReadOnlyRanges.vb region=add}} - -````C# - -RadDocument document = new RadDocument(); -Section section = new Section(); -Paragraph paragraph = new Paragraph(); -Span span = new Span("Content prior range["); -Span span2 = new Span("]Content after range"); -Span readOnlyContent = new Span("READ ONLY"); -ReadOnlyRangeStart rangeStart = new ReadOnlyRangeStart(); -ReadOnlyRangeEnd rangeEnd = new ReadOnlyRangeEnd(); -rangeEnd.PairWithStart(rangeStart); - -paragraph.Inlines.Add(span); -paragraph.Inlines.Add(rangeStart); -paragraph.Inlines.Add(readOnlyContent); -paragraph.Inlines.Add(rangeEnd); -paragraph.Inlines.Add(span2); - -section.Blocks.Add(paragraph); -document.Sections.Add(section); - -```` -````VB.NET -Dim document As New RadDocument() -Dim section As New Section() -Dim paragraph As New Paragraph() -Dim span As New Span("Content prior range[") -Dim span2 As New Span("]Content after range") -Dim readOnlyContent As New Span("READ ONLY") -Dim rangeStart As New ReadOnlyRangeStart() -Dim rangeEnd As New ReadOnlyRangeEnd() -rangeEnd.PairWithStart(rangeStart) -paragraph.Inlines.Add(span) -paragraph.Inlines.Add(rangeStart) -paragraph.Inlines.Add(readOnlyContent) -paragraph.Inlines.Add(rangeEnd) -paragraph.Inlines.Add(span2) -section.Blocks.Add(paragraph) -document.Sections.Add(section) - -```` - -{{endregion}} + + -## Delete Read Only Range -In order to remove a read only range, you should simply call the __DeleteReadOnlyRange()__ method of __RadRichTextEditor__ or __RadDocumentEditor__: -{{source=..\SamplesCS\RichTextEditor\Features\ReadOnlyRanges.cs region=delete}} -{{source=..\SamplesVB\RichTextEditor\Features\ReadOnlyRanges.vb region=delete}} +## Delete Read Only Range -````C# - -this.radRichTextEditor1.DeleteReadOnlyRange(); +In order to remove a read only range, you should simply call the __DeleteReadOnlyRange()__ method of __RadRichTextEditor__ or __RadDocumentEditor__: -```` -````VB.NET -Me.radRichTextEditor1.DeleteReadOnlyRange() + + -```` -{{endregion}} The above-demonstrated method will delete the read only range the caret is currently located in and make the content which was in it editable again. Additionally, if you can obtain a reference to a particular __ReadOnlyRangeStart__ element in the document, you can delete it with the __DeleteReadOnlyRange(ReadOnlyRangeStart start)__ method. For example, if you want to delete a particular range based on its __Tag__, you can do it as follows: -{{source=..\SamplesCS\RichTextEditor\Features\ReadOnlyRanges.cs region=start}} -{{source=..\SamplesVB\RichTextEditor\Features\ReadOnlyRanges.vb region=start}} - -````C# - -ReadOnlyRangeStart start = this.radRichTextEditor1.Document.EnumerateChildrenOfType().Where(x => x.Tag == "ReadOnly").FirstOrDefault(); -if (start != null) -{ - this.radRichTextEditor1.DeleteReadOnlyRange(start); -} - -```` -````VB.NET -Dim start As ReadOnlyRangeStart = Me.radRichTextEditor1.Document.EnumerateChildrenOfType(Of ReadOnlyRangeStart)().Where(Function(x) x.Tag = "ReadOnly").FirstOrDefault() -If start IsNot Nothing Then - Me.radRichTextEditor1.DeleteReadOnlyRange(start) -End If - -```` + + -{{endregion}} # See Also diff --git a/controls/richtexteditor/features/references/bibliographic-references.md b/controls/richtexteditor/features/references/bibliographic-references.md index 848e012ec..ed86b27b4 100644 --- a/controls/richtexteditor/features/references/bibliographic-references.md +++ b/controls/richtexteditor/features/references/bibliographic-references.md @@ -71,80 +71,25 @@ Everything that we can do using UI, we can do in code behind too. All sources re This is how you can add a new source: -{{source=..\SamplesCS\RichTextEditor\Features\BibliographicReferences.cs region=init}} -{{source=..\SamplesVB\RichTextEditor\Features\BibliographicReferences.vb region=init}} - -````C# -BibliographicSource bibliographicSource = new BibliographicSource("test"); -bibliographicSource.Author = "authorTest"; -bibliographicSource.Title = "titleTest"; -bibliographicSource.Editor = "editorTest"; -bibliographicSource.SourceType = BibliographicSourceType.Book; -this.radRichTextEditor1.Document.BibliographicSources.Add(bibliographicSource); - -```` -````VB.NET -Dim bibliographicSource As New BibliographicSource("test") -bibliographicSource.Author = "authorTest" -bibliographicSource.Title = "titleTest" -bibliographicSource.Editor = "editorTest" -bibliographicSource.SourceType = BibliographicSourceType.Book -Me.radRichTextEditor1.Document.BibliographicSources.Add(bibliographicSource) - -```` - -{{endregion}} - -To create a custom __BibliographicStyle__ you have to derive from __BibliographicReferenceStyleBase__ and add the style to the document so it can be usable. All styles are kept in a dictionary that matches a string to a __BibliographicReferenceStyleBase__ object. Usually the string is the key of the particular style. Adding style is as easy as: + + -{{source=..\SamplesCS\RichTextEditor\Features\BibliographicReferences.cs region=add}} -{{source=..\SamplesVB\RichTextEditor\Features\BibliographicReferences.vb region=add}} -````C# -APAFifthEditionStyle APAFifthEdition = new APAFifthEditionStyle(); -this.radRichTextEditor1.Document.BibliographicStyles.Add(APAFifthEdition.Key, APAFifthEdition); -HarvardAnglia2008Style HarvardAnglia2008 = new HarvardAnglia2008Style(); -this.radRichTextEditor1.Document.BibliographicStyles.Add(HarvardAnglia2008.Key, HarvardAnglia2008); -ISO690_FirstElementAndDateStyle ISO690_FirstElementAndDate = -new ISO690_FirstElementAndDateStyle(); -this.radRichTextEditor1.Document.BibliographicStyles.Add(ISO690_FirstElementAndDate.Key, -ISO690_FirstElementAndDate); -```` -````VB.NET -Dim APAFifthEdition As New APAFifthEditionStyle() -Me.radRichTextEditor1.Document.BibliographicStyles.Add(APAFifthEdition.Key, APAFifthEdition) -Dim HarvardAnglia2008 As New HarvardAnglia2008Style() -Me.radRichTextEditor1.Document.BibliographicStyles.Add(HarvardAnglia2008.Key, HarvardAnglia2008) -Dim ISO690_FirstElementAndDate As New ISO690_FirstElementAndDateStyle() -Me.radRichTextEditor1.Document.BibliographicStyles.Add(ISO690_FirstElementAndDate.Key, ISO690_FirstElementAndDate) +To create a custom __BibliographicStyle__ you have to derive from __BibliographicReferenceStyleBase__ and add the style to the document so it can be usable. All styles are kept in a dictionary that matches a string to a __BibliographicReferenceStyleBase__ object. Usually the string is the key of the particular style. Adding style is as easy as: -```` + + -{{endregion}} ### Insert Citation Field using code behind The Citation field is a field not different from every other field. You can use the __InsertFIeld()__ method of __RadDocument__ to insert a citation: -{{source=..\SamplesCS\RichTextEditor\Features\BibliographicReferences.cs region=citation}} -{{source=..\SamplesVB\RichTextEditor\Features\BibliographicReferences.vb region=citation}} - -````C# -CitationField citationField = new CitationField(); -citationField.SourceName = "test"; -this.radRichTextEditor1.InsertField(citationField, FieldDisplayMode.Result); + + -```` -````VB.NET -Dim citationField As New CitationField() -citationField.SourceName = "test" -Me.radRichTextEditor1.InsertField(citationField, FieldDisplayMode.Result) - -```` - -{{endregion}} ### Insert Bibliography Field using code behind @@ -152,39 +97,17 @@ Me.radRichTextEditor1.InsertField(citationField, FieldDisplayMode.Result) The Bibliography field is a field not different from every other field. You can use the __InsertFIeld()__ method of __RadDocument__ to insert a citation: -{{source=..\SamplesCS\RichTextEditor\Features\BibliographicReferences.cs region=bibliography}} -{{source=..\SamplesVB\RichTextEditor\Features\BibliographicReferences.vb region=bibliography}} - -````C# -BibliographyField bibliographyField = new BibliographyField(); -this.radRichTextEditor1.InsertField(bibliographyField, FieldDisplayMode.Result); + + -```` -````VB.NET -Dim bibliographyField As New BibliographyField() -Me.radRichTextEditor1.InsertField(bibliographyField, FieldDisplayMode.Result) -```` - -{{endregion}} ### Changing Bibliographic Style using code behind There is a method called __ChangeBibliographicStyle()__ on __RadRichTextEditor__. It accepts one argument of type __BibliographicReferenceStyleBase__. Changing the current style is as simple as: -{{source=..\SamplesCS\RichTextEditor\Features\BibliographicReferences.cs region=style}} -{{source=..\SamplesVB\RichTextEditor\Features\BibliographicReferences.vb region=style}} - -````C# -this.radRichTextEditor1.ChangeBibliographicStyle(new HarvardAnglia2008Style()); - -```` -````VB.NET -Me.radRichTextEditor1.ChangeBibliographicStyle(New HarvardAnglia2008Style()) - -```` - -{{endregion}} + + diff --git a/controls/richtexteditor/features/references/captions-for-tables-and-figures.md b/controls/richtexteditor/features/references/captions-for-tables-and-figures.md index d070c4351..97219ad57 100644 --- a/controls/richtexteditor/features/references/captions-for-tables-and-figures.md +++ b/controls/richtexteditor/features/references/captions-for-tables-and-figures.md @@ -80,43 +80,17 @@ Using Telerik's rich text editor's API is pretty straight forward. There is a me The __CaptionDefinition__ class contains viable information for the creation of the caption like __Label__, __NumberingFormat__ and __SeparatorType__. The "caption" parameter is of type string and represents the text in the caption that will be inserted after the number (also known as caption text). The "includeLabel" parameter is of type Boolean and if *true* will include the label text to the caption. The "insertBelow" parameter is of type Boolean as well and if *true* will insert the caption below the table or figure. So, in order to insert a caption using this method you would do something like: -{{source=..\SamplesCS\RichTextEditor\Features\Caption.cs region=insert1}} -{{source=..\SamplesVB\RichTextEditor\Features\Caption.vb region=insert1}} + + -````C# -CaptionDefinition captionDefinition = new CaptionDefinition(); -captionDefinition.Label = "testLabel"; -captionDefinition.NumberingFormat = NumberingFormat.Arabic; -captionDefinition.SeparatorType = CaptionSeparatorType.Colon; -this.radRichTextEditor1.InsertCaption(captionDefinition, "captionText", true, true); -```` -````VB.NET -Dim captionDefinition As New CaptionDefinition() -captionDefinition.Label = "testLabel" -captionDefinition.NumberingFormat = NumberingFormat.Arabic -captionDefinition.SeparatorType = CaptionSeparatorType.Colon -Me.radRichTextEditor1.InsertCaption(captionDefinition, "captionText", True, True) - -```` - -{{endregion}} The __RadDocument__ contains the two default __CaptionDefinitions__ by default. They reside in a collection called "CaptionDefinitions" which is of type Dictionary. If you want to insert a caption of a default type, you can do as follow: -{{source=..\SamplesCS\RichTextEditor\Features\Caption.cs region=insert2}} -{{source=..\SamplesVB\RichTextEditor\Features\Caption.vb region=insert2}} - -````C# -this.radRichTextEditor1.InsertCaption(this.radRichTextEditor1.Document.CaptionDefinitions["Table"], "captionText", true, true); - -```` -````VB.NET -Me.radRichTextEditor1.InsertCaption(Me.radRichTextEditor1.Document.CaptionDefinitions("Table"), "captionText", True, True) + + -```` -{{endregion}} This code will insert a default caption with label __Table__. diff --git a/controls/richtexteditor/features/references/cross-reference.md b/controls/richtexteditor/features/references/cross-reference.md index a6f7f486c..3f85398aa 100644 --- a/controls/richtexteditor/features/references/cross-reference.md +++ b/controls/richtexteditor/features/references/cross-reference.md @@ -99,19 +99,10 @@ All types of __Cross-References__ can be inserted using methods of __RadRichText Every bookmark has a unique name. So in order to insert a reference to a bookmark, you need its name. __RadRichTextEditor__ has the following method: -{{source=..\SamplesCS\RichTextEditor\Features\CrossReference.cs region=bookmark}} -{{source=..\SamplesVB\RichTextEditor\Features\CrossReference.vb region=bookmark}} + + -````C# -radRichTextEditor1.InsertCrossReferenceToBookmark("Bookmark Name", ReferenceContentType.EntireContent, false); -```` -````VB.NET -radRichTextEditor1.InsertCrossReferenceToBookmark("Bookmark Name", ReferenceContentType.EntireContent, False) - -```` - -{{endregion}} __ReferenceContentType__ is an enumeration that has five values – __EntireContent__, __OnlyLabelAndNumber__, __OnlyCaption__, __PageNumber__ and __RelativePosition__. As you can see, those values are the same as in the "Insert reference to:" combo box. The parameter "InsertAsHyperlink" is pretty self-explanatory and also can be read about [in this section](#insert-cross-reference). @@ -119,19 +110,10 @@ __ReferenceContentType__ is an enumeration that has five values – __EntireCont You have to pass the paragraph (with heading style applied, of course) that you want to create a Reference to. The method signature is as follows: -{{source=..\SamplesCS\RichTextEditor\Features\CrossReference.cs region=heading}} -{{source=..\SamplesVB\RichTextEditor\Features\CrossReference.vb region=heading}} - -````C# -radRichTextEditor1.InsertCrossReferenceToHeading(headingParagraph, ReferenceContentType.OnlyCaption, true); + + -```` -````VB.NET -radRichTextEditor1.InsertCrossReferenceToHeading(headingParagraph, ReferenceContentType.OnlyCaption, True) -```` - -{{endregion}} The parameters are almost the same, except the first one. It represents the paragraph you want to reference. The other two have the same purpose. @@ -139,19 +121,10 @@ The parameters are almost the same, except the first one. It represents the para The method signature is: -{{source=..\SamplesCS\RichTextEditor\Features\CrossReference.cs region=caption}} -{{source=..\SamplesVB\RichTextEditor\Features\CrossReference.vb region=caption}} - -````C# -radRichTextEditor1.InsertCrossReferenceToCaption(captionParagraph, ReferenceContentType.OnlyLabelAndNumber,false); - -```` -````VB.NET -radRichTextEditor1.InsertCrossReferenceToCaption(captionParagraph, ReferenceContentType.OnlyLabelAndNumber, False) + + -```` -{{endregion}} The first parameter represents the paragraph (__Caption__) you want to refer. diff --git a/controls/richtexteditor/features/references/footnotes-and-endnotes.md b/controls/richtexteditor/features/references/footnotes-and-endnotes.md index 4406204b0..961f3b83c 100644 --- a/controls/richtexteditor/features/references/footnotes-and-endnotes.md +++ b/controls/richtexteditor/features/references/footnotes-and-endnotes.md @@ -1,180 +1,104 @@ ---- -title: Footnotes and Endnotes -page_title: Footnotes and Endnotes - WinForms RichTextEditor Control -description: Footnotes and endnotes (or just notes) in WinForms RichTextEditor are used in documents and books to show the source of borrowed material or to enter explanatory or supplementary information. -slug: winforms/richtexteditor-/features/references/footnotes-and-endnotes -tags: footnotes,and,endnotes -published: True -position: 0 -previous_url: richtexteditor-features-references-footnotes-and-endnotes ---- - -# Footnotes and Endnotes - -Footnotes and endnotes (or just notes) are used in documents and books to show the source of borrowed material or to enter explanatory or supplementary information. Footnotes are positioned at the bottom of a page, containing the annotated text, and endnotes are placed at the end of a document or the section. - -This topic will explain: - -* [Note options](#note-options) - -* [Creating and Inserting](#creating-and-inserting) - -* [Navigating and Scrolling](#navigating-and-scrolling) - -## Note options - -There are various properties that control how notes are positioned and visualized in the document. All of these properties can be applied on the whole document and some of them (concerning the note numbering) can also be applied on sections individually. - -### Footnote options - -Here is the list of the available properties concerning footnotes: - -* __FootnotesNumberingFormat__ - Gets or sets the footnotes numbering format. - -* __FootnotesFirstNumber__ - Gets or sets the footnotes starting number. - -* __FootnotesNumberingRestartType__ - Represents the type of the footnotes numbering restart. The available types are : - - * __Continuous__ - numbering is never restarted. - - * __EachPage__ - numbering is restarted on each page. - - * __EachSection__ - numbering is restarted on each section. - -* __FootnotesPosition__ - __PageBottom__ is the only available option. - -### Endnote options - -Here is the list of the available properties concerning endnotes: - -* __EndnotesNumberingFormat__ - Gets or sets the endnotes numbering format. - -* __EndnotesFirstNumber__ - Gets or sets the endnotes starting number. - -* __EndnotesNumberingRestartType__ - Represents the type of the endnotes numbering restart. The available types are : - - * __Continuous__ - same numbering is used for all endnotes in the document. - - * __EachSection__ - numbering is restarted on each section. - -* __EndnotesPosition__ - Available options are: - - * __DocumentEnd__ - all endnotes are shown at the end of the document. - - * __SectionEnd__ - there is a list of endnotes for each section. - -## Creating and Inserting - -Footnotes and endnotes all contain the __Note__ class which defines the note body and whether a special symbol should be used when visualizing the note in the document. Notes can be inserted in __RadRichTextEditor__ using the following methods: - -{{source=..\SamplesCS\RichTextEditor\Features\FootnotesAndEndnotes.cs region=insert}} -{{source=..\SamplesVB\RichTextEditor\Features\FootnotesAndEndnotes.vb region=insert}} - -````C# -radRichTextEditor1.InsertFootnote(); -radRichTextEditor1.InsertFootnote(new Note()); -radRichTextEditor1.InsertEndnote(); -radRichTextEditor1.InsertEndnote(new Note()); - -```` -````VB.NET -radRichTextEditor1.InsertFootnote() -radRichTextEditor1.InsertFootnote(New Note()) -radRichTextEditor1.InsertEndnote() -radRichTextEditor1.InsertEndnote(New Note()) - -```` - -{{endregion}} - -There is a set of document styles that are used inside notes content. It is recommended that when a note is created by code, these styles are used in the note body, so the document styling is persistent. There are some static helper methods that make the task of creating notes, that have the necessary styles applied, easier: - -{{source=..\SamplesCS\RichTextEditor\Features\FootnotesAndEndnotes.cs region=static}} -{{source=..\SamplesVB\RichTextEditor\Features\FootnotesAndEndnotes.vb region=static}} - -````C# -Note note = Note.CreateCustomMarkFootnote("symbol"); -note = Note.CreateCustomMarkEndnote("symbol", new FontFamily("Arial")); -note = Note.CreateDefaultFootnote(); -note = Note.CreateDefaultEndnote(); - -```` -````VB.NET -Dim note As Note = note.CreateCustomMarkFootnote("symbol") -note = note.CreateCustomMarkEndnote("symbol", New FontFamily("Arial")) -note = note.CreateDefaultFootnote() -note = note.CreateDefaultEndnote() - -```` - -{{endregion}} - -Here is for example how to insert a footnote with a custom mark – dollar sign with *Calibri* font: - -{{source=..\SamplesCS\RichTextEditor\Features\FootnotesAndEndnotes.cs region=add}} -{{source=..\SamplesVB\RichTextEditor\Features\FootnotesAndEndnotes.vb region=add}} - -````C# -Note note1 = Note.CreateCustomMarkFootnote("$", new FontFamily("Calibri")); -this.radRichTextEditor1.InsertFootnote(note1); - -```` -````VB.NET -Dim note1 As Note = note.CreateCustomMarkFootnote("$", New FontFamily("Calibri")) -Me.radRichTextEditor1.InsertFootnote(note1) - -```` - -{{endregion}} - -## Navigating and Scrolling - -You can programmatically navigate the document caret position through the notes in the document using the following methods of the __RadRichTextEditor__: - -{{source=..\SamplesCS\RichTextEditor\Features\FootnotesAndEndnotes.cs region=move}} -{{source=..\SamplesVB\RichTextEditor\Features\FootnotesAndEndnotes.vb region=move}} - -````C# - -radRichTextEditor1.GoToNextFootnote(); -radRichTextEditor1.GoToPreviousFootnote(); -radRichTextEditor1.GoToNextEndnote(); -radRichTextEditor1.GoToPreviousEndnote(); - -```` -````VB.NET -radRichTextEditor1.GoToNextFootnote() -radRichTextEditor1.GoToPreviousFootnote() -radRichTextEditor1.GoToNextEndnote() -radRichTextEditor1.GoToPreviousEndnote() - -```` - -{{endregion}} - -You can use the __ScrollToNote()__ method to scroll the viewport so that a note content is visible. A reference to the note object can be obtained through the __FootnoteRangeStart__ and __EndnoteRangeStart__ annotations. These annotations are contained inside the document and mark the beginning of the note symbol that acts like a reference to the note. Here is an example of how to scroll to the content of the first endnote in the document: - -{{source=..\SamplesCS\RichTextEditor\Features\FootnotesAndEndnotes.cs region=range}} -{{source=..\SamplesVB\RichTextEditor\Features\FootnotesAndEndnotes.vb region=range}} - -````C# -EndnoteRangeStart noteRangeStart = this.radRichTextEditor1.Document.EnumerateChildrenOfType().FirstOrDefault(); - -if (noteRangeStart != null) -{ - this.radRichTextEditor1.ScrollToNote(noteRangeStart.Note); -} - -```` -````VB.NET -Dim noteRangeStart As EndnoteRangeStart = Me.radRichTextEditor1.Document.EnumerateChildrenOfType(Of EndnoteRangeStart)().FirstOrDefault() -If noteRangeStart IsNot Nothing Then - Me.radRichTextEditor1.ScrollToNote(noteRangeStart.Note) -End If - -```` - -{{endregion}} - - - +--- +title: Footnotes and Endnotes +page_title: Footnotes and Endnotes - WinForms RichTextEditor Control +description: Footnotes and endnotes (or just notes) in WinForms RichTextEditor are used in documents and books to show the source of borrowed material or to enter explanatory or supplementary information. +slug: winforms/richtexteditor-/features/references/footnotes-and-endnotes +tags: footnotes,and,endnotes +published: True +position: 0 +previous_url: richtexteditor-features-references-footnotes-and-endnotes +--- + +# Footnotes and Endnotes + +Footnotes and endnotes (or just notes) are used in documents and books to show the source of borrowed material or to enter explanatory or supplementary information. Footnotes are positioned at the bottom of a page, containing the annotated text, and endnotes are placed at the end of a document or the section. + +This topic will explain: + +* [Note options](#note-options) + +* [Creating and Inserting](#creating-and-inserting) + +* [Navigating and Scrolling](#navigating-and-scrolling) + +## Note options + +There are various properties that control how notes are positioned and visualized in the document. All of these properties can be applied on the whole document and some of them (concerning the note numbering) can also be applied on sections individually. + +### Footnote options + +Here is the list of the available properties concerning footnotes: + +* __FootnotesNumberingFormat__ - Gets or sets the footnotes numbering format. + +* __FootnotesFirstNumber__ - Gets or sets the footnotes starting number. + +* __FootnotesNumberingRestartType__ - Represents the type of the footnotes numbering restart. The available types are : + + * __Continuous__ - numbering is never restarted. + + * __EachPage__ - numbering is restarted on each page. + + * __EachSection__ - numbering is restarted on each section. + +* __FootnotesPosition__ - __PageBottom__ is the only available option. + +### Endnote options + +Here is the list of the available properties concerning endnotes: + +* __EndnotesNumberingFormat__ - Gets or sets the endnotes numbering format. + +* __EndnotesFirstNumber__ - Gets or sets the endnotes starting number. + +* __EndnotesNumberingRestartType__ - Represents the type of the endnotes numbering restart. The available types are : + + * __Continuous__ - same numbering is used for all endnotes in the document. + + * __EachSection__ - numbering is restarted on each section. + +* __EndnotesPosition__ - Available options are: + + * __DocumentEnd__ - all endnotes are shown at the end of the document. + + * __SectionEnd__ - there is a list of endnotes for each section. + +## Creating and Inserting + +Footnotes and endnotes all contain the __Note__ class which defines the note body and whether a special symbol should be used when visualizing the note in the document. Notes can be inserted in __RadRichTextEditor__ using the following methods: + + + + + + +There is a set of document styles that are used inside notes content. It is recommended that when a note is created by code, these styles are used in the note body, so the document styling is persistent. There are some static helper methods that make the task of creating notes, that have the necessary styles applied, easier: + + + + + + +Here is for example how to insert a footnote with a custom mark – dollar sign with *Calibri* font: + + + + + + +## Navigating and Scrolling + +You can programmatically navigate the document caret position through the notes in the document using the following methods of the __RadRichTextEditor__: + + + + + + +You can use the __ScrollToNote()__ method to scroll the viewport so that a note content is visible. A reference to the note object can be obtained through the __FootnoteRangeStart__ and __EndnoteRangeStart__ annotations. These annotations are contained inside the document and mark the beginning of the note symbol that acts like a reference to the note. Here is an example of how to scroll to the content of the first endnote in the document: + + + + + + diff --git a/controls/richtexteditor/features/repeat-table-header-row.md b/controls/richtexteditor/features/repeat-table-header-row.md index 30be439a1..cf84dceec 100644 --- a/controls/richtexteditor/features/repeat-table-header-row.md +++ b/controls/richtexteditor/features/repeat-table-header-row.md @@ -43,39 +43,19 @@ The __[TableRow class](https://docs.telerik.com/devtools/winforms/api/telerik.wi #### Set a Repeat Table Header Row using the RepeatOnEveryPage property. -{{source=..\SamplesCS\RichTextEditor\Features\RepeatTableHeaderRowCode.cs region=CreateNewRow}} -{{source=..\SamplesVB\RichTextEditor\Features\RepeatTableHeaderRowCode.vb region=CreateNewRow}} -````C# -var row = new Telerik.WinForms.Documents.Model.TableRow(); -row.RepeatOnEveryPage = true; + + -```` -````VB.NET -Dim row = New Telerik.WinForms.Documents.Model.TableRow() -row.RepeatOnEveryPage = True -```` - -{{endregion}} Another option is to use the __ChangeTableRowRepeatOnEveryPage__ method of __RadRichTextBox__, which allows you to change whether a row will be repeated or not. The below code snippet demonstrates how to get the first __TableRow__ in a __[RadDocument]({%slug winforms/richtexteditor-/document-elements/raddocument%})__ and set it as a repeated header row. #### Set a Repeat Table Header Row using the ChangeTableRowRepeatOnEveryPage method. -{{source=..\SamplesCS\RichTextEditor\Features\RepeatTableHeaderRowCode.cs region=RepeatRowApi}} -{{source=..\SamplesVB\RichTextEditor\Features\RepeatTableHeaderRowCode.vb region=RepeatRowApi}} -````C# -var firstRow = this.radRichTextEditor1.Document.EnumerateChildrenOfType().First(); -this.radRichTextEditor1.RichTextBoxElement.ChangeTableRowRepeatOnEveryPage(firstRow); - -```` -````VB.NET -Dim firstRow = Me.radRichTextEditor1.Document.EnumerateChildrenOfType(Of Telerik.WinForms.Documents.Model.TableRow)().First() -Me.radRichTextEditor1.RichTextBoxElement.ChangeTableRowRepeatOnEveryPage(firstRow) + + -```` -{{endregion}} ### Via the Built-in UI diff --git a/controls/richtexteditor/features/search.md b/controls/richtexteditor/features/search.md index b09dd9037..7be6acf9e 100644 --- a/controls/richtexteditor/features/search.md +++ b/controls/richtexteditor/features/search.md @@ -18,147 +18,43 @@ __RadRichTextEditor__ supports searching the contents of the document along with The simplest scenario – finding a string in the content of the document can be implemented with the following code: -{{source=..\SamplesCS\RichTextEditor\Features\Search.cs region=search}} -{{source=..\SamplesVB\RichTextEditor\Features\Search.vb region=search}} + + + -````C# - -private void SelectAllMatches(string toSearch) -{ - this.radRichTextEditor1.Document.Selection.Clear(); // this clears the selection before processing - Telerik.WinForms.Documents.TextSearch.DocumentTextSearch search = new Telerik.WinForms.Documents.TextSearch.DocumentTextSearch(this.radRichTextEditor1.Document); - foreach (var textRange in search.FindAll(toSearch)) - { - this.radRichTextEditor1.Document.Selection.AddSelectionStart(textRange.StartPosition); - this.radRichTextEditor1.Document.Selection.AddSelectionEnd(textRange.EndPosition); - } -} - -```` -````VB.NET -Private Sub SelectAllMatches(ByVal toSearch As String) - Me.radRichTextEditor1.Document.Selection.Clear() ' this clears the selection before processing - Dim search As New Telerik.WinForms.Documents.TextSearch.DocumentTextSearch(Me.radRichTextEditor1.Document) - For Each textRange In search.FindAll(toSearch) - Me.radRichTextEditor1.Document.Selection.AddSelectionStart(textRange.StartPosition) - Me.radRichTextEditor1.Document.Selection.AddSelectionEnd(textRange.EndPosition) - Next textRange -End Sub - -```` - -{{endregion}} Note that the __FindAll()__ method of the DocumentTextSearch class takes a string as an argument, but regards it as a regular expression. For example, searching __“[a-z]*control[a-z]*”__ will find all words that contain the word "control" as a substring. Thus, if you have the word "Telerik UI" in the document, executing the __SelectAllMatches("control")__ will result in only these six letters being selected, as opposed to the whole word "Telerik UI" being selected when __SelectAllMatches("[a-z]*control[a-z]*")__. You can use all kinds of regular expressions, such as __"(asp|silverlight)\s*control(s)?"__ (which would match both "ASP Controls" and "SilverlightControl"), __[a-z]*(.)\1[a-z]*__ (which finds all words that have a doubled letter), and basically everything else you can come up with. Make sure to use correct expressions if you want to utilize this functionality, or escape the string in case you want a simple search for a word that can contain special symbols like "?", "+", "{" etc. This can be automatically done by invoking the following code before proceeding with the search. -{{source=..\SamplesCS\RichTextEditor\Features\Search.cs region=regex}} -{{source=..\SamplesVB\RichTextEditor\Features\Search.vb region=regex}} - -````C# -string toSearch = ""; -toSearch = Regex.Escape(toSearch); + + -```` -````VB.NET -Dim toSearch As String = "" -toSearch = Regex.Escape(toSearch) -```` - -{{endregion}} Selecting the results of the search is particularly useful, as most formatting commands that are executed on __RadRichTextEditor__ (or its document) are selection-based, i.e. they operate on the currently selected parts of the document. You can use that fact by invoking one of these commands after having selected the words in the document. Here is an example. -{{source=..\SamplesCS\RichTextEditor\Features\Search.cs region=style}} -{{source=..\SamplesVB\RichTextEditor\Features\Search.vb region=style}} - -````C# - -this.radRichTextEditor1.ChangeTextHighlightColor(Telerik.WinControls.RichTextEditor.UI.Colors.LightGray); // will highlight all selected words in LightGray -this.radRichTextEditor1.ChangeFontSize(Unit.PointToDip(32)); // will increase the font size of the words to 30 DIP -this.radRichTextEditor1.ChangeFontFamily(new Telerik.WinControls.RichTextEditor.UI.FontFamily("Comic Sans MS")); // will change the font family of the spans, containing these words. - -```` -````VB.NET -Me.radRichTextEditor1.ChangeTextHighlightColor(Telerik.WinControls.RichTextEditor.UI.Colors.LightGray) ' will highlight all selected words in LightGray -Me.radRichTextEditor1.ChangeFontSize(Telerik.WinForms.Documents.Model.Unit.PointToDip(32)) ' will increase the font size of the words to 30 DIP -Me.radRichTextEditor1.ChangeFontFamily(New Telerik.WinControls.RichTextEditor.UI.FontFamily("Comic Sans MS")) ' will change the font family of the spans, containing these words. + + -```` -{{endregion}} Most of the time, you would like to remove the selection at the end of the operations, which is done by calling the __Clear()__ method of the __DocumentSelection__ object. -{{source=..\SamplesCS\RichTextEditor\Features\Search.cs region=clear}} -{{source=..\SamplesVB\RichTextEditor\Features\Search.vb region=clear}} + + -````C# - -this.radRichTextEditor1.Document.Selection.Clear(); - -```` -````VB.NET -Me.radRichTextEditor1.Document.Selection.Clear() - -```` -{{endregion}} >caution You should have in mind that performing these actions in __DocumentContentChanged__ event handler will not only raise performance issues, but will also produce an infinite loop, as the changes of the formatting are also considered document changes. > On a side note, the find and select functionality can be extended in order to implement a replace of all occurrences matching the searched string with another string. Here is a sample code: -{{source=..\SamplesCS\RichTextEditor\Features\Search.cs region=allmatches}} -{{source=..\SamplesVB\RichTextEditor\Features\Search.vb region=allmatches}} + + + -````C# - -private void ReplaceAllMatches(string toSearch, string toReplaceWith) -{ - this.radRichTextEditor1.Document.Selection.Clear(); // this clears the selection before processing - Telerik.WinForms.Documents.TextSearch.DocumentTextSearch search = new Telerik.WinForms.Documents.TextSearch.DocumentTextSearch(this.radRichTextEditor1.Document); - List rangesTrackingDocumentChanges = new List(); - foreach (var textRange in search.FindAll(toSearch)) - { - Telerik.WinForms.Documents.TextSearch.TextRange newRange = new Telerik.WinForms.Documents.TextSearch.TextRange(new Telerik.WinForms.Documents.DocumentPosition(textRange.StartPosition, true), new Telerik.WinForms.Documents.DocumentPosition(textRange.EndPosition, true)); - rangesTrackingDocumentChanges.Add(newRange); - } - foreach (var textRange in rangesTrackingDocumentChanges) - { - this.radRichTextEditor1.Document.Selection.AddSelectionStart(textRange.StartPosition); - this.radRichTextEditor1.Document.Selection.AddSelectionEnd(textRange.EndPosition); - this.radRichTextEditor1.Insert(toReplaceWith); - textRange.StartPosition.Dispose(); - textRange.EndPosition.Dispose(); - } -} - -```` -````VB.NET -Private Sub ReplaceAllMatches(ByVal toSearch As String, ByVal toReplaceWith As String) - Me.radRichTextEditor1.Document.Selection.Clear() ' this clears the selection before processing - Dim search As New Telerik.WinForms.Documents.TextSearch.DocumentTextSearch(Me.radRichTextEditor1.Document) - Dim rangesTrackingDocumentChanges As New List(Of Telerik.WinForms.Documents.TextSearch.TextRange)() - For Each textRange In search.FindAll(toSearch) - Dim newRange As New Telerik.WinForms.Documents.TextSearch.TextRange(New Telerik.WinForms.Documents.DocumentPosition(textRange.StartPosition, True), New Telerik.WinForms.Documents.DocumentPosition(textRange.EndPosition, True)) - rangesTrackingDocumentChanges.Add(newRange) - Next textRange - For Each textRange In rangesTrackingDocumentChanges - Me.radRichTextEditor1.Document.Selection.AddSelectionStart(textRange.StartPosition) - Me.radRichTextEditor1.Document.Selection.AddSelectionEnd(textRange.EndPosition) - Me.radRichTextEditor1.Insert(toReplaceWith) - textRange.StartPosition.Dispose() - textRange.EndPosition.Dispose() - Next textRange -End Sub - -```` - -{{endregion}} There is a need to create new __TextRanges__ with document positions that track the changes to the document, because the deletion and insertion affects the document positions. The document positions created using the 2-parameter constructor with the second parameter set to "*true*" keep their relative position as the document changes. They, however, have to be manually disposed of, as they subscribe to events in order to track the changes to the document and must detach their handlers at the end of their use. This is done using the __Dispose__ method. If you skip that step, there will be memory leaks in your application. diff --git a/controls/richtexteditor/features/section-columns.md b/controls/richtexteditor/features/section-columns.md index bc3890edc..20194f7cb 100644 --- a/controls/richtexteditor/features/section-columns.md +++ b/controls/richtexteditor/features/section-columns.md @@ -52,19 +52,10 @@ The **SectionColumnCollection** class contains the information about the text co #### Example 1: Create SectionColumnCollection -{{source=..\SamplesCS\RichTextEditor\Features\SectionColumnCode.cs region=NewCollection}} -{{source=..\SamplesVB\RichTextEditor\Features\SectionColumnCode.vb region=NewCollection}} + + -````C# -SectionColumnCollection sectionColumnCollection = new SectionColumnCollection(2, 75, true); -```` -````VB.NET -Dim sectionColumnCollection As New SectionColumnCollection(2, 75, True) - -```` - -{{endregion}} __Figure 2__ demonstrates the result of __Example 1__. @@ -82,19 +73,10 @@ To create text columns with equal width, you could directly use the **SectionCol #### Example 2: Apply columns with equal width -{{source=..\SamplesCS\RichTextEditor\Features\SectionColumnCode.cs region=AssignCollection}} -{{source=..\SamplesVB\RichTextEditor\Features\SectionColumnCode.vb region=AssignCollection}} + + -````C# -section.Columns = sectionColumnCollection; -```` -````VB.NET -section.Columns = sectionColumnCollection - -```` - -{{endregion}} ### Apply Columns With Different Width @@ -102,31 +84,10 @@ The API allows you create the columns severally from each other with the **Secti #### Example 3: Apply columns with different width -{{source=..\SamplesCS\RichTextEditor\Features\SectionColumnCode.cs region=DifferentWidth}} -{{source=..\SamplesVB\RichTextEditor\Features\SectionColumnCode.vb region=DifferentWidth}} -````C# -IEnumerable columns = new List() -{ - new SectionColumn(100, 5), - new SectionColumn(200, 10), - new SectionColumn(300, 15) -}; -SectionColumnCollection sectionColumnCollection1 = new SectionColumnCollection(columns); -section.Columns = sectionColumnCollection1; - -```` -````VB.NET -Dim columns As IEnumerable(Of SectionColumn) = New List(Of SectionColumn)() From { - New SectionColumn(100, 5), - New SectionColumn(200, 10), - New SectionColumn(300, 15) -} -Dim sectionColumnCollection1 As New SectionColumnCollection(columns) -section.Columns = sectionColumnCollection1 - -```` - -{{endregion}} + + + + ### Apply Columns With RadDocumentEditor @@ -146,19 +107,10 @@ In addition to the so far discussed approaches, [RadDocumentEditor]({%slug winfo #### Example 4: Apply columns through editor -{{source=..\SamplesCS\RichTextEditor\Features\SectionColumnCode.cs region=Editor}} -{{source=..\SamplesVB\RichTextEditor\Features\SectionColumnCode.vb region=Editor}} - -````C# -editor.ChangeSectionColumns(SectionColumnsLayout.Left); + + -```` -````VB.NET -editor.ChangeSectionColumns(SectionColumnsLayout.Left) -```` - -{{endregion}} >caption __Figure 3: SectionColumnsLayout.Left applied on a section__ diff --git a/controls/richtexteditor/features/selection.md b/controls/richtexteditor/features/selection.md index 7813e5e1b..c18ab83f0 100644 --- a/controls/richtexteditor/features/selection.md +++ b/controls/richtexteditor/features/selection.md @@ -27,25 +27,11 @@ You can modify the appearance of the selection in the control through the **Sele #### Customize the appearance of the selection -{{source=..\SamplesCS\RichTextEditor\Features\Selection.cs region=Fill}} -{{source=..\SamplesVB\RichTextEditor\Features\Selection.vb region=Fill}} + + -````C# - -this.radRichTextEditor1.SelectionFill = Color.FromArgb(125, 255, 0, 0); -this.radRichTextEditor1.SelectionStroke = Color.DarkRed; -```` -````VB.NET - -Me.radRichTextEditor1.SelectionFill = Color.FromArgb(125, 255, 0, 0) -Me.radRichTextEditor1.SelectionStroke = Color.DarkRed - -```` - -{{endregion}} - ![WinForms RadRichTextEditor Text Selection](images/richtexteditor-features-selection002.png) ## Programmatic Selection @@ -103,66 +89,20 @@ Here is an example of how to select the current word. #### Select current word -{{source=..\SamplesCS\RichTextEditor\Features\Selection.cs region=position}} -{{source=..\SamplesVB\RichTextEditor\Features\Selection.vb region=position}} - -````C# - -DocumentPosition startPosition = this.radRichTextEditor1.Document.CaretPosition; //new DocumentPosition( this.radRichTextBox.Document ); -DocumentPosition endPosition = new DocumentPosition(startPosition); -startPosition.MoveToCurrentWordStart(); -endPosition.MoveToCurrentWordEnd(); -this.radRichTextEditor1.Document.Selection.AddSelectionStart(startPosition); -this.radRichTextEditor1.Document.Selection.AddSelectionEnd(endPosition); + + -```` -````VB.NET -Dim _startPosition As DocumentPosition = Me.radRichTextEditor1.Document.CaretPosition 'new DocumentPosition( this.radRichTextBox.Document ); -Dim endPosition As New DocumentPosition(_startPosition) -_startPosition.MoveToCurrentWordStart() -endPosition.MoveToCurrentWordEnd() -Me.radRichTextEditor1.Document.Selection.AddSelectionStart(_startPosition) -Me.radRichTextEditor1.Document.Selection.AddSelectionEnd(endPosition) -```` - -{{endregion}} The next snippet demonstrates how you can check the content that is selected and select and delete the current paragraph if the text in the selection contains the word "Test". #### Select current paragraph and delete it -{{source=..\SamplesCS\RichTextEditor\Features\Selection.cs region=DeleteSelection}} -{{source=..\SamplesVB\RichTextEditor\Features\Selection.vb region=DeleteSelection}} - -````C# - if (selectedText.Contains("Test")) - { - this.radRichTextEditor1.Document.Selection.Clear(); - Paragraph currentParagraph = this.radRichTextEditor1.Document.CaretPosition.GetCurrentParagraph(); - - this.radRichTextEditor1.Document.Selection.AddDocumentElementToSelection(currentParagraph); - this.radRichTextEditor1.Delete(true); - } - -```` -````VB.NET - -Dim selectedText As String = Me.radRichTextBox.Document.Selection.GetSelectedText() - -If (selectedText.Contains("Test")) Then - - Me.radRichTextBox.Document.Selection.Clear() - Dim currentParagraph As Paragraph = Me.radRichTextBox.Document.CaretPosition.GetCurrentParagraph() - - Me.radRichTextBox.Document.Selection.AddDocumentElementToSelection(currentParagraph) - Me.radRichTextBox.Delete(True) -End If + + -```` -{{endregion}} ### What is Selection Range? @@ -183,28 +123,10 @@ The selection in **RadRichTextEditor** consists of selection ranges. These range #### Check the type of the elements inside the selection -{{source=..\SamplesCS\RichTextEditor\Features\Selection.cs region=ElementType}} -{{source=..\SamplesVB\RichTextEditor\Features\Selection.vb region=ElementType}} + + -````C# - - SelectionRange selectionRange = this.radRichTextEditor1.Document.Selection.Ranges.First(); - if (selectionRange.RangeType == SelectionRangeType.Table) - { - //SetTableProperties(); - } -```` -````VB.NET - - Dim selectionRange As Telerik.WinForms.Documents.Selection.SelectionRange = Me.radRichTextEditor1.Document.Selection.Ranges.First() - If selectionRange.RangeType = SelectionRangeType.Table Then - 'SetTableProperties() - End If - -```` - -{{endregion}} ## Multi-Range Selection @@ -214,43 +136,10 @@ Here is an example of selecting each "*RadRichTextEditor*" word in the text. Thi #### Select all occurrences of the "RadRichTextBox" word -{{source=..\SamplesCS\RichTextEditor\Features\Selection.cs region=multiselect}} -{{source=..\SamplesVB\RichTextEditor\Features\Selection.vb region=multiselect}} - -````C# - -DocumentPosition position = new DocumentPosition(this.radRichTextEditor1.Document); -do -{ - //GetCurrentSpan().Text returns the word at the position - string word = position.GetCurrentSpanBox().Text; - if (word.Contains("RadRichTextBox")) - { - DocumentPosition wordEndPosition = new DocumentPosition(position); - wordEndPosition.MoveToCurrentWordEnd(); - this.radRichTextEditor1.Document.Selection.AddSelectionStart(position); - this.radRichTextEditor1.Document.Selection.AddSelectionEnd(wordEndPosition); - } -} -while (position.MoveToNextWordStart()); - -```` -````VB.NET -Dim position As New DocumentPosition(Me.radRichTextEditor1.Document) -Do - 'GetCurrentSpan().Text returns the word at the position - Dim word As String = position.GetCurrentSpanBox().Text - If word.Contains("RadRichTextEditor") Then - Dim wordEndPosition As New DocumentPosition(position) - wordEndPosition.MoveToCurrentWordEnd() - Me.radRichTextEditor1.Document.Selection.AddSelectionStart(position) - Me.radRichTextEditor1.Document.Selection.AddSelectionEnd(wordEndPosition) - End If -Loop While position.MoveToNextWordStart() - -```` - -{{endregion}} + + + + ![WinForms RadRichTextEditor Multi-Range Selection](images/richtexteditor-features-selection001.png) @@ -264,115 +153,17 @@ The following example shows how to implement a custom selection behavior which s #### Creating a Custom MouseSelectionHandler -{{source=..\SamplesCS\RichTextEditor\Features\Selection.cs region=CustomMouseSelectionHandler}} -{{source=..\SamplesVB\RichTextEditor\Features\Selection.vb region=CustomMouseSelectionHandler}} - -````C# - -public class CustomMouseSelectionHandler : MouseSelectionHandler -{ - RadDocument currentDocument; - public CustomMouseSelectionHandler(RadDocument document, DocumentPresenterBase presenter) - : base(document, presenter) - { - currentDocument = document; - } - - protected override void RegisterDocumentSingleMouseDown(bool ctrlPressed, bool shiftPressed, Telerik.WinControls.RichTextEditor.UI.Point position, UIElement originalSource) - { - base.RegisterDocumentSingleMouseDown(ctrlPressed, shiftPressed, position, originalSource); - } - - public override void RegisterDocumentMouseUp(SourceType source = SourceType.Mouse, Telerik.WinControls.RichTextEditor.UI.Point? position = null) - { - base.RegisterDocumentMouseUp(source, position); - SelectEmptyAnnotation(); - } - - public void SelectEmptyAnnotation() - { - var position = currentDocument.CaretPosition; - var span = position.GetCurrentInline() as Span; - - if (span != null && span.Text.Contains(" ")) - { - var start = new DocumentPosition(currentDocument); - var end = new DocumentPosition(currentDocument); - - start.MoveToDocumentElementStart(span); - end.MoveToDocumentElementEnd(span); - end.MoveToNext(); - - this.currentDocument.Selection.SetSelectionStart(start); - this.currentDocument.Selection.AddSelectionEnd(end); - } - } -} - -```` -````VB.NET -Public Class CustomMouseSelectionHandler - Inherits MouseSelectionHandler - - Private currentDocument As RadDocument - Public Sub New(ByVal document As RadDocument, ByVal presenter As DocumentPresenterBase) - MyBase.New(document, presenter) - currentDocument = document - End Sub - Protected Overrides Sub RegisterDocumentSingleMouseDown(ByVal ctrlPressed As Boolean, ByVal shiftPressed As Boolean, ByVal position As Telerik.WinControls.RichTextEditor.UI.Point, ByVal originalSource As UIElement) - MyBase.RegisterDocumentSingleMouseDown(ctrlPressed, shiftPressed, position, originalSource) - End Sub - Public Overrides Sub RegisterDocumentMouseUp(ByVal Optional source As SourceType = SourceType.Mouse, ByVal Optional position As Telerik.WinControls.RichTextEditor.UI.Point? = Nothing) - MyBase.RegisterDocumentMouseUp(source, position) - SelectEmptyAnnotation() - End Sub - Public Sub SelectEmptyAnnotation() - Dim position = currentDocument.CaretPosition - Dim span = TryCast(position.GetCurrentInline(), Span) - - If span IsNot Nothing AndAlso span.Text.Contains(" ") Then - Dim start = New DocumentPosition(currentDocument) - Dim [end] = New DocumentPosition(currentDocument) - start.MoveToDocumentElementStart(span) - [end].MoveToDocumentElementEnd(span) - [end].MoveToNext() - Me.currentDocument.Selection.SetSelectionStart(start) - Me.currentDocument.Selection.AddSelectionEnd([end]) - End If - End Sub -End Class - -```` - -{{endregion}} + + + + #### Assign the custom MouseSelectionHandler to the ActiveEditorPresenter -{{source=..\SamplesCS\RichTextEditor\Features\Selection.cs region=AssignCustomMouseSelectionHandler}} -{{source=..\SamplesVB\RichTextEditor\Features\Selection.vb region=AssignCustomMouseSelectionHandler}} - -````C# -private void RadRichTextEditor1_DocumentChanged(object sender, EventArgs e) -{ - DocumentPresenterBase presenter = this.radRichTextEditor1.RichTextBoxElement.ActiveEditorPresenter as DocumentPresenterBase; - if (presenter != null) - { - presenter.MouseSelectionHandler = new CustomMouseSelectionHandler(this.radRichTextEditor1.Document, presenter); - } -} - -```` -````VB.NET -Private Sub RadRichTextEditor1_DocumentChanged(ByVal sender As Object, ByVal e As EventArgs) - Dim presenter As DocumentPresenterBase = TryCast(Me.radRichTextEditor1.RichTextBoxElement.ActiveEditorPresenter, DocumentPresenterBase - If presenter IsNot Nothing Then - presenter.MouseSelectionHandler = New CustomMouseSelectionHandler(Me.radRichTextEditor1.Document, presenter) - End If -End Sub - -```` - -{{endregion}} + + + + #### Custom Selection Behavior ![WinForms RadRichTextEditor custom MouseSelectionHandler](images/richtexteditor-features-selection003.png) diff --git a/controls/richtexteditor/features/spellcheck.md b/controls/richtexteditor/features/spellcheck.md index 486f92c92..a555af6f2 100644 --- a/controls/richtexteditor/features/spellcheck.md +++ b/controls/richtexteditor/features/spellcheck.md @@ -56,28 +56,10 @@ Here is an example of a __RadDictionary__ loaded from a TDF file. >note The given example doesn't contain the logic used to read the __TDF__ file as a __Stream__ . > -{{source=..\SamplesCS\RichTextEditor\Features\SpellCheck.cs region=load}} -{{source=..\SamplesVB\RichTextEditor\Features\SpellCheck.vb region=load}} + + -````C# -private void LoadDictionary(Stream tdfFileStream) -{ - RadDictionary dictionary = new RadDictionary(); - dictionary.Load(tdfFileStream); - ((DocumentSpellChecker)this.radRichTextEditor1.SpellChecker).AddDictionary(dictionary, CultureInfo.InvariantCulture); -} -```` -````VB.NET -Private Sub LoadDictionary(ByVal tdfFileStream As Stream) - Dim dictionary As New RadDictionary() - dictionary.Load(tdfFileStream) - CType(Me.radRichTextEditor1.SpellChecker, DocumentSpellChecker).AddDictionary(dictionary, CultureInfo.InvariantCulture) -End Sub - -```` - -{{endregion}} ## RadWordsDictionary @@ -85,58 +67,19 @@ __RadWordsDictionary__ implements the __IWordDictionary__ interface and is capab #### Load stream in RadWordsDictionary -{{source=..\SamplesCS\RichTextEditor\Features\SpellCheck.cs region=LoadWordDictionaryStream}} -{{source=..\SamplesVB\RichTextEditor\Features\SpellCheck.vb region=LoadWordDictionaryStream}} - -````C# -private void LoadWordDictionaryStream(Stream dictStrem) -{ - Telerik.WinControls.SpellChecker.Proofing.RadWordsDictionary dictionary = new Telerik.WinControls.SpellChecker.Proofing.RadWordsDictionary(); - dictionary.Load(dictStrem); -} - -```` -````VB.NET -Private Sub LoadWordDictionaryStream(dictStrem As Stream) - Dim dictionary As New Telerik.WinControls.SpellChecker.Proofing.RadWordsDictionary() - dictionary.Load(dictStrem) -End Sub + + -```` -{{endregion}} One of the constructor overloads of the **RadWordsDictionary** class enables you to pass a parameter of type __IEnumerable<string>__, which can help you create your own dictionary with a custom set of words. #### Create RadWordsDictionary from strings -{{source=..\SamplesCS\RichTextEditor\Features\SpellCheck.cs region=LoadWordDictionaryWords}} -{{source=..\SamplesVB\RichTextEditor\Features\SpellCheck.vb region=LoadWordDictionaryWords}} -````C# -private void LoadWordDictionaryStream() -{ - List words = new List(); - words.Add("Test"); - words.Add("Teacher"); - words.Add("Sister"); - Telerik.WinControls.SpellChecker.Proofing.RadWordsDictionary dictionary = new Telerik.WinControls.SpellChecker.Proofing.RadWordsDictionary(); - dictionary.Load(words); -} - -```` -````VB.NET -Private Sub LoadWordDictionaryStream() - Dim words As New List(Of String)() - words.Add("Test") - words.Add("Teacher") - words.Add("Sister") - Dim dictionary As New Telerik.WinControls.SpellChecker.Proofing.RadWordsDictionary() - dictionary.Load(words) -End Sub - -```` - -{{endregion}} + + + + ## Custom Dictionaries @@ -152,28 +95,10 @@ Here is an example of a such dictionary which adds the words in the "CustomDicti >note When adding a dictionary that implements the __ICustomWordDictionary__ interface object use __AddCustomDictionary(ICustomWordDictionary customDictionary, CultureInfo culture)__ method for the __DocumentSpellChecker__ class. You can also associate a custom dictionary to a specific culture. The method to remove it is __RemoveCustomDictionary(ICustomWordDictionary customDictionary, CultureInfo culture)__ . > -{{source=..\SamplesCS\RichTextEditor\Features\SpellCheck.cs region=custom}} -{{source=..\SamplesVB\RichTextEditor\Features\SpellCheck.vb region=custom}} - -````C# -private void CreateCustomDictionary() -{ - RadIsolatedStorageCustomDictionary dictionary = new RadIsolatedStorageCustomDictionary(IsolatedStorageScope.Site, "CustomDictionary.txt"); - DocumentSpellChecker spellchecker = new DocumentSpellChecker(dictionary); - this.radRichTextEditor1.SpellChecker = spellchecker; -} + + -```` -````VB.NET -Private Sub CreateCustomDictionary() - Dim dictionary As New RadIsolatedStorageCustomDictionary(IsolatedStorageScope.Site, "CustomDictionary.txt") - Dim spellchecker As New DocumentSpellChecker(dictionary) - Me.radRichTextEditor1.SpellChecker = spellchecker -End Sub -```` - -{{endregion}} If you want to have a temporary custom dictionary, that will only be available for a single application session, you can use the __RadNonPersistentCustomDictionary__ object. @@ -188,19 +113,9 @@ Using the __AddWord__ method of the dictionary itself will add the word only to Here is an example. -{{source=..\SamplesCS\RichTextEditor\Features\SpellCheck.cs region=addword}} -{{source=..\SamplesVB\RichTextEditor\Features\SpellCheck.vb region=addword}} - -````C# -this.radRichTextEditor1.SpellChecker.AddWord("RadRichTextEditor", CultureInfo.InvariantCulture); - -```` -````VB.NET -Me.radRichTextEditor1.SpellChecker.AddWord("RadRichTextEditor", CultureInfo.InvariantCulture) + + -```` - -{{endregion}} ## Internationalization @@ -212,28 +127,10 @@ Here is an example. >note The given example doesn't contain the logic used to read the __TDF__ file as a __Stream__ . > -{{source=..\SamplesCS\RichTextEditor\Features\SpellCheck.cs region=load}} -{{source=..\SamplesVB\RichTextEditor\Features\SpellCheck.vb region=load}} - -````C# -private void LoadDictionary(Stream tdfFileStream) -{ - RadDictionary dictionary = new RadDictionary(); - dictionary.Load(tdfFileStream); - ((DocumentSpellChecker)this.radRichTextEditor1.SpellChecker).AddDictionary(dictionary, CultureInfo.InvariantCulture); -} - -```` -````VB.NET -Private Sub LoadDictionary(ByVal tdfFileStream As Stream) - Dim dictionary As New RadDictionary() - dictionary.Load(tdfFileStream) - CType(Me.radRichTextEditor1.SpellChecker, DocumentSpellChecker).AddDictionary(dictionary, CultureInfo.InvariantCulture) -End Sub + + -```` -{{endregion}} ## See Also diff --git a/controls/richtexteditor/features/styles/list-styles.md b/controls/richtexteditor/features/styles/list-styles.md index fa4bd084c..c116a0fd4 100644 --- a/controls/richtexteditor/features/styles/list-styles.md +++ b/controls/richtexteditor/features/styles/list-styles.md @@ -50,43 +50,10 @@ The default list styles come handy, as they require little to no effort on your Here as an example of creating a __ListStyle__ and a __DocumentList__ programmatically: -{{source=..\SamplesCS\RichTextEditor\Features\ListStyles.cs region=listStyle}} -{{source=..\SamplesVB\RichTextEditor\Features\ListStyles.vb region=listStyle}} - -````C# -ListStyle upperRomanHierarchical = new ListStyle(); -upperRomanHierarchical.StyleLink = "Style1"; -for (int i = 0; i < ListStyle.ListLevels; ++i) -{ - StringBuilder levelText = new StringBuilder(); - for (int j = 0; j < i + 1; ++j) - { - levelText.Append("{" + j + "}."); - } - upperRomanHierarchical.Levels.Add(new ListLevelStyle() - { - StartingIndex = 1, - NumberingFormat = ListNumberingFormat.UpperRoman, - LevelText = levelText.ToString(), - Indent = 48 + i * 24 - }); -} - -```` -````VB.NET -Dim upperRomanHierarchical As New ListStyle() -upperRomanHierarchical.StyleLink = "Style1" -For i As Integer = 0 To ListStyle.ListLevels - 1 - Dim levelText As New StringBuilder() - For j As Integer = 0 To i - levelText.Append("{" & j & "}.") - Next j - upperRomanHierarchical.Levels.Add(New ListLevelStyle() With {.StartingIndex = 1, .NumberingFormat = ListNumberingFormat.UpperRoman, .LevelText = levelText.ToString(), .Indent = 48 + i * 24}) -Next i - -```` - -{{endregion}} + + + + >caution Don't forget to specify the __StyleLink__ property. It is the name of the list and it is mandatory for a ListStyle. > @@ -97,54 +64,24 @@ After creating a __ListStyle__ you need to add it to the document. Besides using If you want to apply a style to a paragraph using the user interface you would move the caret to the paragraph and click the appropriate **ListStyle** in the gallery. In code behind things are similar. First you need a reference to the paragraph you want to be added to a list. Let's say you need the current paragraph (in which the caret position resides). The code is as follows: -{{source=..\SamplesCS\RichTextEditor\Features\ListStyles.cs region=paragraph}} -{{source=..\SamplesVB\RichTextEditor\Features\ListStyles.vb region=paragraph}} - -````C# -Paragraph paragraph = this.radRichTextEditor1.Document.CaretPosition.GetCurrentParagraphBox().AssociatedParagraph; + + -```` -````VB.NET -Dim paragraph As Paragraph = Me.radRichTextEditor1.Document.CaretPosition.GetCurrentParagraphBox().AssociatedParagraph -```` - -{{endregion}} All you have to do now is set the __ListId__ property of the paragraph. However this id should be the ID of a __DocumentList__ that uses the new __ListStyle__. This document list is created automatically when using the user interface, but in code you have to create it on your own. As the logic of creating a custom list style is rather complex, the method __AddCustomListStyle__ does that and returns an instance of **ListStyle** which is different from the one you passed. When creating the new document list you need to pass the list style returned from this method. So creating a document list look like this: -{{source=..\SamplesCS\RichTextEditor\Features\ListStyles.cs region=newStyle}} -{{source=..\SamplesVB\RichTextEditor\Features\ListStyles.vb region=newStyle}} + + -````C# -ListStyle newListStyle = this.radRichTextEditor1.Document.AddCustomListStyle(upperRomanHierarchical); -DocumentList documentList = new DocumentList(newListStyle, this.radRichTextEditor1.Document); -```` -````VB.NET -Dim newListStyle As ListStyle = Me.radRichTextEditor1.Document.AddCustomListStyle(upperRomanHierarchical) -Dim documentList As New DocumentList(newListStyle, Me.radRichTextEditor1.Document) -```` -{{endregion}} - Having the new __DocumentList__ all you have to do in order the paragraph to be added to the list is to set it's __ListId__ property to the ID of the new __DocumentList__: -{{source=..\SamplesCS\RichTextEditor\Features\ListStyles.cs region=assing}} -{{source=..\SamplesVB\RichTextEditor\Features\ListStyles.vb region=assing}} - -````C# -paragraph.ListId = documentList.ID; - -```` -````VB.NET -paragraph.ListId = documentList.ID - -```` - -{{endregion}} + + diff --git a/controls/richtexteditor/features/styles/style-sheets.md b/controls/richtexteditor/features/styles/style-sheets.md index e232ca3b8..ba73f4532 100644 --- a/controls/richtexteditor/features/styles/style-sheets.md +++ b/controls/richtexteditor/features/styles/style-sheets.md @@ -26,71 +26,15 @@ __XamlFormatProvider__ has been extended to import and export style sheets to ba Here is an example of how to load a style sheet from a file using the __LoadStylesheet__ method of __XamlFormatProvider__: -{{source=..\SamplesCS\RichTextEditor\Features\StyleSheets.cs region=add}} -{{source=..\SamplesVB\RichTextEditor\Features\StyleSheets.vb region=add}} + + -````C# - -OpenFileDialog ofd = new OpenFileDialog(); -ofd.Filter = "Xaml Files|*.xaml"; -if (ofd.ShowDialog() == DialogResult.OK) -{ - using (var stream = ofd.OpenFile()) - { - Stylesheet stylesheet = XamlFormatProvider.LoadStylesheet(stream); - stylesheet.ApplyStylesheetToDocument(this.radRichTextEditor1.Document); - } -} -```` -````VB.NET -Dim ofd As New OpenFileDialog() -ofd.Filter = "Xaml Files|*.xaml" -If ofd.ShowDialog() = System.Windows.Forms.DialogResult.OK Then - Using stream = ofd.OpenFile() - Dim stylesheet As Stylesheet = XamlFormatProvider.LoadStylesheet(stream) - stylesheet.ApplyStylesheetToDocument(Me.radRichTextEditor1.Document) - End Using -End If - -```` - -{{endregion}} This is how you can save a style sheet with the __SaveStyleSheet__ method of __XamlFormatProvider__: -{{source=..\SamplesCS\RichTextEditor\Features\StyleSheets.cs region=save}} -{{source=..\SamplesVB\RichTextEditor\Features\StyleSheets.vb region=save}} - -````C# - -SaveFileDialog sfd = new SaveFileDialog(); -sfd.Filter = "Xaml Files|*.xaml"; -if (sfd.ShowDialog() == DialogResult.OK) -{ - using (var stream = sfd.OpenFile()) - { - Stylesheet stylesheet = new Stylesheet(); - stylesheet.ExtractStylesheetFromDocument(this.radRichTextEditor1.Document); - XamlFormatProvider.SaveStylesheet(stylesheet, stream); - } -} - -```` -````VB.NET -Dim sfd As New SaveFileDialog() -sfd.Filter = "Xaml Files|*.xaml" -If sfd.ShowDialog() = System.Windows.Forms.DialogResult.OK Then - Using stream = sfd.OpenFile() - Dim stylesheet As New Stylesheet() - stylesheet.ExtractStylesheetFromDocument(Me.radRichTextEditor1.Document) - XamlFormatProvider.SaveStylesheet(stylesheet, stream) - End Using -End If - -```` - -{{endregion}} + + diff --git a/controls/richtexteditor/features/styles/styles.md b/controls/richtexteditor/features/styles/styles.md index 07434d691..14d8c0911 100644 --- a/controls/richtexteditor/features/styles/styles.md +++ b/controls/richtexteditor/features/styles/styles.md @@ -1,305 +1,203 @@ ---- -title: Styles Overview -page_title: Styles Overview - WinForms RichTextEditor Control -description: WinForms RichTextEditor supports Styles similar to the ones in Microsoft Office. Styles can be created and added to a document programmatically or via the Styles dialog. -slug: winforms/richtexteditor/features/styles -tags: styles -published: True -position: 0 -previous_url: richtexteditor-features-styles ---- - -# Styles - -__RadRichTextEditor__ sccc - -Styles can be created and added to a document programmatically or via the __Styles__ dialog. In addition, styles can be instantiated from a **docx** or a **XAML** document on import, to provide for a consistent look of the document and richer editing capabilities. - -This topic covers: - -* [Style Definition Overview](#styledefinition-overview) - -* [Types Of Styles](#types-of-styles) - -* [Declaring New Styles](#declaring-new-styles) - -* [Applying a Style](#applying-a-style) - -* [Default Styles](#default-styles) - -* [Style Evaluation](#style-evaluation) - -## StyleDefinition Overview - -The class that contains the logic behind the styles feature is __StyleDefinition__. - -Each __StyleDefinition__ has the following properties: - -* __Name__ - the name of the style. All styles in a document have a unique name, which is used as an identifier when applying the style. - -* __DisplayName__ - a name that will be shown in the UI. - -* __Type__ - specifies which document elements the style will target, e.g. a **Paragraph**, a **Table**, a **Span**. - -* __BasedOn__ - specifies that the current style inherits the **StyleDefinition** set to this property. This is how hierarchical Styles can be defined. - ->caution The type of the style must match that of the inherited style. It is not possible to have a Character style inherit a Paragraph style for example. -> - -* __BasedOnName__ - the same as above, the only difference being in the way the style is set - using its Name. - -* __LinkedStyle__ - provides a relation between a **Paragraph** and **Character** style. - ->caution The __Name__ and __Type__ properties are compulsory for each **StyleDefinition**. -> - -## Types of Styles - -The style types that are most commonly used are **Character** styles and styles for **Paragraph**. - -The former styles set values for the properties of **Span**, such as **FontSize**, **ForeColor** and **FontWeight**. These values are contained in the __SpanProperties__ of the style. When such a style is applied to a document, it changes the formatting of the text in the selection or (if there is no selection) the formatting of the word that the **Caret** is positioned in. - -**Paragraph Styles** include properties of a **Paragraph**, such as **Background**, **TextAlignment**, **LineSpacing**, **SpacingAfter**, etc. The values of these properties are kept in the __ParagraphProperties__ of the **StyleDefinition** object. This type of styles can also contain values of **Character** styles in the __SpanProperties__ property. When applied, the values of the **ParagraphProperties** will be applied to the **Paragraphs** and the values of the **SpanProperties** - to all **Spans** in these **Paragraphs**. - -You can have a **Paragraph** style linked to a **Character** style using the __LinkedStyle__ property. In this way, you can apply **Paragraph** and **Span** properties at the same time. The difference between this case and the **Paragraph Styles** that also set **SpanProperties** is the way they are applied. With linked styles, if you have selection which includes text in only one **Paragraph** the **Paragraph Style** is not applied. In that case, the **Character** style is applied only on the selected part of the document. - -Table styles include properties of **Table**, such as **Borders** and **Background**. They are contained in the __TableProperties__ of the style. When such a style is applied to a document, it changes the formatting of the tables. - -## Declaring New Styles - -New Styles can be declared and added to the **StylesRepository** of the document. In this way they will be discovered by the default UI and could be applied to parts of the document. - -### Declaring a Character Style - -This is how a **Character** style can be defined and registered: - -{{source=..\SamplesCS\RichTextEditor\Features\Styles.cs region=style}} -{{source=..\SamplesVB\RichTextEditor\Features\Styles.vb region=style}} - -````C# +--- +title: Styles Overview +page_title: Styles Overview - WinForms RichTextEditor Control +description: WinForms RichTextEditor supports Styles similar to the ones in Microsoft Office. Styles can be created and added to a document programmatically or via the Styles dialog. +slug: winforms/richtexteditor/features/styles +tags: styles +published: True +position: 0 +previous_url: richtexteditor-features-styles +--- + +# Styles + +__RadRichTextEditor__ sccc + +Styles can be created and added to a document programmatically or via the __Styles__ dialog. In addition, styles can be instantiated from a **docx** or a **XAML** document on import, to provide for a consistent look of the document and richer editing capabilities. + +This topic covers: + +* [Style Definition Overview](#styledefinition-overview) + +* [Types Of Styles](#types-of-styles) + +* [Declaring New Styles](#declaring-new-styles) + +* [Applying a Style](#applying-a-style) + +* [Default Styles](#default-styles) + +* [Style Evaluation](#style-evaluation) + +## StyleDefinition Overview + +The class that contains the logic behind the styles feature is __StyleDefinition__. + +Each __StyleDefinition__ has the following properties: + +* __Name__ - the name of the style. All styles in a document have a unique name, which is used as an identifier when applying the style. + +* __DisplayName__ - a name that will be shown in the UI. + +* __Type__ - specifies which document elements the style will target, e.g. a **Paragraph**, a **Table**, a **Span**. + +* __BasedOn__ - specifies that the current style inherits the **StyleDefinition** set to this property. This is how hierarchical Styles can be defined. + +>caution The type of the style must match that of the inherited style. It is not possible to have a Character style inherit a Paragraph style for example. +> + +* __BasedOnName__ - the same as above, the only difference being in the way the style is set - using its Name. -StyleDefinition charStyle = new StyleDefinition(); -charStyle.Type = StyleType.Character; -charStyle.SpanProperties.FontFamily = new Telerik.WinControls.RichTextEditor.UI.FontFamily("Calibri"); -charStyle.SpanProperties.FontSize = Unit.PointToDip(20); -charStyle.SpanProperties.ForeColor = Colors.Orange; -charStyle.DisplayName = "charStyle"; -charStyle.Name = "charStyle"; +* __LinkedStyle__ - provides a relation between a **Paragraph** and **Character** style. -this.radRichTextEditor1.Document.StyleRepository.Add(charStyle); - -```` -````VB.NET -Dim charStyle As New StyleDefinition() -charStyle.Type = StyleType.Character -charStyle.SpanProperties.FontFamily = New Telerik.WinControls.RichTextEditor.UI.FontFamily("Calibri") -charStyle.SpanProperties.FontSize = Unit.PointToDip(20) -charStyle.SpanProperties.ForeColor = Colors.Orange -charStyle.DisplayName = "charStyle" -charStyle.Name = "charStyle" -Me.radRichTextEditor1.Document.StyleRepository.Add(charStyle) - -```` - -{{endregion}} - -This style will set "*Calibri*" as a **FontFamily** to the part of the document it is applied to, *20 dip* as a **FontSize** and *Orange* as a **ForeColor**. - -### Declaring a Paragraph Style - -A paragraph style can be defined as follows: - -{{source=..\SamplesCS\RichTextEditor\Features\Styles.cs region=paragraph}} -{{source=..\SamplesVB\RichTextEditor\Features\Styles.vb region=paragraph}} - -````C# -paragraph.StyleName = RadDocumentDefaultStyles.GetHeadingStyleNameByIndex(1); - -```` -````VB.NET -paragraph.StyleName = RadDocumentDefaultStyles.GetHeadingStyleNameByIndex(1) - -```` - -{{endregion}} - -When applied to a **Paragraph**, this style will set the Background color of the **Paragraph** to *Red* and the **TextAlignment** to *Center*. - -### Declaring a Linked Style - -Linked styles should be used when both properties of **Paragraph** and **Span** should be set by the same style. They can be declared like this: - -{{source=..\SamplesCS\RichTextEditor\Features\Styles.cs region=linked}} -{{source=..\SamplesVB\RichTextEditor\Features\Styles.vb region=linked}} - -````C# +>caution The __Name__ and __Type__ properties are compulsory for each **StyleDefinition**. +> + +## Types of Styles + +The style types that are most commonly used are **Character** styles and styles for **Paragraph**. + +The former styles set values for the properties of **Span**, such as **FontSize**, **ForeColor** and **FontWeight**. These values are contained in the __SpanProperties__ of the style. When such a style is applied to a document, it changes the formatting of the text in the selection or (if there is no selection) the formatting of the word that the **Caret** is positioned in. + +**Paragraph Styles** include properties of a **Paragraph**, such as **Background**, **TextAlignment**, **LineSpacing**, **SpacingAfter**, etc. The values of these properties are kept in the __ParagraphProperties__ of the **StyleDefinition** object. This type of styles can also contain values of **Character** styles in the __SpanProperties__ property. When applied, the values of the **ParagraphProperties** will be applied to the **Paragraphs** and the values of the **SpanProperties** - to all **Spans** in these **Paragraphs**. + +You can have a **Paragraph** style linked to a **Character** style using the __LinkedStyle__ property. In this way, you can apply **Paragraph** and **Span** properties at the same time. The difference between this case and the **Paragraph Styles** that also set **SpanProperties** is the way they are applied. With linked styles, if you have selection which includes text in only one **Paragraph** the **Paragraph Style** is not applied. In that case, the **Character** style is applied only on the selected part of the document. + +Table styles include properties of **Table**, such as **Borders** and **Background**. They are contained in the __TableProperties__ of the style. When such a style is applied to a document, it changes the formatting of the tables. + +## Declaring New Styles + +New Styles can be declared and added to the **StylesRepository** of the document. In this way they will be discovered by the default UI and could be applied to parts of the document. + +### Declaring a Character Style + +This is how a **Character** style can be defined and registered: + + + + + + +This style will set "*Calibri*" as a **FontFamily** to the part of the document it is applied to, *20 dip* as a **FontSize** and *Orange* as a **ForeColor**. + +### Declaring a Paragraph Style + +A paragraph style can be defined as follows: + + + + + + +When applied to a **Paragraph**, this style will set the Background color of the **Paragraph** to *Red* and the **TextAlignment** to *Center*. + +### Declaring a Linked Style + +Linked styles should be used when both properties of **Paragraph** and **Span** should be set by the same style. They can be declared like this: + + + + + + +>note Only styles of type __Paragraph__ and __Character__ can be linked. +> + +## Applying a Style + +Styles are applied using the __ChangeStyleName__ method of __RadRichTextEditor__ or the __ChangeStyleNameCommand__. In both cases, the parameter that has to be passed is the __Name__ of the **StyleDefinition**. + +Styles of type **Character** get applied to the currently selected part of the document. If there is no selection, the values that will be changed are those of the word that the **Caret** is positioned in. + +Styles of type **Paragraph** follow the same logic and are applied to all paragraphs in the selection or the current paragraph. + +For example, the following line will apply the "*linkedParagraphStyle*" to the current **Paragraph** and the parts of the text which are selected: + + + + + + +Styles of type **LinkedStyle** change the values of the paragraph when there is no selection and apply both their **Paragraph** and **Span** properties. When there is selection, **LinkedStyle** changes only the **Span** properties of the selected text. + +## Default Styles + +The default style for span and paragraph properties is __Normal__. It internally inherits the default style of the document located in __RadDocument.Style__. + +The document's default style is only for the current instance of the document and if you create a new document, those settings will not be copied. For this purpose you can use the __DocumentInheritsDefaultStyleSettings__ property of __RadRichTextEditor__ . When set to *true* it will copy each property you set in __RadRichTextEditor.DefaultStyleSettings__ to newly created documents. You can find more information on setting default style settings on the document [here]({%slug winforms/richtexteditor-/frequently-asked-questions%})) + +The default style for table properties is __TableNormal__, which does not inherit any other styles. It has an inheritor - __TableGrid__, which contains predefined borders and is the one applied when inserting a table from the UI of __RadRichTextEditor__. + +All default styles as well as some other predefined styles can be applied using the members exposed by the __RadDocumentDefaultStyles__ class. The set of properties provided by the class are of type *string* and should be applied using the __StyleName__ property of the respective document element. + +For example the __TableGrid__ style can be applied to a table as follows: + + + + + + +And a paragraph can have __Heading 1__ style applied to it like this: + + + + + + +## Style Evaluation + +Each style first checks its local value for the property that is being evaluated and then turns to its base style. If no local value is found, it turns to its default style. If no local value is found, the evaluation system turns to the default style of the document. + +Here is how style properties for different styles are inherited: + +### Span style + +**Span** styles can only be based on other span styles. The inheritance is as follows: + +* Span properties are inherited from the base span style. + +### Paragraph style + +**Paragraph** styles can be based on other paragraph styles or on linked styles. + +When a paragraph style is based on another paragraph style the inheritance of the properties is as follows: + +* Paragraph properties are inherited from the base paragraph style. + +* Span properties are inherited from the base paragraph style. + +When a paragraph style is based on a linked style the inheritance of the properties is as follows: + +* Paragraph properties are inherited from the paragraph style part in its base linked style. + +* Span properties are inherited from the span style part in its base linked style + +### Linked style + +**Linked** styles are composite styles and their components are a paragraph and a span style with link between them. When paragraph properties need to be applied they are taken from the linked paragraph style and accordingly when span properties need to be applied they are taken from the linked span style. -StyleDefinition linkedParagraphStyle = new StyleDefinition(); -linkedParagraphStyle.Type = StyleType.Paragraph; -linkedParagraphStyle.ParagraphProperties.Background = Colors.Yellow; -linkedParagraphStyle.DisplayName = "linkedParagraphStyle"; -linkedParagraphStyle.Name = "linkedParagraphStyle"; - -StyleDefinition linkedCharStyle = new StyleDefinition(); -linkedCharStyle.Type = StyleType.Character; -linkedCharStyle.SpanProperties.FontWeight = FontWeights.Bold; -linkedCharStyle.SpanProperties.FontSize = Unit.PointToDip(30); -linkedCharStyle.SpanProperties.ForeColor = Colors.Purple; -linkedCharStyle.DisplayName = "linkedCharStyle"; -linkedCharStyle.Name = "linkedCharStyle"; -linkedParagraphStyle.LinkedStyle = linkedCharStyle; - -this.radRichTextEditor1.Document.StyleRepository.Add(linkedParagraphStyle); -this.radRichTextEditor1.Document.StyleRepository.Add(linkedCharStyle); - -```` -````VB.NET -Dim linkedParagraphStyle As New StyleDefinition() -linkedParagraphStyle.Type = StyleType.Paragraph -linkedParagraphStyle.ParagraphProperties.Background = Colors.Yellow -linkedParagraphStyle.DisplayName = "linkedParagraphStyle" -linkedParagraphStyle.Name = "linkedParagraphStyle" -Dim linkedCharStyle As New StyleDefinition() -linkedCharStyle.Type = StyleType.Character -linkedCharStyle.SpanProperties.FontWeight = FontWeights.Bold -linkedCharStyle.SpanProperties.FontSize = Unit.PointToDip(30) -linkedCharStyle.SpanProperties.ForeColor = Colors.Purple -linkedCharStyle.DisplayName = "linkedCharStyle" -linkedCharStyle.Name = "linkedCharStyle" -linkedParagraphStyle.LinkedStyle = linkedCharStyle -Me.radRichTextEditor1.Document.StyleRepository.Add(linkedParagraphStyle) -Me.radRichTextEditor1.Document.StyleRepository.Add(linkedCharStyle) - -```` - -{{endregion}} - ->note Only styles of type __Paragraph__ and __Character__ can be linked. -> - -## Applying a Style - -Styles are applied using the __ChangeStyleName__ method of __RadRichTextEditor__ or the __ChangeStyleNameCommand__. In both cases, the parameter that has to be passed is the __Name__ of the **StyleDefinition**. - -Styles of type **Character** get applied to the currently selected part of the document. If there is no selection, the values that will be changed are those of the word that the **Caret** is positioned in. - -Styles of type **Paragraph** follow the same logic and are applied to all paragraphs in the selection or the current paragraph. - -For example, the following line will apply the "*linkedParagraphStyle*" to the current **Paragraph** and the parts of the text which are selected: - -{{source=..\SamplesCS\RichTextEditor\Features\Styles.cs region=ChangeStyleName}} -{{source=..\SamplesVB\RichTextEditor\Features\Styles.vb region=ChangeStyleName}} - -````C# - -this.radRichTextEditor1.RichTextBoxElement.ChangeStyleName("linkedParagraphStyle"); - -```` -````VB.NET -Me.radRichTextEditor1.RichTextBoxElement.ChangeStyleName("linkedParagraphStyle") - -```` - -{{endregion}} - -Styles of type **LinkedStyle** change the values of the paragraph when there is no selection and apply both their **Paragraph** and **Span** properties. When there is selection, **LinkedStyle** changes only the **Span** properties of the selected text. - -## Default Styles - -The default style for span and paragraph properties is __Normal__. It internally inherits the default style of the document located in __RadDocument.Style__. - -The document's default style is only for the current instance of the document and if you create a new document, those settings will not be copied. For this purpose you can use the __DocumentInheritsDefaultStyleSettings__ property of __RadRichTextEditor__ . When set to *true* it will copy each property you set in __RadRichTextEditor.DefaultStyleSettings__ to newly created documents. You can find more information on setting default style settings on the document [here]({%slug winforms/richtexteditor-/frequently-asked-questions%})) - -The default style for table properties is __TableNormal__, which does not inherit any other styles. It has an inheritor - __TableGrid__, which contains predefined borders and is the one applied when inserting a table from the UI of __RadRichTextEditor__. - -All default styles as well as some other predefined styles can be applied using the members exposed by the __RadDocumentDefaultStyles__ class. The set of properties provided by the class are of type *string* and should be applied using the __StyleName__ property of the respective document element. - -For example the __TableGrid__ style can be applied to a table as follows: - -{{source=..\SamplesCS\RichTextEditor\Features\Styles.cs region=table}} -{{source=..\SamplesVB\RichTextEditor\Features\Styles.vb region=table}} - -````C# -table.StyleName = RadDocumentDefaultStyles.DefaultTableGridStyleName; - -```` -````VB.NET -table.StyleName = RadDocumentDefaultStyles.DefaultTableGridStyleName - -```` - -{{endregion}} - -And a paragraph can have __Heading 1__ style applied to it like this: - -{{source=..\SamplesCS\RichTextEditor\Features\Styles.cs region=paragraph}} -{{source=..\SamplesVB\RichTextEditor\Features\Styles.vb region=paragraph}} - -````C# -paragraph.StyleName = RadDocumentDefaultStyles.GetHeadingStyleNameByIndex(1); - -```` -````VB.NET -paragraph.StyleName = RadDocumentDefaultStyles.GetHeadingStyleNameByIndex(1) - -```` - -{{endregion}} - -## Style Evaluation - -Each style first checks its local value for the property that is being evaluated and then turns to its base style. If no local value is found, it turns to its default style. If no local value is found, the evaluation system turns to the default style of the document. - -Here is how style properties for different styles are inherited: - -### Span style - -**Span** styles can only be based on other span styles. The inheritance is as follows: - -* Span properties are inherited from the base span style. - -### Paragraph style - -**Paragraph** styles can be based on other paragraph styles or on linked styles. - -When a paragraph style is based on another paragraph style the inheritance of the properties is as follows: - -* Paragraph properties are inherited from the base paragraph style. - -* Span properties are inherited from the base paragraph style. - -When a paragraph style is based on a linked style the inheritance of the properties is as follows: - -* Paragraph properties are inherited from the paragraph style part in its base linked style. - -* Span properties are inherited from the span style part in its base linked style - -### Linked style - -**Linked** styles are composite styles and their components are a paragraph and a span style with link between them. When paragraph properties need to be applied they are taken from the linked paragraph style and accordingly when span properties need to be applied they are taken from the linked span style. - -**Linked** styles can be based on other linked styles or on paragraph styles. - -* When a linked style is based on a paragraph style the inheritance of the properties is as follows: - -* Paragraph properties are inherited from the base paragraph style. - -* Span properties are inherited from the base paragraph style. - -* When a linked style is based on another linked style the inheritance of the properties is as follows: - -* Paragraph properties are inherited from the paragraph style part in its base linked style. - -* Span properties are inherited from the span style part in its base linked style. - -### Table style - -Table styles can only be based on other table styles. The inheritance is as follows: - -* Span properties are inherited from the base table style. - -* Paragraph properties are inherited from the base table style. - -* Table cell properties are inherited from the base table style. - -* Table properties are inherited from the base table style. +**Linked** styles can be based on other linked styles or on paragraph styles. + +* When a linked style is based on a paragraph style the inheritance of the properties is as follows: + +* Paragraph properties are inherited from the base paragraph style. + +* Span properties are inherited from the base paragraph style. + +* When a linked style is based on another linked style the inheritance of the properties is as follows: + +* Paragraph properties are inherited from the paragraph style part in its base linked style. + +* Span properties are inherited from the span style part in its base linked style. + +### Table style + +Table styles can only be based on other table styles. The inheritance is as follows: + +* Span properties are inherited from the base table style. + +* Paragraph properties are inherited from the base table style. + +* Table cell properties are inherited from the base table style. + +* Table properties are inherited from the base table style. diff --git a/controls/richtexteditor/features/track-changes.md b/controls/richtexteditor/features/track-changes.md index 56bed4fde..78ffc40a8 100644 --- a/controls/richtexteditor/features/track-changes.md +++ b/controls/richtexteditor/features/track-changes.md @@ -25,19 +25,10 @@ __Track Changes__ is a way for __RadRichTextEditor__ to keep track of the change You can activate change tracking through the __IsTrackChangesEnabled__ property of __RadRichTextEditor__: -{{source=..\SamplesCS\RichTextEditor\Features\TrackChanges.cs region=enable}} -{{source=..\SamplesVB\RichTextEditor\Features\TrackChanges.vb region=enable}} + + -````C# -this.radRichTextEditor1.IsTrackChangesEnabled = true; -```` -````VB.NET -Me.radRichTextEditor1.IsTrackChangesEnabled = True - -```` - -{{endregion}} When change tracking is enabled all changes made in the document will be tracked. This includes: @@ -53,27 +44,10 @@ When change tracking is enabled all changes made in the document will be tracked As you can see tracked changes are visualized inside the rich text box with different colors. You can modify these colors by using the __TrackChangesOptions__ property of __RadRichTextEditor__. Here is for example how to customize the look of the tracked changes so that insertions are shown in green, deletions are shown in underlined orange and the vertical line indicating changes is red: -{{source=..\SamplesCS\RichTextEditor\Features\TrackChanges.cs region=options}} -{{source=..\SamplesVB\RichTextEditor\Features\TrackChanges.vb region=options}} - -````C# -this.radRichTextEditor1.RichTextBoxElement.TrackChangesOptions.Insert.Decoration = RevisionDecoration.ColorOnly; -this.radRichTextEditor1.RichTextBoxElement.TrackChangesOptions.Insert.ColorOptions = new RevisionColor(Color.Green); -this.radRichTextEditor1.RichTextBoxElement.TrackChangesOptions.Delete.Decoration = RevisionDecoration.Underline; -this.radRichTextEditor1.RichTextBoxElement.TrackChangesOptions.Delete.ColorOptions = new RevisionColor(Color.Orange); -this.radRichTextEditor1.RichTextBoxElement.TrackChangesOptions.ChangedLinesDecorationColorOptions.ColorOptions = new RevisionColor(Color.Red); + + -```` -````VB.NET -Me.radRichTextEditor1.RichTextBoxElement.TrackChangesOptions.Insert.Decoration = RevisionDecoration.ColorOnly -Me.radRichTextEditor1.RichTextBoxElement.TrackChangesOptions.Insert.ColorOptions = New RevisionColor(Color.Green) -Me.radRichTextEditor1.RichTextBoxElement.TrackChangesOptions.Delete.Decoration = RevisionDecoration.Underline -Me.radRichTextEditor1.RichTextBoxElement.TrackChangesOptions.Delete.ColorOptions = New RevisionColor(Color.Orange) -Me.radRichTextEditor1.RichTextBoxElement.TrackChangesOptions.ChangedLinesDecorationColorOptions.ColorOptions = New RevisionColor(Color.Red) -```` - -{{endregion}} The result is: @@ -83,19 +57,10 @@ The result is: All changes made while track changes are enabled are made on behalf of the current user. The current user can be changed by setting the __CurrentUser__ property of the __RadRichTextEditor__: -{{source=..\SamplesCS\RichTextEditor\Features\TrackChanges.cs region=user}} -{{source=..\SamplesVB\RichTextEditor\Features\TrackChanges.vb region=user}} - -````C# -this.radRichTextEditor1.CurrentUser = new UserInfo("Group", "Boby", "Boby", "bobby@telerik.com"); + + -```` -````VB.NET -Me.radRichTextEditor1.CurrentUser = New UserInfo("Group", "Boby", "Boby", "bobby@telerik.com") -```` - -{{endregion}} Here is the result: @@ -115,26 +80,8 @@ By default, insert and delete changes by different authors will be displayed in All revision have a **RevisionInfo** object associated to them, which contains information about the user who made the change and the date and time it was made. Revisions in the document can be accessed and selected with the following methods of **RadDocument**: -{{source=..\SamplesCS\RichTextEditor\Features\TrackChanges.cs region=revision}} -{{source=..\SamplesVB\RichTextEditor\Features\TrackChanges.vb region=revision}} - -````C# -Revision prev = document.GoToPreviousRevision(); -Revision next = document.GoToNextRevision(); -Revision getCurrent = document.GetCurrentRevision(); -Revision getPrev = document.GetPreviousRevision(); -Revision getNext = document.GetNextRevision(); -IEnumerable all = document.GetAllRevisions(); - -```` -````VB.NET -Dim prev As Revision = document.GoToPreviousRevision() -Dim [next] As Revision = document.GoToNextRevision() -Dim getCurrent As Revision = document.GetCurrentRevision() -Dim getPrev As Revision = document.GetPreviousRevision() -Dim getNext As Revision = document.GetNextRevision() -Dim all As IEnumerable(Of Revision) = document.GetAllRevisions() - -```` - -{{endregion}} + + + + + diff --git a/controls/richtexteditor/features/watermark.md b/controls/richtexteditor/features/watermark.md index 8708b27c1..915cbded7 100644 --- a/controls/richtexteditor/features/watermark.md +++ b/controls/richtexteditor/features/watermark.md @@ -36,69 +36,26 @@ There are two types of watermarks - text and image. Both of them are shown behin There is also a set of predefined textual watermarks - the most commonly used ones like ASAP, Urgent, Confidential, etc., that can be easily set in the following way: -{{source=..\SamplesCS\RichTextEditor\Features\Watermark.cs region=set}} -{{source=..\SamplesVB\RichTextEditor\Features\Watermark.vb region=set}} + + -````C# -this.radRichTextEditor1.SetWatermark(PredefinedWatermarkType.Confidential); -```` -````VB.NET -Me.radRichTextEditor1.SetWatermark(PredefinedWatermarkType.Confidential) - -```` - -{{endregion}} You can create custom watermarks using the __WatermarkTextSettings__ and __WatermarkImageSettings__ classes and the respective methods of __RadRichTextEditor__ - __SetWatermarkText()__ and __SetWatermarkImage()__. The following example demonstrates how to create a text watermark and apply it to the document in the editor: -{{source=..\SamplesCS\RichTextEditor\Features\Watermark.cs region=settings}} -{{source=..\SamplesVB\RichTextEditor\Features\Watermark.vb region=settings}} - -````C# -WatermarkTextSettings textSettings = new WatermarkTextSettings(); -textSettings.Text = "Purple Watermark"; -textSettings.RotateAngle = 30; -textSettings.Opacity = 1; -textSettings.ForegroundColor = Colors.Purple; -this.radRichTextEditor1.SetWatermarkText(textSettings); + + -```` -````VB.NET -Dim textSettings As New WatermarkTextSettings() -textSettings.Text = "Purple Watermark" -textSettings.RotateAngle = 30 -textSettings.Opacity = 1 -textSettings.ForegroundColor = Colors.Purple -Me.radRichTextEditor1.SetWatermarkText(textSettings) -```` - -{{endregion}} And this is how you create an image watermark and apply it: -{{source=..\SamplesCS\RichTextEditor\Features\Watermark.cs region=image}} -{{source=..\SamplesVB\RichTextEditor\Features\Watermark.vb region=image}} - -````C# -WatermarkImageSettings imageSettings = new WatermarkImageSettings(); -imageSettings.UriSource = uri; -imageSettings.Size = new Size(500, 665); -this.radRichTextEditor1.SetWatermarkImage(imageSettings); - -```` -````VB.NET -Dim imageSettings As New WatermarkImageSettings() -imageSettings.UriSource = uri -imageSettings.Size = New Size(500, 665) -Me.radRichTextEditor1.SetWatermarkImage(imageSettings) + + -```` -{{endregion}} # See Also diff --git a/controls/richtexteditor/frequently-asked-questions.md b/controls/richtexteditor/frequently-asked-questions.md index 0f8ffc46d..3ec519037 100644 --- a/controls/richtexteditor/frequently-asked-questions.md +++ b/controls/richtexteditor/frequently-asked-questions.md @@ -1,221 +1,122 @@ ---- -title: Frequently Asked Questions -page_title: Frequently Asked Questions - WinForms RichTextEditor Control -description: Get familiar with some of the frequently asked questions about the use of WinForms RichTextEditor. -slug: winforms/richtexteditor-/frequently-asked-questions -tags: frequently,asked,questions -published: True -position: 3 -previous_url: richtexteditor-frequently-asked-questions ---- - -# Frequently Asked Questions - -This topic aims to answer some of the frequently asked questions about the use of __RadRichTextEditor__ , namely: - -[Setting Default Style Settings on the Document](#setting-default-style-settings-on-the-document) - -[How to Get and Set the Text of RadRichTextEditor](#how-to-get-and-set-the-text-of-radrichtexteditor) - -[Setting the Margins of the Document](#setting-the-margins-of-the-document) - -[Inserting multiple consecutive tables](#inserting-multiple-consecutive-tables) - -## Setting Default Style Settings on the Document - -__RadRichTextEditor__ has a *Boolean* property called __DocumentInheritsDefaultStyleSettings__, which must be set to *true*, if you want to set some default font properties. Otherwise, your settings for the following properties would be disregarded: - -* **FontFamily**; - -* **FontSize**; - -* **FontStyle** (Normal/Italic); - -* **FontWeight** (Normal/Bold). - -You can set these properties in code behind: - -{{source=..\SamplesCS\RichTextEditor\FAQ.cs region=properties}} -{{source=..\SamplesVB\RichTextEditor\FAQ.vb region=properties}} - -````C# +--- +title: Frequently Asked Questions +page_title: Frequently Asked Questions - WinForms RichTextEditor Control +description: Get familiar with some of the frequently asked questions about the use of WinForms RichTextEditor. +slug: winforms/richtexteditor-/frequently-asked-questions +tags: frequently,asked,questions +published: True +position: 3 +previous_url: richtexteditor-frequently-asked-questions +--- + +# Frequently Asked Questions + +This topic aims to answer some of the frequently asked questions about the use of __RadRichTextEditor__ , namely: + +[Setting Default Style Settings on the Document](#setting-default-style-settings-on-the-document) + +[How to Get and Set the Text of RadRichTextEditor](#how-to-get-and-set-the-text-of-radrichtexteditor) + +[Setting the Margins of the Document](#setting-the-margins-of-the-document) + +[Inserting multiple consecutive tables](#inserting-multiple-consecutive-tables) + +## Setting Default Style Settings on the Document + +__RadRichTextEditor__ has a *Boolean* property called __DocumentInheritsDefaultStyleSettings__, which must be set to *true*, if you want to set some default font properties. Otherwise, your settings for the following properties would be disregarded: -public void SetDefaultFontPropertiesToEditor(RadRichTextEditor editor) -{ - editor.RichTextBoxElement.ChangeFontFamily(new Telerik.WinControls.RichTextEditor.UI.FontFamily("Comic Sans MS")); - editor.RichTextBoxElement.ChangeFontSize(Unit.PointToDip(12)); - editor.RichTextBoxElement.ChangeFontStyle(Telerik.WinControls.RichTextEditor.UI.FontStyles.Italic); - editor.RichTextBoxElement.ChangeFontWeight(Telerik.WinControls.RichTextEditor.UI.FontWeights.Bold); - - editor.DocumentInheritsDefaultStyleSettings = true; -} - -```` -````VB.NET -Public Sub SetDefaultFontPropertiesToEditor(ByVal editor As RadRichTextEditor) - editor.RichTextBoxElement.ChangeFontFamily(New Telerik.WinControls.RichTextEditor.UI.FontFamily("Comic Sans MS")) - editor.RichTextBoxElement.ChangeFontSize(Unit.PointToDip(12)) - editor.RichTextBoxElement.ChangeFontStyle(Telerik.WinControls.RichTextEditor.UI.FontStyles.Italic) - editor.RichTextBoxElement.ChangeFontWeight(Telerik.WinControls.RichTextEditor.UI.FontWeights.Bold) - editor.DocumentInheritsDefaultStyleSettings = True -End Sub - -```` - -{{endregion}} - ->note These settings will not be applied on text which is imported by a rich text **FormatProvider**, as the settings defined in the input file/string will be applied. - ->tip You can set the caret width with the **CaretWidth** property as well. - -## How to Get and Set the Text of RadRichTextEditor - -__RadRichTextEditor__ does not have a **Text** property because different formats for import and export of documents are supported – RTF, HTML, XAML, docX, plain text and PDF (export only). In order to set the contents of the document, it should be clear what format the data is in. For easier extensibility and separation of concerns, format providers that deal with the import and export of the documents are used. Here is a list of the currently available format providers and the namespaces they are included in: - -* **TxtFormatProvider** (plain text) – Telerik.WinForms.Documents.FormatProviders.Txt; - -* **DocxFormatProvider** - Telerik.WinForms.Documents.FormatProviders.OpenXml.Docx and Telerik.Windows.Zip; - -* **HtmlFormatProvider** - Telerik.WinForms.Documents.FormatProviders.Html; - -* **XamlFormatProvider** - Telerik.WinForms.Documents.FormatProviders.Xaml; - -* **RtfFormatProvider** – Telerik.WinForms.Documents.FormatProviders.Rtf; - -* **PdfFormatProvider** - Telerik.WinForms.Documents.FormatProviders.Pdf; and Telerik.Windows.Zip. - -You can read more about the use of format providers [here]({%slug winforms/richtexteditor/import-export/overview%}). Overall, what you need to do to get the content of the document in a specific format is to create an instance of the corresponding provider and export the document. An example is illustrated below: - -{{source=..\SamplesCS\RichTextEditor\FAQ.cs region=xaml}} -{{source=..\SamplesVB\RichTextEditor\FAQ.vb region=xaml}} - -````C# +* **FontFamily**; + +* **FontSize**; + +* **FontStyle** (Normal/Italic); + +* **FontWeight** (Normal/Bold). + +You can set these properties in code behind: + + + + + + +>note These settings will not be applied on text which is imported by a rich text **FormatProvider**, as the settings defined in the input file/string will be applied. + +>tip You can set the caret width with the **CaretWidth** property as well. + +## How to Get and Set the Text of RadRichTextEditor + +__RadRichTextEditor__ does not have a **Text** property because different formats for import and export of documents are supported – RTF, HTML, XAML, docX, plain text and PDF (export only). In order to set the contents of the document, it should be clear what format the data is in. For easier extensibility and separation of concerns, format providers that deal with the import and export of the documents are used. Here is a list of the currently available format providers and the namespaces they are included in: + +* **TxtFormatProvider** (plain text) – Telerik.WinForms.Documents.FormatProviders.Txt; + +* **DocxFormatProvider** - Telerik.WinForms.Documents.FormatProviders.OpenXml.Docx and Telerik.Windows.Zip; + +* **HtmlFormatProvider** - Telerik.WinForms.Documents.FormatProviders.Html; + +* **XamlFormatProvider** - Telerik.WinForms.Documents.FormatProviders.Xaml; + +* **RtfFormatProvider** – Telerik.WinForms.Documents.FormatProviders.Rtf; + +* **PdfFormatProvider** - Telerik.WinForms.Documents.FormatProviders.Pdf; and Telerik.Windows.Zip. + +You can read more about the use of format providers [here]({%slug winforms/richtexteditor/import-export/overview%}). Overall, what you need to do to get the content of the document in a specific format is to create an instance of the corresponding provider and export the document. An example is illustrated below: + + + + + + +To get the text stripped of all formatting, you can use __TxtFormatProvider__. Setting the content of __RadRichTextEditor__ can be done in the same manner, if you have the content in one of these formats. For example, importing an HTML string to __RadDocument__ can be done as follows: + + + + + + +If you wish to preserve the initial content of the document and insert text at different positions in the document, you can use the __Insert__ methods of __RadRichTextEditor__ or [RadDocumentEditor]({%slug winforms/richtexteditor-/features/raddocumenteditor%}). The **Insert** method of **RadRichTextEditor** uses the current span style of the document, i.e. the text is included in the document just as it would have been if you typed it at that position. + + + + + + +You can manipulate the caret position before invoking the insert method in order to change the position where you wish the text to appear. You can find more information on document positions and their usage [here]({%slug winforms/richtexteditor-/features/positioning%}). -public string GetXAML(RadDocument document) -{ - XamlFormatProvider provider = new XamlFormatProvider(); - return provider.Export(document); -} - -```` -````VB.NET -Public Function GetXAML(ByVal document As RadDocument) As String - Dim provider As New XamlFormatProvider() - Return provider.Export(document) -End Function - -```` - -{{endregion}} - -To get the text stripped of all formatting, you can use __TxtFormatProvider__. Setting the content of __RadRichTextEditor__ can be done in the same manner, if you have the content in one of these formats. For example, importing an HTML string to __RadDocument__ can be done as follows: - -{{source=..\SamplesCS\RichTextEditor\FAQ.cs region=html}} -{{source=..\SamplesVB\RichTextEditor\FAQ.vb region=html}} - -````C# +## Setting the Margins of the Document + +If you are using a document in flow layout mode, the document respects the value you set to the **Padding** property that **RadRichTextEditor** inherits from **Control**. + + + + + + +With paged layout mode, you can set the margin of the document like this: + + + + + + +If you are using data providers to bind the content of the **RichTextBox**, a new document will be created for every change in the string property which is the binding source. In that case, setting these properties should be done on **DocumentChanged**. -public RadDocument ImportHtml(string content) -{ - HtmlFormatProvider provider = new HtmlFormatProvider(); - return provider.Import(content); -} - -```` -````VB.NET -Public Function ImportHtml(ByVal content As String) As RadDocument - Dim provider As New HtmlFormatProvider() - Return provider.Import(content) -End Function - -```` - -{{endregion}} - -If you wish to preserve the initial content of the document and insert text at different positions in the document, you can use the __Insert__ methods of __RadRichTextEditor__ or [RadDocumentEditor]({%slug winforms/richtexteditor-/features/raddocumenteditor%}). The **Insert** method of **RadRichTextEditor** uses the current span style of the document, i.e. the text is included in the document just as it would have been if you typed it at that position. - -{{source=..\SamplesCS\RichTextEditor\FAQ.cs region=text}} -{{source=..\SamplesVB\RichTextEditor\FAQ.vb region=text}} - -````C# - -this.radRichTextEditor1.Insert(textToInsert); - -```` -````VB.NET -Me.radRichTextEditor1.Insert(textToInsert) - -```` - -{{endregion}} - -You can manipulate the caret position before invoking the insert method in order to change the position where you wish the text to appear. You can find more information on document positions and their usage [here]({%slug winforms/richtexteditor-/features/positioning%}). - -## Setting the Margins of the Document - -If you are using a document in flow layout mode, the document respects the value you set to the **Padding** property that **RadRichTextEditor** inherits from **Control**. - -{{source=..\SamplesCS\RichTextEditor\FAQ.cs region=padding}} -{{source=..\SamplesVB\RichTextEditor\FAQ.vb region=padding}} - -````C# - -this.radRichTextEditor1.Padding = new Telerik.WinControls.RichTextEditor.UI.Thickness(0, 20, 100, 60); - -```` -````VB.NET -Me.radRichTextEditor1.Padding = New Telerik.WinControls.RichTextEditor.UI.Thickness(0, 20, 100, 60) - -```` - -{{endregion}} - -With paged layout mode, you can set the margin of the document like this: - -{{source=..\SamplesCS\RichTextEditor\FAQ.cs region=margin}} -{{source=..\SamplesVB\RichTextEditor\FAQ.vb region=margin}} - -````C# - -this.radRichTextEditor1.LayoutMode = DocumentLayoutMode.Paged; -this.radRichTextEditor1.Document.SectionDefaultPageMargin = new Telerik.WinForms.Documents.Layout.Padding(0, 20, 100, 60); - -```` -````VB.NET -Me.radRichTextEditor1.LayoutMode = DocumentLayoutMode.Paged -Me.radRichTextEditor1.Document.SectionDefaultPageMargin = New Telerik.WinForms.Documents.Layout.Padding(0, 20, 100, 60) - -```` - -{{endregion}} - -If you are using data providers to bind the content of the **RichTextBox**, a new document will be created for every change in the string property which is the binding source. In that case, setting these properties should be done on **DocumentChanged**. - ->caution The value of the __SectionDefaultPageMarginProperty__ is respected when the __PageMargin__ property of a **Section** does not specify a value. When the document is measured, the value of the __SectionDefaultPageMarginProperty__ will be applied to the **Section** and further changes to the property will not affect the section. -> - -In order to change the margin of an already measured **Section**, you can use the following method: - -{{source=..\SamplesCS\RichTextEditor\FAQ.cs region=margin2}} -{{source=..\SamplesVB\RichTextEditor\FAQ.vb region=margin2}} - -````C# -radRichTextEditor1.Document.Sections.First.PageMargin = new Telerik.WinForms.Documents.Layout.Padding(0, 20, 100, 60); - -```` -````VB.NET -radRichTextEditor1.Document.Sections.First.PageMargin = New Telerik.WinForms.Documents.Layout.Padding(0, 20, 100, 60) - -```` - -{{endregion}} - -## Inserting multiple consecutive tables - -Inserting multiple [Table]({%slug winforms/richtexteditor-/document-elements/table%}) elements in a **RadDocument** one after another results in them being separated by some space. This may also happen when importing a document from one of the supported formats. The additional space is caused by an empty paragraph appended between the tables and is expected as **RadDocument**'s structure does not allow adjacent tables. - -When [building a document from code]({%slug winforms/richtexteditor-/getting-started%}), you should also follow the same approach and add paragraphs between tables in order to prevent possible issues from arising. - ->warning Removing paragraphs separating tables manually is highly inadvisable and may cause unexpected crashes. -> - +>caution The value of the __SectionDefaultPageMarginProperty__ is respected when the __PageMargin__ property of a **Section** does not specify a value. When the document is measured, the value of the __SectionDefaultPageMarginProperty__ will be applied to the **Section** and further changes to the property will not affect the section. +> + +In order to change the margin of an already measured **Section**, you can use the following method: + + + + + + +## Inserting multiple consecutive tables + +Inserting multiple [Table]({%slug winforms/richtexteditor-/document-elements/table%}) elements in a **RadDocument** one after another results in them being separated by some space. This may also happen when importing a document from one of the supported formats. The additional space is caused by an empty paragraph appended between the tables and is expected as **RadDocument**'s structure does not allow adjacent tables. + +When [building a document from code]({%slug winforms/richtexteditor-/getting-started%}), you should also follow the same approach and add paragraphs between tables in order to prevent possible issues from arising. + +>warning Removing paragraphs separating tables manually is highly inadvisable and may cause unexpected crashes. +> + diff --git a/controls/richtexteditor/getting-started/formatting-api.md b/controls/richtexteditor/getting-started/formatting-api.md index aacce6b7c..9320e0522 100644 --- a/controls/richtexteditor/getting-started/formatting-api.md +++ b/controls/richtexteditor/getting-started/formatting-api.md @@ -1,132 +1,78 @@ ---- -title: Formatting API -page_title: Getting Started with Formatting API - WinForms RichTextEditor Control -description: WinForms RichTextEditor is a control that allows you to display and edit rich text content including sections, paragraphs, spans, italic text, bold text, inline images, tables etc. -slug: winforms/richtexteditor-/getting-started/formatting-api -tags: formatting,api -published: True -position: 2 -previous_url: richtexteditor-getting-started-formatting-api ---- - -# Formatting API - -If you want to format the content of __RadRichTextEditor__ at run time, you have to use the API exposed by __RadRichTextEditor__. This is essential, as the main purpose of __RadRichTextEditor__ is to allow the users to format their input via UI. The UI should call the respective API methods of the control. - -## Changing the Text Formatting - -__RadRichTextEditor__ exposes methods that change the style of the selected text or the paragraph. When a method is called, the respective style is applied to the selected text. If there is no selection available, the style is applied to the word in which the caret is located. - -Here is an example of a toggle button that upon checking should make the selection or the current word bold. In the handler of the __Click__ event of __RadToggleButton__, the __ToggleBold()__ method of __RadRichTextEditor__ is called. - -{{source=..\SamplesCS\RichTextEditor\GettingStarted\FormatingAPI.cs region=bold}} -{{source=..\SamplesVB\RichTextEditor\GettingStarted\FormatingAPI.vb region=bold}} - -````C# +--- +title: Formatting API +page_title: Getting Started with Formatting API - WinForms RichTextEditor Control +description: WinForms RichTextEditor is a control that allows you to display and edit rich text content including sections, paragraphs, spans, italic text, bold text, inline images, tables etc. +slug: winforms/richtexteditor-/getting-started/formatting-api +tags: formatting,api +published: True +position: 2 +previous_url: richtexteditor-getting-started-formatting-api +--- + +# Formatting API + +If you want to format the content of __RadRichTextEditor__ at run time, you have to use the API exposed by __RadRichTextEditor__. This is essential, as the main purpose of __RadRichTextEditor__ is to allow the users to format their input via UI. The UI should call the respective API methods of the control. + +## Changing the Text Formatting + +__RadRichTextEditor__ exposes methods that change the style of the selected text or the paragraph. When a method is called, the respective style is applied to the selected text. If there is no selection available, the style is applied to the word in which the caret is located. + +Here is an example of a toggle button that upon checking should make the selection or the current word bold. In the handler of the __Click__ event of __RadToggleButton__, the __ToggleBold()__ method of __RadRichTextEditor__ is called. + + + + + + +## Using the active editor + +__RadRichTextEditor__ supports headers and footers. They are represented through separate instances of __RadRichTextEditor__. When a document has headers and footers you can use the __ActiveDocumentEditor__ property of __RadRichTextEditor__ to get the editor instance where the caret is currently situated. -private void togglebutton_Click(object sender, EventArgs e) -{ - this.radRichTextEditor.ToggleBold(); -} - -```` -````VB.NET -Private Sub togglebutton_Click(ByVal sender As Object, ByVal e As EventArgs) - Me.radRichTextEditor.ToggleBold() -End Sub - -```` - -{{endregion}} - - -## Using the active editor - -__RadRichTextEditor__ supports headers and footers. They are represented through separate instances of __RadRichTextEditor__. When a document has headers and footers you can use the __ActiveDocumentEditor__ property of __RadRichTextEditor__ to get the editor instance where the caret is currently situated. - ->tip You can find more about the Header and Footer functionality in [this article]({%slug winforms/richtexteditor-/features/headers-and-footers%}). -> - -The following example inserts the word "text" at the **CaretPosition**. - -{{source=..\SamplesCS\RichTextEditor\GettingStarted\FormatingAPI.cs region=insert}} -{{source=..\SamplesVB\RichTextEditor\GettingStarted\FormatingAPI.vb region=insert}} - -````C# +>tip You can find more about the Header and Footer functionality in [this article]({%slug winforms/richtexteditor-/features/headers-and-footers%}). +> + +The following example inserts the word "text" at the **CaretPosition**. + + + + + + +## Creating a DocumentFragment + +One of the common uses of the API is creating and inserting a __DocumentFragment__. Currently, you can create a fragment in two ways: + +* through __DocumentFragment__'s constructor; -this.radRichTextEditor.Insert("text"); - -```` -````VB.NET -Me.radRichTextEditor.Insert("text") - -```` - -{{endregion}} - -## Creating a DocumentFragment - -One of the common uses of the API is creating and inserting a __DocumentFragment__. Currently, you can create a fragment in two ways: - -* through __DocumentFragment__'s constructor; - -* through selection. - -Both approaches can be used to insert content at the caret position with the __InsertFragment__ method: - -{{source=..\SamplesCS\RichTextEditor\GettingStarted\FormatingAPI.cs region=fragment}} -{{source=..\SamplesVB\RichTextEditor\GettingStarted\FormatingAPI.vb region=fragment}} - -````C# +* through selection. -this.radRichTextEditor.InsertFragment(fragment); - -```` -````VB.NET -Me.radRichTextEditor.InsertFragment(fragment) - -```` - -{{endregion}} - -**Using the constructor of DocumentFragment** - -If you create a fragment in this way, it will end with a new paragraph. This is convenient when you want to separate the inserted fragment and end it with a new line. Furthermore, in this way if the last paragraph is in a list, it will appear properly in the new document. - -{{source=..\SamplesCS\RichTextEditor\GettingStarted\FormatingAPI.cs region=insert1}} -{{source=..\SamplesVB\RichTextEditor\GettingStarted\FormatingAPI.vb region=insert1}} - -````C# -DocumentFragment fragmentFromDocument = new DocumentFragment(this.radRichTextEditor.Document); - -```` -````VB.NET -Dim fragmentFromDocument As New DocumentFragment(Me.radRichTextEditor.Document) - -```` - -{{endregion}} - -This is also the suggested approach when merging several documents into one. - -**Using the selection** - -If you choose to use the document selection when creating a __DocumentFragment__, there will be no additional paragraph after the fragment. - -{{source=..\SamplesCS\RichTextEditor\GettingStarted\FormatingAPI.cs region=selection}} -{{source=..\SamplesVB\RichTextEditor\GettingStarted\FormatingAPI.vb region=selection}} - -````C# -DocumentFragment fragmentFromSelection = this.radRichTextEditor.Document.Selection.CopySelectedDocumentElements(); - -```` -````VB.NET -Dim fragmentFromSelection As DocumentFragment = Me.radRichTextEditor.Document.Selection.CopySelectedDocumentElements() - -```` - -{{endregion}} - -# See Also - - * [Import/Export]({%slug winforms/richtexteditor/import-export/overview%}) +Both approaches can be used to insert content at the caret position with the __InsertFragment__ method: + + + + + + +**Using the constructor of DocumentFragment** + +If you create a fragment in this way, it will end with a new paragraph. This is convenient when you want to separate the inserted fragment and end it with a new line. Furthermore, in this way if the last paragraph is in a list, it will appear properly in the new document. + + + + + + +This is also the suggested approach when merging several documents into one. + +**Using the selection** + +If you choose to use the document selection when creating a __DocumentFragment__, there will be no additional paragraph after the fragment. + + + + + + +# See Also + + * [Import/Export]({%slug winforms/richtexteditor/import-export/overview%}) diff --git a/controls/richtexteditor/getting-started/getting-started.md b/controls/richtexteditor/getting-started/getting-started.md index 9fdecff17..c6a7bef6d 100644 --- a/controls/richtexteditor/getting-started/getting-started.md +++ b/controls/richtexteditor/getting-started/getting-started.md @@ -53,108 +53,25 @@ The Telerik UI for WinForms assemblies can be install by using one of the availa You can declare a new __RadRichTextEditor__ as any normal WinForms control. -{{source=..\SamplesCS\RichTextEditor\GettingStarted\Main.cs region=declare}} -{{source=..\SamplesVB\RichTextEditor\GettingStarted\Main.vb region=declare}} + + -````C# -private RadRichTextEditor radRichTextEditor1 = new RadRichTextEditor(); -```` -````VB.NET -Private radRichTextEditor1 As New RadRichTextEditor() - -```` - -{{endregion}} ## Formatting via a sample UI If you want to allow the user to edit and format the content of __RadRichTextEditor__, you have to create UI and use the API exposed by __RadRichTextEditor__. The __API__ exposes methods (like __ToggleBold()__, __ToggleItalic()__ etc.) that modify the text in the control when called. Here is an example of using the API for making the text bold, italic and underlined. -{{source=..\SamplesCS\RichTextEditor\GettingStarted\Main.cs region=API}} -{{source=..\SamplesVB\RichTextEditor\GettingStarted\Main.vb region=API}} - -````C# -private void BoldButton_Click(object sender, RoutedEventArgs e) -{ - this.radRichTextEditor1.ToggleBold(); - this.radRichTextEditor1.Focus(); //return focus to the control -} -private void ItalicButton_Click(object sender, RoutedEventArgs e) -{ - this.radRichTextEditor1.ToggleItalic(); - this.radRichTextEditor1.Focus(); //return focus to the control -} -private void UnderlineButton_Click(object sender, RoutedEventArgs e) -{ - this.radRichTextEditor1.ToggleUnderline(); - this.radRichTextEditor1.Focus(); //return focus to the control -} - -```` -````VB.NET -Private Sub BoldButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) - Me.radRichTextEditor1.ToggleBold() - Me.radRichTextEditor1.Focus() 'return focus to the control -End Sub -Private Sub ItalicButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) - Me.radRichTextEditor1.ToggleItalic() - Me.radRichTextEditor1.Focus() 'return focus to the control -End Sub -Private Sub UnderlineButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) - Me.radRichTextEditor1.ToggleUnderline() - Me.radRichTextEditor1.Focus() 'return focus to the control -End Sub - -```` - -{{endregion}} + + + + The UI should also respond when the caret is on a document position where the text is modified. For example, the BoldButton should be toggled if the caret is on bold text. This can be done by handling the **ToggleStateChanged** event. Here is an example: -{{source=..\SamplesCS\RichTextEditor\GettingStarted\Main.cs region=commands}} -{{source=..\SamplesVB\RichTextEditor\GettingStarted\Main.vb region=commands}} - -````C# -void Main_Load(object sender, EventArgs e) -{ - this.radRichTextEditor1.Commands.ToggleBoldCommand.ToggleStateChanged += new EventHandler>(this.ToggleBoldCommand_ToggleStateChanged); - this.radRichTextEditor1.Commands.ToggleItalicCommand.ToggleStateChanged += new EventHandler>(this.ToggleItalicCommand_ToggleStateChanged); - this.radRichTextEditor1.Commands.ToggleUnderlineCommand.ToggleStateChanged += new EventHandler>(this.ToggleUnderlineCommand_ToggleStateChanged); -} -private void ToggleBoldCommand_ToggleStateChanged(object sender, Telerik.WinForms.Documents.RichTextBoxCommands.StylePropertyChangedEventArgs e) -{ - this.BoldButton.IsChecked = e.NewValue; -} -private void ToggleUnderlineCommand_ToggleStateChanged(object sender, Telerik.WinForms.Documents.RichTextBoxCommands.StylePropertyChangedEventArgs e) -{ - this.UnderlineButton.IsChecked = e.NewValue; -} -private void ToggleItalicCommand_ToggleStateChanged(object sender, Telerik.WinForms.Documents.RichTextBoxCommands.StylePropertyChangedEventArgs e) -{ - this.ItalicButton.IsChecked = e.NewValue; -} - -```` -````VB.NET -Private Sub Main_Load(ByVal sender As Object, ByVal e As EventArgs) - AddHandler radRichTextEditor1.Commands.ToggleBoldCommand.ToggleStateChanged, AddressOf ToggleBoldCommand_ToggleStateChanged - AddHandler radRichTextEditor1.Commands.ToggleItalicCommand.ToggleStateChanged, AddressOf ToggleItalicCommand_ToggleStateChanged - AddHandler radRichTextEditor1.Commands.ToggleUnderlineCommand.ToggleStateChanged, AddressOf ToggleUnderlineCommand_ToggleStateChanged -End Sub -Private Sub ToggleBoldCommand_ToggleStateChanged(ByVal sender As Object, ByVal e As Telerik.WinForms.Documents.RichTextBoxCommands.StylePropertyChangedEventArgs(Of Boolean)) - Me.BoldButton.IsChecked = e.NewValue -End Sub -Private Sub ToggleUnderlineCommand_ToggleStateChanged(ByVal sender As Object, ByVal e As Telerik.WinForms.Documents.RichTextBoxCommands.StylePropertyChangedEventArgs(Of Boolean)) - Me.UnderlineButton.IsChecked = e.NewValue -End Sub -Private Sub ToggleItalicCommand_ToggleStateChanged(ByVal sender As Object, ByVal e As Telerik.WinForms.Documents.RichTextBoxCommands.StylePropertyChangedEventArgs(Of Boolean)) - Me.ItalicButton.IsChecked = e.NewValue -End Sub - -```` - -{{endregion}} + + + ![WinForms RadRichTextEditor Format](images/richtexteditor-getting-started001.png) @@ -179,119 +96,10 @@ The whole hierarchy of the elements can be found [here]({%slug winforms/richtext Here is an example of a document created from code-behind: -{{source=..\SamplesCS\RichTextEditor\GettingStarted\Main.cs region=code}} -{{source=..\SamplesVB\RichTextEditor\GettingStarted\Main.vb region=code}} - -````C# -RadDocument document = new RadDocument(); -Section section = new Section(); -Paragraph paragraph1 = new Paragraph(); -paragraph1.TextAlignment = Telerik.WinForms.Documents.Layout.RadTextAlignment.Center; -Span span1 = new Span("Thank you for choosing Telerik"); -paragraph1.Inlines.Add(span1); -Span span2 = new Span(); -span2.Text = " RadRichTextEditor!"; -span2.FontWeight = Telerik.WinControls.RichTextEditor.UI.FontWeights.Bold; -paragraph1.Inlines.Add(span2); -section.Blocks.Add(paragraph1); -Paragraph paragraph2 = new Paragraph(); -Span span3 = new Span("RadRichTextEditor"); -span3.FontWeight = Telerik.WinControls.RichTextEditor.UI.FontWeights.Bold; -paragraph2.Inlines.Add(span3); -Span span4 = new Span(" is a control that is able to display and edit rich-text content including formatted text arranged in pages, paragraphs, spans (runs) etc."); -paragraph2.Inlines.Add(span4); -section.Blocks.Add(paragraph2); -Table table = new Table(); -table.LayoutMode = TableLayoutMode.AutoFit; -table.StyleName = RadDocumentDefaultStyles.DefaultTableGridStyleName; -TableRow row1 = new TableRow(); -TableCell cell1 = new TableCell(); -Paragraph p1 = new Paragraph(); -Span s1 = new Span(); -s1.Text = "Cell 1"; -p1.Inlines.Add(s1); -cell1.Blocks.Add(p1); -row1.Cells.Add(cell1); -TableCell cell2 = new TableCell(); -Paragraph p2 = new Paragraph(); -Span s2 = new Span(); -s2.Text = "Cell 2"; -p2.Inlines.Add(s2); -cell2.Blocks.Add(p2); -row1.Cells.Add(cell2); -table.Rows.Add(row1); -TableRow row2 = new TableRow(); -TableCell cell3 = new TableCell(); -cell3.ColumnSpan = 2; -Paragraph p3 = new Paragraph(); -Span s3 = new Span(); -s3.Text = "Cell 3"; -p3.Inlines.Add(s3); -cell3.Blocks.Add(p3); -row2.Cells.Add(cell3); -table.Rows.Add(row2); -section.Blocks.Add(table); -section.Blocks.Add(new Paragraph()); -document.Sections.Add(section); -this.radRichTextEditor1.Document = document; - -```` -````VB.NET -Dim document As New RadDocument() -Dim section As New Section() -Dim paragraph1 As New Paragraph() -paragraph1.TextAlignment = Telerik.WinForms.Documents.Layout.RadTextAlignment.Center -Dim span1 As New Span("Thank you for choosing Telerik") -paragraph1.Inlines.Add(span1) -Dim span2 As New Span() -span2.Text = " radRichTextEditor1!" -span2.FontWeight = Telerik.WinControls.RichTextEditor.UI.FontWeights.Bold -paragraph1.Inlines.Add(span2) -section.Blocks.Add(paragraph1) -Dim paragraph2 As New Paragraph() -Dim span3 As New Span("radRichTextEditor1") -span3.FontWeight = Telerik.WinControls.RichTextEditor.UI.FontWeights.Bold -paragraph2.Inlines.Add(span3) -Dim span4 As New Span(" is a control that is able to display and edit rich-text content including formatted text arranged in pages, paragraphs, spans (runs) etc.") -paragraph2.Inlines.Add(span4) -section.Blocks.Add(paragraph2) -Dim table As New Table() -table.LayoutMode = TableLayoutMode.AutoFit -table.StyleName = RadDocumentDefaultStyles.DefaultTableGridStyleName -Dim row1 As New TableRow() -Dim cell1 As New TableCell() -Dim p1 As New Paragraph() -Dim s1 As New Span() -s1.Text = "Cell 1" -p1.Inlines.Add(s1) -cell1.Blocks.Add(p1) -row1.Cells.Add(cell1) -Dim cell2 As New TableCell() -Dim p2 As New Paragraph() -Dim s2 As New Span() -s2.Text = "Cell 2" -p2.Inlines.Add(s2) -cell2.Blocks.Add(p2) -row1.Cells.Add(cell2) -table.Rows.Add(row1) -Dim row2 As New TableRow() -Dim cell3 As New TableCell() -cell3.ColumnSpan = 2 -Dim p3 As New Paragraph() -Dim s3 As New Span() -s3.Text = "Cell 3" -p3.Inlines.Add(s3) -cell3.Blocks.Add(p3) -row2.Cells.Add(cell3) -table.Rows.Add(row2) -section.Blocks.Add(table) -section.Blocks.Add(New Paragraph()) -document.Sections.Add(section) -Me.radRichTextEditor1.Document = document - -```` - -{{endregion}} + + + + ![WinForms RadRichTextEditor Sample Document](images/richtexteditor-getting-started002.png) diff --git a/controls/richtexteditor/getting-started/use-as-rich-content-viewer.md b/controls/richtexteditor/getting-started/use-as-rich-content-viewer.md index a22a2835c..7225b0d7f 100644 --- a/controls/richtexteditor/getting-started/use-as-rich-content-viewer.md +++ b/controls/richtexteditor/getting-started/use-as-rich-content-viewer.md @@ -13,20 +13,10 @@ previous_url: richtexteditor-getting-started-use-as-rich-content-viewer To use __RadRichTextEditor__ as a rich content viewer you have to disable the user from editing its content. This is done via the __IsReadOnly__ property. You just have to set it to *true*. -{{source=..\SamplesCS\RichTextEditor\GettingStarted\FormatingAPI.cs region=readonly}} -{{source=..\SamplesVB\RichTextEditor\GettingStarted\FormatingAPI.vb region=readonly}} + + -````C# - -this.radRichTextEditor.IsReadOnly = true; -```` -````VB.NET -Me.radRichTextEditor.IsReadOnly = True - -```` - -{{endregion}} In addition to the __IsReadOnly__ property, there are several other properties that can be used to control the response of __RadRichTextEditor__ towards the user actions against it: diff --git a/controls/richtexteditor/how-to/customize-presentation-through-ui-layers.md b/controls/richtexteditor/how-to/customize-presentation-through-ui-layers.md index f4c428f3a..a94b5069f 100644 --- a/controls/richtexteditor/how-to/customize-presentation-through-ui-layers.md +++ b/controls/richtexteditor/how-to/customize-presentation-through-ui-layers.md @@ -1,117 +1,54 @@ ---- -title: Customize Presentation through UI Layers -page_title: Customize Presentation through UI Layers - WinForms RichTextEditor Control -description: UILayers provide an extensible approach to showing different parts of WinForms RichTextEditor Document. -slug: winforms/richtexteditor-/how-to/customize-presentation-through-ui-layers -tags: customize,presentation,through,ui,layers -published: True -position: 0 -previous_url: richtexteditor-how-to-customize-presentation-trought-ui-layers ---- - -# Customize Presentation through UI Layers - -__UILayers__ provide an extensible approach to showing different parts of __RadRichTextEditor__ Document. For example, there are separate layers showing the comments, the selection, the table borders, etc. - -The existing layers can be removed and additional ones can be defined to customize the presentation of different parts of the document. - -All UILayers implement the __IUILayer__ interface. There is an abstract class, which implements this interface - __DecorationUILayerBase__, and by inheriting it, you can easily define a new layer for custom representations of your document’s layout. The main method to put your logic in is: - -{{source=..\SamplesCS\RichTextEditor\HowTo\UILayers.cs region=override}} -{{source=..\SamplesVB\RichTextEditor\HowTo\UILayers.vb region=override}} - -````C# -public override void UpdateUIViewPortOverride(UILayerUpdateContext context) - -```` -````VB.NET -Public Overrides Sub UpdateUIViewPortOverride(ByVal context As UILayerUpdateContext) - -```` - -{{endregion}} - -You can use the context which is passed as a parameter to the method to get all visible layout boxes and perform your decorations and customizations on them. You can also use the __Document__ property that your decoration layer inherits from __DecorationUILayerBase__ and everything that comes with it (like the current **CaretPosition**). - -Last but not least, you should not forget to override the **Name** property of the layer like this: - -{{source=..\SamplesCS\RichTextEditor\HowTo\UILayers.cs region=name}} -{{source=..\SamplesVB\RichTextEditor\HowTo\UILayers.vb region=name}} - -````C# -public override string Name -{ - get - { - return this.customLayerName; - } -} - -```` -````VB.NET -Public Overrides ReadOnly Property Name() As String - Get - Return Me.customLayerName - End Get -End Property - -```` - -{{endregion}} - -After having implemented the logic of your custom UI layer, you can plug it in the editor by creating a __CustomUILayerBuilder__. - -{{source=..\SamplesCS\RichTextEditor\HowTo\UILayers.cs region=builder}} -{{source=..\SamplesVB\RichTextEditor\HowTo\UILayers.vb region=builder}} - -````C# -public class CustomLayersBuilder : UILayersBuilder - -```` -````VB.NET -Public Class CustomLayersBuilder - Inherits UILayersBuilder - -```` - -{{endregion}} - -You can assign the new builder to specific instance of **RadRichTextEditor** like this: - -{{source=..\SamplesCS\RichTextEditor\HowTo\UILayers.cs region=change}} -{{source=..\SamplesVB\RichTextEditor\HowTo\UILayers.vb region=change}} - -````C# -this.radRichTextEditor1.RichTextBoxElement.UILayersBuilder = new CustomLayersBuilder(); - -```` -````VB.NET -Me.radRichTextEditor1.RichTextBoxElement.UILayersBuilder = New CustomLayersBuilder() - -```` - -{{endregion}} - -All that is left is to specify the place of your layer, i.e. which layers should be shown above and which - below your layer. This is done in the __BuildUILayersOverride__ method. For example, a layer can be shown under the selection, after the highlighting layer in the following way: - -{{source=..\SamplesCS\RichTextEditor\HowTo\UILayers.cs region=overrideBuild}} -{{source=..\SamplesVB\RichTextEditor\HowTo\UILayers.vb region=overrideBuild}} - -````C# -protected override void BuildUILayersOverride(IUILayerContainer uiLayerContainer) -{ - uiLayerContainer.UILayers.AddAfter(DefaultUILayers.HighlightDecoration, new CustomDecorationUILayerBase()); -} - -```` -````VB.NET -Protected Overrides Sub BuildUILayersOverride(ByVal uiLayerContainer As IUILayerContainer) - uiLayerContainer.UILayers.AddAfter(DefaultUILayers.HighlightDecoration, New CustomDecorationUILayerBase()) -End Sub - -```` - -{{endregion}} - - - +--- +title: Customize Presentation through UI Layers +page_title: Customize Presentation through UI Layers - WinForms RichTextEditor Control +description: UILayers provide an extensible approach to showing different parts of WinForms RichTextEditor Document. +slug: winforms/richtexteditor-/how-to/customize-presentation-through-ui-layers +tags: customize,presentation,through,ui,layers +published: True +position: 0 +previous_url: richtexteditor-how-to-customize-presentation-trought-ui-layers +--- + +# Customize Presentation through UI Layers + +__UILayers__ provide an extensible approach to showing different parts of __RadRichTextEditor__ Document. For example, there are separate layers showing the comments, the selection, the table borders, etc. + +The existing layers can be removed and additional ones can be defined to customize the presentation of different parts of the document. + +All UILayers implement the __IUILayer__ interface. There is an abstract class, which implements this interface - __DecorationUILayerBase__, and by inheriting it, you can easily define a new layer for custom representations of your document’s layout. The main method to put your logic in is: + + + + + + +You can use the context which is passed as a parameter to the method to get all visible layout boxes and perform your decorations and customizations on them. You can also use the __Document__ property that your decoration layer inherits from __DecorationUILayerBase__ and everything that comes with it (like the current **CaretPosition**). + +Last but not least, you should not forget to override the **Name** property of the layer like this: + + + + + + +After having implemented the logic of your custom UI layer, you can plug it in the editor by creating a __CustomUILayerBuilder__. + + + + + + +You can assign the new builder to specific instance of **RadRichTextEditor** like this: + + + + + + +All that is left is to specify the place of your layer, i.e. which layers should be shown above and which - below your layer. This is done in the __BuildUILayersOverride__ method. For example, a layer can be shown under the selection, after the highlighting layer in the following way: + + + + + + diff --git a/controls/richtexteditor/how-to/drag-and-drop.md b/controls/richtexteditor/how-to/drag-and-drop.md index 17cc72dd9..7cba8ad28 100644 --- a/controls/richtexteditor/how-to/drag-and-drop.md +++ b/controls/richtexteditor/how-to/drag-and-drop.md @@ -20,47 +20,10 @@ Like other standard WinForms controls **RadRichTextEditor** also supports drag a #### Initial Controls Setup -{{source=..\SamplesCS\RichTextEditor\HowTo\RadRichTextEditorDragAndDropForm.cs region=SetupControls}} -{{source=..\SamplesVB\RichTextEditor\HowTo\RadRichTextEditorDragAndDropForm.vb region=SetupControls}} -````C# -public RadRichTextEditorDragAndDropForm() -{ - InitializeComponent(); - this.radListView1.ListViewElement.DragDropService.PreviewDragOver += DragDropService_PreviewDragOver; - this.radListView1.ListViewElement.DragDropService.PreviewDragDrop += DragDropService_PreviewDragDrop; - this.radRichTextEditor1.RichTextBoxElement.AllowDrop = true; - this.radListView1.Items.Add("London"); - this.radListView1.Items.Add("Madrid"); - this.radListView1.Items.Add("Paris"); - this.radListView1.Items.Add("Sofia"); - this.radListView1.Items.Add("Berlin"); - this.radListView1.Items.Add("Moscow"); - this.radListView1.Items.Add("Rome"); - this.radListView1.Items.Add("Athens"); -} - -```` -````VB.NET -Public Sub New() - InitializeComponent() - AddHandler Me.radListView1.ListViewElement.DragDropService.PreviewDragOver, AddressOf DragDropService_PreviewDragOver - AddHandler Me.radListView1.ListViewElement.DragDropService.PreviewDragDrop, AddressOf DragDropService_PreviewDragDrop - Me.radRichTextEditor1.RichTextBoxElement.AllowDrop = True - Me.radListView1.Items.Add("London") - Me.radListView1.Items.Add("Madrid") - Me.radListView1.Items.Add("Paris") - Me.radListView1.Items.Add("Sofia") - Me.radListView1.Items.Add("Berlin") - Me.radListView1.Items.Add("Moscow") - Me.radListView1.Items.Add("Rome") - Me.radListView1.Items.Add("Athens") -End Sub - -```` - - - -{{endregion}} + + + + ## Handling Events @@ -68,96 +31,19 @@ In the **PreviewDragOver** event one needs to first focus the control so that th #### PreviewDragOver Event -{{source=..\SamplesCS\RichTextEditor\HowTo\RadRichTextEditorDragAndDropForm.cs region=DragOverEvent}} -{{source=..\SamplesVB\RichTextEditor\HowTo\RadRichTextEditorDragAndDropForm.vb region=DragOverEvent}} -````C# -private void DragDropService_PreviewDragOver(object sender, Telerik.WinControls.RadDragOverEventArgs e) -{ - if (e.HitTarget is Telerik.WinForms.RichTextEditor.RadRichTextBox) - { - e.CanDrop = true; - if (!this.radRichTextEditor1.Focused) - { - this.radRichTextEditor1.Focus(); - } - DocumentPosition position = this.radRichTextEditor1.RichTextBoxElement.ActiveEditorPresenter.GetDocumentPositionFromViewPoint(this.GetPosition(System.Windows.Forms.Control.MousePosition, - this.radRichTextEditor1.RichTextBoxElement)); - this.radRichTextEditor1.Document.CaretPosition.MoveToPosition(position); - } -} -private Telerik.WinControls.RichTextEditor.UI.Point GetPosition(System.Drawing.Point mousePoint, Telerik.WinControls.RichTextEditor.UI.UIElement element) -{ - System.Drawing.Point point = element.PointFromScreen(mousePoint); - Telerik.WinControls.Layouts.RadMatrix matrix = element.TotalTransform; - matrix.Invert(); - return new System.Drawing.PointF(point.X * matrix.ScaleX, point.Y * matrix.ScaleY); -} - -```` -````VB.NET -Private Sub DragDropService_PreviewDragOver(ByVal sender As Object, ByVal e As Telerik.WinControls.RadDragOverEventArgs) - If TypeOf e.HitTarget Is Telerik.WinForms.RichTextEditor.RadRichTextBox Then - e.CanDrop = True - If Not Me.radRichTextEditor1.Focused Then - Me.radRichTextEditor1.Focus() - End If - Dim position As DocumentPosition = Me.radRichTextEditor1.RichTextBoxElement.ActiveEditorPresenter.GetDocumentPositionFromViewPoint(Me.GetPosition(System.Windows.Forms.Control.MousePosition, Me.radRichTextEditor1.RichTextBoxElement)) - Me.radRichTextEditor1.Document.CaretPosition.MoveToPosition(position) - End If -End Sub -Private Function GetPosition(ByVal mousePoint As System.Drawing.Point, ByVal element As Telerik.WinControls.RichTextEditor.UI.UIElement) As Telerik.WinControls.RichTextEditor.UI.Point - Dim point As System.Drawing.Point = element.PointFromScreen(mousePoint) - Dim matrix As Telerik.WinControls.Layouts.RadMatrix = element.TotalTransform - matrix.Invert() - Return New System.Drawing.PointF(point.X * matrix.ScaleX, point.Y * matrix.ScaleY) -End Function - -```` - - - -{{endregion}} + + + + The **PreviewDragDrop** event will be handled so that a text is inserted inside the document. #### PreviewDragDrop Event -{{source=..\SamplesCS\RichTextEditor\HowTo\RadRichTextEditorDragAndDropForm.cs region=DragDropEvent}} -{{source=..\SamplesVB\RichTextEditor\HowTo\RadRichTextEditorDragAndDropForm.vb region=DragDropEvent}} -````C# -private void DragDropService_PreviewDragDrop(object sender, Telerik.WinControls.RadDropEventArgs e) -{ - BaseListViewVisualItem draggedItem = e.DragInstance as BaseListViewVisualItem; - Telerik.WinForms.RichTextEditor.RadRichTextBox radRichTextBox = e.HitTarget as Telerik.WinForms.RichTextEditor.RadRichTextBox; - if (radRichTextBox == null) - { - return; - } - RadDocumentEditor editor = new RadDocumentEditor(this.radRichTextEditor1.Document); - editor.Insert(" "); - editor.Insert(draggedItem.Text); - e.Handled = true; -} - -```` -````VB.NET -Private Sub DragDropService_PreviewDragDrop(ByVal sender As Object, ByVal e As Telerik.WinControls.RadDropEventArgs) - Dim draggedItem As BaseListViewVisualItem = TryCast(e.DragInstance, BaseListViewVisualItem) - Dim radRichTextBox As Telerik.WinForms.RichTextEditor.RadRichTextBox = TryCast(e.HitTarget, Telerik.WinForms.RichTextEditor.RadRichTextBox) - If radRichTextBox Is Nothing Then - Return - End If - Dim editor As RadDocumentEditor = New RadDocumentEditor(Me.radRichTextEditor1.Document) - editor.Insert(" ") - editor.Insert(draggedItem.Text) - e.Handled = True -End Sub - -```` - - - -{{endregion}} + + + + # See Also diff --git a/controls/richtexteditor/how-to/repalce-default-dialogs.md b/controls/richtexteditor/how-to/repalce-default-dialogs.md index 7f6d6c321..61fe54b1e 100644 --- a/controls/richtexteditor/how-to/repalce-default-dialogs.md +++ b/controls/richtexteditor/how-to/repalce-default-dialogs.md @@ -21,153 +21,31 @@ This article will demonstrate how you can replace the default __FindAndRepacle__ 2\. Open the code behind and add event handler for the button. You can add a method that will perform the search as well: -{{source=..\SamplesCS\RichTextEditor\HowTo\FindAllDialog.cs region=search}} -{{source=..\SamplesVB\RichTextEditor\HowTo\FindAllDialog.vb region=search}} - -````C# - -private void radButton1_Click(object sender, EventArgs e) -{ - string textToFind = radTextBox1.Text; - SelectAllMatches(textToFind); - var color = radColorBox1.Value; - richTextBox.ChangeTextHighlightColor(color); - this.richTextBox.Document.Selection.Clear(); -} - -private void SelectAllMatches(string toSearch) -{ - this.richTextBox.Document.Selection.Clear(); - DocumentTextSearch search = new DocumentTextSearch(this.richTextBox.Document); - foreach (var textRange in search.FindAll(toSearch)) - { - this.richTextBox.Document.Selection.AddSelectionStart(textRange.StartPosition); - this.richTextBox.Document.Selection.AddSelectionEnd(textRange.EndPosition); - } -} - -```` -````VB.NET -Private Sub radButton1_Click(ByVal sender As Object, ByVal e As EventArgs) - Dim textToFind As String = radTextBox1.Text - SelectAllMatches(textToFind) - Dim color = radColorBox1.Value - richTextBox.ChangeTextHighlightColor(color) - Me.richTextBox.Document.Selection.Clear() -End Sub -Private Sub SelectAllMatches(ByVal toSearch As String) - Me.richTextBox.Document.Selection.Clear() - Dim search As New DocumentTextSearch(Me.richTextBox.Document) - For Each textRange In search.FindAll(toSearch) - Me.richTextBox.Document.Selection.AddSelectionStart(textRange.StartPosition) - Me.richTextBox.Document.Selection.AddSelectionEnd(textRange.EndPosition) - Next textRange -End Sub - -```` - -{{endregion}} + + -3\. The new dialog need to implement the __IFindReplaceDialog__ otherwise you cannot replace the default one. So go ahead and add the interface to the form's class declaration: -{{source=..\SamplesCS\RichTextEditor\HowTo\FindAllDialog.cs region=declare}} -{{source=..\SamplesVB\RichTextEditor\HowTo\FindAllDialog.vb region=declare}} -````C# - -public partial class FindAllDialog : RadForm, IFindReplaceDialog +3\. The new dialog need to implement the __IFindReplaceDialog__ otherwise you cannot replace the default one. So go ahead and add the interface to the form's class declaration: -```` -````VB.NET -Partial Public Class FindAllDialog - Inherits RadForm - Implements IFindReplaceDialog + + -```` -{{endregion}} Now, you are ready to add the required fields, property and methods: -{{source=..\SamplesCS\RichTextEditor\HowTo\FindAllDialog.cs region=interface}} -{{source=..\SamplesVB\RichTextEditor\HowTo\FindAllDialog.vb region=interface}} + + -````C# - -RadRichTextBox richTextBox; -bool isOpen; - -public bool IsOpen -{ - get - { - return this.isOpen; - } -} - -public void Show(RadRichTextBox richTextBox, Func replaceCallback, string textToFind) -{ - this.Owner = richTextBox.ElementTree.Control.FindForm(); - this.richTextBox = richTextBox; - this.Show(); -} - -protected override void OnShown(EventArgs e) -{ - this.isOpen = true; - base.OnShown(e); -} - -protected override void OnActivated(EventArgs e) -{ - this.isOpen = false; - base.OnActivated(e); -} - -```` -````VB.NET -Private richTextBox As RadRichTextBox -Private _isOpen As Boolean -Public ReadOnly Property IsOpen() As Boolean Implements IFindReplaceDialog.IsOpen - Get - Return Me._isOpen - End Get -End Property -Public Sub Show(ByVal richTextBox As RadRichTextBox, ByVal replaceCallback As Func(Of String, Boolean), ByVal textToFind As String) Implements IFindReplaceDialog.Show - Me.Owner = richTextBox.ElementTree.Control.FindForm() - Me.richTextBox = richTextBox - MyBase.Show() -End Sub -Public Sub Close() Implements IFindReplaceDialog.Close -End Sub -Protected Overrides Sub OnShown(ByVal e As EventArgs) - Me._isOpen = True - MyBase.OnShown(e) -End Sub -Protected Overrides Sub OnActivated(ByVal e As EventArgs) - Me._isOpen = False - MyBase.OnActivated(e) -End Sub - -```` - -{{endregion}} - -4\. The final step is to assign a new instance of the dialog to the corresponding property: -{{source=..\SamplesCS\RichTextEditor\HowTo\ChangeDefaultDialogs.cs region=assign}} -{{source=..\SamplesVB\RichTextEditor\HowTo\ChangeDefaultDialogs.vb region=assign}} -````C# -radRichTextEditor1.RichTextBoxElement.FindReplaceDialog = new FindAllDialog(); +4\. The final step is to assign a new instance of the dialog to the corresponding property: -```` -````VB.NET -radRichTextEditor1.RichTextBoxElement.FindReplaceDialog = New FindAllDialog() + + -```` -{{endregion}} ## Dialogs that can be replaced diff --git a/controls/richtexteditor/import-export/docx/docxformatprovider.md b/controls/richtexteditor/import-export/docx/docxformatprovider.md index a8f0b98c2..76ca60832 100644 --- a/controls/richtexteditor/import-export/docx/docxformatprovider.md +++ b/controls/richtexteditor/import-export/docx/docxformatprovider.md @@ -20,101 +20,37 @@ All you have to do in order to use DocxFormatProvider is to reference the **Tele In order to import a __.docx__ file, you need to use the Import() method of DocxFormatProvider. The code example shows how to use __DocxFormatProvider__ to import a Docx document from a file. #### Import Document from a File -{{source=..\SamplesCS\RichTextEditor\ImportExport\DocxFormatProviderForm.cs region=ImportDocumentFromFile}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\DocxFormatProviderForm.vb region=ImportDocumentFromFile}} -````C# -DocxFormatProvider provider = new DocxFormatProvider(); -using (FileStream inputStream = File.OpenRead(@"..\..\RichTextEditor\ImportExport\Sample.docx")) -{ - this.radRichTextEditor1.Document = provider.Import(inputStream); -} + + -```` -````VB.NET -Dim provider As DocxFormatProvider = New DocxFormatProvider() -Using inputStream As FileStream = File.OpenRead("..\..\RichTextEditor\ImportExport\Sample.docx") - Me.radRichTextEditor1.Document = provider.Import(inputStream) -End Using -```` - - - -{{endregion}} And here is how you can import a document from byte array containing the Docx document: #### Import Document from a Byte Array -{{source=..\SamplesCS\RichTextEditor\ImportExport\DocxFormatProviderForm.cs region=ImportDocumentFromByteArray}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\DocxFormatProviderForm.vb region=ImportDocumentFromByteArray}} -````C# -DocxFormatProvider provider = new DocxFormatProvider(); -byte[] input = File.ReadAllBytes(@"..\..\RichTextEditor\ImportExport\Sample.docx"); -this.radRichTextEditor1.Document = provider.Import(input); - -```` -````VB.NET -Dim provider As DocxFormatProvider = New DocxFormatProvider() -Dim input As Byte() = File.ReadAllBytes("..\..\RichTextEditor\ImportExport\Sample.docx") -Me.radRichTextEditor1.Document = provider.Import(input) - -```` - + + -{{endregion}} ## Export In order to export a document to DOCX, you need to use the Export() method of DocxFormatProvider. The example shows how to use __DocxFormatProvider__ to export __RadDocument__ to a file. #### Export Document to a File -{{source=..\SamplesCS\RichTextEditor\ImportExport\DocxFormatProviderForm.cs region=ExportDocumentToFile}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\DocxFormatProviderForm.vb region=ExportDocumentToFile}} -````C# -DocxFormatProvider provider = new DocxFormatProvider(); -using (FileStream output = File.OpenWrite("Sample.docx")) -{ - RadDocument document = this.radRichTextEditor1.Document; - provider.Export(document, output); -} + + -```` -````VB.NET -Dim provider As DocxFormatProvider = New DocxFormatProvider() -Using output As FileStream = File.OpenWrite("Sample.docx") - Dim document As RadDocument = Me.radRichTextEditor1.Document - provider.Export(document, output) -End Using -```` - - - -{{endregion}} You can also export the document to a byte array and preserve it in a database. #### Export Document to a Byte Array -{{source=..\SamplesCS\RichTextEditor\ImportExport\DocxFormatProviderForm.cs region=ExportDocumentToByteArray}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\DocxFormatProviderForm.vb region=ExportDocumentToByteArray}} -````C# -DocxFormatProvider provider = new DocxFormatProvider(); -RadDocument document = this.radRichTextEditor1.Document; -byte[] output = provider.Export(document); - -```` -````VB.NET -Dim provider As DocxFormatProvider = New DocxFormatProvider() -Dim document As RadDocument = Me.radRichTextEditor1.Document -Dim output As Byte() = provider.Export(document) - -```` - + + -{{endregion}} The resulting documents can be opened in any application that supports DOCX documents. diff --git a/controls/richtexteditor/import-export/docx/settings.md b/controls/richtexteditor/import-export/docx/settings.md index 05302ad51..237bde20f 100644 --- a/controls/richtexteditor/import-export/docx/settings.md +++ b/controls/richtexteditor/import-export/docx/settings.md @@ -1,49 +1,35 @@ ---- -title: Settings -page_title: Settings - WinForms RichTextEditor Control -description: DocxFormatProvider allows import of DOCX documents and respectively export of RadDocument to DOCX. -slug: winforms/richtexteditor/import-export/docx/settings -tags: import/export -published: True -position: 1 ---- - -# Settings - -__DocxFormatProvider__ allows for import of DOCX documents and respectively export of RadDocument to DOCX. Additionally, the export settings provide modification options. The current article outlines the available settings. - -## Export Settings - -__DocxFormatProvider__ exposes __ExportSettings__, which allow customization in how fields are exported. By default, all fields are exported using their result value in the docx document. If you would like to save the document of the editor as a mail merge template and not include the value of the current item of the __MailMergeDataSource__, a new instance of __DocxExportSettings__ should be created and assigned to the format provider. The value of the __FieldResultMode__ of these settings must be set to __FieldDisplayMode.DisplayName__. - -#### DocxFormatProvider Settings - -{{source=..\SamplesCS\RichTextEditor\ImportExport\DocxFormatProviderForm.cs region=DocxFormatProvider}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\DocxFormatProviderForm.vb region=DocxFormatProvider}} -````C# -DocxFormatProvider docxFormatProvider = DocumentFormatProvidersManager.GetProviderByExtension("docx") as DocxFormatProvider; -DocxExportSettings docxExportSettings = new DocxExportSettings(); -docxFormatProvider.ExportSettings = docxExportSettings; - -```` -````VB.NET -Dim docxFormatProvider As DocxFormatProvider = TryCast(DocumentFormatProvidersManager.GetProviderByExtension("docx"), DocxFormatProvider) -Dim docxExportSettings As DocxExportSettings = New DocxExportSettings() -docxFormatProvider.ExportSettings = docxExportSettings - -```` - - - -{{endregion}} - -The __FieldResultMode__ property of the __DocxExportSettings__ is an enumeration and it allows the following values: -* __Code__: Shows all fields codes in the current document. -* __DisplayName__: Shows all fields names in the current document. -* __Result__: Replaces the merge fields in your document with actual data from your recipient list. -* __Null__: When the **FieldResultMode** is set to *null*, fields' display mode is not changed. This can provide a better performance and lower memory usage while exporting. - -## See Also - - * [Getting Started]({%slug winforms/richtexteditor-/getting-started%}) - * [Using DocxFormatProvider]({%slug winforms/richtexteditor/import-export/docx/docxformatprovider%}) \ No newline at end of file +--- +title: Settings +page_title: Settings - WinForms RichTextEditor Control +description: DocxFormatProvider allows import of DOCX documents and respectively export of RadDocument to DOCX. +slug: winforms/richtexteditor/import-export/docx/settings +tags: import/export +published: True +position: 1 +--- + +# Settings + +__DocxFormatProvider__ allows for import of DOCX documents and respectively export of RadDocument to DOCX. Additionally, the export settings provide modification options. The current article outlines the available settings. + +## Export Settings + +__DocxFormatProvider__ exposes __ExportSettings__, which allow customization in how fields are exported. By default, all fields are exported using their result value in the docx document. If you would like to save the document of the editor as a mail merge template and not include the value of the current item of the __MailMergeDataSource__, a new instance of __DocxExportSettings__ should be created and assigned to the format provider. The value of the __FieldResultMode__ of these settings must be set to __FieldDisplayMode.DisplayName__. + +#### DocxFormatProvider Settings + + + + + + +The __FieldResultMode__ property of the __DocxExportSettings__ is an enumeration and it allows the following values: +* __Code__: Shows all fields codes in the current document. +* __DisplayName__: Shows all fields names in the current document. +* __Result__: Replaces the merge fields in your document with actual data from your recipient list. +* __Null__: When the **FieldResultMode** is set to *null*, fields' display mode is not changed. This can provide a better performance and lower memory usage while exporting. + +## See Also + + * [Getting Started]({%slug winforms/richtexteditor-/getting-started%}) + * [Using DocxFormatProvider]({%slug winforms/richtexteditor/import-export/docx/docxformatprovider%}) diff --git a/controls/richtexteditor/import-export/html/htmlformatprovider.md b/controls/richtexteditor/import-export/html/htmlformatprovider.md index 157fc7455..bd487e604 100644 --- a/controls/richtexteditor/import-export/html/htmlformatprovider.md +++ b/controls/richtexteditor/import-export/html/htmlformatprovider.md @@ -1,132 +1,68 @@ ---- -title: Using HtmlFormatProvider -page_title: Using HtmlFormatProvider - WinForms RichTextEditor Control -description: HtmlFormatProvider makes it easy to import and export RadDocument to/from HTML format, preserving as much as possible of the document structure and formatting in WinForms RichTextEditor. -slug: winforms/richtexteditor/import-export/html/htmlformatprovider -tags: import/export -published: True -position: 2 ---- - -# Using HtmlFormatProvider - -__HtmlFormatProvider__ makes it easy to import and export __RadDocument__ to/from HTML format, preserving as much as possible of the document structure and formatting. - -To use __HtmlFormatProvider__, you should reference the **Telerik.WinControls.RichTextEditor.dll** assembly and add the following namespace: - -* __Telerik.WinForms.Documents.FormatProviders.Html__ - -## Import - -In order to import an HTML document you can use the overloads of the __HtmlFormatProvider.Import()__ method. - -The first example shows how to use **HtmlFormatProvider** to import an HTML document from a file. - -#### Import Html File - -{{source=..\SamplesCS\RichTextEditor\ImportExport\HtmlFormatProviderForm.cs region=ImportDocumentFromFile}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\HtmlFormatProviderForm.vb region=ImportDocumentFromFile}} -````C# -HtmlFormatProvider provider = new HtmlFormatProvider(); -using (FileStream inputStream = File.OpenRead(@"..\..\RichTextEditor\ImportExport\Sample.html")) -{ - this.radRichTextEditor1.Document = provider.Import(inputStream); -} - -```` -````VB.NET -Dim provider As HtmlFormatProvider = New HtmlFormatProvider() -Using inputStream As FileStream = File.OpenRead("..\..\RichTextEditor\ImportExport\Sample.html") - Me.radRichTextEditor1.Document = provider.Import(inputStream) -End Using - -```` - - - -{{endregion}} - -This example shows how you can import an HTML string. - -#### Import Html String - -{{source=..\SamplesCS\RichTextEditor\ImportExport\HtmlFormatProviderForm.cs region=ImportHtmlString}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\HtmlFormatProviderForm.vb region=ImportHtmlString}} -````C# -string html = "

hello world!

"; -HtmlFormatProvider provider = new HtmlFormatProvider(); -this.radRichTextEditor1.Document = provider.Import(html); - -```` -````VB.NET -Dim html As String = "

hello world!

" -Dim provider As HtmlFormatProvider = New HtmlFormatProvider() -Me.radRichTextEditor1.Document = provider.Import(html) - -```` - - - -{{endregion}} - -The resulting __RadDocument__ can be used like any code-generated document. - -## Export - -With the overloads of the __Export__ method you can export the document to an HTML string or a file. - -The first example shows how to use the **HtmlFormatProvider** to export an instance of **RadDocument** to a file: - -#### Export Html to File - -{{source=..\SamplesCS\RichTextEditor\ImportExport\HtmlFormatProviderForm.cs region=ExportHtmlToFile}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\HtmlFormatProviderForm.vb region=ExportHtmlToFile}} -````C# -HtmlFormatProvider provider = new HtmlFormatProvider(); -using (Stream output = File.OpenWrite("Sample.html")) -{ - RadDocument document = this.radRichTextEditor1.Document; - provider.Export(document, output); -} - -```` -````VB.NET -Dim provider As HtmlFormatProvider = New HtmlFormatProvider() -Using output As Stream = File.OpenWrite("Sample.html") - Dim document As RadDocument = Me.radRichTextEditor1.Document - provider.Export(document, output) -End Using - -```` - - - -{{endregion}} - -You can also export the document to a string variable like shown in the example below. - -#### Export Html to String - -{{source=..\SamplesCS\RichTextEditor\ImportExport\HtmlFormatProviderForm.cs region=ExportHtmlToString}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\HtmlFormatProviderForm.vb region=ExportHtmlToString}} -````C# -RadDocument document = this.radRichTextEditor1.Document; -HtmlFormatProvider provider = new HtmlFormatProvider(); -string html = provider.Export(document); - -```` -````VB.NET -Dim document As RadDocument = Me.radRichTextEditor1.Document -Dim provider As HtmlFormatProvider = New HtmlFormatProvider() -Dim html As String = provider.Export(document) - -```` - - - -{{endregion}} - -## See Also - -* [Getting Started]({%slug winforms/richtexteditor-/getting-started%}) -* [Settings]({%slug winforms/richtexteditor/import-export/html/settings%}) \ No newline at end of file +--- +title: Using HtmlFormatProvider +page_title: Using HtmlFormatProvider - WinForms RichTextEditor Control +description: HtmlFormatProvider makes it easy to import and export RadDocument to/from HTML format, preserving as much as possible of the document structure and formatting in WinForms RichTextEditor. +slug: winforms/richtexteditor/import-export/html/htmlformatprovider +tags: import/export +published: True +position: 2 +--- + +# Using HtmlFormatProvider + +__HtmlFormatProvider__ makes it easy to import and export __RadDocument__ to/from HTML format, preserving as much as possible of the document structure and formatting. + +To use __HtmlFormatProvider__, you should reference the **Telerik.WinControls.RichTextEditor.dll** assembly and add the following namespace: + +* __Telerik.WinForms.Documents.FormatProviders.Html__ + +## Import + +In order to import an HTML document you can use the overloads of the __HtmlFormatProvider.Import()__ method. + +The first example shows how to use **HtmlFormatProvider** to import an HTML document from a file. + +#### Import Html File + + + + + + +This example shows how you can import an HTML string. + +#### Import Html String + + + + + + +The resulting __RadDocument__ can be used like any code-generated document. + +## Export + +With the overloads of the __Export__ method you can export the document to an HTML string or a file. + +The first example shows how to use the **HtmlFormatProvider** to export an instance of **RadDocument** to a file: + +#### Export Html to File + + + + + + +You can also export the document to a string variable like shown in the example below. + +#### Export Html to String + + + + + + +## See Also + +* [Getting Started]({%slug winforms/richtexteditor-/getting-started%}) +* [Settings]({%slug winforms/richtexteditor/import-export/html/settings%}) diff --git a/controls/richtexteditor/import-export/html/settings.md b/controls/richtexteditor/import-export/html/settings.md index 807a90c7a..17cafce68 100644 --- a/controls/richtexteditor/import-export/html/settings.md +++ b/controls/richtexteditor/import-export/html/settings.md @@ -1,196 +1,102 @@ ---- -title: Settings -page_title: Settings - WinForms RichTextEditor Control -description: HtmlFormatProvider allows for import of HTML documents and respectively export of WinForms RichTextEditor to HTML. -slug: winforms/richtexteditor/import-export/html/settings -tags: import/export -published: True -position: 1 ---- - -# Settings - -__HtmlFormatProvider__ allows for import of HTML documents and respectively export of RadRichTextEditor to HTML. Additionally, the import/export settings provide modification options. The current article outlines the available settings. - -## Export Settings - -__HtmlFormatProvider__ exposes __ExportSettings__, which allow you to control the export of the RadRichTextEditor document. - -### ExportSettings Properties - -* __DocumentExportLevel__: A property of type DocumentExportLevel that gets or sets which element tags should be exported. - * __Document__: This is the default value. Includes the HTML declaration, more specifically <HTML>, <TITLE>, <HEAD> and <BODY> tags. - * __Fragment__: When this setting is applied, only the HTML <BODY> tag will be exported. -* __ExportBoldAsStrong__: A property of type __bool__ that controls whether elements with font-weight bold are exported as tag. -* __ExportEmptyDocumentAsEmptyString__: A property of type __bool__ that gets or sets whether an empty document should be exported as an empty string. The default value of this property is __false__. -* __ExportFontStylesAsTags__: A property of type __bool__ that gets or sets whether the font styles should be exported as tags. Specifies if <i>, <b> and <u> tags should be used instead of setting properties as elements of a style. -* __ExportHeadingsAsTags__: A property of type __bool__ that gets or sets whether Heading styles should be exported as HTML heading tags (<h1>, <h2> etc.). -* __ExportItalicAsEm__: A property of type __bool__ that controls whether elements with font weight italic are exported as <em> tag. -* __ExportLocalOrStyleValueSource__: A property of type __bool__. Gets or sets whether only properties which have local or style value source will be exported. -* __ExportStyleMetadata__: A property of type __bool__ that sets whether the additional metadata should be exported when exporting CSS classes. -* __ImageExportMode__: A property of type __ImageExportMode__ that gets or sets how the image should be exported. This property is an enumeration and it allows the following values: - * __None__: Images are not exported. - * __AutomaticInline__: The best mode to export the image is chosen automatically. - * __Base64EncodedSplit__: Images are inline Base64 encoded and split into parts laid out in a table. - * __Base64Encoded__: Images are inline Base64 encoded. - * __ImageExportingEvent__: Event is fired on exporting. - * __UriSource__: The UriSource property is set as src attribute of the img tag. -* __PropertiesToIgnore__: A property of type __Dictionary__ that allows you add properties which will not be exported for certain HTML tags. The full collection of properties that can be excluded is demonstrated in __Example 1__. -* __SpanExportMode__: A property of type __SpanExportMode__ that gets or sets how the spans in the document are exported. This option does not affect the content of the span but only how the span tag is exported. This property is an enumeration and it allows the following values: - * __DefaultBehavior__: HTML <span> tags will be exported when they have styling. - * __AlwaysExport__: HTML <span> tags will be always exported. -* __StyleRepositoryExportMode__: A property of type __StyleRepositoryExportMode__ that gets or sets the style repository export mode. This property is an enumeration and it allows the following values: - * __ExportStylesAsCssClasses__: Export styles from the document styles repository to CSS classes. - * __DontExportStyles__: Don't export styles from the document styles repository. -* __StylesExportMode__: A property of type __StylesExportMode__ that gets or sets the styles export mode. This controls how the properties of the document elements will be exported. - * __Classes__: Create CSS classes containing properties of document elements. - * __Inline__: Inline properties of document elements using style attribute. -* __Title__: A property of type __string__ that allows you to set a Title to the generated HTML file. - -#### Exclude Properties -{{source=..\SamplesCS\RichTextEditor\ImportExport\HtmlFormatProviderForm.cs region=ExcludeProperties}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\HtmlFormatProviderForm.vb region=ExcludeProperties}} -````C# -HtmlExportSettings htmlExportSettings = new HtmlExportSettings(); -htmlExportSettings.PropertiesToIgnore["span"].Add("color"); -htmlExportSettings.PropertiesToIgnore["span"].Add("text-decoration"); -htmlExportSettings.PropertiesToIgnore["span"].Add("font-weight"); -htmlExportSettings.PropertiesToIgnore["span"].Add("font-style"); -htmlExportSettings.PropertiesToIgnore["span"].Add("font-family"); -htmlExportSettings.PropertiesToIgnore["span"].Add("font-size"); -htmlExportSettings.PropertiesToIgnore["span"].Add("dir"); -htmlExportSettings.PropertiesToIgnore["p"].Add("margin-top"); -htmlExportSettings.PropertiesToIgnore["p"].Add("margin-bottom"); -htmlExportSettings.PropertiesToIgnore["p"].Add("margin-left"); -htmlExportSettings.PropertiesToIgnore["p"].Add("margin-right"); -htmlExportSettings.PropertiesToIgnore["p"].Add("line-height"); -htmlExportSettings.PropertiesToIgnore["p"].Add("text-indent"); -htmlExportSettings.PropertiesToIgnore["p"].Add("text-align"); -htmlExportSettings.PropertiesToIgnore["p"].Add("direction"); -htmlExportSettings.PropertiesToIgnore["table"].Add("border-top"); -htmlExportSettings.PropertiesToIgnore["table"].Add("border-bottom"); -htmlExportSettings.PropertiesToIgnore["table"].Add("border-left"); -htmlExportSettings.PropertiesToIgnore["table"].Add("border-right"); -htmlExportSettings.PropertiesToIgnore["table"].Add("table-layout"); -htmlExportSettings.PropertiesToIgnore["table"].Add("margin-left"); -htmlExportSettings.PropertiesToIgnore["table"].Add("border-spacing"); -htmlExportSettings.PropertiesToIgnore["td"].Add("border-top"); -htmlExportSettings.PropertiesToIgnore["td"].Add("border-bottom"); -htmlExportSettings.PropertiesToIgnore["td"].Add("border-left"); -htmlExportSettings.PropertiesToIgnore["td"].Add("border-right"); -htmlExportSettings.PropertiesToIgnore["td"].Add("padding"); -htmlExportSettings.PropertiesToIgnore["td"].Add("vertical-align"); - -```` -````VB.NET -Dim htmlExportSettings As HtmlExportSettings = New HtmlExportSettings() -htmlExportSettings.PropertiesToIgnore("span").Add("color") -htmlExportSettings.PropertiesToIgnore("span").Add("text-decoration") -htmlExportSettings.PropertiesToIgnore("span").Add("font-weight") -htmlExportSettings.PropertiesToIgnore("span").Add("font-style") -htmlExportSettings.PropertiesToIgnore("span").Add("font-family") -htmlExportSettings.PropertiesToIgnore("span").Add("font-size") -htmlExportSettings.PropertiesToIgnore("span").Add("dir") -htmlExportSettings.PropertiesToIgnore("p").Add("margin-top") -htmlExportSettings.PropertiesToIgnore("p").Add("margin-bottom") -htmlExportSettings.PropertiesToIgnore("p").Add("margin-left") -htmlExportSettings.PropertiesToIgnore("p").Add("margin-right") -htmlExportSettings.PropertiesToIgnore("p").Add("line-height") -htmlExportSettings.PropertiesToIgnore("p").Add("text-indent") -htmlExportSettings.PropertiesToIgnore("p").Add("text-align") -htmlExportSettings.PropertiesToIgnore("p").Add("direction") -htmlExportSettings.PropertiesToIgnore("table").Add("border-top") -htmlExportSettings.PropertiesToIgnore("table").Add("border-bottom") -htmlExportSettings.PropertiesToIgnore("table").Add("border-left") -htmlExportSettings.PropertiesToIgnore("table").Add("border-right") -htmlExportSettings.PropertiesToIgnore("table").Add("table-layout") -htmlExportSettings.PropertiesToIgnore("table").Add("margin-left") -htmlExportSettings.PropertiesToIgnore("table").Add("border-spacing") -htmlExportSettings.PropertiesToIgnore("td").Add("border-top") -htmlExportSettings.PropertiesToIgnore("td").Add("border-bottom") -htmlExportSettings.PropertiesToIgnore("td").Add("border-left") -htmlExportSettings.PropertiesToIgnore("td").Add("border-right") -htmlExportSettings.PropertiesToIgnore("td").Add("padding") -htmlExportSettings.PropertiesToIgnore("td").Add("vertical-align") - -```` - -{{endregion}} - -### Telerik Reporting - -In order to achieve best compatibility of the generated HTML with __Telerik Reporting__, you should apply the following settings: -* __DocumentExportLevel__: Fragment; -* __StylesExportMode__: Inline; -* __StyleRepositoryExportMode__: DontExportStyles; -* __ExportFontStylesAsTags__: true. - -### ExportSettings Events -* __CssClassExporting__: This event is fired on every attempt to export a CSS class. The CssClassExporting event is triggered only when StyleRepositoryExportMode is set to ExportStylesAsCssClasses. -* __FloatingUIContainerExporting__: This event is fired on every attempt to export a __FloatingUIContainer__. -* __ImageExporting__: This event is fired only when the respective option of ImageExportMode is applied. -* __InlineUIContainerExporting__: This event is fired on every attempt to export an __InlineUIContainer__. For more information, please refer to the article about InlineUIContainers. - -#### ExportSettings of the HtmlFormatProvider -{{source=..\SamplesCS\RichTextEditor\ImportExport\HtmlFormatProviderForm.cs region=HtmlExportSettings}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\HtmlFormatProviderForm.vb region=HtmlExportSettings}} -````C# -HtmlExportSettings htmlExportSettings = new HtmlExportSettings(); -htmlExportSettings.ExportBoldAsStrong = true; -htmlExportSettings.SpanExportMode = SpanExportMode.AlwaysExport; -HtmlFormatProvider htmlFormatProvider = new HtmlFormatProvider(); -htmlFormatProvider.ExportSettings = htmlExportSettings; - -```` -````VB.NET -Dim htmlExportSettings As HtmlExportSettings = New HtmlExportSettings() -htmlExportSettings.ExportBoldAsStrong = True -htmlExportSettings.SpanExportMode = SpanExportMode.AlwaysExport -Dim htmlFormatProvider As HtmlFormatProvider = New HtmlFormatProvider() -htmlFormatProvider.ExportSettings = htmlExportSettings - -```` - -{{endregion}} - -## Import Settings - -__HtmlFormatProvider__ exposes __ImportSettings__, which allow you to control the import of the HTML file. - -### ImportSettings Properties -* __UseDefaultStylesheetForFontProperties__: A property of type __bool__ that indicates whether the default font properties of RadRichTextEditor or the defaults in the HTML specification should be used for the elements that do not set their FontSize, FontFamily, FontWeight and FontStyle explicitly. -* __UseHtmlHeadingStyles__: A property of type __bool__ that indicates whether the heading style of the imported HTML should be imported or not. - -### ImportSettings Events - -* __FloatingUIContainerImporting__: This event is fired on every attempt to import a __FloatingUIContainer__. -* __FloatingUIContainerImported__: This event is fired every time when the __FloatingUIContainer__ is imported. -* __FontSubstituting__: This event allows you to handle the cases when the __HTML__ source specifies a Font that is not available to the RichTextBox. -* __InlineUIContainerImported__: This event is fired every time when the __InlineUIContainer__ is imported. -* __InlineUIContainerImporting__: This event is fired on every attempt to import a __InlineUIContainer__. -* __LoadImageFromUrl__: This event was introduced at a time when __HtmlFormatProvider__ did not automatically load images from URLs. The feature is currently supported out of the box, but this event can be useful if using virtual directories and files on the server. - -#### ImportSettings of the HtmlFormatProvider -{{source=..\SamplesCS\RichTextEditor\ImportExport\HtmlFormatProviderForm.cs region=HtmlImportSettings}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\HtmlFormatProviderForm.vb region=HtmlImportSettings}} -````C# -HtmlImportSettings htmlImportSettings = new HtmlImportSettings(); -htmlImportSettings.UseDefaultStylesheetForFontProperties = true; -HtmlFormatProvider htmlFormatProvider = new HtmlFormatProvider(); -htmlFormatProvider.ImportSettings = htmlImportSettings; - -```` -````VB.NET -Dim htmlImportSettings As HtmlImportSettings = New HtmlImportSettings() -htmlImportSettings.UseDefaultStylesheetForFontProperties = True -Dim htmlFormatProvider As HtmlFormatProvider = New HtmlFormatProvider() -htmlFormatProvider.ImportSettings = htmlImportSettings - -```` - -{{endregion}} - -## See Also - - * [Getting Started]({%slug winforms/richtexteditor-/getting-started%}) - * [Using HtmlFormatProvider]({%slug winforms/richtexteditor/import-export/html/htmlformatprovider%}) \ No newline at end of file +--- +title: Settings +page_title: Settings - WinForms RichTextEditor Control +description: HtmlFormatProvider allows for import of HTML documents and respectively export of WinForms RichTextEditor to HTML. +slug: winforms/richtexteditor/import-export/html/settings +tags: import/export +published: True +position: 1 +--- + +# Settings + +__HtmlFormatProvider__ allows for import of HTML documents and respectively export of RadRichTextEditor to HTML. Additionally, the import/export settings provide modification options. The current article outlines the available settings. + +## Export Settings + +__HtmlFormatProvider__ exposes __ExportSettings__, which allow you to control the export of the RadRichTextEditor document. + +### ExportSettings Properties + +* __DocumentExportLevel__: A property of type DocumentExportLevel that gets or sets which element tags should be exported. + * __Document__: This is the default value. Includes the HTML declaration, more specifically <HTML>, <TITLE>, <HEAD> and <BODY> tags. + * __Fragment__: When this setting is applied, only the HTML <BODY> tag will be exported. +* __ExportBoldAsStrong__: A property of type __bool__ that controls whether elements with font-weight bold are exported as tag. +* __ExportEmptyDocumentAsEmptyString__: A property of type __bool__ that gets or sets whether an empty document should be exported as an empty string. The default value of this property is __false__. +* __ExportFontStylesAsTags__: A property of type __bool__ that gets or sets whether the font styles should be exported as tags. Specifies if <i>, <b> and <u> tags should be used instead of setting properties as elements of a style. +* __ExportHeadingsAsTags__: A property of type __bool__ that gets or sets whether Heading styles should be exported as HTML heading tags (<h1>, <h2> etc.). +* __ExportItalicAsEm__: A property of type __bool__ that controls whether elements with font weight italic are exported as <em> tag. +* __ExportLocalOrStyleValueSource__: A property of type __bool__. Gets or sets whether only properties which have local or style value source will be exported. +* __ExportStyleMetadata__: A property of type __bool__ that sets whether the additional metadata should be exported when exporting CSS classes. +* __ImageExportMode__: A property of type __ImageExportMode__ that gets or sets how the image should be exported. This property is an enumeration and it allows the following values: + * __None__: Images are not exported. + * __AutomaticInline__: The best mode to export the image is chosen automatically. + * __Base64EncodedSplit__: Images are inline Base64 encoded and split into parts laid out in a table. + * __Base64Encoded__: Images are inline Base64 encoded. + * __ImageExportingEvent__: Event is fired on exporting. + * __UriSource__: The UriSource property is set as src attribute of the img tag. +* __PropertiesToIgnore__: A property of type __Dictionary__ that allows you add properties which will not be exported for certain HTML tags. The full collection of properties that can be excluded is demonstrated in __Example 1__. +* __SpanExportMode__: A property of type __SpanExportMode__ that gets or sets how the spans in the document are exported. This option does not affect the content of the span but only how the span tag is exported. This property is an enumeration and it allows the following values: + * __DefaultBehavior__: HTML <span> tags will be exported when they have styling. + * __AlwaysExport__: HTML <span> tags will be always exported. +* __StyleRepositoryExportMode__: A property of type __StyleRepositoryExportMode__ that gets or sets the style repository export mode. This property is an enumeration and it allows the following values: + * __ExportStylesAsCssClasses__: Export styles from the document styles repository to CSS classes. + * __DontExportStyles__: Don't export styles from the document styles repository. +* __StylesExportMode__: A property of type __StylesExportMode__ that gets or sets the styles export mode. This controls how the properties of the document elements will be exported. + * __Classes__: Create CSS classes containing properties of document elements. + * __Inline__: Inline properties of document elements using style attribute. +* __Title__: A property of type __string__ that allows you to set a Title to the generated HTML file. + +#### Exclude Properties + + + + + +### Telerik Reporting + +In order to achieve best compatibility of the generated HTML with __Telerik Reporting__, you should apply the following settings: +* __DocumentExportLevel__: Fragment; +* __StylesExportMode__: Inline; +* __StyleRepositoryExportMode__: DontExportStyles; +* __ExportFontStylesAsTags__: true. + +### ExportSettings Events +* __CssClassExporting__: This event is fired on every attempt to export a CSS class. The CssClassExporting event is triggered only when StyleRepositoryExportMode is set to ExportStylesAsCssClasses. +* __FloatingUIContainerExporting__: This event is fired on every attempt to export a __FloatingUIContainer__. +* __ImageExporting__: This event is fired only when the respective option of ImageExportMode is applied. +* __InlineUIContainerExporting__: This event is fired on every attempt to export an __InlineUIContainer__. For more information, please refer to the article about InlineUIContainers. + +#### ExportSettings of the HtmlFormatProvider + + + + + +## Import Settings + +__HtmlFormatProvider__ exposes __ImportSettings__, which allow you to control the import of the HTML file. + +### ImportSettings Properties +* __UseDefaultStylesheetForFontProperties__: A property of type __bool__ that indicates whether the default font properties of RadRichTextEditor or the defaults in the HTML specification should be used for the elements that do not set their FontSize, FontFamily, FontWeight and FontStyle explicitly. +* __UseHtmlHeadingStyles__: A property of type __bool__ that indicates whether the heading style of the imported HTML should be imported or not. + +### ImportSettings Events + +* __FloatingUIContainerImporting__: This event is fired on every attempt to import a __FloatingUIContainer__. +* __FloatingUIContainerImported__: This event is fired every time when the __FloatingUIContainer__ is imported. +* __FontSubstituting__: This event allows you to handle the cases when the __HTML__ source specifies a Font that is not available to the RichTextBox. +* __InlineUIContainerImported__: This event is fired every time when the __InlineUIContainer__ is imported. +* __InlineUIContainerImporting__: This event is fired on every attempt to import a __InlineUIContainer__. +* __LoadImageFromUrl__: This event was introduced at a time when __HtmlFormatProvider__ did not automatically load images from URLs. The feature is currently supported out of the box, but this event can be useful if using virtual directories and files on the server. + +#### ImportSettings of the HtmlFormatProvider + + + + + +## See Also + + * [Getting Started]({%slug winforms/richtexteditor-/getting-started%}) + * [Using HtmlFormatProvider]({%slug winforms/richtexteditor/import-export/html/htmlformatprovider%}) diff --git a/controls/richtexteditor/import-export/pdf/pdfformatprovider.md b/controls/richtexteditor/import-export/pdf/pdfformatprovider.md index 1f3c37a19..1869f155d 100644 --- a/controls/richtexteditor/import-export/pdf/pdfformatprovider.md +++ b/controls/richtexteditor/import-export/pdf/pdfformatprovider.md @@ -23,31 +23,14 @@ In order to export a document to PDF you need to use the __Export()__ method of The code snippet in __Example 1__ shows how to create a __PdfFormatProvider__ instance and use it to export the document to PDF. #### Export to Pdf File -{{source=..\SamplesCS\RichTextEditor\ImportExport\PdfFormatProviderForm.cs region=ExportPdfToFile}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\PdfFormatProviderForm.vb region=ExportPdfToFile}} -````C# -PdfFormatProvider provider = new PdfFormatProvider(); -using (Stream output = File.OpenWrite("sample.pdf")) -{ - RadDocument document = this.radRichTextEditor1.Document; - provider.Export(document, output); -} - -```` -````VB.NET -Dim provider As PdfFormatProvider = New PdfFormatProvider() -Using output As Stream = File.OpenWrite("Sample.pdf") - Dim document As RadDocument = Me.radRichTextEditor1.Document - provider.Export(document, output) -End Using - -```` - -{{endregion}} + + + + The result from the method is a document that can be opened in any application that supports PDF documents. ## See Also * [Getting Started]({%slug winforms/richtexteditor-/getting-started%}) - * [Settings]({%slug winforms/richtexteditor/import-export/pdf/settings%}) \ No newline at end of file + * [Settings]({%slug winforms/richtexteditor/import-export/pdf/settings%}) diff --git a/controls/richtexteditor/import-export/pdf/settings.md b/controls/richtexteditor/import-export/pdf/settings.md index 2f9af18dc..a0ade380e 100644 --- a/controls/richtexteditor/import-export/pdf/settings.md +++ b/controls/richtexteditor/import-export/pdf/settings.md @@ -1,75 +1,59 @@ ---- -title: Settings -page_title: Settings - WinForms RichTextEditor Control -description: PdfFormatProvider allows for export of PDF documents and respectively export of WinForms RichTextEditor to Pdf. The export settings provide modification options. -slug: winforms/richtexteditor/import-export/pdf/settings -tags: import/export -published: True -position: 1 ---- - -# Settings - -__PdfFormatProvider__ allows for export of PDF documents and respectively export of RadRichTextEditor to Pdf. Additionally, the export settings provide modification options. The current article outlines the available settings. - -## Export Settings - -__PdfFormatProvider__ exposes __ExportSettings__, which allow you to control image quality, encryption, compliance level and other PDF format related properties. - -* __CommentsExportMode__: A property of type __PdfCommentsExportMode__ that gets or sets how the comments should be exported. - * __None__: Default mode. The comments will not be exported. - * __NativePdfAnnotations__: The comments will be exported as PDF annotation. -* __ContentsCompressionMode__: A property of type __PdfContentsCompressionMode__ that gets or sets a value indicating the compression mode used when compressing page contents. This property is an enumeration and it allows the following values: - * __None__: No compression. - * __Deflate__: The deflate algorithm will be applied to compress the text content of the document. - * __Automatic__: Default mode. The best algorithm will be automatically decided upon for you. Currently __Deflate__ is always used. -* __ContentsDeflaterCompressionLevel__: A property of type __integer__ between -1 and 9 that gets or sets a value indicating the compression level to be used when deflating the content of the document. - * __-1__: Automatic compression, which is currently 6 (Optimal Compression). - * __0__: No Compression. This is the default value of the property. - * __9__: Best Compression. -* __DocumentInfo__: A property of type __PdfDocumentInfo__. You can use this class to retrieve or change the document information. The document information which you can get or change is: Author, Creator, IncludeCreationDate, Keywords, Producer, Subject, Title. -* __DrawPageBodyBackground__: A property of type __bool__ that gets or sets a value indicating whether the exporter will draw a rectangle below the page body contents. -* __FloatingUIContainersExportMode:__ A property of type __PdfInlineUIContainersExportMode__ that get or sets the current mode when exporting floating UI containers. - * __None__: When set, the floating UI containers will not be exported. - * __Image__: Default mode. All the __FloatingUIContainers__ in the document are added as images in the PDF document. -* __ImagesCompressionMode:__ A property of type __PdfImagesCompressionMode__ that gets or sets a value indicating the compression mode used when compressing images. - * __None__: No compression. - * __Deflate__: The deflate algorithm will be applied to compress the images. - * __Jpeg__: The Jpeg algorithm will be applied to compress the images. - * __Automatic__: Default mode. The best algorithm will be automatically decided upon for you. Currently, __Jpeg__ is used for JPEG images, and __Deflate__ for all others. -* __ImagesDeflaterCompressionLevel__: A property of type __integer__ between -1 and 9 that gets or sets a value indicating the compression level to be used when deflating the images in the document. This property is respected when an image is compressed with __Deflate__ mode (see __ImagesCompressionMode__). - * __-1__: Automatic compression, which is currently 6 (Optimal Compression). - * __0__: No Compression. This is the default value of the property. - * __9__: Best Compression. -* __InlineUIContainersExportMode__: A property of type __PdfInlineUIContainersExportMode__ that get or sets the mode used when exporting inline UI containers. - * __None__: The inline UI containers will not be exported. - * __Image__: Default mode. All the __InlineUIContainers__ are added as images to the PDF document. - -#### Setting the ExportSettings of the PdfFormatProvider -{{source=..\SamplesCS\RichTextEditor\ImportExport\PdfFormatProviderForm.cs region=SetupPdfExportSettings}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\PdfFormatProviderForm.vb region=SetupPdfExportSettings}} -````C# -PdfExportSettings pdfExportSettings = new PdfExportSettings(); -pdfExportSettings.ContentsDeflaterCompressionLevel = 9; -pdfExportSettings.DrawPageBodyBackground = false; -PdfFormatProvider pdfFormatProvider = new PdfFormatProvider(); -pdfFormatProvider.ExportSettings = pdfExportSettings; - -```` -````VB.NET -Dim pdfExportSettings As PdfExportSettings = New PdfExportSettings() -pdfExportSettings.ContentsDeflaterCompressionLevel = 9 -pdfExportSettings.DrawPageBodyBackground = False -Dim pdfFormatProvider As PdfFormatProvider = New PdfFormatProvider() -pdfFormatProvider.ExportSettings = pdfExportSettings - -```` - -{{endregion}} - ->note __Pdf import__ is currently __not__ supported, so there are no import settings. - -## See Also - - * [Getting Started]({%slug winforms/richtexteditor-/getting-started%}) - * [Using PdfFormatProvider]({%slug winforms/richtexteditor/import-export/pdf/pdfformatprovider%}) \ No newline at end of file +--- +title: Settings +page_title: Settings - WinForms RichTextEditor Control +description: PdfFormatProvider allows for export of PDF documents and respectively export of WinForms RichTextEditor to Pdf. The export settings provide modification options. +slug: winforms/richtexteditor/import-export/pdf/settings +tags: import/export +published: True +position: 1 +--- + +# Settings + +__PdfFormatProvider__ allows for export of PDF documents and respectively export of RadRichTextEditor to Pdf. Additionally, the export settings provide modification options. The current article outlines the available settings. + +## Export Settings + +__PdfFormatProvider__ exposes __ExportSettings__, which allow you to control image quality, encryption, compliance level and other PDF format related properties. + +* __CommentsExportMode__: A property of type __PdfCommentsExportMode__ that gets or sets how the comments should be exported. + * __None__: Default mode. The comments will not be exported. + * __NativePdfAnnotations__: The comments will be exported as PDF annotation. +* __ContentsCompressionMode__: A property of type __PdfContentsCompressionMode__ that gets or sets a value indicating the compression mode used when compressing page contents. This property is an enumeration and it allows the following values: + * __None__: No compression. + * __Deflate__: The deflate algorithm will be applied to compress the text content of the document. + * __Automatic__: Default mode. The best algorithm will be automatically decided upon for you. Currently __Deflate__ is always used. +* __ContentsDeflaterCompressionLevel__: A property of type __integer__ between -1 and 9 that gets or sets a value indicating the compression level to be used when deflating the content of the document. + * __-1__: Automatic compression, which is currently 6 (Optimal Compression). + * __0__: No Compression. This is the default value of the property. + * __9__: Best Compression. +* __DocumentInfo__: A property of type __PdfDocumentInfo__. You can use this class to retrieve or change the document information. The document information which you can get or change is: Author, Creator, IncludeCreationDate, Keywords, Producer, Subject, Title. +* __DrawPageBodyBackground__: A property of type __bool__ that gets or sets a value indicating whether the exporter will draw a rectangle below the page body contents. +* __FloatingUIContainersExportMode:__ A property of type __PdfInlineUIContainersExportMode__ that get or sets the current mode when exporting floating UI containers. + * __None__: When set, the floating UI containers will not be exported. + * __Image__: Default mode. All the __FloatingUIContainers__ in the document are added as images in the PDF document. +* __ImagesCompressionMode:__ A property of type __PdfImagesCompressionMode__ that gets or sets a value indicating the compression mode used when compressing images. + * __None__: No compression. + * __Deflate__: The deflate algorithm will be applied to compress the images. + * __Jpeg__: The Jpeg algorithm will be applied to compress the images. + * __Automatic__: Default mode. The best algorithm will be automatically decided upon for you. Currently, __Jpeg__ is used for JPEG images, and __Deflate__ for all others. +* __ImagesDeflaterCompressionLevel__: A property of type __integer__ between -1 and 9 that gets or sets a value indicating the compression level to be used when deflating the images in the document. This property is respected when an image is compressed with __Deflate__ mode (see __ImagesCompressionMode__). + * __-1__: Automatic compression, which is currently 6 (Optimal Compression). + * __0__: No Compression. This is the default value of the property. + * __9__: Best Compression. +* __InlineUIContainersExportMode__: A property of type __PdfInlineUIContainersExportMode__ that get or sets the mode used when exporting inline UI containers. + * __None__: The inline UI containers will not be exported. + * __Image__: Default mode. All the __InlineUIContainers__ are added as images to the PDF document. + +#### Setting the ExportSettings of the PdfFormatProvider + + + + + +>note __Pdf import__ is currently __not__ supported, so there are no import settings. + +## See Also + + * [Getting Started]({%slug winforms/richtexteditor-/getting-started%}) + * [Using PdfFormatProvider]({%slug winforms/richtexteditor/import-export/pdf/pdfformatprovider%}) diff --git a/controls/richtexteditor/import-export/plain-text/txtformatprovider.md b/controls/richtexteditor/import-export/plain-text/txtformatprovider.md index 8e27b4d9d..b4cecbd1b 100644 --- a/controls/richtexteditor/import-export/plain-text/txtformatprovider.md +++ b/controls/richtexteditor/import-export/plain-text/txtformatprovider.md @@ -1,127 +1,65 @@ ---- -title: Using TxtFormatProvider -page_title: Using TxtFormatProvider - WinForms RichTextEditor Control -description: TxtFormatProvider makes it easy to import and export RadDocument to/from plain text format, preserving the document structure in WinForms RichTextEditor. -slug: winforms/richtexteditor/import-export/plain-text/txtformatprovider -tags: import/export -published: True -position: 1 ---- - -# Using TxtFormatProvider - -__TxtFormatProvider__ makes it easy to import and export __RadDocument__ to/from plain text format, preserving the document structure. - -To use __TxtFormatProvider__, you should reference the **Telerik.WinControls.RichTextEditor.dll** and add the following namespace: - -* __Telerik.WinForms.Documents.FormatProviders.Txt__ - -## Import - -In order to import a plain text document, you need to use the __Import()__ method of __TxtFormatProvider__. The first example shows how to use __TxtFormatProvider__ to import a document from a file. - -#### Import Document from a File - -{{source=..\SamplesCS\RichTextEditor\ImportExport\TxtFormatProviderForm.cs region=ImportDocumentFromFile}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\TxtFormatProviderForm.vb region=ImportDocumentFromFile}} -````C# -TxtFormatProvider provider = new TxtFormatProvider(); -using (Stream input = File.OpenRead(@"..\..\RichTextEditor\ImportExport\Sample.txt")) -{ - this.radRichTextEditor1.Document = provider.Import(input); -} - -```` -````VB.NET -Dim provider As TxtFormatProvider = New TxtFormatProvider() -Using input As Stream = File.OpenRead("..\..\RichTextEditor\ImportExport\Sample.txt") - Me.radRichTextEditor1.Document = provider.Import(input) -End Using - -```` - - - -{{endregion}} - -And here is how you can import a document from string: - -#### Import Document from a String - -{{source=..\SamplesCS\RichTextEditor\ImportExport\TxtFormatProviderForm.cs region=ImportDocumentFromString}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\TxtFormatProviderForm.vb region=ImportDocumentFromString}} -````C# -TxtFormatProvider provider = new TxtFormatProvider(); -this.radRichTextEditor1.Document = provider.Import(input); - -```` -````VB.NET -Dim provider As TxtFormatProvider = New TxtFormatProvider() -Me.radRichTextEditor1.Document = provider.Import(input) - -```` - - - -{{endregion}} - -The resulting __RadDocument__ can be manipulated like any code-generated document. - -## Export - -In order to export a document to plain text, you need to use the __Export()__ method of __TxtFormatProvider__. - -This example shows how to use __TxtFormatProvider__ to export __RadDocument__ to a file. - -#### Export a Document to a File - -{{source=..\SamplesCS\RichTextEditor\ImportExport\TxtFormatProviderForm.cs region=ExportDocumentToFile}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\TxtFormatProviderForm.vb region=ExportDocumentToFile}} -````C# -TxtFormatProvider provider = new TxtFormatProvider(); -using (Stream output = File.OpenWrite("sample.txt")) -{ - RadDocument document = this.radRichTextEditor1.Document; - provider.Export(document, output); -} - -```` -````VB.NET -Dim provider As TxtFormatProvider = New TxtFormatProvider() -Using output As Stream = File.OpenWrite("sample.txt") - Dim document As RadDocument = Me.radRichTextEditor1.Document - provider.Export(document, output) -End Using - -```` - - - -{{endregion}} - -You can also export the document to a string and preserve it in a database. - -#### Export a Document to a String - -{{source=..\SamplesCS\RichTextEditor\ImportExport\TxtFormatProviderForm.cs region=ExportDocumentToString}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\TxtFormatProviderForm.vb region=ExportDocumentToString}} -````C# -TxtFormatProvider provider = new TxtFormatProvider(); -RadDocument document = this.radRichTextEditor1.Document; -string output = provider.Export(document); - -```` -````VB.NET -Dim provider As TxtFormatProvider = New TxtFormatProvider() -Dim document As RadDocument = Me.radRichTextEditor1.Document -Dim output As String = provider.Export(document) - -```` - - - -{{endregion}} - -## See Also - - * [Getting Started]({%slug winforms/richtexteditor-/getting-started%}) \ No newline at end of file +--- +title: Using TxtFormatProvider +page_title: Using TxtFormatProvider - WinForms RichTextEditor Control +description: TxtFormatProvider makes it easy to import and export RadDocument to/from plain text format, preserving the document structure in WinForms RichTextEditor. +slug: winforms/richtexteditor/import-export/plain-text/txtformatprovider +tags: import/export +published: True +position: 1 +--- + +# Using TxtFormatProvider + +__TxtFormatProvider__ makes it easy to import and export __RadDocument__ to/from plain text format, preserving the document structure. + +To use __TxtFormatProvider__, you should reference the **Telerik.WinControls.RichTextEditor.dll** and add the following namespace: + +* __Telerik.WinForms.Documents.FormatProviders.Txt__ + +## Import + +In order to import a plain text document, you need to use the __Import()__ method of __TxtFormatProvider__. The first example shows how to use __TxtFormatProvider__ to import a document from a file. + +#### Import Document from a File + + + + + + +And here is how you can import a document from string: + +#### Import Document from a String + + + + + + +The resulting __RadDocument__ can be manipulated like any code-generated document. + +## Export + +In order to export a document to plain text, you need to use the __Export()__ method of __TxtFormatProvider__. + +This example shows how to use __TxtFormatProvider__ to export __RadDocument__ to a file. + +#### Export a Document to a File + + + + + + +You can also export the document to a string and preserve it in a database. + +#### Export a Document to a String + + + + + + +## See Also + + * [Getting Started]({%slug winforms/richtexteditor-/getting-started%}) diff --git a/controls/richtexteditor/import-export/rtf/rtfformatprovider.md b/controls/richtexteditor/import-export/rtf/rtfformatprovider.md index f214a6d61..08c2459d9 100644 --- a/controls/richtexteditor/import-export/rtf/rtfformatprovider.md +++ b/controls/richtexteditor/import-export/rtf/rtfformatprovider.md @@ -1,131 +1,70 @@ ---- -title: Using RtfFormatProvider -page_title: Using RtfFormatProvider - WinForms RichTextEditor Control -description: RtfFormatProvider makes it easy to import and export RadDocument to/from RTF format, preserving the entire document structure and formatting in WinForms RichTextEditor. -slug: winforms/richtexteditor/import-export/rtf/rtfformatprovider -tags: import/export -published: True -position: 2 ---- - -# Using RtfFormatProvider - -__RtfFormatProvider__ makes it easy to import and export __RadDocument__ to/from RTF format, preserving the entire document structure and formatting. - -To use __RtfFormatProvider__, you should reference the **Telerik.WinControls.RichTextEditor.dll** assembly and add the following namespace: - -* __Telerik.WinForms.Documents.FormatProviders.Rtf__ - -## Import - -In order to import an RTF document, you need to use the __Import__ method of __RtfFormatProvider__. - -The code from __Example 1__ shows how to use __RtfFormatProvider__ to import an RTF document from a file. - -#### Import Document from a File - -{{source=..\SamplesCS\RichTextEditor\ImportExport\RtfFormatProviderForm.cs region=ImportDocumentFromFile}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\RtfFormatProviderForm.vb region=ImportDocumentFromFile}} -````C# -RtfFormatProvider provider = new RtfFormatProvider(); -using (Stream input = File.OpenRead(@"..\..\RichTextEditor\ImportExport\Sample.rtf")) -{ - this.radRichTextEditor1.Document = provider.Import(input); -} - -```` -````VB.NET -Dim provider As RtfFormatProvider = New RtfFormatProvider() -Using input As Stream = File.OpenRead("..\..\RichTextEditor\ImportExport\Sample.rtf") - Me.radRichTextEditor1.Document = provider.Import(input) -End Using - -```` - - -{{endregion}} - -And here is how you can import a document from string containing the RTF document: - -#### Import Document from a String - -{{source=..\SamplesCS\RichTextEditor\ImportExport\RtfFormatProviderForm.cs region=ImportDocumentFromString}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\RtfFormatProviderForm.vb region=ImportDocumentFromString}} -````C# -RtfFormatProvider provider = new RtfFormatProvider(); -this.radRichTextEditor1.Document = provider.Import(input); - -```` -````VB.NET -Dim provider As RtfFormatProvider = New RtfFormatProvider() -Me.radRichTextEditor1.Document = provider.Import(input) - -```` - - - -{{endregion}} - -The resulting __RadDocument__ can be used like any code-generated document. - -## Export - -In order to export a document to RTF, you need to use the __Export__ method of __RtfFormatProvider__. - -The example below shows how to use __RtfFormatProvider__ to export __RadDocument__ to a file. - -#### Export a Document to a File - -{{source=..\SamplesCS\RichTextEditor\ImportExport\RtfFormatProviderForm.cs region=ExportDocumentToFile}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\RtfFormatProviderForm.vb region=ExportDocumentToFile}} -````C# -RtfFormatProvider provider = new RtfFormatProvider(); -using (Stream output = File.Create("Sample.rtf")) -{ - RadDocument document = this.radRichTextEditor1.Document; - provider.Export(document, output); -} - -```` -````VB.NET -Dim provider As RtfFormatProvider = New RtfFormatProvider() -Using output As Stream = File.OpenWrite("Sample.rtf") - Dim document As RadDocument = Me.radRichTextEditor1.Document - provider.Export(document, output) -End Using - -```` - - - - -{{endregion}} - -You can also export the document to a string and preserve it in a database. - -#### Export a Document to a String - -{{source=..\SamplesCS\RichTextEditor\ImportExport\RtfFormatProviderForm.cs region=ExportDocumentToString}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\RtfFormatProviderForm.vb region=ExportDocumentToString}} -````C# -RtfFormatProvider provider = new RtfFormatProvider(); -RadDocument document = this.radRichTextEditor1.Document; -string output = provider.Export(document); - -```` -````VB.NET -Dim provider As RtfFormatProvider = New RtfFormatProvider() -Dim document As RadDocument = Me.radRichTextEditor1.Document -Dim output As String = provider.Export(document) - -```` - - -{{endregion}} - -The resulting documents can be opened in any application that supports RTF documents. - -## See Also - - * [Getting Started]({%slug winforms/richtexteditor-/getting-started%}) - * [Settings]({%slug winforms/richtexteditor/import-export/rtf/settings%}) \ No newline at end of file +--- +title: Using RtfFormatProvider +page_title: Using RtfFormatProvider - WinForms RichTextEditor Control +description: RtfFormatProvider makes it easy to import and export RadDocument to/from RTF format, preserving the entire document structure and formatting in WinForms RichTextEditor. +slug: winforms/richtexteditor/import-export/rtf/rtfformatprovider +tags: import/export +published: True +position: 2 +--- + +# Using RtfFormatProvider + +__RtfFormatProvider__ makes it easy to import and export __RadDocument__ to/from RTF format, preserving the entire document structure and formatting. + +To use __RtfFormatProvider__, you should reference the **Telerik.WinControls.RichTextEditor.dll** assembly and add the following namespace: + +* __Telerik.WinForms.Documents.FormatProviders.Rtf__ + +## Import + +In order to import an RTF document, you need to use the __Import__ method of __RtfFormatProvider__. + +The code from __Example 1__ shows how to use __RtfFormatProvider__ to import an RTF document from a file. + +#### Import Document from a File + + + + + + +And here is how you can import a document from string containing the RTF document: + +#### Import Document from a String + + + + + + +The resulting __RadDocument__ can be used like any code-generated document. + +## Export + +In order to export a document to RTF, you need to use the __Export__ method of __RtfFormatProvider__. + +The example below shows how to use __RtfFormatProvider__ to export __RadDocument__ to a file. + +#### Export a Document to a File + + + + + + +You can also export the document to a string and preserve it in a database. + +#### Export a Document to a String + + + + + + +The resulting documents can be opened in any application that supports RTF documents. + +## See Also + + * [Getting Started]({%slug winforms/richtexteditor-/getting-started%}) + * [Settings]({%slug winforms/richtexteditor/import-export/rtf/settings%}) diff --git a/controls/richtexteditor/import-export/rtf/settings.md b/controls/richtexteditor/import-export/rtf/settings.md index e698e1059..479826168 100644 --- a/controls/richtexteditor/import-export/rtf/settings.md +++ b/controls/richtexteditor/import-export/rtf/settings.md @@ -1,106 +1,52 @@ ---- -title: Settings -page_title: Settings - WinForms RichTextEditor Control -description: RtfFormatProvider allows for import of RTF documents and respectively export of WinForms RichTextEditor to RTF. -slug: winforms/richtexteditor/import-export/rtf/settings -tags: import/export -published: True -position: 1 ---- - -# Settings - -__RtfFormatProvider__ allows for import of RTF documents and respectively export of RadRichTextEditor to Rtf. Additionally, the import/export settings provide modification options. The current article outlines the available settings. - -## Export Settings - -__RtfFormatProvider__ exposes __ExportSettings__, which allow customization in how fields are exported. The __ExportSetting__s property is of type RtfExportSettings which have the following properties and events: - -* __ExportImagesInCompatibilityMode__: A property of type bool that gets or sets whether the images should be exported in compatibility mode. You can use this option when the document will be used in older readers. -* __ImageExporting__: Handling this event allows you to change the bytes and the extension of the image before exporting it. -* __FieldResultMode__: This property defines how the fields are exported in the RTF content. This property is an enumeration and it allows the following values: - * __Code__: Shows all fields codes in the current document. - * __DisplayName__: Show all fields names in the current document. - * __Result__: Replace the merge fields in your document with actual data from your recipient list. - -#### Setting the ExportSettings of the RtfFormatProvider -{{source=..\SamplesCS\RichTextEditor\ImportExport\RtfFormatProviderForm.cs region=SetupRtfExportSettings}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\RtfFormatProviderForm.vb region=SetupRtfExportSettings}} -````C# -RtfExportSettings exportSettings = new RtfExportSettings(); -exportSettings.ExportImagesInCompatibilityMode = true; -exportSettings.FieldResultMode = FieldDisplayMode.DisplayName; -RtfFormatProvider rtfFormatProvider = new RtfFormatProvider(); -rtfFormatProvider.ExportSettings = exportSettings; - -```` -````VB.NET -Dim exportSettings As RtfExportSettings = New RtfExportSettings() -exportSettings.ExportImagesInCompatibilityMode = True -exportSettings.FieldResultMode = FieldDisplayMode.DisplayName -Dim rtfFormatProvider As RtfFormatProvider = New RtfFormatProvider() -rtfFormatProvider.ExportSettings = exportSettings - -```` - - - -{{endregion}} - -## Import Settings - -Through the __ImportSettings__ of __RtfFormatProvider__ you can utilize the __FontSubstituting__ event. This event allows you to handle the cases when the Rtf source specifies a __Font__ that is not available to the __RichTextBox__. This is particularly useful in __Silverlight__ when the __Font__ can be resolved only if it is among the default ones when you do not want to rely on it being installed on the client machine. __Example 4__ shows how you can subscribe to the event and handle it. - -#### Setup Default RtfFormatProvider -{{source=..\SamplesCS\RichTextEditor\ImportExport\RtfFormatProviderForm.cs region=SetupDefaultRtfFormatProvider}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\RtfFormatProviderForm.vb region=SetupDefaultRtfFormatProvider}} -````C# -RtfFormatProvider rtfFormatProvider = DocumentFormatProvidersManager.GetProviderByExtension("rtf") as RtfFormatProvider; -RtfImportSettings rtfImportSettings = new RtfImportSettings(); -rtfImportSettings.FontSubstituting += rtfImportSettings_FontSubstituting; -rtfFormatProvider.ImportSettings = rtfImportSettings; - -```` -````VB.NET -Dim rtfFormatProvider As RtfFormatProvider = TryCast(DocumentFormatProvidersManager.GetProviderByExtension("rtf"), RtfFormatProvider) -Dim rtfImportSettings As RtfImportSettings = New RtfImportSettings() -AddHandler rtfImportSettings.FontSubstituting, AddressOf rtfImportSettings_FontSubstituting -rtfFormatProvider.ImportSettings = rtfImportSettings - -```` - - - -{{endregion}} - -#### FontSubstituting Event - -{{source=..\SamplesCS\RichTextEditor\ImportExport\RtfFormatProviderForm.cs region=FontSubstituting}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\RtfFormatProviderForm.vb region=FontSubstituting}} -````C# -private void rtfImportSettings_FontSubstituting(object sender, FontSubstitutingEventArgs e) -{ - if (e.OriginalFontName.Equals("Cambria")) - { - e.SubstitutionFontFamily = new Telerik.WinControls.RichTextEditor.UI.FontFamily("Calibri"); - } -} - -```` -````VB.NET -Private Sub rtfImportSettings_FontSubstituting(ByVal sender As Object, ByVal e As FontSubstitutingEventArgs) - If e.OriginalFontName.Equals("Cambria") Then - e.SubstitutionFontFamily = New Telerik.WinControls.RichTextEditor.UI.FontFamily("Calibri") - End If -End Sub - -```` - - - -{{endregion}} - -## See Also - - * [Getting Started]({%slug winforms/richtexteditor-/getting-started%}) - * [Using PdfFormatProvider]({%slug winforms/richtexteditor/import-export/rtf/rtfformatprovider%}) \ No newline at end of file +--- +title: Settings +page_title: Settings - WinForms RichTextEditor Control +description: RtfFormatProvider allows for import of RTF documents and respectively export of WinForms RichTextEditor to RTF. +slug: winforms/richtexteditor/import-export/rtf/settings +tags: import/export +published: True +position: 1 +--- + +# Settings + +__RtfFormatProvider__ allows for import of RTF documents and respectively export of RadRichTextEditor to Rtf. Additionally, the import/export settings provide modification options. The current article outlines the available settings. + +## Export Settings + +__RtfFormatProvider__ exposes __ExportSettings__, which allow customization in how fields are exported. The __ExportSetting__s property is of type RtfExportSettings which have the following properties and events: + +* __ExportImagesInCompatibilityMode__: A property of type bool that gets or sets whether the images should be exported in compatibility mode. You can use this option when the document will be used in older readers. +* __ImageExporting__: Handling this event allows you to change the bytes and the extension of the image before exporting it. +* __FieldResultMode__: This property defines how the fields are exported in the RTF content. This property is an enumeration and it allows the following values: + * __Code__: Shows all fields codes in the current document. + * __DisplayName__: Show all fields names in the current document. + * __Result__: Replace the merge fields in your document with actual data from your recipient list. + +#### Setting the ExportSettings of the RtfFormatProvider + + + + + +## Import Settings + +Through the __ImportSettings__ of __RtfFormatProvider__ you can utilize the __FontSubstituting__ event. This event allows you to handle the cases when the Rtf source specifies a __Font__ that is not available to the __RichTextBox__. This is particularly useful in __Silverlight__ when the __Font__ can be resolved only if it is among the default ones when you do not want to rely on it being installed on the client machine. __Example 4__ shows how you can subscribe to the event and handle it. + +#### Setup Default RtfFormatProvider + + + + + +#### FontSubstituting Event + + + + + + +## See Also + + * [Getting Started]({%slug winforms/richtexteditor-/getting-started%}) + * [Using PdfFormatProvider]({%slug winforms/richtexteditor/import-export/rtf/rtfformatprovider%}) diff --git a/controls/richtexteditor/import-export/xaml/settings.md b/controls/richtexteditor/import-export/xaml/settings.md index 7cceb2c5b..1b3b314ef 100644 --- a/controls/richtexteditor/import-export/xaml/settings.md +++ b/controls/richtexteditor/import-export/xaml/settings.md @@ -1,137 +1,77 @@ ---- -title: Settings -page_title: Settings - WinForms RichTextEditor Control -description: XamlFormatProvider allows for import of XAML documents and respectively export of WinForms RichTextEditor to XAML file. -slug: winforms/richtexteditor/import-export/xaml/settings -tags: import/export -published: True -position: 1 ---- - -# Settings - -__XamlFormatProvider__ allows for import of XAML documents and respectively export of RadRichTextEditor to XAML file. Additionally, the import/export settings provide modification options. The current article outlines the available settings. - ->note Since R2 2023 SP1 the XamlFormatProvider automatically verifies the imported XAML. More information is available in the [Xaml Verification]({%slug richtexteditor-xaml-verification%}) article. - -## Export Settings - -__XamlFormatProvider__ exposes __ExportSettings__, which allow you to control the export of the RadRichTextEditor document. - -### Export Settings Properties -* __ImageExportMode__: A property of type __ImageExportMode__ that gets or sets how the image should be exported. This property is an enumeration and it allows the following values: - * __None__: Images are not exported. - * __RawData__: Images are exported using their RawData. - * __ImageExportingEvent__: Event is fired on exporting. - * __UriSource__: The UriSource property is used instead of RawData. Bare in mind that this property may not be set on all images. - -### Export Settings Events -* __ImageExporting__: This event is fired every time before exporting an Image. -* __InlineUIContainerExporting__: This event is fired every time before exporting an __InlineUIContainer__. - ->These events will be called when the __ImageExportMode__ enumeration property is set to __ImageExportingEvent__. - -#### Setting the ExportSettings of the XamlFormatProvider -{{source=..\SamplesCS\RichTextEditor\ImportExport\XamlFormatProviderForm.cs region=SetupXamlExportSettings}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\XamlFormatProviderForm.vb region=SetupXamlExportSettings}} -````C# -XamlFormatProvider xamlFormatProvider = new XamlFormatProvider(); -XamlExportSettings settings = new XamlExportSettings(); -settings.ImageExportMode = ImageExportMode.UriSource; -xamlFormatProvider.ExportSettings = settings; - -```` -````VB.NET -Dim xamlFormatProvider As XamlFormatProvider = New XamlFormatProvider() -Dim settings As XamlExportSettings = New XamlExportSettings() -settings.ImageExportMode = ImageExportMode.UriSource -xamlFormatProvider.ExportSettings = settings - -```` -{{endregion}} - -## Import Settings - -__XamlFormatProvider__ exposes __ImportSettings__, which allow you to control the import of the XAML file. - -### Import Settings Events -* __ImageImported__: This event is fired every time when the __Image__ is imported. +--- +title: Settings +page_title: Settings - WinForms RichTextEditor Control +description: XamlFormatProvider allows for import of XAML documents and respectively export of WinForms RichTextEditor to XAML file. +slug: winforms/richtexteditor/import-export/xaml/settings +tags: import/export +published: True +position: 1 +--- + +# Settings + +__XamlFormatProvider__ allows for import of XAML documents and respectively export of RadRichTextEditor to XAML file. Additionally, the import/export settings provide modification options. The current article outlines the available settings. + +>note Since R2 2023 SP1 the XamlFormatProvider automatically verifies the imported XAML. More information is available in the [Xaml Verification]({%slug richtexteditor-xaml-verification%}) article. + +## Export Settings + +__XamlFormatProvider__ exposes __ExportSettings__, which allow you to control the export of the RadRichTextEditor document. + +### Export Settings Properties +* __ImageExportMode__: A property of type __ImageExportMode__ that gets or sets how the image should be exported. This property is an enumeration and it allows the following values: + * __None__: Images are not exported. + * __RawData__: Images are exported using their RawData. + * __ImageExportingEvent__: Event is fired on exporting. + * __UriSource__: The UriSource property is used instead of RawData. Bare in mind that this property may not be set on all images. + +### Export Settings Events +* __ImageExporting__: This event is fired every time before exporting an Image. +* __InlineUIContainerExporting__: This event is fired every time before exporting an __InlineUIContainer__. + +>These events will be called when the __ImageExportMode__ enumeration property is set to __ImageExportingEvent__. + +#### Setting the ExportSettings of the XamlFormatProvider + + + + + +## Import Settings + +__XamlFormatProvider__ exposes __ImportSettings__, which allow you to control the import of the XAML file. + +### Import Settings Events +* __ImageImported__: This event is fired every time when the __Image__ is imported. * __InlineUIContainerImported__: This event is fired every time when the __InlineUIContainer__ is imported. -* __PreProcessingXaml__: This event is fired right before the XAML is parsed and allows you to check it for undesired content. The event arguments expose the following options: - - __Xaml__: The XAML string that is being imported. You can changed it and then pass it again to the property so the changed XAML is imported. - - __SkipXamlValidation__: Allows you to skip the default XAML types validation. - -#### Disable the default XAML validation__ - -{{source=..\SamplesCS\RichTextEditor\ImportExport\XamlFormatProviderForm.cs region=SkipVerification}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\XamlFormatProviderForm.vb region=SkipVerification}} - -````C# - -XamlFormatProvider provider = new XamlFormatProvider(); -provider.ImportSettings.PreProcessingXaml += (s, args) => { - - args.SkipXamlValidation = true; -}; - -```` -````VB.NET - -Dim provider As XamlFormatProvider = New XamlFormatProvider() -AddHandler provider.ImportSettings.PreProcessingXaml, Function(s, args) - args.SkipXamlValidation = True - End Function - -```` - -{{endregion}}} - -#### Setting the ImportSettings of the XamlFormatProvider - -{{source=..\SamplesCS\RichTextEditor\ImportExport\XamlFormatProviderForm.cs region=SetupXamlImportSettings}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\XamlFormatProviderForm.vb region=SetupXamlImportSettings}} -````C# -XamlFormatProvider xamlFormatProvider = new XamlFormatProvider(); -XamlImportSettings settings = new XamlImportSettings(); -xamlFormatProvider.ImportSettings = settings; -settings.ImageImported += XamlImportSettings_ImageImported; - -```` -````VB.NET -Dim xamlFormatProvider As XamlFormatProvider = New XamlFormatProvider() -Dim settings As XamlImportSettings = New XamlImportSettings() -xamlFormatProvider.ImportSettings = settings -AddHandler settings.ImageImported, AddressOf XamlImportSettings_ImageImported - -```` - -{{endregion}} - -#### ImageImported Event - -{{source=..\SamplesCS\RichTextEditor\ImportExport\XamlFormatProviderForm.cs region=ImageImportedEvent}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\XamlFormatProviderForm.vb region=ImageImportedEvent}} - -````C# - -private void XamlImportSettings_ImageImported(object sender, ImageImportedEventArgs e) -{ - var img = e.Image; +* __PreProcessingXaml__: This event is fired right before the XAML is parsed and allows you to check it for undesired content. The event arguments expose the following options: + - __Xaml__: The XAML string that is being imported. You can changed it and then pass it again to the property so the changed XAML is imported. + - __SkipXamlValidation__: Allows you to skip the default XAML types validation. + +#### Disable the default XAML validation__ + + + + + + } - -```` -````VB.NET - -Private Sub XamlImportSettings_ImageImported(ByVal sender As Object, ByVal e As ImageImportedEventArgs) - Dim img = e.Image -End Sub - -```` - -{{endregion}} - - -## See Also - - * [Getting Started]({%slug winforms/richtexteditor-/getting-started%}) - * [Using XamlFormatProvider]({%slug winforms/richtexteditor/import-export/xaml/xamlformatprovider%}) \ No newline at end of file + +#### Setting the ImportSettings of the XamlFormatProvider + + + + + + +#### ImageImported Event + + + + + + +## See Also + + * [Getting Started]({%slug winforms/richtexteditor-/getting-started%}) + * [Using XamlFormatProvider]({%slug winforms/richtexteditor/import-export/xaml/xamlformatprovider%}) diff --git a/controls/richtexteditor/import-export/xaml/xaml-verification.md b/controls/richtexteditor/import-export/xaml/xaml-verification.md index 3927c8d48..5c4c7899f 100644 --- a/controls/richtexteditor/import-export/xaml/xaml-verification.md +++ b/controls/richtexteditor/import-export/xaml/xaml-verification.md @@ -18,28 +18,10 @@ If you are sure that the imported XAML can be trusted for example it comes inter #### Disable the default XAML validation -{{source=..\SamplesCS\RichTextEditor\ImportExport\XamlFormatProviderForm.cs region=SkipVerification}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\XamlFormatProviderForm.vb region=SkipVerification}} + + -````C# - -XamlFormatProvider provider = new XamlFormatProvider(); -provider.ImportSettings.PreProcessingXaml += (s, args) => { - - args.SkipXamlValidation = true; -}; - -```` -````VB.NET - -Dim provider As XamlFormatProvider = New XamlFormatProvider() -AddHandler provider.ImportSettings.PreProcessingXaml, Function(s, args) - args.SkipXamlValidation = True - End Function - -```` -{{endregion}} ## Add custom assembly to the allowed assemblies. diff --git a/controls/richtexteditor/import-export/xaml/xamlformatprovider.md b/controls/richtexteditor/import-export/xaml/xamlformatprovider.md index 802d5ead6..701cbfb2f 100644 --- a/controls/richtexteditor/import-export/xaml/xamlformatprovider.md +++ b/controls/richtexteditor/import-export/xaml/xamlformatprovider.md @@ -24,27 +24,9 @@ In order to import a XAML document you can use the overloads of the __Import()__ The first example shows how to use XamlFormatProvider to import XAML document from a file. #### Import XAML Document from a File -{{source=..\SamplesCS\RichTextEditor\ImportExport\XamlFormatProviderForm.cs region=ImportDocumentFromFile}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\XamlFormatProviderForm.vb region=ImportDocumentFromFile}} -````C# -XamlFormatProvider xamlformatProvider = new XamlFormatProvider(); -using (Stream stream = File.OpenRead(@"..\..\RichTextEditor\ImportExport\Sample.xaml")) -{ - this.radRichTextEditor1.Document = xamlformatProvider.Import(stream); -} + + -```` -````VB.NET -Dim xamlformatProvider As XamlFormatProvider = New XamlFormatProvider() -Using inputStream As FileStream = File.OpenRead("..\..\RichTextEditor\ImportExport\Sample.xml") - Me.radRichTextEditor1.Document = xamlformatProvider.Import(inputStream) -End Using - -```` - - - -{{endregion}} ## Export @@ -53,29 +35,10 @@ In order to export a document to XAML, you need to use the __Export()__ method o This example shows how to use __XamlFormatProvider__ to export __RadDocument__ to a file. #### Export Document to a File -{{source=..\SamplesCS\RichTextEditor\ImportExport\XamlFormatProviderForm.cs region=ExportDocumentToFile}} -{{source=..\SamplesVB\RichTextEditor\ImportExport\XamlFormatProviderForm.vb region=ExportDocumentToFile}} -````C# -XamlFormatProvider provider = new XamlFormatProvider(); -using (FileStream output = File.OpenWrite("Sample.xaml")) -{ - RadDocument document = this.radRichTextEditor1.Document; - provider.Export(document, output); -} - -```` -````VB.NET -Dim provider As XamlFormatProvider = New XamlFormatProvider() -Using output As FileStream = File.OpenWrite("Sample.xaml") - Dim document As RadDocument = Me.radRichTextEditor1.Document - provider.Export(document, output) -End Using - -```` - + + -{{endregion}} ## See Also diff --git a/controls/richtexteditor/keyboard-support.md b/controls/richtexteditor/keyboard-support.md index 95fa35257..4b555d620 100644 --- a/controls/richtexteditor/keyboard-support.md +++ b/controls/richtexteditor/keyboard-support.md @@ -1,139 +1,82 @@ ---- -title: Keyboard Support -page_title: Keyboard Support - WinForms RichTextEditor Control -description: WinForms RichTextEditor supports shortcuts. There are default key-bindings defined for the most widely used operations. -slug: winforms/richtexteditor-/keyboard-support -tags: keyboard,support -published: True -position: 10 -previous_url: richtexteditor-keyboard-support ---- - -# Keyboard Support -Telerik __RadRichTextEditor__ for WinForms supports shortcuts. There are default key-bindings defined for the most widely used operations, namely: - -| __Action__ | __Hotkey__ | -| ------ | ------ | -|Copy|Ctrl+C| -|Paste|Ctrl+V| -|Cut|Ctrl+X| -|Delete|Delete| -|Undo|Ctrl+Z| -|Redo|Ctrl+Y| -|InsertLineBreak|Shift+Enter| -|InsertPageBreak|Ctrl+Enter| -|ToggleBold|Ctrl+B, Ctrl+Shift+B| -|ToggleItalic|Ctrl+I, Ctrl+Shift+I| -|ToggleSuperscript|Ctrl+'+'| -|ToggleSubscript|Ctrl+Shift+'+'| -|ToggleUnderline|Ctrl+U| -|ClearFormatting|Ctrl+Space| -|Copy Formatting|Ctrl+Shift+C| -|Paste Formatting|Ctrl+Shift+V| -|Cancel Format Painter|Esc| -|ChangeTextAlignment with parameter RadTextAlignment.Justify|Ctrl+J| -|ChangeTextAlignment with parameter RadTextAlignment.Right|Ctrl+R| -|ChangeTextAlignment with parameter RadTextAlignment.Left|Ctrl+L| -|ChangeTextAlignment with parameter RadTextAlignment.Center|Ctrl+E| -|SelectAll|Ctrl+A| -|MoveCaret with parameter MoveCaretDirections.Previous|Left Arrow| -|MoveCaret with parameter MoveCaretDirections.Next|Right Arrow| -|MoveCaret with parameter MoveCaretDirections.PreviousWord|Ctrl+Left Arrow| -|MoveCaret with parameter MoveCaretDirections.NextWord|Ctrl+Right Arrow| -|MoveCaret with parameter MoveCaretDirections.Up|Upper Arrow| -|MoveCaret with parameter MoveCaretDirections.Down|Down Arrow| -|MoveCaret with parameter MoveCaretDirections. ParagraphStart|Ctrl+Upper Arrow| -|MoveCaret with parameter MoveCaretDirections. ParagraphEnd|Ctrl+Down Arrow| -|MoveCaret with parameter MoveCaretDirections.Home|Home| -|MoveCaret with parameter MoveCaretDirections.DocumentStart|Ctrl+Home| -|MoveCaret with parameter MoveCaretDirections.End|End| -|MoveCaret with parameter MoveCaretDirections.DocumentEnd|Ctrl+End| -|MoveCaret with parameter MoveCaretDirections.PageUp|PageUp| -|MoveCaret with parameter MoveCaretDirections.PageDown|PageDown| -|ShowFindReplaceDialog|Ctrl+F| -|ShowFontPropertiesDialog|Ctrl+D| -|ShowInsertHyperlinkDialog|Ctrl+K| - -Now, these key shortcuts can be overridden and customized to the liking of the user. This can be achieved by creating a custom __RichTextEditorInputBehavior__ descendant: - -{{source=..\SamplesCS\RichTextEditor\KeyboardSupport.cs region=input}} -{{source=..\SamplesVB\RichTextEditor\KeyboardSupport.vb region=input}} - -````C# - -public class MyInputBehavior : Telerik.WinForms.RichTextEditor.RichTextEditorInputBehavior -{ - public MyInputBehavior(RadRichTextBox editor) : base(editor) - { - } - protected override void PerformCopyOperation(System.Windows.Forms.KeyEventArgs e) - { - base.PerformCutOperation(e); - } -} - -```` -````VB.NET -Public Class MyInputBehavior - Inherits Telerik.WinForms.RichTextEditor.RichTextEditorInputBehavior - Public Sub New(ByVal editor As RadRichTextBox) - MyBase.New(editor) - End Sub - Protected Overrides Sub PerformCopyOperation(ByVal e As System.Windows.Forms.KeyEventArgs) - MyBase.PerformCutOperation(e) - End Sub -End Class - -```` - -{{endregion}} - -The default behavior can be changed like this: - -{{source=..\SamplesCS\RichTextEditor\KeyboardSupport.cs region=change}} -{{source=..\SamplesVB\RichTextEditor\KeyboardSupport.vb region=change}} - -````C# - -radRichTextEditor1.InputHandler = new MyInputBehavior(radRichTextEditor1.RichTextBoxElement); - -```` -````VB.NET -radRichTextEditor1.InputHandler = New MyInputBehavior(radRichTextEditor1.RichTextBoxElement) - -```` - -{{endregion}} - -Another way to customize the control behavior is to use the __PreviewEditorKeyDown__ event. For example, pressing **RightAlt** causes **Control** and **Alt** to be sent as arguments to the **PreviewKeyDown** event. Thus, **RightAlt**+**E** triggers a formatting command for paragraph alignment instead of inputting the **ę** character. In that case, you can handle the **PreviewEditorKeyDown** event in the following way: - -{{source=..\SamplesCS\RichTextEditor\KeyboardSupport.cs region=keyDown}} -{{source=..\SamplesVB\RichTextEditor\KeyboardSupport.vb region=keyDown}} - -````C# - -void RichTextBoxElement_PreviewEditorKeyDown(object sender, PreviewEditorKeyEventArgs e) -{ - if ((Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))) - { - e.SuppressDefaultAction = true; - } -} - -```` -````VB.NET -Private Sub RichTextBoxElement_PreviewEditorKeyDown(ByVal sender As Object, ByVal e As PreviewEditorKeyEventArgs) - If (Keyboard.IsKeyDown(Key.LeftShift) OrElse Keyboard.IsKeyDown(Key.RightShift)) Then - e.SuppressDefaultAction = True - End If -End Sub - -```` - -{{endregion}} - -# See Also - - * [Clipboard Support]({%slug winforms/richtexteditor-/features/clipboard-support%}) - - * [Formatting API]({%slug winforms/richtexteditor-/getting-started/formatting-api%}) +--- +title: Keyboard Support +page_title: Keyboard Support - WinForms RichTextEditor Control +description: WinForms RichTextEditor supports shortcuts. There are default key-bindings defined for the most widely used operations. +slug: winforms/richtexteditor-/keyboard-support +tags: keyboard,support +published: True +position: 10 +previous_url: richtexteditor-keyboard-support +--- + +# Keyboard Support +Telerik __RadRichTextEditor__ for WinForms supports shortcuts. There are default key-bindings defined for the most widely used operations, namely: + +| __Action__ | __Hotkey__ | +| ------ | ------ | +|Copy|Ctrl+C| +|Paste|Ctrl+V| +|Cut|Ctrl+X| +|Delete|Delete| +|Undo|Ctrl+Z| +|Redo|Ctrl+Y| +|InsertLineBreak|Shift+Enter| +|InsertPageBreak|Ctrl+Enter| +|ToggleBold|Ctrl+B, Ctrl+Shift+B| +|ToggleItalic|Ctrl+I, Ctrl+Shift+I| +|ToggleSuperscript|Ctrl+'+'| +|ToggleSubscript|Ctrl+Shift+'+'| +|ToggleUnderline|Ctrl+U| +|ClearFormatting|Ctrl+Space| +|Copy Formatting|Ctrl+Shift+C| +|Paste Formatting|Ctrl+Shift+V| +|Cancel Format Painter|Esc| +|ChangeTextAlignment with parameter RadTextAlignment.Justify|Ctrl+J| +|ChangeTextAlignment with parameter RadTextAlignment.Right|Ctrl+R| +|ChangeTextAlignment with parameter RadTextAlignment.Left|Ctrl+L| +|ChangeTextAlignment with parameter RadTextAlignment.Center|Ctrl+E| +|SelectAll|Ctrl+A| +|MoveCaret with parameter MoveCaretDirections.Previous|Left Arrow| +|MoveCaret with parameter MoveCaretDirections.Next|Right Arrow| +|MoveCaret with parameter MoveCaretDirections.PreviousWord|Ctrl+Left Arrow| +|MoveCaret with parameter MoveCaretDirections.NextWord|Ctrl+Right Arrow| +|MoveCaret with parameter MoveCaretDirections.Up|Upper Arrow| +|MoveCaret with parameter MoveCaretDirections.Down|Down Arrow| +|MoveCaret with parameter MoveCaretDirections. ParagraphStart|Ctrl+Upper Arrow| +|MoveCaret with parameter MoveCaretDirections. ParagraphEnd|Ctrl+Down Arrow| +|MoveCaret with parameter MoveCaretDirections.Home|Home| +|MoveCaret with parameter MoveCaretDirections.DocumentStart|Ctrl+Home| +|MoveCaret with parameter MoveCaretDirections.End|End| +|MoveCaret with parameter MoveCaretDirections.DocumentEnd|Ctrl+End| +|MoveCaret with parameter MoveCaretDirections.PageUp|PageUp| +|MoveCaret with parameter MoveCaretDirections.PageDown|PageDown| +|ShowFindReplaceDialog|Ctrl+F| +|ShowFontPropertiesDialog|Ctrl+D| +|ShowInsertHyperlinkDialog|Ctrl+K| + +Now, these key shortcuts can be overridden and customized to the liking of the user. This can be achieved by creating a custom __RichTextEditorInputBehavior__ descendant: + + + + + + +The default behavior can be changed like this: + + + + + + +Another way to customize the control behavior is to use the __PreviewEditorKeyDown__ event. For example, pressing **RightAlt** causes **Control** and **Alt** to be sent as arguments to the **PreviewKeyDown** event. Thus, **RightAlt**+**E** triggers a formatting command for paragraph alignment instead of inputting the **ę** character. In that case, you can handle the **PreviewEditorKeyDown** event in the following way: + + + + + + +# See Also + + * [Clipboard Support]({%slug winforms/richtexteditor-/features/clipboard-support%}) + + * [Formatting API]({%slug winforms/richtexteditor-/getting-started/formatting-api%}) diff --git a/controls/richtexteditor/localization.md b/controls/richtexteditor/localization.md index d7d571b1c..9e8697c52 100644 --- a/controls/richtexteditor/localization.md +++ b/controls/richtexteditor/localization.md @@ -13,20 +13,10 @@ previous_url: richtexteditor-localization To change the default English localization provider you should use the __CurrentProvider__ static property of the __RichTextBoxLocalizationProvider__ class. For example, you can load the string from a XML file like this: -{{source=..\SamplesCS\RichTextEditor\Localization.cs region=xml}} -{{source=..\SamplesVB\RichTextEditor\Localization.vb region=xml}} + + -````C# - -RichTextBoxLocalizationProvider.CurrentProvider = RichTextBoxLocalizationProvider.FromFile(@"C:\RichTextBoxStrings.xml"); -```` -````VB.NET -RichTextBoxLocalizationProvider.CurrentProvider = RichTextBoxLocalizationProvider.FromFile("C:\RichTextBoxStrings.xml") - -```` - -{{endregion}} >important You can download a XML file that contains all the currently used strings from here: [Strings file](https://github.com/telerik/winforms-sdk/blob/master/Localization%20Providers/RichTextBoxStrings.xml) > @@ -36,102 +26,16 @@ RichTextBoxLocalizationProvider.CurrentProvider = RichTextBoxLocalizationProvide Another approach is to create a custom localization provider class which inherits __RichTextBoxLocalizationProvider__. In it you should just override the __GetLocalizedString__ method and return the localized string depending on current id. -{{source=..\SamplesCS\RichTextEditor\Localization.cs region=custom}} -{{source=..\SamplesVB\RichTextEditor\Localization.vb region=custom}} - -````C# - -public class MyRichTextBoxLocalizationProvider : RichTextBoxLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case "Documents_FindReplaceDialog_FindNext": - return "Weitersuchen"; - case "Documents_FindReplaceDialog_Header": - return "Suchen und Ersetzen"; - case "Documents_FindReplaceDialog_Replace": - return "Ersetzen"; - case "Documents_FindReplaceDialog_ReplaceAll": - return "Alle ersetzen"; - case "Documents_FindReplaceDialog_ReplaceWith": - return "Ersetzen durch"; - case "Documents_FindReplaceDialog_TextToFind": - return "Suchen nach"; - case "Documents_FindReplaceDialog_RestartSearch": - return "Zeigen unten die Multifunktionsleiste"; - case "Documents_FindReplaceDialog_SearchedTextNotFound": - return "Der Suchbegriff wurde nicht gefunden"; - case "RibbonUI_BackstageButtonPrint": - return "Druck"; - case "Invalid_Hyperlink_Message": - return "Ungültige oder bösartiger Hyperlink. Sei vorsichtig:"; - case "Invalid_Hyperlink_Caption": - return "Ungültige Hyperlink Beschriftung"; - - } - - return base.GetLocalizedString(id); - } -} - -```` -````VB.NET -Public Class MyRichTextBoxLocalizationProvider - Inherits RichTextBoxLocalizationProvider - Public Overrides Function GetLocalizedString(ByVal id As String) As String - Select Case id - Case "Documents_FindReplaceDialog_FindNext" - Return "Weitersuchen" - Case "Documents_FindReplaceDialog_Header" - Return "Suchen und Ersetzen" - Case "Documents_FindReplaceDialog_Replace" - Return "Ersetzen" - Case "Documents_FindReplaceDialog_ReplaceAll" - Return "Alle ersetzen" - Case "Documents_FindReplaceDialog_ReplaceWith" - Return "Ersetzen durch" - Case "Documents_FindReplaceDialog_TextToFind" - Return "Suchen nach" - Case "Documents_FindReplaceDialog_RestartSearch" - Return "Zeigen unten die Multifunktionsleiste" - Case "Documents_FindReplaceDialog_SearchedTextNotFound" - Return "Der Suchbegriff wurde nicht gefunden" - Case "RibbonUI_BackstageButtonPrint" - Return "Druck" - Case "Invalid_Hyperlink_Message" - Return "Ungültige oder bösartiger Hyperlink. Sei vorsichtig:" - Case "Invalid_Hyperlink_Caption" - Return "Ungültige Hyperlink Beschriftung" - End Select - Return MyBase.GetLocalizedString(id) - End Function -End Class - -```` - -{{endregion}} + + -The following code snippet shows how you can use the new class: -{{source=..\SamplesCS\RichTextEditor\Localization.cs region=change}} -{{source=..\SamplesVB\RichTextEditor\Localization.vb region=change}} -````C# - -RichTextBoxLocalizationProvider.CurrentProvider = new MyRichTextBoxLocalizationProvider(); - -InitializeComponent(); - -```` -````VB.NET -RichTextBoxLocalizationProvider.CurrentProvider = New MyRichTextBoxLocalizationProvider() -InitializeComponent() +The following code snippet shows how you can use the new class: -```` + + -{{endregion}} >note It is necessary to specify the RichTextBoxLocalizationProvider. __CurrentProvider__ property before initializing the components. diff --git a/controls/richtexteditor/printing.md b/controls/richtexteditor/printing.md index c4d6d20ff..a125ff4b0 100644 --- a/controls/richtexteditor/printing.md +++ b/controls/richtexteditor/printing.md @@ -25,23 +25,10 @@ In order to take advantage of the printing functionality, the document you want Additionally to using the UI, you can print by taking advantage of the __Print()__, __Print(bool showPrinterSettings)__ and __Print(bool showPrinterSettings, RadPrintDocument document)__ methods of __RadRichTextEditor__. In addition **RadRichTextEditor** also provides a __PrintPreview()__ and __PrintPreview(RadPrintDocument document)__ methods. -{{source=..\SamplesCS\RichTextEditor\Print.cs region=print}} -{{source=..\SamplesVB\RichTextEditor\Print.vb region=print}} + + -````C# -this.radRichTextEditor1.Print(); -//or -this.radRichTextEditor1.PrintPreview(); -```` -````VB.NET -Me.radRichTextEditor1.Print() -'or -Me.radRichTextEditor1.PrintPreview() - -```` - -{{endregion}} If you want to specify any print setting you can create an instance of [RadPrintDocument]({%slug winforms/telerik-presentation-framework/printing-support/radprintdocument%}) and pass it to the respective method override. diff --git a/controls/richtexteditor/radrichtexteditorruler.md b/controls/richtexteditor/radrichtexteditorruler.md index 9e800163c..d1b0841e2 100644 --- a/controls/richtexteditor/radrichtexteditorruler.md +++ b/controls/richtexteditor/radrichtexteditorruler.md @@ -36,36 +36,8 @@ Since __RadRichTextEditorRuler__ is a separate control it is available in the to You can add the control in code as well. The following snippet demonstrates how to add __RadRichTextEditorRuler__ and __RadRichTextEditor__ to a form: -{{source=..\SamplesCS\RichTextEditor\RadRichTextEditorRulerCode.cs region=ruler}} -{{source=..\SamplesVB\RichTextEditor\RadRichTextEditorRulerCode.vb region=ruler}} - -````C# -void RadRichTextEditorRuler_Load(object sender, EventArgs e) -{ - RadRichTextEditor radRichTextEditor1 = new RadRichTextEditor(); - radRichTextEditor1.LayoutMode = DocumentLayoutMode.Paged; - RadRichTextEditorRuler documentRuler1 = new Telerik.WinControls.UI.RadRichTextEditorRuler(); - documentRuler1.AssociatedRichTextBox = radRichTextEditor1; - documentRuler1.Dock = System.Windows.Forms.DockStyle.Fill; - documentRuler1.Controls.Add(radRichTextEditor1); - this.Controls.Add(documentRuler1); -} - -```` -````VB.NET -Private Sub RadRichTextEditorRuler_Load(ByVal sender As Object, ByVal e As EventArgs) - Dim radRichTextEditor1 As New RadRichTextEditor() - radRichTextEditor1.LayoutMode = DocumentLayoutMode.Paged - Dim documentRuler1 As RadRichTextEditorRuler = New Telerik.WinControls.UI.RadRichTextEditorRuler() - documentRuler1.AssociatedRichTextBox = radRichTextEditor1 - documentRuler1.Dock = System.Windows.Forms.DockStyle.Fill - documentRuler1.Controls.Add(radRichTextEditor1) - Me.Controls.Add(documentRuler1) -End Sub - -```` - -{{endregion}} + + diff --git a/controls/richtexteditor/ui-for-applying-rich-text-formatting/context-menu.md b/controls/richtexteditor/ui-for-applying-rich-text-formatting/context-menu.md index badeec371..0e27f59df 100644 --- a/controls/richtexteditor/ui-for-applying-rich-text-formatting/context-menu.md +++ b/controls/richtexteditor/ui-for-applying-rich-text-formatting/context-menu.md @@ -21,24 +21,10 @@ The context menu is enabled by default. You can control this with the __IsContex #### Disabling the context menu -{{source=..\SamplesCS\RichTextEditor\UI\ContextMenuCode.cs region=DisableContextMenu}} -{{source=..\SamplesVB\RichTextEditor\UI\ContextMenuCode.vb region=DisableContextMenu}} + + -````C# -private void DisableContextMenu() -{ - this.radRichTextEditor1.IsContextMenuEnabled = false; -} -```` -````VB.NET -Private Sub DisableContextMenu() - Me.RadRichTextEditor1.IsContextMenuEnabled = False -End Sub - -```` - -{{endregion}} The menu is accessible through the __ContextMenu__ property of __RadRichTextEditor__ control. @@ -58,66 +44,17 @@ The first one involves subscribing to the __Showing__ event of the default __Con #### Subscribe to Event -{{source=..\SamplesCS\RichTextEditor\UI\ContextMenuCode.cs region=SubscribeShowingEvent}} -{{source=..\SamplesVB\RichTextEditor\UI\ContextMenuCode.vb region=SubscribeShowingEvent}} -````C# -Telerik.WinControls.RichTextEditor.UI.ContextMenu contextMenu = (Telerik.WinControls.RichTextEditor.UI.ContextMenu)this.radRichTextEditor1.RichTextBoxElement.ContextMenu; -contextMenu.Showing += this.ContextMenu_Showing; - -```` -````VB.NET -Dim contextMenu As Telerik.WinControls.RichTextEditor.UI.ContextMenu = DirectCast(Me.RadRichTextEditor1.RichTextBoxElement.ContextMenu, Telerik.WinControls.RichTextEditor.UI.ContextMenu) -AddHandler contextMenu.Showing, AddressOf Me.ContextMenu_Showing + + -```` -{{endregion}} #### Handle Event -{{source=..\SamplesCS\RichTextEditor\UI\ContextMenuCode.cs region=HandleShowingEvent}} -{{source=..\SamplesVB\RichTextEditor\UI\ContextMenuCode.vb region=HandleShowingEvent}} - -````C# -private void ContextMenu_Showing(object sender, Telerik.WinForms.RichTextEditor.RichTextBoxUI.Menus.ContextMenuEventArgs e) -{ - if (!this.radRichTextEditor1.Document.Selection.IsEmpty) - { - RadMenuItem menuItem = new RadMenuItem() - { - Text = "Change selection foreground" - }; - menuItem.Click += this.OnChangeSelectionForeground; - ContextMenuGroup contextMenuGroup = new ContextMenuGroup(); - contextMenuGroup.Add(menuItem); - e.ContextMenuGroupCollection.Add(contextMenuGroup); - } -} -private void OnChangeSelectionForeground(object sender, EventArgs e) -{ - this.radRichTextEditor1.ChangeTextForeColor(Colors.Red); -} - -```` -````VB.NET -Private Sub ContextMenu_Showing(sender As Object, e As Telerik.WinForms.RichTextEditor.RichTextBoxUI.Menus.ContextMenuEventArgs) - If Not Me.RadRichTextEditor1.Document.Selection.IsEmpty Then - Dim menuItem As New RadMenuItem() With { - .Text = "Change selection foreground" - } - AddHandler menuItem.Click, AddressOf Me.OnChangeSelectionForeground - Dim contextMenuGroup As New ContextMenuGroup() - contextMenuGroup.Add(menuItem) - e.ContextMenuGroupCollection.Add(contextMenuGroup) - End If -End Sub -Private Sub OnChangeSelectionForeground(sender As Object, e As EventArgs) - Me.RadRichTextEditor1.ChangeTextForeColor(Colors.Red) -End Sub - -```` - -{{endregion}} + + + + >caption Figure 2: Changing Text Color @@ -129,78 +66,19 @@ The second approach is more suitable when you need to reuse the customization ac #### Custom Builder Class -{{source=..\SamplesCS\RichTextEditor\UI\ContextMenuCode.cs region=CustomContextMenuBuilderClass}} -{{source=..\SamplesVB\RichTextEditor\UI\ContextMenuCode.vb region=CustomContextMenuBuilderClass}} - -````C# -public class CustomContextMenuContentBuilder : ContextMenuContentBuilder -{ - public override ContextMenuGroupCollection Construct() - { - var groupsCollection = base.Construct(); - if (!this.RadRichTextBox.Document.Selection.IsEmpty) - { - RadMenuItem menuItem = new RadMenuItem() - { - Text = "Change selection foreground" - }; - menuItem.Click += this.OnChangeSelectionForeground; - ContextMenuGroup contextMenuGroup = new ContextMenuGroup(); - contextMenuGroup.Add(menuItem); - groupsCollection.Add(contextMenuGroup); - } - return groupsCollection; - } - private void OnChangeSelectionForeground(object sender, EventArgs e) - { - this.RadRichTextBox.ChangeTextForeColor(Colors.Red); - } -} - -```` -````VB.NET -Public Class CustomContextMenuContentBuilder - Inherits ContextMenuContentBuilder - Public Overrides Function Construct() As ContextMenuGroupCollection - Dim groupsCollection = MyBase.Construct() - If Not Me.RadRichTextBox.Document.Selection.IsEmpty Then - Dim menuItem As New RadMenuItem() With { - .Text = "Change selection foreground" - } - AddHandler menuItem.Click, AddressOf Me.OnChangeSelectionForeground - Dim contextMenuGroup As New ContextMenuGroup() - contextMenuGroup.Add(menuItem) - groupsCollection.Add(contextMenuGroup) - End If - Return groupsCollection - End Function - Private Sub OnChangeSelectionForeground(sender As Object, e As EventArgs) - Me.RadRichTextBox.ChangeTextForeColor(Colors.Red) - End Sub -End Class - -```` -{{endregion}} + + -Now you can simply assign the instance of your class to the __ContentBuilder__ property of the context menu: -#### Assinging Builder -{{source=..\SamplesCS\RichTextEditor\UI\ContextMenuCode.cs region=AssignCustomContextMenuBuilder}} -{{source=..\SamplesVB\RichTextEditor\UI\ContextMenuCode.vb region=AssignCustomContextMenuBuilder}} +Now you can simply assign the instance of your class to the __ContentBuilder__ property of the context menu: -````C# -Telerik.WinControls.RichTextEditor.UI.ContextMenu contextMenu = (Telerik.WinControls.RichTextEditor.UI.ContextMenu)this.radRichTextEditor1.RichTextBoxElement.ContextMenu; -contextMenu.ContentBuilder = new CustomContextMenuContentBuilder(); +#### Assinging Builder -```` -````VB.NET -Dim contextMenu As Telerik.WinControls.RichTextEditor.UI.ContextMenu = DirectCast(Me.RadRichTextEditor1.RichTextBoxElement.ContextMenu, Telerik.WinControls.RichTextEditor.UI.ContextMenu) -contextMenu.ContentBuilder = New CustomContextMenuContentBuilder() + + -```` -{{endregion}} And of course, for those of you who don’t need additional UI pop-ups, these can be disabled by setting the __IsContextMenuEnabled__ property of the __RadRichTextEditor__ to __False__. diff --git a/controls/richtexteditor/ui-for-applying-rich-text-formatting/editing-images.md b/controls/richtexteditor/ui-for-applying-rich-text-formatting/editing-images.md index a478a252b..e83909c24 100644 --- a/controls/richtexteditor/ui-for-applying-rich-text-formatting/editing-images.md +++ b/controls/richtexteditor/ui-for-applying-rich-text-formatting/editing-images.md @@ -37,50 +37,17 @@ As most features of the editor, the image editing capabilities can be easily dis To remove the image adorner from your application you can create a new __UILayersBuilder__ as shown [here]({%slug winforms/richtexteditor-/how-to/customize-presentation-through-ui-layers%}) and remove the __AdornerLayer__. -{{source=..\SamplesCS\RichTextEditor\UI\EditingImages.cs region=layer}} -{{source=..\SamplesVB\RichTextEditor\UI\EditingImages.vb region=layer}} - -````C# -public class CustomLayersBuilder : UILayersBuilder -{ - protected override void BuildUILayersOverride(IUILayerContainer uiLayerContainer) - { - uiLayerContainer.UILayers.Remove("AdornerLayer"); - } -} - -```` -````VB.NET -Public Class CustomLayersBuilder - Inherits UILayersBuilder - Protected Overrides Sub BuildUILayersOverride(ByVal uiLayerContainer As IUILayerContainer) - uiLayerContainer.UILayers.Remove("AdornerLayer") - End Sub -End Class - -```` - -{{endregion}} + + -Alternatively, you can disable the capabilities of the image adorner by accessing it though **RadRichTextEditor**'s __ImageSelectionAdornerSettings__ property. This allows you to set the Boolean properties __CanDrag__, __CanResize__ and __CanRotate__ which disable/enable respectively dragging of the image, resizing it or rotating it. -{{source=..\SamplesCS\RichTextEditor\UI\EditingImages.cs region=disable}} -{{source=..\SamplesVB\RichTextEditor\UI\EditingImages.vb region=disable}} -````C# -this.radRichTextEditor1.ImageSelectionAdornerSettings.CanDrag = false; -this.radRichTextEditor1.ImageSelectionAdornerSettings.CanResize = false; -this.radRichTextEditor1.ImageSelectionAdornerSettings.CanRotate = false; +Alternatively, you can disable the capabilities of the image adorner by accessing it though **RadRichTextEditor**'s __ImageSelectionAdornerSettings__ property. This allows you to set the Boolean properties __CanDrag__, __CanResize__ and __CanRotate__ which disable/enable respectively dragging of the image, resizing it or rotating it. -```` -````VB.NET -Me.radRichTextEditor1.ImageSelectionAdornerSettings.CanDrag = False -Me.radRichTextEditor1.ImageSelectionAdornerSettings.CanResize = False -Me.radRichTextEditor1.ImageSelectionAdornerSettings.CanRotate = False + + -```` -{{endregion}} # See Also diff --git a/controls/richtexteditor/ui-for-applying-rich-text-formatting/how-to/custom-ribbon.md b/controls/richtexteditor/ui-for-applying-rich-text-formatting/how-to/custom-ribbon.md index 6d01b45ff..0e985d91f 100644 --- a/controls/richtexteditor/ui-for-applying-rich-text-formatting/how-to/custom-ribbon.md +++ b/controls/richtexteditor/ui-for-applying-rich-text-formatting/how-to/custom-ribbon.md @@ -16,52 +16,10 @@ A common scenario is to hide the "Save As" button and override the functionality #### Create custom RichTextEditorRibbonBar class -{{source=..\SamplesCS\RichTextEditor\UI\CustomRichTextEditorRibbonBar.cs region=CustomRibbonCode}} -{{source=..\SamplesVB\RichTextEditor\UI\CustomRichTextEditorRibbonBar.vb region=CustomRibbonCode}} -````C# -class CustomRichTextEditorRibbonBar : RichTextEditorRibbonBar -{ - public CustomRichTextEditorRibbonBar() - { - buttonSaveHTML.Visible = false; - buttonSavePDF.Visible = false; - buttonSavePlain.Visible = false; - buttonSaveRich.Visible = false; - buttonSaveWord.Visible = false; - buttonXAML.Visible = false; - backstageTabItemSaveAs.Visibility = Telerik.WinControls.ElementVisibility.Collapsed; - } - protected override void ButtonSave_Click(object sender, EventArgs e) - { - var provider = new HtmlFormatProvider(); - string content = provider.Export(this.AssociatedRichTextEditor.Document); - //save the content to the database for example - } -} + + -```` -````VB.NET -Friend Class CustomRichTextEditorRibbonBar - Inherits RichTextEditorRibbonBar - Public Sub New() - buttonSaveHTML.Visible = False - buttonSavePDF.Visible = False - buttonSavePlain.Visible = False - buttonSaveRich.Visible = False - buttonSaveWord.Visible = False - buttonXAML.Visible = False - backstageTabItemSaveAs.Visibility = Telerik.WinControls.ElementVisibility.Collapsed - End Sub - Protected Overrides Sub ButtonSave_Click(ByVal sender As Object, ByVal e As EventArgs) - Dim provider = New HtmlFormatProvider() - Dim content As String = provider.Export(Me.AssociatedRichTextEditor.Document) - 'save the content to the database for example - End Sub -End Class -```` - -{{endregion}} |Default|Custom| |---|---| diff --git a/controls/richtexteditor/upgrading-to-radrichtexteditor.md b/controls/richtexteditor/upgrading-to-radrichtexteditor.md index a400838a8..e366d501e 100644 --- a/controls/richtexteditor/upgrading-to-radrichtexteditor.md +++ b/controls/richtexteditor/upgrading-to-radrichtexteditor.md @@ -21,25 +21,10 @@ In order to convert **RadRichTextBox** to __RadRichTextEditor__ you should take 2\. Replace the __RadRichTextBox__ type with __RadRichTextEditor__ (you can change the name as well) -{{source=..\SamplesCS\RichTextEditor\Upgrade.cs region=upgrade}} -{{source=..\SamplesVB\RichTextEditor\Upgrade.vb region=upgrade}} + + -````C# -//old -private RadRichTextBox radRichTextBox1 = new RadRichTextBox(); -//new -private RadRichTextEditor radRichTextEditor1 = new RadRichTextEditor(); -```` -````VB.NET -'old -' Private radRichTextBox1 As New RadRichTextBox() -'new -Private radRichTextEditor1 As New RadRichTextEditor() - -```` - -{{endregion}} 3\. __RadRichTextEditor__ supports all features that are supported by the **RadRichTextBox** (and much more). However, some of them may not be at the same place and some compile time errors may occur. The final step is to fix these errors, it can be achieved by finding the new equivalents of the missing properties and methods and replacing them. Should you have any issues finding a property or a method, feel free to submit a support ticket and we will gladly assist you. @@ -56,74 +41,30 @@ Private radRichTextEditor1 As New RadRichTextEditor() * The __ShowInsertHyperlinkDialog__ method is moved to the control and now it can be used like this: -{{source=..\SamplesCS\RichTextEditor\ConvertToRadRichTextEditor.cs region=insertHyperlink}} -{{source=..\SamplesVB\RichTextEditor\ConvertToRadRichTextEditor.vb region=insertHyperlink}} - -````C# - -radRichTextEditor1.ShowInsertHyperlinkDialog(); - -```` -````VB.NET -radRichTextEditor1.ShowInsertHyperlinkDialog() + + -```` - -{{endregion}} * The __ShowManageBookmarksDialog__ now can be used as follows: -{{source=..\SamplesCS\RichTextEditor\ConvertToRadRichTextEditor.cs region=insertBookmark}} -{{source=..\SamplesVB\RichTextEditor\ConvertToRadRichTextEditor.vb region=insertBookmark}} - -````C# - -radRichTextEditor1.ShowManageBookmarksDialog(); - -```` -````VB.NET -radRichTextEditor1.ShowManageBookmarksDialog() + + -```` - -{{endregion}} * When you are inserting an image it is mandatory to specify the extension: -{{source=..\SamplesCS\RichTextEditor\ConvertToRadRichTextEditor.cs region=insertImage}} -{{source=..\SamplesVB\RichTextEditor\ConvertToRadRichTextEditor.vb region=insertImage}} - -````C# - -radRichTextEditor1.InsertImage(stream, extension); - -```` -````VB.NET -radRichTextEditor1.InsertImage(stream, extension) - -```` + + -{{endregion}} * Now you can insert table by using the built-in dialog rather than using **InsertTableForm**: -{{source=..\SamplesCS\RichTextEditor\ConvertToRadRichTextEditor.cs region=insertTable}} -{{source=..\SamplesVB\RichTextEditor\ConvertToRadRichTextEditor.vb region=insertTable}} - -````C# - -radRichTextEditor1.ShowInsertTableDialog(); - -```` -````VB.NET -radRichTextEditor1.ShowInsertTableDialog() - -```` + + -{{endregion}} # See Also diff --git a/controls/rotator/tutorial-creating-a-slide-viewer-with-radrotator.md b/controls/rotator/tutorial-creating-a-slide-viewer-with-radrotator.md index 3c2a2e023..6bdeae016 100644 --- a/controls/rotator/tutorial-creating-a-slide-viewer-with-radrotator.md +++ b/controls/rotator/tutorial-creating-a-slide-viewer-with-radrotator.md @@ -27,20 +27,10 @@ The following tutorial demonstrates how to programmatically load images from the 6\. Change the declaration of the form so that it derives from `RadForm`. -{{source=..\SamplesCS\Rotator\TutorialCreatingASlideViewerWithRadRotator.cs region=inheritFromRadForm}} -{{source=..\SamplesVB\Rotator\TutorialCreatingASlideViewerWithRadRotator.Designer.vb region=inheritFromRadForm}} + + -````C# -public partial class TutorialCreatingASlideViewerWithRadRotator : RadForm -```` -````VB.NET -Partial Class TutorialCreatingASlideViewerWithRadRotator - Inherits Telerik.WinControls.UI.RadForm - -```` - -{{endregion}} 7\. Return to the design view of the form. Visual Studio will repaint the form. @@ -48,87 +38,10 @@ Partial Class TutorialCreatingASlideViewerWithRadRotator 8\. Click the **Events** tab of the **Properties** window and navigate to the `Load` event of the form. Double-click it to create a `Load` event handler and replace the code with the following snippet. The code uses the `Directory.GetFiles()` method to retrieve all `.jpg` file paths. Each file path is passed to a `GetThumbNail()` method that returns a `RadImageItem`, which is added to the **RadRotator** `Items` collection. After the image items are loaded, the `Start()` method is called to begin the animation. -{{source=..\SamplesCS\Rotator\TutorialCreatingASlideViewerWithRadRotator.cs region=rotatorExample}} -{{source=..\SamplesVB\Rotator\TutorialCreatingASlideViewerWithRadRotator.vb region=rotatorExample}} - -````C# -public TutorialCreatingASlideViewerWithRadRotator() -{ - InitializeComponent(); - radRotator1.BeginRotate += new BeginRotateEventHandler(radRotator1_BeginRotate); -} -private void TutorialCreatingASlideViewerWithRadRotator_Load(object sender, EventArgs e) -{ - string myPicturesPath = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); - foreach (string fileName in Directory.GetFiles(myPicturesPath, "*.jpg")) - { - radRotator1.Items.Add(GetThumbNail(fileName)); - } - radRotator1.Start(true); - radRotator1.ShouldStopOnMouseOver = false; -} -private RadImageItem GetThumbNail(string path) -{ - RadImageItem imageItem = new RadImageItem(); - Image image = Image.FromFile(path); - // workaround to prevent using internal image thumbnail - image.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); - image.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); - // calculate aspect ratio so image is not distorted - double ratio = 0; - if (image.Width > image.Height) - { - ratio = ClientRectangle.Width / image.Width; - } - else - { - ratio = ClientRectangle.Height / image.Height; - } - int newWidth = (int)(image.Width * ratio); - int newHeight = (int)(image.Height * ratio); - imageItem.Image = image.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero); - return imageItem; -} -void radRotator1_BeginRotate(object sender, BeginRotateEventArgs e) -{ - radLabelElement1.Text = String.Format("Rotating from item {0} to {1}", e.From, e.To); -} - -```` -````VB.NET -Private Sub TutorialCreatingASlideViewerWithRadRotator_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load - Dim myPicturesPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures) - For Each fileName As String In Directory.GetFiles(myPicturesPath, "*.jpg") - RadRotator1.Items.Add(GetThumbNail(fileName)) - Next - RadRotator1.Start(True) - RadRotator1.ShouldStopOnMouseOver = False -End Sub -Private Function GetThumbNail(ByVal path As String) As RadImageItem - Dim imageItem As New RadImageItem() - Dim image As Image = image.FromFile(path) - ' workaround to prevent using internal image thumbnail - image.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone) - image.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone) - ' calculate aspect ratio so image is not distorted - Dim ratio As Double = 0 - If image.Width > image.Height Then - ratio = ClientRectangle.Width / image.Width - Else - ratio = ClientRectangle.Height / image.Height - End If - Dim newWidth As Integer = Convert.ToInt32(image.Width * ratio) - Dim newHeight As Integer = Convert.ToInt32(image.Height * ratio) - imageItem.Image = image.GetThumbnailImage(newWidth, newHeight, Nothing, IntPtr.Zero) - Return imageItem -End Function -Private Sub RadRotator1_BeginRotate(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.BeginRotateEventArgs) Handles RadRotator1.BeginRotate - RadLabelElement1.Text = [String].Format("Rotating from item {0} to {1}", e.From, e.[To]) -End Sub + + -```` -{{endregion}} 9\. Press `F5` to run the application.  diff --git a/controls/scheduler/appearance/formatting-appointments.md b/controls/scheduler/appearance/formatting-appointments.md index 823993974..ab5bf3403 100644 --- a/controls/scheduler/appearance/formatting-appointments.md +++ b/controls/scheduler/appearance/formatting-appointments.md @@ -20,83 +20,20 @@ The code snippet below demonstrates how to change the font, fore color, border c #### Formatting Appointments -{{source=..\SamplesCS\Scheduler\Appearance\FormattingAppointments.cs region=AppointmentFormatting}} -{{source=..\SamplesVB\Scheduler\Appearance\FormattingAppointments.vb region=AppointmentFormatting}} - -````C# - -Font font = new Font("Verdana", 10f, FontStyle.Bold); - -private void radScheduler1_AppointmentFormatting(object sender, Telerik.WinControls.UI.SchedulerAppointmentEventArgs e) -{ - if (e.AppointmentElement.Selected) - { - e.AppointmentElement.Font = font; - e.AppointmentElement.ForeColor = Color.Fuchsia; - e.AppointmentElement.TextAlignment = ContentAlignment.MiddleCenter; - e.AppointmentElement.UseDefaultPaint = true; - e.AppointmentElement.BorderColor = Color.Aqua; - e.AppointmentElement.BorderBoxStyle = BorderBoxStyle.SingleBorder; - e.AppointmentElement.BorderWidth = 3; - } - else - { - e.AppointmentElement.ResetValue(VisualElement.FontProperty, ValueResetFlags.Local); - e.AppointmentElement.ResetValue(VisualElement.ForeColorProperty, ValueResetFlags.Local); - e.AppointmentElement.ResetValue(LightVisualElement.TextAlignmentProperty, ValueResetFlags.Local); - e.AppointmentElement.UseDefaultPaint = false; - e.AppointmentElement.ResetValue(LightVisualElement.BorderColorProperty, ValueResetFlags.Local); - e.AppointmentElement.ResetValue(LightVisualElement.BorderWidthProperty, ValueResetFlags.Local); - e.AppointmentElement.ResetValue(LightVisualElement.BorderBoxStyleProperty, ValueResetFlags.Local); - } -} - -```` -````VB.NET -Private font As New Font("Verdana", 10.0F, FontStyle.Bold) -Private Sub RadScheduler1_AppointmentFormatting(sender As Object, e As Telerik.WinControls.UI.SchedulerAppointmentEventArgs) Handles RadScheduler1.AppointmentFormatting - If e.AppointmentElement.Selected Then - e.AppointmentElement.Font = font - e.AppointmentElement.ForeColor = Color.Fuchsia - e.AppointmentElement.TextAlignment = ContentAlignment.MiddleCenter - e.AppointmentElement.UseDefaultPaint = True - e.AppointmentElement.BorderColor = Color.Aqua - e.AppointmentElement.BorderBoxStyle = BorderBoxStyle.SingleBorder - e.AppointmentElement.BorderWidth = 3 - Else - e.AppointmentElement.ResetValue(VisualElement.FontProperty, ValueResetFlags.Local) - e.AppointmentElement.ResetValue(VisualElement.ForeColorProperty, ValueResetFlags.Local) - e.AppointmentElement.ResetValue(LightVisualElement.TextAlignmentProperty, ValueResetFlags.Local) - e.AppointmentElement.UseDefaultPaint = False - e.AppointmentElement.ResetValue(LightVisualElement.BorderColorProperty, ValueResetFlags.Local) - e.AppointmentElement.ResetValue(LightVisualElement.BorderWidthProperty, ValueResetFlags.Local) - e.AppointmentElement.ResetValue(LightVisualElement.BorderBoxStyleProperty, ValueResetFlags.Local) - End If -End Sub - -```` - -{{endregion}} + + + + >caption Figure 1: Formatting Appointments ![WinForms RadScheduler Formatting Appointments](images/scheduler-appearance-formatting-appointments001.png) It is possible to change the appointments’ shape setting the SchedulerElement.__AppointmentShape__ property to the desired shape. Changing the __AppointmentShape__ will also change the shape of the shadow and the appointment type indicator (tentative/busy).#_[C#] _ -{{source=..\SamplesCS\Scheduler\Appearance\FormattingAppointments.cs region=AppointmentShape}} -{{source=..\SamplesVB\Scheduler\Appearance\FormattingAppointments.vb region=AppointmentShape}} - -````C# - - this.radScheduler1.SchedulerElement.AppointmentShape = new HeartShape(); - -```` -````VB.NET -Me.RadScheduler1.SchedulerElement.AppointmentShape = New HeartShape() + + -```` -{{endregion}} >caption Figure 2: Custom Shapes ![WinForms RadScheduler Custom Shapes](images/scheduler-appearance-formatting-appointments002.png) diff --git a/controls/scheduler/appearance/formatting-cells.md b/controls/scheduler/appearance/formatting-cells.md index 09222d5fc..b6c74ef5c 100644 --- a/controls/scheduler/appearance/formatting-cells.md +++ b/controls/scheduler/appearance/formatting-cells.md @@ -47,34 +47,10 @@ Let's now format some data cells. We will make red the SchedulerCellElements tha #### Data Cells -{{source=..\SamplesCS\Scheduler\Views\FormattingSchedulerCells.cs region=settingRedColor}} -{{source=..\SamplesVB\Scheduler\Views\FormattingSchedulerCells.vb region=settingRedColor}} - -````C# -void radScheduler1_CellFormatting1(object sender, Telerik.WinControls.UI.SchedulerCellEventArgs e) -{ - if (e.CellElement.Date.Month == 4 && e.CellElement.Date.Day == 13) - { - if (!(e.CellElement is SchedulerHeaderCellElement)) - { - e.CellElement.BackColor = Color.Red; - } - } -} - -```` -````VB.NET -Private Sub radScheduler1_CellFormatting1(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.SchedulerCellEventArgs) - If e.CellElement.Date.Month = 4 AndAlso e.CellElement.Date.Day = 13 Then - If Not (TypeOf e.CellElement Is SchedulerHeaderCellElement) Then - e.CellElement.BackColor = Color.Red - End If - End If -End Sub - -```` - -{{endregion}} + + + + We have the desired result. The data cells of April 13 are red. @@ -90,45 +66,10 @@ As you can see, undesired cells become red as well. RadScheduler is using elemen #### Reset Loaclly Set Values -{{source=..\SamplesCS\Scheduler\Views\FormattingSchedulerCells.cs region=resettingRedColor}} -{{source=..\SamplesVB\Scheduler\Views\FormattingSchedulerCells.vb region=resettingRedColor}} - -````C# -void radScheduler1_CellFormatting2(object sender, Telerik.WinControls.UI.SchedulerCellEventArgs e) -{ - if (e.CellElement.Date.Month == 4 && e.CellElement.Date.Day == 13) - { - if (!(e.CellElement is SchedulerHeaderCellElement)) - { - e.CellElement.BackColor = Color.Red; - } - } - else - { - if (!(e.CellElement is SchedulerHeaderCellElement)) - { - e.CellElement.ResetValue(VisualElement.BackColorProperty, ValueResetFlags.Local); - } - } -} - -```` -````VB.NET -Private Sub radScheduler1_CellFormatting2(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.SchedulerCellEventArgs) - If e.CellElement.Date.Month = 4 AndAlso e.CellElement.Date.Day = 13 Then - If Not (TypeOf e.CellElement Is SchedulerHeaderCellElement) Then - e.CellElement.BackColor = Color.Red - End If - Else - If Not (TypeOf e.CellElement Is SchedulerHeaderCellElement) Then - e.CellElement.ResetValue(VisualElement.BackColorProperty, ValueResetFlags.Local) - End If - End If -End Sub - -```` - -{{endregion}} + + + + As you can see in the screenshot below, the styling is now correct, because if the red cells now represent a day different from April 13, the red color is removed. @@ -141,73 +82,10 @@ We are going to make the header cells that displays the text orange, while the h #### Header Cells. -{{source=..\SamplesCS\Scheduler\Views\FormattingSchedulerCells.cs region=headerCellFormatting}} -{{source=..\SamplesVB\Scheduler\Views\FormattingSchedulerCells.vb region=headerCellFormatting}} - -````C# -void radScheduler1_CellFormatting3(object sender, Telerik.WinControls.UI.SchedulerCellEventArgs e) -{ - if (e.CellElement is SchedulerHeaderCellElement) - { - if (e.CellElement.Date.Month == DateTime.Now.Month && e.CellElement.Date.Day == DateTime.Now.Day) - { - if (e.CellElement.Parent is DayViewHeader) - { - e.CellElement.Text = "Birthday!"; - e.CellElement.BackColor = Color.Yellow; - e.CellElement.GradientStyle = GradientStyles.Solid; - e.CellElement.DrawFill = true; - } - else if (e.CellElement.Parent is DayViewAllDayHeader && e.CellElement.Text != "Local") - { - e.CellElement.DrawFill = true; - e.CellElement.BackColor = Color.DarkRed; - } - else - { - e.CellElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local); - } - } - else - { - e.CellElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local); - } - } -} - -```` -````VB.NET -Private Sub radScheduler1_CellFormatting3(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.SchedulerCellEventArgs) - If TypeOf e.CellElement Is SchedulerHeaderCellElement Then - If e.CellElement.[Date].Month = DateTime.Now.Month AndAlso e.CellElement.[Date].Day = DateTime.Now.Day Then - If TypeOf e.CellElement.Parent Is DayViewHeader Then - e.CellElement.Text = "Birthday!" - e.CellElement.BackColor = Color.Yellow - e.CellElement.GradientStyle = GradientStyles.Solid - e.CellElement.DrawFill = True - ElseIf TypeOf e.CellElement.Parent Is DayViewAllDayHeader AndAlso e.CellElement.Text <> "Local" Then - e.CellElement.DrawFill = True - e.CellElement.BackColor = Color.DarkRed - Else - e.CellElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local) - End If - Else - e.CellElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local) - End If - End If -End Sub - -```` - -{{endregion}} + + + + The result of the code snippet above is shown below: >caption Figure 5: Formatted Header Cells diff --git a/controls/scheduler/appearance/modify-size-of-rows-columns-and-resources.md b/controls/scheduler/appearance/modify-size-of-rows-columns-and-resources.md index 3136fa9fb..4f44be9a5 100644 --- a/controls/scheduler/appearance/modify-size-of-rows-columns-and-resources.md +++ b/controls/scheduler/appearance/modify-size-of-rows-columns-and-resources.md @@ -24,22 +24,10 @@ Here is how you can make the middle columns three times bigger: #### Resize Column -{{source=..\SamplesCS\Scheduler\Appearance\ModifySizeOfRowsColumnsAndResources.cs region=DayView}} -{{source=..\SamplesVB\Scheduler\Appearance\ModifySizeOfRowsColumnsAndResources.vb region=DayView}} + + -````C# -scheduler.ActiveViewType = SchedulerViewType.Day; // this can be changed to either Week or WorkWeek, the ViewElement is always SchedulerDayViewElement -(scheduler.ViewElement as SchedulerDayViewElement).SetColumnWidth(1, 3); -```` -````VB.NET -scheduler.ActiveViewType = SchedulerViewType.Day -' this can be changed to either Week or WorkWeek, the ViewElement is always SchedulerDayViewElement -TryCast(scheduler.ViewElement, SchedulerDayViewElement).SetColumnWidth(1, 3) - -```` - -{{endregion}} >important The actual width of a column will be calculated proportionally according to the values other columns have. The default value of each column is 1. This means that setting a value of 2 for a given column will make it twice as large compared to other columns. @@ -56,23 +44,10 @@ The approach for this view is similar: #### Resize Column -{{source=..\SamplesCS\Scheduler\Appearance\ModifySizeOfRowsColumnsAndResources.cs region=MonthView}} -{{source=..\SamplesVB\Scheduler\Appearance\ModifySizeOfRowsColumnsAndResources.vb region=MonthView}} - -````C# -scheduler.ActiveViewType = SchedulerViewType.Month; -(scheduler.ViewElement as SchedulerMonthViewElement).SetColumnWidth(1, 2.5f); -(scheduler.ViewElement as SchedulerMonthViewElement).SetRowHeight(1, 2.5f); - -```` -````VB.NET -scheduler.ActiveViewType = SchedulerViewType.Month -TryCast(scheduler.ViewElement, SchedulerMonthViewElement).SetColumnWidth(1, 2.5F) -TryCast(scheduler.ViewElement, SchedulerMonthViewElement).SetRowHeight(1, 2.5F) + + -```` -{{endregion}} >caption Figure 4: Increased Column Width ![WinForms RadScheduler Increased Column Width](images/scheduler-appearance-modifying-size-of-rows-columns-and-resources004.png) @@ -86,21 +61,10 @@ Here we see the columns named as 19-25 may. The same approach can be applied her #### Resize Column -{{source=..\SamplesCS\Scheduler\Appearance\ModifySizeOfRowsColumnsAndResources.cs region=TimelineView}} -{{source=..\SamplesVB\Scheduler\Appearance\ModifySizeOfRowsColumnsAndResources.vb region=TimelineView}} + + -````C# -scheduler.ActiveViewType = SchedulerViewType.Timeline; -(scheduler.ViewElement as SchedulerTimelineViewElement).SetColumnWidth(1, 3f); -```` -````VB.NET -scheduler.ActiveViewType = SchedulerViewType.Timeline -TryCast(scheduler.ViewElement, SchedulerTimelineViewElement).SetColumnWidth(1, 3.0F) - -```` - -{{endregion}} >caption Figure 6: Increased Column Width ![WinForms RadScheduler Increased Column Width](images/scheduler-appearance-modifying-size-of-rows-columns-and-resources006.png) @@ -114,23 +78,10 @@ Here we see the resources - *"Conference Room 112/113"*. Resizing them can happe #### Resize Resource -{{source=..\SamplesCS\Scheduler\Appearance\ModifySizeOfRowsColumnsAndResources.cs region=ResourceView}} -{{source=..\SamplesVB\Scheduler\Appearance\ModifySizeOfRowsColumnsAndResources.vb region=ResourceView}} - -````C# -scheduler.GroupType = GroupType.Resource; -scheduler.ActiveViewType = SchedulerViewType.Day; -(scheduler.ViewElement as SchedulerDayViewGroupedByResourceElement).SetResourceSize(0, 0.25f); - -```` -````VB.NET -scheduler.GroupType = GroupType.Resource -scheduler.ActiveViewType = SchedulerViewType.Day -TryCast(scheduler.ViewElement, SchedulerDayViewGroupedByResourceElement).SetResourceSize(0, 0.25F) + + -```` -{{endregion}} >caption Figure 8: Increased Resource Size ![WinForms RadScheduler Increased Resource Size](images/scheduler-appearance-modifying-size-of-rows-columns-and-resources008.png) diff --git a/controls/scheduler/appointments-and-dialogs/adding-a-custom-field-to-the-editappointment-dialog.md b/controls/scheduler/appointments-and-dialogs/adding-a-custom-field-to-the-editappointment-dialog.md index 859b0d209..132101595 100644 --- a/controls/scheduler/appointments-and-dialogs/adding-a-custom-field-to-the-editappointment-dialog.md +++ b/controls/scheduler/appointments-and-dialogs/adding-a-custom-field-to-the-editappointment-dialog.md @@ -34,205 +34,39 @@ Here is a step by step guide how to achieve that: 3\. Here is the form's implementation: -{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\CustomAppointmentEditForm.cs region=customAppEditForm}} -{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\CustomAppointmentEditForm.vb region=customAppEditForm}} -````C# -public partial class CustomAppointmentEditForm : EditAppointmentDialog -{ - public CustomAppointmentEditForm() - { - InitializeComponent(); - } - protected override void LoadSettingsFromEvent(IEvent ev) - { - base.LoadSettingsFromEvent(ev); - AppointmentWithEmail appointmentWithEmail = ev as AppointmentWithEmail; - if (appointmentWithEmail != null) - { - this.txtEmail.Text = appointmentWithEmail.Email; - } - } - protected override void ApplySettingsToEvent(IEvent ev) - { - AppointmentWithEmail appointmentWithEmail = ev as AppointmentWithEmail; - if (appointmentWithEmail != null) - { - appointmentWithEmail.Email = this.txtEmail.Text; - } - base.ApplySettingsToEvent(ev); - } - protected override IEvent CreateNewEvent() - { - return new AppointmentWithEmail(); - } -} - -```` -````VB.NET -Public Class CustomAppointmentEditForm - Public Sub New() - InitializeComponent() - End Sub - Protected Overrides Sub LoadSettingsFromEvent(ByVal ev As IEvent) - MyBase.LoadSettingsFromEvent(ev) - Dim appointmentWithEmail As AppointmentWithEmail = TryCast(ev, AppointmentWithEmail) - If appointmentWithEmail IsNot Nothing Then - Me.txtEmail.Text = appointmentWithEmail.Email - End If - End Sub - Protected Overrides Sub ApplySettingsToEvent(ByVal ev As IEvent) - Dim appointmentWithEmail As AppointmentWithEmail = TryCast(ev, AppointmentWithEmail) - If appointmentWithEmail IsNot Nothing Then - appointmentWithEmail.Email = Me.txtEmail.Text - End If - MyBase.ApplySettingsToEvent(ev) - End Sub - Protected Overrides Function CreateNewEvent() As IEvent - Return New AppointmentWithEmail() - End Function -End Class - -```` - -{{endregion}} + + + + 4\. Create a new appointment class (let's call it AppointmentWithEmail) which derives from the __Appointment__ class and add an Email property as shown: -{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\AddingCustomFieldHelper.cs region=appWithMail}} -{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\AddingCustomFieldHelper.vb region=appWithMail}} -````C# - -public class AppointmentWithEmail : Appointment -{ - public AppointmentWithEmail() : base() - { - } - - protected override Event CreateOccurrenceInstance() - { - return new AppointmentWithEmail(); - } - - private string email = string.Empty; - - public string Email - { - get - { - return this.email; - } - set - { - if (this.email != value) - { - this.email = value; - this.OnPropertyChanged("Email"); - } - } - } -} - -```` -````VB.NET -Public Class AppointmentWithEmail -Inherits Appointment - Public Sub New() - MyBase.New() - End Sub - Protected Overrides Function CreateOccurrenceInstance() As [Event] - Return New AppointmentWithEmail() - End Function - Private _email As String = String.Empty - Public Property Email() As String - Get - Return Me._email - End Get - Set(ByVal value As String) - If Me._email <> value Then - Me._email = value - Me.OnPropertyChanged("Email") - End If - End Set - End Property -End Class - -```` - -{{endregion}} + + -5\. Create an appointment factory which returns our AppointmentWithEmail when creating appointments: -{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\AddingCustomFieldHelper.cs region=customAppFactory}} -{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\AddingCustomFieldHelper.vb region=customAppFactory}} -````C# - -public class CustomAppointmentFactory : IAppointmentFactory -{ - public IEvent CreateNewAppointment() - { - return new AppointmentWithEmail(); - } -} +5\. Create an appointment factory which returns our AppointmentWithEmail when creating appointments: -```` -````VB.NET -Public Class CustomAppointmentFactory -Implements IAppointmentFactory - Public Function CreateNewAppointment() As IEvent Implements IAppointmentFactory.CreateNewAppointment - Return New AppointmentWithEmail() - End Function -End Class + + -```` -{{endregion}} 6\. Subscribe to the AppointmentEditDialogShowing event and in the event handler use the AppointmentEditDialog property of the event arguments to change the default dialog with the custom one you just created. For optimization, you can create a global variable, which can be reused, instead of creating a new instance of the form every time. -{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\AddingCustomField.cs region=showing}} -{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\AddingCustomField.vb region=showing}} - -````C# -CustomAppointmentEditForm appointmentDialog = null; -void radScheduler1_AppointmentEditDialogShowing(object sender, AppointmentEditDialogShowingEventArgs e) -{ - if (this.appointmentDialog == null) - { - this.appointmentDialog = new CustomAppointmentEditForm(); - } - e.AppointmentEditDialog = this.appointmentDialog; -} - -```` -````VB.NET -Private appointmentDialog As CustomAppointmentEditForm = Nothing -Private Sub radScheduler1_AppointmentEditDialogShowing(ByVal sender As Object, ByVal e As AppointmentEditDialogShowingEventArgs) - If Me.appointmentDialog Is Nothing Then - Me.appointmentDialog = New CustomAppointmentEditForm() - End If - e.AppointmentEditDialog = Me.appointmentDialog -End Sub - -```` - -{{endregion}} + + + + 7\. Last, but not least we should assign the custom AppointmentFactory to our RadScheduler. This will come in handy when you create your appointments in-line: -{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\AddingCustomField.cs region=settingFactory}} -{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\AddingCustomField.vb region=settingFactory}} -````C# -this.radScheduler1.AppointmentFactory = new CustomAppointmentFactory(); - -```` -````VB.NET -Me.RadScheduler1.AppointmentFactory = New CustomAppointmentFactory() + + -```` -{{endregion}} >caption Figure 2: Custom Edit Appointment Dialog diff --git a/controls/scheduler/appointments-and-dialogs/adding-tooltips-to-appointments.md b/controls/scheduler/appointments-and-dialogs/adding-tooltips-to-appointments.md index 8d57caa75..ebd3c06a3 100644 --- a/controls/scheduler/appointments-and-dialogs/adding-tooltips-to-appointments.md +++ b/controls/scheduler/appointments-and-dialogs/adding-tooltips-to-appointments.md @@ -15,23 +15,10 @@ You can create and associate a tooltip to an appointment in __RadScheduler__ by #### Add Appointment Tooltip -{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\WorkingWithAppointments.cs region=toolTips}} -{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\WorkingWithAppointments.vb region=toolTips}} + + -````C# -Appointment myAppointment = new Appointment(DateTime.Now, TimeSpan.FromMinutes(30), "Summary", "Description"); -myAppointment.ToolTipText = "Custom Tooltip"; -this.radScheduler1.Appointments.Add(myAppointment); -```` -````VB.NET -Dim myAppointment As New Appointment(Date.Now, TimeSpan.FromMinutes(30), "Summary", "Description") -myAppointment.ToolTipText = "Custom Tooltip" -Me.RadScheduler1.Appointments.Add(myAppointment) - -```` - -{{endregion}} # See Also diff --git a/controls/scheduler/appointments-and-dialogs/custom-appointment-element.md b/controls/scheduler/appointments-and-dialogs/custom-appointment-element.md index 173df73d5..15242339a 100644 --- a/controls/scheduler/appointments-and-dialogs/custom-appointment-element.md +++ b/controls/scheduler/appointments-and-dialogs/custom-appointment-element.md @@ -18,175 +18,24 @@ position: 6 1\. Let's start with creating a derivative of the **AppointmentElement** class. We will add the desired elements in the **CreateChildElements** method. The **Synchronize** method is the appropriate place to display the correct data in the custom elements in the **AppointmentElement**. It is also necessary to override the **DrawEventText** method and leave it empty in order to prevent drawing the default text. -{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\CustomAppointmentElement.cs region=CustomElement}} -{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\CustomAppointmentElement.vb region=CustomElement}} - -````C# - -public class MyAppointmentElement : AppointmentElement -{ - public MyAppointmentElement(RadScheduler scheduler, SchedulerView view, IEvent appointment) : base(scheduler, view, appointment) - { - } - - StackLayoutElement panel = new StackLayoutElement(); - RadButtonElement button = new RadButtonElement(); - LightVisualElement timeInterval = new LightVisualElement(); - LightVisualElement description = new LightVisualElement(); - - protected override void CreateChildElements() - { - base.CreateChildElements(); - - panel.StretchHorizontally = true; - panel.StretchVertically = true; - panel.Orientation = Orientation.Vertical; - panel.Children.Add(timeInterval); - panel.Children.Add(description); - panel.Children.Add(button); - button.Click += button_Click; - button.Text = "Cancel"; - panel.ShouldHandleMouseInput = false; - panel.NotifyParentOnMouseInput = true; - timeInterval.ShouldHandleMouseInput = false; - timeInterval.NotifyParentOnMouseInput = true; - description.ShouldHandleMouseInput = false; - description.NotifyParentOnMouseInput = true; - button.ShouldHandleMouseInput = true; - - this.Children.Add(panel); - } - - private void button_Click(object sender, EventArgs e) - { - this.Scheduler.Appointments.Remove(this.Appointment); - } - - public override void Synchronize() - { - base.Synchronize(); - timeInterval.Text = this.Appointment.Start.ToLongTimeString() + " - " + this.Appointment.End.ToLongTimeString(); - description.Text = this.Appointment.Summary; - } - - public override void DrawEventText(Telerik.WinControls.Paint.IGraphics graphics) - { - //leave the method empty to prevent the default appointment information to be drawn - } -} - -```` -````VB.NET - -Public Class MyAppointmentElement -Inherits AppointmentElement - Public Sub New(scheduler As RadScheduler, view As SchedulerView, appointment As IEvent) - MyBase.New(scheduler, view, appointment) - End Sub - Private panel As StackLayoutElement - Private button As RadButtonElement - Private timeInterval As LightVisualElement - Private description As LightVisualElement - Protected Overrides Sub CreateChildElements() - MyBase.CreateChildElements() - panel = New StackLayoutElement() - button = New RadButtonElement() - timeInterval = New LightVisualElement() - description = New LightVisualElement() - panel.StretchHorizontally = True - panel.StretchVertically = True - panel.Orientation = Orientation.Vertical - panel.Children.Add(timeInterval) - panel.Children.Add(description) - panel.Children.Add(button) - AddHandler button.Click, AddressOf button_Click - button.Text = "Cancel" - panel.ShouldHandleMouseInput = False - panel.NotifyParentOnMouseInput = True - timeInterval.ShouldHandleMouseInput = False - timeInterval.NotifyParentOnMouseInput = True - description.ShouldHandleMouseInput = False - description.NotifyParentOnMouseInput = True - button.ShouldHandleMouseInput = True - Me.Children.Add(panel) - End Sub - Private Sub button_Click(sender As Object, e As EventArgs) - Me.Scheduler.Appointments.Remove(Me.Appointment) - End Sub - Public Overrides Sub Synchronize() - MyBase.Synchronize() - timeInterval.Text = Me.Appointment.Start.ToLongTimeString() + " - " + Me.Appointment.[End].ToLongTimeString() - description.Text = Me.Appointment.Summary - End Sub - Public Overrides Sub DrawEventText(graphics As Telerik.WinControls.Paint.IGraphics) - 'leave the method empty to prevent the default appointment information to be drawn - End Sub -End Class - -```` - -{{endregion}} + + + + 2\. Next, it is necessary to replace the default **AppointmentElement** with the custom class. For this purpose, it is necessary to create a [SchedulerElementProvider]({%slug winforms/scheduler/fundamentals/scheduler-element-provider-%}) and override its **CreateElement<T>** method: -{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\CustomAppointmentElement.cs region=CustomProvider}} -{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\CustomAppointmentElement.vb region=CustomProvider}} - -````C# - -public class MyElementProvider : SchedulerElementProvider -{ - public MyElementProvider(RadScheduler scheduler) : base(scheduler) - { - } - - protected override T CreateElement(SchedulerView view, object context) - { - if (typeof(T) == typeof(AppointmentElement)) - { - return new MyAppointmentElement(this.Scheduler, view, (IEvent)context)as T; - } - - return base.CreateElement(view, context); - } -} - -```` -````VB.NET - -Public Class MyElementProvider -Inherits SchedulerElementProvider - Public Sub New(scheduler As RadScheduler) - MyBase.New(scheduler) - End Sub - Protected Overrides Function CreateElement(Of T As SchedulerVisualElement)(view As SchedulerView, context As Object) As T - If GetType(T) = GetType(AppointmentElement) Then - Return TryCast(New MyAppointmentElement(Me.Scheduler, view, DirectCast(context, IEvent)), T) - End If - Return MyBase.CreateElement(Of T)(view, context) - End Function -End Class - -```` - -{{endregion}} + + -3\. Last, you should set the RadScheduler.**ElementProvider** property to a new instance of the custom provider: -{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\CustomAppointmentElement.cs region=ReplaceElementProvider}} -{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\CustomAppointmentElement.vb region=ReplaceElementProvider}} - -````C# - -this.radScheduler1.ElementProvider = new MyElementProvider(this.radScheduler1); -```` -````VB.NET -Me.RadScheduler1.ElementProvider = New MyElementProvider(Me.RadScheduler1) +3\. Last, you should set the RadScheduler.**ElementProvider** property to a new instance of the custom provider: + + + -```` -{{endregion}} # See Also diff --git a/controls/scheduler/appointments-and-dialogs/recurrence-rule-walkthrough.md b/controls/scheduler/appointments-and-dialogs/recurrence-rule-walkthrough.md index 7e20d272a..ee1b7ddfd 100644 --- a/controls/scheduler/appointments-and-dialogs/recurrence-rule-walkthrough.md +++ b/controls/scheduler/appointments-and-dialogs/recurrence-rule-walkthrough.md @@ -20,70 +20,10 @@ This example will create a single appointment, then define a recurrence rule th 2\. Add the code below to the form's Load Event handler: -{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\RecurrenceRuleWalkthrough.cs region=addingAndTraversing}} -{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\RecurrenceRuleWalkthrough.vb region=addingAndTraversing}} + + -````C# -DateTime startDate = new DateTime(2008, 10, 1, 3, 30, 0); -// Create a sample appointment that starts at 10/1/2008 3:30 AM and lasts half an hour. -Appointment recurringAppointment = new Appointment(startDate, - TimeSpan.FromHours(1.0), "Appointment Subject"); -// Create a recurrence rule to repeat the appointment every 2 hours for 10 occurrences. -HourlyRecurrenceRule rrule = - new HourlyRecurrenceRule(recurringAppointment.Start, 2, 10); -//Assign the hourly recurrence rule to the appointment -recurringAppointment.RecurrenceRule = rrule; -radScheduler1.Appointments.Add(recurringAppointment); -// iterate all appointment occurrances -foreach (IEvent ev in recurringAppointment.Occurrences) -{ - lcAll.Items.Add( - new RadListDataItem(ev.Start.ToShortTimeString() + " - " + - ev.End.ToShortTimeString())); -} -// iterate only occurrances after 10am -IEnumerable occurrencesAfter10AM = recurringAppointment.GetOccurrences( - new DateTime(2008, 10, 1, 10, 0, 0), DateTime.Now); -foreach (IEvent ev in occurrencesAfter10AM) -{ - lcAfter10.Items.Add( - new RadListDataItem(ev.Start.ToShortTimeString() + " - " + - ev.End.ToShortTimeString())); - // set the background id to "Important" and make this occurence an "Exception" - ev.BackgroundId = (int)AppointmentBackground.Important; - ev.StatusId = (int)AppointmentStatus.Tentative; - ev.MasterEvent.Exceptions.Add(ev); -} -radScheduler1.FocusedDate = startDate; -```` -````VB.NET -Dim startDate As New Date(2008, 10, 1, 3, 30, 0) -' Create a sample appointment that starts at 10/1/2008 3:30 AM and lasts half an hour. -Dim recurringAppointment As New Appointment(startDate, TimeSpan.FromHours(1.0), "Appointment Subject") -' Create a recurrence rule to repeat the appointment every 2 hours for 10 occurrences. -Dim rrule As New HourlyRecurrenceRule(recurringAppointment.Start, 2, 10) -'Assign the hourly recurrence rule to the appointment -recurringAppointment.RecurrenceRule = rrule -radScheduler1.Appointments.Add(recurringAppointment) -' iterate all appointment occurrances -For Each ev As IEvent In recurringAppointment.Occurrences - lcAll.Items.Add(New RadListDataItem(ev.Start.ToShortTimeString() & " - " & ev.End.ToShortTimeString())) -Next ev -' iterate only occurrances after 10am -Dim occurrencesAfter10AM As IEnumerable(Of IEvent) = recurringAppointment.GetOccurrences(New Date(2008, 10, 1, 10, 0, 0), Date.Now) -For Each ev As IEvent In occurrencesAfter10AM - lcAfter10.Items.Add(New RadListDataItem(ev.Start.ToShortTimeString() & " - " & ev.End.ToShortTimeString())) - ' set the background id to "Important" and make this occurence an "Exception" - ev.BackgroundId = CInt(Fix(AppointmentBackground.Important)) - ev.StatusId = CInt(Fix(AppointmentStatus.Tentative)) - ev.MasterEvent.Exceptions.Add(ev) -Next ev -RadScheduler1.FocusedDate = startDate - -```` - -{{endregion}} 3\. Run the application. Notice that the background and status for appointments after 10am are changed to reflect changes made to members of the collection returned by GetOccurrences(). diff --git a/controls/scheduler/appointments-and-dialogs/working-with-appointments.md b/controls/scheduler/appointments-and-dialogs/working-with-appointments.md index c0fa6a645..d783595cd 100644 --- a/controls/scheduler/appointments-and-dialogs/working-with-appointments.md +++ b/controls/scheduler/appointments-and-dialogs/working-with-appointments.md @@ -27,25 +27,10 @@ Use one of many overloads to build a new __Appointment__ instance. The example b #### New Appointment -{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\WorkingWithAppointments.cs region=creatingAppointment}} -{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\WorkingWithAppointments.vb region=creatingAppointment}} + + -````C# -Appointment appointment = new Appointment(DateTime.Now, TimeSpan.FromMinutes(60), "Summary", "Description"); -appointment.StatusId = 2; -appointment.BackgroundId = 6; -this.radScheduler1.Appointments.Add(appointment); -```` -````VB.NET -Dim appointment As New Appointment(Date.Now, TimeSpan.FromMinutes(60), "Summary", "Description") -appointment.StatusId = 2 -appointment.BackgroundId = 6 -Me.RadScheduler1.Appointments.Add(appointment) - -```` - -{{endregion}} #### Figure 1: Appointmennt Element ![WinForms RadScheduler Appointmennt Element](images/scheduler-appointments-and-dialogs-working-with-appointments003.png) @@ -68,19 +53,10 @@ Me.RadScheduler1.Appointments.Add(appointment) #### Appointment Status -{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\WorkingWithAppointments.cs region=addStatus}} -{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\WorkingWithAppointments.vb region=addStatus}} - -````C# -this.radScheduler1.Statuses.Add(new AppointmentStatusInfo(5, "test", Color.Purple, Color.Purple, AppointmentStatusFillType.Solid)); + + -```` -````VB.NET -Me.RadScheduler1.Statuses.Add(New AppointmentStatusInfo(5, "test", Color.Purple, Color.Purple, AppointmentStatusFillType.Solid)) -```` - -{{endregion}} * To add new a Background to an appointment, the __Backgrounds__ collection should be used. By default this collection is filled with the following statuses: @@ -116,19 +92,10 @@ Me.RadScheduler1.Statuses.Add(New AppointmentStatusInfo(5, "test", Color.Purple, #### Appointment Background -{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\WorkingWithAppointments.cs region=addBackground}} -{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\WorkingWithAppointments.vb region=addBackground}} - -````C# -this.radScheduler1.Backgrounds.Add(new AppointmentBackgroundInfo(12, "test", Color.Purple)); + + -```` -````VB.NET -Me.RadScheduler1.Backgrounds.Add(New AppointmentBackgroundInfo(12, "test", Color.Purple)) -```` - -{{endregion}} * In order to change the background of an appointment, use the Appointment's __BackgroundId__ property and choose a value from a value list. @@ -142,19 +109,10 @@ Me.RadScheduler1.Backgrounds.Add(New AppointmentBackgroundInfo(12, "test", Color #### Appointment Title Format -{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\WorkingWithAppointments.cs region=appointmentFormat}} -{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\WorkingWithAppointments.vb region=appointmentFormat}} - -````C# -this.radScheduler1.AppointmentTitleFormat = "{0} to {1}, {2} ({3})"; - -```` -````VB.NET -Me.RadScheduler1.AppointmentTitleFormat = "{0} to {1}, {2} ({3})" + + -```` -{{endregion}} Here is a list with the different elements and their content: @@ -182,19 +140,10 @@ Here is a list with the different elements and their content: #### Appointment ToolTip Text -{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\WorkingWithAppointments.cs region=toolTipText}} -{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\WorkingWithAppointments.vb region=toolTipText}} - -````C# -appointment.ToolTipText = "Some text"; - -```` -````VB.NET -appointment.ToolTipText = "Some text" + + -```` -{{endregion}} * In order to enable/disable Appointment's editing and deleting operations, use the Appointment's __AllowEdit__ and __AllowDelete__ properties. diff --git a/controls/scheduler/appointments-and-dialogs/working-with-recurring-appointments.md b/controls/scheduler/appointments-and-dialogs/working-with-recurring-appointments.md index 5a312fcbe..66bb0e7c6 100644 --- a/controls/scheduler/appointments-and-dialogs/working-with-recurring-appointments.md +++ b/controls/scheduler/appointments-and-dialogs/working-with-recurring-appointments.md @@ -37,78 +37,28 @@ One of several constructor overloads lets you set the start time, duration and n #### RecurrenceRule Property -{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\RecurringAppointments.cs region=addingRecRule}} -{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\RecurringAppointments.vb region=addingRecRule}} + + -````C# -radScheduler1.Appointments[0].RecurrenceRule = new HourlyRecurrenceRule(DateTime.Now, 2, 10); -```` -````VB.NET -RadScheduler1.Appointments(0).RecurrenceRule = New HourlyRecurrenceRule(Date.Now, 2, 10) - -```` - -{{endregion}} The Appointment __Occurrences__ property lets you iterate a list of __IEvent__ instances. To get only some occurrences between specific starting and stopping times, use the Appointment __GetOccurrences()__ method. #### Retrieving Occurrences -{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\RecurringAppointments.cs region=iterating}} -{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\RecurringAppointments.vb region=iterating}} - -````C# -// iterate all appointment occurrances -foreach (IEvent ev in recurringAppointment.Occurrences) -{ - //... -} -// iterate only occurrances after 10am -IEnumerable occurrencesAfter10AM = recurringAppointment.GetOccurrences( - new DateTime(2008, 10, 1, 10, 0, 0), DateTime.Now); -foreach (IEvent ev in occurrencesAfter10AM) -{ - //... -} - -```` -````VB.NET -' iterate all appointment occurrances -For Each ev As IEvent In recurringAppointment.Occurrences - '... -Next ev -' iterate only occurrances after 10am -Dim occurrencesAfter10AM As IEnumerable(Of IEvent) = recurringAppointment.GetOccurrences(New Date(2008, 10, 1, 10, 0, 0), Date.Now) -For Each ev As IEvent In occurrencesAfter10AM - '... -Next ev - -```` - -{{endregion}} + + -When the user changes a specific occurrence and not the entire series, an "Exception" is created. "Exceptions" in this context refer to "Exceptions to a rule", not the .NET Exception class related to error handling. You can create exceptions programmatically by adding to the IEvent __MasterEvent.Exceptions__ collection. The snippet below changes the background and status of an IEvent instance and adds the IEvent to its own MasterEvent Exceptions collection. -#### Recurrence Rule Exception -{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\RecurringAppointments.cs region=addingExceptions}} -{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\RecurringAppointments.vb region=addingExceptions}} +When the user changes a specific occurrence and not the entire series, an "Exception" is created. "Exceptions" in this context refer to "Exceptions to a rule", not the .NET Exception class related to error handling. You can create exceptions programmatically by adding to the IEvent __MasterEvent.Exceptions__ collection. The snippet below changes the background and status of an IEvent instance and adds the IEvent to its own MasterEvent Exceptions collection. -````C# -myEvent.BackgroundId = (int)AppointmentBackground.Important; -myEvent.StatusId = (int)AppointmentStatus.Tentative; -myEvent.MasterEvent.Exceptions.Add(myEvent); +#### Recurrence Rule Exception -```` -````VB.NET -myEvent.BackgroundId = CInt(Fix(AppointmentBackground.Important)) -myEvent.StatusId = CInt(Fix(AppointmentStatus.Tentative)) -myEvent.MasterEvent.Exceptions.Add(myEvent) + + -```` -{{endregion}} ## Examples @@ -116,51 +66,10 @@ Here is an example using the __HourlyRecurrenceRule__ class: #### Setting HourlyReccurrenceRule -{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\RecurringAppointments.cs region=console}} -{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\RecurringAppointments.vb region=console}} - -````C# -// Create a sample appointment that starts at 10/1/2008 3:30 AM and lasts half an hour. -Appointment recurringAppointment = new Appointment(new DateTime(2008, 10, 1, 3, 30, 0), - TimeSpan.FromHours(1.0), "Appointment Subject"); -// Create a recurrence rule to repeat the appointment every 2 hours for 10 occurrences. -HourlyRecurrenceRule rrule = new HourlyRecurrenceRule(recurringAppointment.Start, 2, 10); -//Assign the hourly recurrence rule to the appointment -recurringAppointment.RecurrenceRule = rrule; -Console.WriteLine("The appointment recurrs at the following times"); -foreach (IEvent ev in recurringAppointment.Occurrences) -{ - Console.WriteLine("\t{0}", ev); -} -IEnumerable occurrencesAfter10AM = recurringAppointment.GetOccurrences( - new DateTime(2008, 10, 1, 10, 0, 0), DateTime.Now); -Console.WriteLine("And here are the occurrences after 10 AM:"); -foreach (IEvent ev in occurrencesAfter10AM) -{ - Console.WriteLine("\t{0}", ev); -} - -```` -````VB.NET -' Create a sample appointment that starts at 10/1/2008 3:30 AM and lasts half an hour. -Dim recurringAppointment As New Appointment(New Date(2008, 10, 1, 3, 30, 0), TimeSpan.FromHours(1.0), "Appointment Subject") -' Create a recurrence rule to repeat the appointment every 2 hours for 10 occurrences. -Dim rrule As New HourlyRecurrenceRule(recurringAppointment.Start, 2, 10) -'Assign the hourly recurrence rule to the appointment -recurringAppointment.RecurrenceRule = rrule -Console.WriteLine("The appointment recurrs at the following times") -For Each ev As IEvent In recurringAppointment.Occurrences - Console.WriteLine(vbTab & "{0}", ev) -Next ev -Dim occurrencesAfter10AM As IEnumerable(Of IEvent) = recurringAppointment.GetOccurrences(New Date(2008, 10, 1, 10, 0, 0), Date.Now) -Console.WriteLine("And here are the occurrences after 10 AM:") -For Each ev As IEvent In occurrencesAfter10AM - Console.WriteLine(vbTab & "{0}", ev) -Next ev - -```` - -{{endregion}} + + + + The __Occurrences__ property of the __Appointment__ class returns an enumerator that can be used to retrieve all the occurrences defined by the rule. Similarly the __GetOccurrences__ method of the __Appointment__ class can be used to retrieve all occurrences in a given interval. The example above produces the following output: diff --git a/controls/scheduler/appointments-and-dialogs/working-with-resources.md b/controls/scheduler/appointments-and-dialogs/working-with-resources.md index df7316c49..b72eb11ee 100644 --- a/controls/scheduler/appointments-and-dialogs/working-with-resources.md +++ b/controls/scheduler/appointments-and-dialogs/working-with-resources.md @@ -29,23 +29,9 @@ One **Appointment** may refer to one or many resources. Each **Appoinment** offe #### Apply a single resource to an appointment -{{source=..\SamplesCS\Scheduler\Views\GroupingByResources.cs region=SingleResource}} -{{source=..\SamplesVB\Scheduler\Views\GroupingByResources.vb region=SingleResource}} + + -````C# - Appointment appointment = new Appointment(DateTime.Today.AddDays(1).AddHours(12).AddMinutes(30), TimeSpan.FromHours(2), "Business Lunch"); - appointment.ResourceId = this.radScheduler1.Resources[2].Id; - this.radScheduler1.Appointments.Add(appointment); - -```` -````VB.NET - Dim appointment As Appointment = New Appointment(DateTime.Today.AddDays(1).AddHours(12).AddMinutes(30), TimeSpan.FromHours(2), "Business Lunch") - appointment.ResourceId = Me.radScheduler1.Resources(2).Id - Me.radScheduler1.Appointments.Add(appointment) - -```` - -{{endregion}} ![WinForms RadScheduler Appointment Resource](images/winforms-scheduler-working-with-resources001.png) @@ -53,25 +39,10 @@ One **Appointment** may refer to one or many resources. Each **Appoinment** offe #### Apply multiple resources to an appointment -{{source=..\SamplesCS\Scheduler\Views\GroupingByResources.cs region=MultipleResources}} -{{source=..\SamplesVB\Scheduler\Views\GroupingByResources.vb region=MultipleResources}} - -````C# - Appointment appointmentWithMultipleResources = new Appointment(DateTime.Today.AddDays(1).AddHours(12).AddMinutes(30), TimeSpan.FromHours(2), "Business Lunch"); - appointmentWithMultipleResources.ResourceIds.Add(this.radScheduler1.Resources[2].Id); - appointmentWithMultipleResources.ResourceIds.Add(this.radScheduler1.Resources[1].Id); - this.radScheduler1.Appointments.Add(appointmentWithMultipleResources); - -```` -````VB.NET - Dim appointmentWithMultipleResources As Appointment = New Appointment(DateTime.Today.AddDays(1).AddHours(12).AddMinutes(30), TimeSpan.FromHours(2), "Business Lunch") - appointmentWithMultipleResources.ResourceIds.Add(Me.radScheduler1.Resources(2).Id) - appointmentWithMultipleResources.ResourceIds.Add(Me.radScheduler1.Resources(1).Id) - Me.RadScheduler1.Appointments.Add(appointmentWithMultipleResources) + + -```` -{{endregion}} ![WinForms RadScheduler Multiple Resources](images/winforms-scheduler-working-with-resources002.png) diff --git a/controls/scheduler/context-menu/customize-the-contextmenu.md b/controls/scheduler/context-menu/customize-the-contextmenu.md index 3883a605d..a7818f3d9 100644 --- a/controls/scheduler/context-menu/customize-the-contextmenu.md +++ b/controls/scheduler/context-menu/customize-the-contextmenu.md @@ -24,35 +24,10 @@ __RadScheduler__ gives you the ability to easily customize its default context m 1. In the __ContextMenuOpenning__ event handler replace the default context menus with the newly created ones. -{{source=..\SamplesCS\Scheduler\CustomizeContextMenu.cs region=contextMenuOpening}} -{{source=..\SamplesVB\Scheduler\CustomizeContextMenu.vb region=contextMenuOpening}} - -````C# -void radScheduler1_ContextMenuOpening(object sender, SchedulerContextMenuOpeningEventArgs e) -{ - if (e.Element is AppointmentElement) - { - e.Menu = this.radContextMenu1; - } - else - { - e.Menu = this.radContextMenu2; - } -} - -```` -````VB.NET -Private Sub radScheduler1_ContextMenuOpening(sender As Object, e As SchedulerContextMenuOpeningEventArgs) Handles RadScheduler1.ContextMenuOpening - If TypeOf e.Element Is AppointmentElement Then - e.Menu = Me.RadContextMenu1 - Else - e.Menu = Me.RadContextMenu2 - End If -End Sub - -```` - -{{endregion}} + + + + As you can see in the screenshots below, we can set different context menus depending on the element that invokes the context menu creation. @@ -68,35 +43,10 @@ The __Menu__ property of the __SchedulerContextMenuOpeningEventArgs__ objects gi #### Handle ContextMenuOpening -{{source=..\SamplesCS\Scheduler\CustomizeContextMenu.cs region=contextMenuOpening1}} -{{source=..\SamplesVB\Scheduler\CustomizeContextMenu.vb region=contextMenuOpening1}} - -````C# -void radScheduler1_ContextMenuOpening1(object sender, SchedulerContextMenuOpeningEventArgs e) -{ - if (e.Element is AppointmentElement) - { - e.Menu.Items.RemoveAt(0); - } - else - { - e.Cancel = true; - } -} - -```` -````VB.NET -Private Sub radScheduler1_ContextMenuOpening1(sender As Object, e As SchedulerContextMenuOpeningEventArgs) - If TypeOf e.Element Is AppointmentElement Then - e.Menu.Items.RemoveAt(0) - Else - e.Cancel = True - End If -End Sub - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/scheduler/data-binding/binding-to-business-objects.md b/controls/scheduler/data-binding/binding-to-business-objects.md index 7228a1999..a20257d4f 100644 --- a/controls/scheduler/data-binding/binding-to-business-objects.md +++ b/controls/scheduler/data-binding/binding-to-business-objects.md @@ -19,327 +19,19 @@ The code below is an example appointment. Keep in mind that the particular const #### Custom Appointment Class -{{source=..\SamplesCS\Scheduler\DataBinding\CustomAppointment.cs region=customAppointment}} -{{source=..\SamplesVB\Scheduler\DataBinding\CustomAppointment.vb region=customAppointment}} - -````C# -public class CustomAppointment : INotifyPropertyChanged -{ - private DateTime start = DateTime.Now; - private DateTime end = DateTime.Now; - private string subject = string.Empty; - private string description = string.Empty; - private string location = string.Empty; - private Guid id = Guid.NewGuid(); - private List exceptions; - public CustomAppointment() - { - } - public CustomAppointment(DateTime start, DateTime end, string subject, string description, string location) - { - this.start = start; - this.end = end; - this.subject = subject; - this.description = description; - this.location = location; - List exceptions = new List(); - } - public List Exceptions - { - get - { - return this.exceptions; - } - set - { - if (this.exceptions != value) - { - this.exceptions = value; - this.OnPropertyChanged("Exceptions"); - } - } - } - public Guid Id - { - get - { - return this.id; - } - set - { - if (this.id != value) - { - this.id = value; - this.OnPropertyChanged("Id"); - } - } - } - public DateTime Start - { - get - { - return this.start; - } - set - { - if (this.start != value) - { - this.start = value; - this.OnPropertyChanged("Start"); - } - } - } - public DateTime End - { - get - { - return this.end; - } - set - { - if (this.end != value) - { - this.end = value; - this.OnPropertyChanged("End"); - } - } - } - public string Subject - { - get - { - return this.subject; - } - set - { - if (this.subject != value) - { - this.subject = value; - this.OnPropertyChanged("Subject"); - } - } - } - public string Description - { - get - { - return this.description; - } - set - { - if (this.description != value) - { - this.description = value; - this.OnPropertyChanged("Description"); - } - } - } - public string Location - { - get - { - return this.location; - } - set - { - if (this.location != value) - { - this.location = value; - this.OnPropertyChanged("Location"); - } - } - } - public event PropertyChangedEventHandler PropertyChanged; - protected virtual void OnPropertyChanged(string propertyName) - { - if (this.PropertyChanged != null) - { - this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); - } - } - -```` -````VB.NET -Public Class CustomAppointment - Implements INotifyPropertyChanged - Private _start As Date = Date.Now - Private _end As Date = Date.Now - Private _subject As String = String.Empty - Private _description As String = String.Empty - Private _location As String = String.Empty - Private _id As Guid = Guid.NewGuid() - Private _exceptions As List(Of CustomAppointment) - Public Sub New() - End Sub - Public Sub New(ByVal start As Date, ByVal [end] As Date, ByVal subject As String, ByVal description As String, ByVal location As String) - Me._start = start - Me._end = [end] - Me._subject = subject - Me._description = description - Me._location = location - Dim _exceptions As New List(Of CustomAppointment)() - End Sub - Public Property Exceptions() As List(Of CustomAppointment) - Get - Return Me._exceptions - End Get - Set(ByVal value As List(Of CustomAppointment)) - If Me._exceptions IsNot value Then - Me._exceptions = value - Me.OnPropertyChanged("Exceptions") - End If - End Set - End Property - Public Property Id() As Guid - Get - Return Me._id - End Get - Set(ByVal value As Guid) - If Me._id <> value Then - Me._id = value - Me.OnPropertyChanged("Id") - End If - End Set - End Property - Public Property Start() As Date - Get - Return Me._start - End Get - Set(ByVal value As Date) - If Me._start <> value Then - Me._start = value - Me.OnPropertyChanged("Start") - End If - End Set - End Property - Public Property [End]() As Date - Get - Return Me._end - End Get - Set(ByVal value As Date) - If Me._end <> value Then - Me._end = value - Me.OnPropertyChanged("End") - End If - End Set - End Property - Public Property Subject() As String - Get - Return Me._subject - End Get - Set(ByVal value As String) - If Me._subject <> value Then - Me._subject = value - Me.OnPropertyChanged("Subject") - End If - End Set - End Property - Public Property Description() As String - Get - Return Me._description - End Get - Set(ByVal value As String) - If Me._description <> value Then - Me._description = value - Me.OnPropertyChanged("Description") - End If - End Set - End Property - Public Property Location() As String - Get - Return Me._location - End Get - Set(ByVal value As String) - If Me._location <> value Then - Me._location = value - Me.OnPropertyChanged("Location") - End If - End Set - End Property - Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged - Protected Overridable Sub OnPropertyChanged(ByVal propertyName As String) - If Me.PropertyChangedEvent IsNot Nothing Then - RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName)) - End If - End Sub - -```` - -{{endregion}} + + + + To use your custom object, create CustomAppointment instances and place them in a generic list before mapping and binding to the __SchedulerBindingDataSource__ component. #### Create Appointments -{{source=..\SamplesCS\Scheduler\DataBinding\BindingToBusinessObjects.cs region=bindingToList}} -{{source=..\SamplesVB\Scheduler\DataBinding\BindingToBusinessObjects.vb region=bindingToList}} - -````C# -// create a list of CustomAppointment objects -BindingList appointments = new BindingList(); -for (int i = 0; i < 10; i++) -{ - // add every other appointment, populate with sample data - if ((i % 2) == 0) - { - int appointmentNumber = i + 1; - CustomAppointment myAppointment = - new CustomAppointment( - DateTime.Now.AddHours(appointmentNumber), - DateTime.Now.AddHours(appointmentNumber + 2), - "Appointment " + appointmentNumber.ToString(), - "Description for Appointment " + appointmentNumber.ToString(), - "Conference room " + appointmentNumber.ToString()); - appointments.Add(myAppointment); - } -} -// create and configure a scheduler binding source -SchedulerBindingDataSource dataSource = new SchedulerBindingDataSource(); -// map the MyAppointment properties to the scheduler -AppointmentMappingInfo appointmentMappingInfo = new AppointmentMappingInfo(); -appointmentMappingInfo.Start = "Start"; -appointmentMappingInfo.End = "End"; -appointmentMappingInfo.Summary = "Subject"; -appointmentMappingInfo.Description = "Description"; -appointmentMappingInfo.Location = "Location"; -appointmentMappingInfo.UniqueId = "Id"; -appointmentMappingInfo.Exceptions = "Exceptions"; -dataSource.EventProvider.Mapping = appointmentMappingInfo; -// assign the generic List of CustomAppointment as the EventProvider data source -dataSource.EventProvider.DataSource = appointments; -this.radScheduler1.DataSource = dataSource; - -```` -````VB.NET -'create a list of CustomAppointment objects -Dim appointments As New BindingList(Of CustomAppointment)() -For i As Integer = 0 To 9 - 'add every other appointment, populate with sample data - If (i Mod 2) = 0 Then - Dim appointmentNumber As Integer = i + 1 - Dim myAppointment As New CustomAppointment(DateTime.Now.AddHours(appointmentNumber), DateTime.Now.AddHours(appointmentNumber + 2), "Appointment " + appointmentNumber.ToString(), "Description for Appointment " + appointmentNumber.ToString(), "Conference room " + appointmentNumber.ToString()) - appointments.Add(myAppointment) - End If -Next -'create_and_configure_a_scheduler_binding_source -Dim dataSource As New SchedulerBindingDataSource() -'map the MyAppointment properties to the scheduler -Dim appointmentMappingInfo As New AppointmentMappingInfo() -appointmentMappingInfo.Start = "Start" -appointmentMappingInfo.[End] = "End" -appointmentMappingInfo.Summary = "Subject" -appointmentMappingInfo.Description = "Description" -appointmentMappingInfo.Location = "Location" -appointmentMappingInfo.UniqueId = "Id" -appointmentMappingInfo.Exceptions = "Exceptions" -dataSource.EventProvider.Mapping = appointmentMappingInfo -'assign the generic List of CustomAppointment as the EventProvider data source -dataSource.EventProvider.DataSource = appointments -Me.radScheduler1.DataSource = dataSource - -```` - -{{endregion}} + + + + When you run the application, a series of CustomAppointment objects will show up in the scheduler. @@ -352,132 +44,19 @@ To use grouping by resource in this scenario, first you will need to create the #### Custom Resource Class -{{source=..\SamplesCS\Scheduler\DataBinding\BindingToBusinessObjects.cs region=createTheResourceObject}} -{{source=..\SamplesVB\Scheduler\DataBinding\BindingToBusinessObjects.vb region=createTheResourceObject}} - -````C# -public class CustomResource : INotifyPropertyChanged -{ - private int id; - private string name; - public int Id - { - get - { - return this.id; - } - set - { - if (this.id != value) - { - this.id = value; - this.OnPropertyChanged("Id"); - } - } - } - public string Name - { - get - { - return this.name; - } - set - { - if (this.name != value) - { - this.name = value; - this.OnPropertyChanged("Name"); - } - } - } - public event PropertyChangedEventHandler PropertyChanged; - protected virtual void OnPropertyChanged(string propertyName) - { - if (this.PropertyChanged != null) - { - this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); - } - } -} - -```` -````VB.NET -Public Class CustomResource - Implements INotifyPropertyChanged - Private m_id As Integer - Private m_name As String - Public Property Id() As Integer - Get - Return Me.m_id - End Get - Set(value As Integer) - If Me.m_id <> value Then - Me.m_id = value - Me.OnPropertyChanged("Id") - End If - End Set - End Property - Public Property Name() As String - Get - Return Me.m_name - End Get - Set(value As String) - If Me.m_name <> value Then - Me.m_name = value - Me.OnPropertyChanged("Name") - End If - End Set - End Property - Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged - Protected Overridable Sub OnPropertyChanged(propertyName As String) - RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName)) - End Sub -End Class - -```` - -{{endregion}} + + + + Now we need to bind the __ResourceProvider__ of __SchedulerBindingDataSource__ to a collection of __CustomResource__ objects: #### Bind Resource Provider -{{source=..\SamplesCS\Scheduler\DataBinding\BindingToBusinessObjects.cs region=bind_the_resource_provider}} -{{source=..\SamplesVB\Scheduler\DataBinding\BindingToBusinessObjects.vb region=bind_the_resource_provider}} - -````C# -BindingList resources = new BindingList(); -for (int i = 0; i < 5; i++) -{ - CustomResource resource = new CustomResource(); - resource.Id = i; - resource.Name = "Resource " + i; - resources.Add(resource); -} -ResourceMappingInfo resourceMappingInfo = new ResourceMappingInfo(); -resourceMappingInfo.Name = "Name"; -resourceMappingInfo.Id = "Id"; -dataSource.ResourceProvider.Mapping = resourceMappingInfo; -dataSource.ResourceProvider.DataSource = resources; - -```` -````VB.NET -Dim resources As New BindingList(Of CustomResource)() -For i As Integer = 0 To 4 - Dim resource As New CustomResource() - resource.Id = i - resource.Name = "Resource " & i - resources.Add(resource) -Next -Dim resourceMappingInfo As New ResourceMappingInfo() -resourceMappingInfo.Name = "Name" -resourceMappingInfo.Id = "Id" -dataSource.ResourceProvider.Mapping = resourceMappingInfo -dataSource.ResourceProvider.DataSource = resources - -```` - -{{endregion}} + + + + Next we need to create the relation between appointments and resources. We can create either one-to-many relation or many-to-many relation. The following two sections cover each of these scenarios. @@ -487,65 +66,16 @@ To create a one-to-many relation between appointments and resources we need to a #### Define One-to-many Relation -{{source=..\SamplesCS\Scheduler\DataBinding\CustomAppointment.cs region=CustomAppointmentWithOneToManyRelation}} -{{source=..\SamplesVB\Scheduler\DataBinding\CustomAppointment.vb region=CustomAppointmentWithOneToManyRelation}} - -````C# -//other fields… -private EventId resourceId; -//other properties… -public EventId ResourceId -{ - get - { - return this.resourceId; - } - set - { - if (this.resourceId != value) - { - this.resourceId = value; - this.OnPropertyChanged("ResourceId"); - } - } -} - -```` -````VB.NET -'other fields… -Private _resourceId As EventId -'other properties… -Public Property ResourceId() As EventId - Get - Return Me._resourceId - End Get - Set(value As EventId) - If Not Object.Equals(Me._resourceId, value) Then - Me._resourceId = value - Me.OnPropertyChanged("ResourceId") - End If - End Set -End Property - -```` - -{{endregion}} + + -To map the new property, add the following setting to your __AppointmentMappingInfo__ instance: -{{source=..\SamplesCS\Scheduler\DataBinding\BindingToBusinessObjects.cs region=OneToMany1}} -{{source=..\SamplesVB\Scheduler\DataBinding\BindingToBusinessObjects.vb region=OneToMany1}} -````C# -appointmentMappingInfo.ResourceId = "ResourceId"; - -```` -````VB.NET -appointmentMappingInfo.ResourceId = "ResourceId" +To map the new property, add the following setting to your __AppointmentMappingInfo__ instance: -```` + + -{{endregion}} >note In this scenario you should __not__ set the __Resources__ property of the __AppointmentMappingInfo__ @@ -553,48 +83,19 @@ appointmentMappingInfo.ResourceId = "ResourceId" #### Set Resource -{{source=..\SamplesCS\Scheduler\DataBinding\BindingToBusinessObjects.cs region=OneToMany2}} -{{source=..\SamplesVB\Scheduler\DataBinding\BindingToBusinessObjects.vb region=OneToMany2}} + + -````C# -CustomAppointment myAppointment = -new CustomAppointment( -DateTime.Now.AddHours(appointmentNumber), -DateTime.Now.AddHours(appointmentNumber + 2), -"Appointment " + appointmentNumber.ToString(), -"Description for Appointment " + appointmentNumber.ToString(), -"Conference room " + appointmentNumber.ToString()); -appointments.Add(myAppointment); -//set the resource id -myAppointment.ResourceId = new EventId(i % 2); -```` -````VB.NET -Dim myAppointment As New CustomAppointment(DateTime.Now.AddHours(appointmentNumber), DateTime.Now.AddHours(appointmentNumber + 2), "Appointment " + appointmentNumber.ToString(), "Description for Appointment " + appointmentNumber.ToString(), "Conference room " + appointmentNumber.ToString()) -appointments.Add(myAppointment) -'set the resource id - -```` - -{{endregion}} To test this scenario, assign each appointment with a __ResourceId__ and enable grouping by setting RadScheduler’s __GroupType__ property: #### Group By Resource -{{source=..\SamplesCS\Scheduler\DataBinding\BindingToBusinessObjects.cs region=OneToMany3}} -{{source=..\SamplesVB\Scheduler\DataBinding\BindingToBusinessObjects.vb region=OneToMany3}} - -````C# -this.radScheduler1.GroupType = GroupType.Resource; + + -```` -````VB.NET -Me.radScheduler1.GroupType = GroupType.Resource -```` - -{{endregion}} >caption Figure 2: One-to-Many Relation ![WinForms RadScheduler One-to-Many Relation](images/scheduler-data-binding-binding-to-business-objects002.png) @@ -605,83 +106,26 @@ This scenario can be implemented similarly to the previous one. Instead of the _ #### Define Many-to-many Relation -{{source=..\SamplesCS\Scheduler\DataBinding\CustomAppointment.cs region=CustomAppointmentWithManyToManyRelation}} -{{source=..\SamplesVB\Scheduler\DataBinding\CustomAppointment.vb region=CustomAppointmentWithManyToManyRelation}} - -````C# -//other fields… -private List resources = new List(); -//other properties… -public List Resources -{ - get - { - return this.resources; - } - set - { - if (this.resources != value) - { - this.resources = value; - this.OnPropertyChanged("Resources"); - } - } -} - -```` -````VB.NET -'other fields… -Private _resources As New List(Of EventId) -'other properties… -Public Property Resources() As List(Of EventId) - Get - Return Me._resources - End Get - Set(value As List(Of EventId)) - If Not Me._resources.Equals(value) Then - Me._resources = value - Me.OnPropertyChanged("Resources") - End If - End Set -End Property - -```` - -{{endregion}} + + -In the __AppointmentMappingInfo__ settings the __ResourceId__ property should be left unset and the __Resources__ property should be set with the name of the collection: -#### Set Resources -{{source=..\SamplesCS\Scheduler\DataBinding\BindingToBusinessObjects.cs region=ManyToMany1}} -{{source=..\SamplesVB\Scheduler\DataBinding\BindingToBusinessObjects.vb region=ManyToMany1}} +In the __AppointmentMappingInfo__ settings the __ResourceId__ property should be left unset and the __Resources__ property should be set with the name of the collection: -````C# -appointmentMappingInfo.Resources = "Resources"; +#### Set Resources -```` -````VB.NET -appointmentMappingInfo.Resources = "Resources" + + -```` -{{endregion}} Now we can add a resource to an appointment by adding its id in the __Resources__ collection of our business objects: -{{source=..\SamplesCS\Scheduler\DataBinding\BindingToBusinessObjects.cs region=ManyToMany2}} -{{source=..\SamplesVB\Scheduler\DataBinding\BindingToBusinessObjects.vb region=ManyToMany2}} - -````C# -myAppointment.Resources.Add(new EventId(resources[i%3].Id)); - -```` -````VB.NET -myAppointment.Resources.Add(New EventId(resources(i Mod 3).Id)) + + -```` -{{endregion}} >caption Figure 3: Many-to-Many Relation ![WinForms RadScheduler Many-to-Many Relation](images/scheduler-data-binding-binding-to-business-objects003.png) diff --git a/controls/scheduler/data-binding/binding-to-custom-fields.md b/controls/scheduler/data-binding/binding-to-custom-fields.md index af9b89d6e..2f43e9f61 100644 --- a/controls/scheduler/data-binding/binding-to-custom-fields.md +++ b/controls/scheduler/data-binding/binding-to-custom-fields.md @@ -17,245 +17,46 @@ __RadScheduler__ has full support for binding to custom fields i.e. __RadSchedul 1. Add a custom appointment class that stores this additional data. Note: *The easiest way to do that is to inherit from the Appointment class that RadScheduler uses by default*. -{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\AddingCustomFieldHelper.cs region=appWithMail}} -{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\AddingCustomFieldHelper.vb region=appWithMail}} - -````C# - -public class AppointmentWithEmail : Appointment -{ - public AppointmentWithEmail() : base() - { - } - - protected override Event CreateOccurrenceInstance() - { - return new AppointmentWithEmail(); - } - - private string email = string.Empty; - - public string Email - { - get - { - return this.email; - } - set - { - if (this.email != value) - { - this.email = value; - this.OnPropertyChanged("Email"); - } - } - } -} - -```` -````VB.NET -Public Class AppointmentWithEmail -Inherits Appointment - Public Sub New() - MyBase.New() - End Sub - Protected Overrides Function CreateOccurrenceInstance() As [Event] - Return New AppointmentWithEmail() - End Function - Private _email As String = String.Empty - Public Property Email() As String - Get - Return Me._email - End Get - Set(ByVal value As String) - If Me._email <> value Then - Me._email = value - Me.OnPropertyChanged("Email") - End If - End Set - End Property -End Class - -```` - -{{endregion}} + + + + 3\. Implement a simple appointment factory and inherit from the default appointment dialog and add some input controls and logic for your custom field. The easiest way to do the latter is to create a form in Visual Studio that inherits from the standard *Edit Appointment *dialog, then open it in the designer, and add your custom UI. The extended form from the example is shown on the screenshot below (notice the Email field on it): >caption Figure 1: Appointment with a Custom Field ![WinForms RadScheduler Appointment with a Custom Field](images/scheduler-data-binding-binding-to-custom-fields001.png) -{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\AddingCustomFieldHelper.cs region=customAppFactory}} -{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\AddingCustomFieldHelper.vb region=customAppFactory}} - -````C# - -public class CustomAppointmentFactory : IAppointmentFactory -{ - public IEvent CreateNewAppointment() - { - return new AppointmentWithEmail(); - } -} - -```` -````VB.NET -Public Class CustomAppointmentFactory -Implements IAppointmentFactory - Public Function CreateNewAppointment() As IEvent Implements IAppointmentFactory.CreateNewAppointment - Return New AppointmentWithEmail() - End Function -End Class - -```` - -{{endregion}} - - -{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\CustomAppointmentEditForm.cs region=customAppEditForm}} -{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\CustomAppointmentEditForm.vb region=customAppEditForm}} - -````C# -public partial class CustomAppointmentEditForm : EditAppointmentDialog -{ - public CustomAppointmentEditForm() - { - InitializeComponent(); - } - protected override void LoadSettingsFromEvent(IEvent ev) - { - base.LoadSettingsFromEvent(ev); - AppointmentWithEmail appointmentWithEmail = ev as AppointmentWithEmail; - if (appointmentWithEmail != null) - { - this.txtEmail.Text = appointmentWithEmail.Email; - } - } - protected override void ApplySettingsToEvent(IEvent ev) - { - AppointmentWithEmail appointmentWithEmail = ev as AppointmentWithEmail; - if (appointmentWithEmail != null) - { - appointmentWithEmail.Email = this.txtEmail.Text; - } - base.ApplySettingsToEvent(ev); - } - protected override IEvent CreateNewEvent() - { - return new AppointmentWithEmail(); - } -} - -```` -````VB.NET -Public Class CustomAppointmentEditForm - Public Sub New() - InitializeComponent() - End Sub - Protected Overrides Sub LoadSettingsFromEvent(ByVal ev As IEvent) - MyBase.LoadSettingsFromEvent(ev) - Dim appointmentWithEmail As AppointmentWithEmail = TryCast(ev, AppointmentWithEmail) - If appointmentWithEmail IsNot Nothing Then - Me.txtEmail.Text = appointmentWithEmail.Email - End If - End Sub - Protected Overrides Sub ApplySettingsToEvent(ByVal ev As IEvent) - Dim appointmentWithEmail As AppointmentWithEmail = TryCast(ev, AppointmentWithEmail) - If appointmentWithEmail IsNot Nothing Then - appointmentWithEmail.Email = Me.txtEmail.Text - End If - MyBase.ApplySettingsToEvent(ev) - End Sub - Protected Overrides Function CreateNewEvent() As IEvent - Return New AppointmentWithEmail() - End Function -End Class - -```` - -{{endregion}} + + + -4\. You should assign the custom AppointmentFactory to RadScheduler: -{{source=..\SamplesCS\Scheduler\DataBinding\BindingToCustomFields.cs region=customFactory}} -{{source=..\SamplesVB\Scheduler\DataBinding\BindingToCustomFields.vb region=customFactory}} -````C# -this.radScheduler1.AppointmentFactory = new CustomAppointmentFactory(); + + -```` -````VB.NET -Me.RadScheduler1.AppointmentFactory = New CustomAppointmentFactory() -```` +4\. You should assign the custom AppointmentFactory to RadScheduler: + + + -{{endregion}} 5\. You need to handle the AppointmentEditDialogShowing event of RadScheduler in order to replace the default appointment dialog with a custom one. You will also have to give an instance of your appointment factory to the RadScheduler so it can create instances of your custom appointment class: -{{source=..\SamplesCS\Scheduler\DataBinding\BindingToCustomFields.cs region=loadAndShowing}} -{{source=..\SamplesVB\Scheduler\DataBinding\BindingToCustomFields.vb region=loadAndShowing}} -````C# -private IEditAppointmentDialog appointmentDialog = null; -protected override void OnLoad(EventArgs e) -{ - base.OnLoad(e); - this.radScheduler1.AppointmentFactory = new CustomAppointmentFactory(); - this.radScheduler1.AppointmentEditDialogShowing += new EventHandler(radSchedulerDemo_AppointmentEditDialogShowing); -} -void radSchedulerDemo_AppointmentEditDialogShowing(object sender, AppointmentEditDialogShowingEventArgs e) -{ - if (this.appointmentDialog == null) - { - this.appointmentDialog = new CustomAppointmentEditForm(); - } - e.AppointmentEditDialog = this.appointmentDialog; -} - -```` -````VB.NET -Private appointmentDialog As IEditAppointmentDialog = Nothing -Protected Overrides Sub OnLoad(ByVal e As EventArgs) - MyBase.OnLoad(e) - Me.RadScheduler1.AppointmentFactory = New CustomAppointmentFactory() - AddHandler RadScheduler1.AppointmentEditDialogShowing, AddressOf radSchedulerDemo_AppointmentEditDialogShowing -End Sub -Private Sub radSchedulerDemo_AppointmentEditDialogShowing(ByVal sender As Object, ByVal e As AppointmentEditDialogShowingEventArgs) - If Me.appointmentDialog Is Nothing Then - Me.appointmentDialog = New CustomAppointmentEditForm() - End If - e.AppointmentEditDialog = Me.appointmentDialog -End Sub - -```` - - - -{{endregion}} + + -6\. Finally, you have to add a mapping for your custom field to the appointment mapping info. Note that the same appointment factory instance is assigned to the event provider. -{{source=..\SamplesCS\Scheduler\DataBinding\BindingToCustomFields.cs region=mappings}} -{{source=..\SamplesVB\Scheduler\DataBinding\BindingToCustomFields.vb region=mappings}} -````C# -SchedulerBindingDataSource dataSource = new SchedulerBindingDataSource(); -dataSource.EventProvider.AppointmentFactory = this.radScheduler1.AppointmentFactory; -AppointmentMappingInfo appointmentMappingInfo = (AppointmentMappingInfo)dataSource.EventProvider.Mapping; -appointmentMappingInfo.Mappings.Add(new SchedulerMapping("Email", "Email")); -```` -````VB.NET -Dim dataSource As New SchedulerBindingDataSource() -dataSource.EventProvider.AppointmentFactory = Me.RadScheduler1.AppointmentFactory -Dim appointmentMappingInfo As AppointmentMappingInfo = DirectCast(dataSource.EventProvider.Mapping, AppointmentMappingInfo) -appointmentMappingInfo.Mappings.Add(New SchedulerMapping("Email", "Email")) +6\. Finally, you have to add a mapping for your custom field to the appointment mapping info. Note that the same appointment factory instance is assigned to the event provider. -```` - + + -{{endregion}} # See Also diff --git a/controls/scheduler/data-binding/binding-to-entityframework-and-telerik-data-access.md b/controls/scheduler/data-binding/binding-to-entityframework-and-telerik-data-access.md index 959f5f3a3..c5470efd9 100644 --- a/controls/scheduler/data-binding/binding-to-entityframework-and-telerik-data-access.md +++ b/controls/scheduler/data-binding/binding-to-entityframework-and-telerik-data-access.md @@ -24,41 +24,19 @@ Now, you need to create a form and add a RadScheduler, in this tutorial it is na #### Create DbContext -{{source=..\SamplesCS\Scheduler\DataBinding\BindingToEntityFrameworkAndTelerikDataAccess.cs region=DbContext}} -{{source=..\SamplesVB\Scheduler\DataBinding\BindingToEntityFrameworkAndTelerikDataAccess.vb region=DbContext}} + + -````C# -private SchedulerDataEntities1 dbContext = new SchedulerDataEntities1(); -```` -````VB.NET -Private dbContext As New SchedulerDataEntities1() - -```` - -{{endregion}} Then, we will need a __SchedulerBindingDataSource__, __AppointmentMappingInfo__ and __ResourceMappingInfo__ which we will use to map our data. You can create them in the Form's constructor. #### Data Source Objects -{{source=..\SamplesCS\Scheduler\DataBinding\BindingToEntityFrameworkAndTelerikDataAccess.cs region=Mappings}} -{{source=..\SamplesVB\Scheduler\DataBinding\BindingToEntityFrameworkAndTelerikDataAccess.vb region=Mappings}} - -````C# -SchedulerBindingDataSource schedulerBindingSource = new SchedulerBindingDataSource(); -AppointmentMappingInfo appointmentMappingInfo = new AppointmentMappingInfo(); -ResourceMappingInfo resourceMappingInfo = new ResourceMappingInfo(); - -```` -````VB.NET -Dim schedulerBindingSource As New SchedulerBindingDataSource() -Dim appointmentMappingInfo As New AppointmentMappingInfo() -Dim resourceMappingInfo As New ResourceMappingInfo() + + -```` -{{endregion}} Now you just need to setup the mappings. The approaches for *Entity Framework* and *Telerik Data Access* are a bit different. @@ -66,59 +44,10 @@ Now you just need to setup the mappings. The approaches for *Entity Framework* a Below you can see the code you need to use with *Entity Framework*: -{{source=..\SamplesCS\Scheduler\DataBinding\BindingToEntityFrameworkAndTelerikDataAccess.cs region=EFCode}} -{{source=..\SamplesVB\Scheduler\DataBinding\BindingToEntityFrameworkAndTelerikDataAccess.vb region=EFCode}} - -````C# -dbContext.Appointments.Load(); -dbContext.Resources.Load(); -appointmentMappingInfo.BackgroundId = "BackgroundID"; -appointmentMappingInfo.Description = "Description"; -appointmentMappingInfo.End = "End"; -appointmentMappingInfo.Exceptions = "FK_Appointments_Appointments"; -appointmentMappingInfo.Location = "Location"; -appointmentMappingInfo.MasterEventId = "ParentID"; -appointmentMappingInfo.RecurrenceRule = "RecurrenceRule"; -appointmentMappingInfo.ResourceId = "ID"; -appointmentMappingInfo.Resources = "Resources"; -appointmentMappingInfo.Start = "Start"; -appointmentMappingInfo.StatusId = "StatusID"; -appointmentMappingInfo.Summary = "Summary"; -appointmentMappingInfo.Visible = "Visible"; -schedulerBindingSource.EventProvider.Mapping = appointmentMappingInfo; -resourceMappingInfo.Id = "ID"; -resourceMappingInfo.Name = "ResourceName"; -schedulerBindingSource.ResourceProvider.Mapping = resourceMappingInfo; -schedulerBindingSource.ResourceProvider.DataSource = dbContext.Resources.Local.ToBindingList(); -schedulerBindingSource.EventProvider.DataSource = dbContext.Appointments.Local.ToBindingList(); - -```` -````VB.NET -dbContext.Appointments.Load() -dbContext.Resources.Load() -appointmentMappingInfo.BackgroundId = "BackgroundID" -appointmentMappingInfo.Description = "Description" -appointmentMappingInfo.[End] = "End" -appointmentMappingInfo.Exceptions = "FK_Appointments_Appointments" -appointmentMappingInfo.Location = "Location" -appointmentMappingInfo.MasterEventId = "ParentID" -appointmentMappingInfo.RecurrenceRule = "RecurrenceRule" -appointmentMappingInfo.ResourceId = "ID" -appointmentMappingInfo.Resources = "Resources" -appointmentMappingInfo.Start = "Start" -appointmentMappingInfo.StatusId = "StatusID" -appointmentMappingInfo.Summary = "Summary" -appointmentMappingInfo.Visible = "Visible" -schedulerBindingSource.EventProvider.Mapping = appointmentMappingInfo -resourceMappingInfo.Id = "ID" -resourceMappingInfo.Name = "ResourceName" -schedulerBindingSource.ResourceProvider.Mapping = resourceMappingInfo -schedulerBindingSource.ResourceProvider.DataSource = dbContext.Resources.Local.ToBindingList() -schedulerBindingSource.EventProvider.DataSource = dbContext.Appointments.Local.ToBindingList() - -```` - -{{endregion}} + + + + >important In order to use the __Load__ extension method you need to add *System.Data.Entity* to your usings(C#) or Imports(VB). > @@ -127,77 +56,19 @@ And the following code needs to be used with *Telerik Data Access*: #### Create Mappings for DataAccess -{{source=..\SamplesCS\Scheduler\DataBinding\BindingToEntityFrameworkAndTelerikDataAccess.cs region=TDACode}} -{{source=..\SamplesVB\Scheduler\DataBinding\BindingToEntityFrameworkAndTelerikDataAccess.vb region=TDACode}} - -````C# -appointmentMappingInfo.BackgroundId = "BackgroundID"; -appointmentMappingInfo.Description = "Description"; -appointmentMappingInfo.End = "End"; -appointmentMappingInfo.Exceptions = "FK_Appointments_Appointments"; -appointmentMappingInfo.Location = "Location"; -appointmentMappingInfo.MasterEventId = "ParentID"; -appointmentMappingInfo.RecurrenceRule = "RecurrenceRule"; -appointmentMappingInfo.ResourceId = "ResourceID"; -appointmentMappingInfo.Resources = "AppointmentsResources"; -appointmentMappingInfo.Start = "Start"; -appointmentMappingInfo.StatusId = "StatusID"; -appointmentMappingInfo.Summary = "Summary"; -appointmentMappingInfo.Visible = "Visible"; - -this.schedulerBindingSource.EventProvider.Mapping = appointmentMappingInfo1; - -resourceMappingInfo.Id = "ID"; -resourceMappingInfo.Name = "ResourceName"; -schedulerBindingSource.ResourceProvider.Mapping = resourceMappingInfo1; -schedulerBindingDataSource.ResourceProvider.DataSource = entityContext.Resources.ToList(); -schedulerBindingDataSource.EventProvider.DataSource = entityContext.Appointments.ToList(); - -```` -````VB.NET -appointmentMappingInfo.BackgroundId = "BackgroundID" -appointmentMappingInfo.Description = "Description" -appointmentMappingInfo.[End] = "End" -appointmentMappingInfo.Exceptions = "FK_Appointments_Appointments" -appointmentMappingInfo.Location = "Location" -appointmentMappingInfo.MasterEventId = "ParentID" -appointmentMappingInfo.RecurrenceRule = "RecurrenceRule" -appointmentMappingInfo.ResourceId = "ResourceID" -appointmentMappingInfo.Resources = "AppointmentsResources" -appointmentMappingInfo.Start = "Start" -appointmentMappingInfo.StatusId = "StatusID" -appointmentMappingInfo.Summary = "Summary" -appointmentMappingInfo.Visible = "Visible" -Me.schedulerBindingSource.EventProvider.Mapping = appointmentMappingInfo1 -resourceMappingInfo.Id = "ID" -resourceMappingInfo.Name = "ResourceName" -schedulerBindingSource.ResourceProvider.Mapping = resourceMappingInfo1 -schedulerBindingDataSource.ResourceProvider.DataSource = entityContext.Resources.ToList() -schedulerBindingDataSource.EventProvider.DataSource = entityContext.Appointments.ToList() - -```` - -{{endregion}} + + -The last step that you need to take in order to complete the binding process is to assign the DataSource property of __RadScheduler__ and group it by resource: -#### Set Data Source -{{source=..\SamplesCS\Scheduler\DataBinding\BindingToEntityFrameworkAndTelerikDataAccess.cs region=DataSourceAndGroup}} -{{source=..\SamplesVB\Scheduler\DataBinding\BindingToEntityFrameworkAndTelerikDataAccess.vb region=DataSourceAndGroup}} +The last step that you need to take in order to complete the binding process is to assign the DataSource property of __RadScheduler__ and group it by resource: -````C# -this.scheduler.DataSource = schedulerBindingSource; -this.scheduler.GroupType = GroupType.Resource; +#### Set Data Source -```` -````VB.NET -Me.scheduler.DataSource = schedulerBindingSource -Me.scheduler.GroupType = GroupType.Resource + + -```` -{{endregion}} >important As of **R1 2021** the EditAppointmentDialog provides UI for selecting multiple resources per appointment. In certain cases (e.g. unbound mode), the *Resource* **RadDropDownList** is replaced with a **RadCheckedDropDownList**. Otherwise, the default drop down with single selection for resources is shown. To enable the multiple resources selection in bound mode, it is necessary to specify the AppointmentMappingInfo. **Resources** property. The **Resources** property should be set to the name of the relation that connects the **Appointments** and the **AppointmentsResources** tables. @@ -209,26 +80,9 @@ Saving changes to the database happens when the __SaveChanges__ method of the Db #### Save Changes -{{source=..\SamplesCS\Scheduler\DataBinding\BindingToEntityFrameworkAndTelerikDataAccess.cs region=Closing}} -{{source=..\SamplesVB\Scheduler\DataBinding\BindingToEntityFrameworkAndTelerikDataAccess.vb region=Closing}} - -````C# -protected override void OnClosing(CancelEventArgs e) -{ - this.dbContext.SaveChanges(); - base.OnClosing(e); -} - -```` -````VB.NET -Protected Overrides Sub OnClosing(e As CancelEventArgs) - Me.dbContext.SaveChanges() - MyBase.OnClosing(e) -End Sub - -```` + + -{{endregion}} # See Also diff --git a/controls/scheduler/data-binding/codeless-data-binding.md b/controls/scheduler/data-binding/codeless-data-binding.md index 11054b8d9..9623b0870 100644 --- a/controls/scheduler/data-binding/codeless-data-binding.md +++ b/controls/scheduler/data-binding/codeless-data-binding.md @@ -110,47 +110,19 @@ At the end the *Appointment Mapping Dialog* should look like the following scree #### Fill Data -{{source=..\SamplesCS\Scheduler\DataBinding\DataBindingWalkthrough.cs region=codelessDatabinding}} -{{source=..\SamplesVB\Scheduler\DataBinding\DataBindingWalkthrough.vb region=codelessDatabinding}} - -````C# -AppointmentsTableAdapter appointmentsAdapter = new AppointmentsTableAdapter(); -appointmentsAdapter.Fill(this.schedulerDataDataSet.Appointments); -ResourcesTableAdapter resourcesAdapter = new ResourcesTableAdapter(); -resourcesAdapter.Fill(this.schedulerDataDataSet.Resources); -AppointmentsResourcesTableAdapter appointmentsResourcesAdapter = new AppointmentsResourcesTableAdapter(); -appointmentsResourcesAdapter.Fill(this.schedulerDataDataSet.AppointmentsResources); - -```` -````VB.NET -Dim appointmentsAdapter As New AppointmentsTableAdapter() -appointmentsAdapter.Fill(Me.SchedulerDataDataSet.Appointments) -Dim resourcesAdapter As New ResourcesTableAdapter() -resourcesAdapter.Fill(Me.SchedulerDataDataSet.Resources) -Dim appointmentsResourcesAdapter As New AppointmentsResourcesTableAdapter() -appointmentsResourcesAdapter.Fill(Me.SchedulerDataDataSet.AppointmentsResources) - -```` - -{{endregion}} + + -20\. Use the __Rebind__ method of the __SchedulerBindingDataSource__ object if the dataset is filled after applying the event provider data source: -#### Rebind the Binding Source -{{source=..\SamplesCS\Scheduler\DataBinding\DataBindingWalkthrough.cs region=Rebind}} -{{source=..\SamplesVB\Scheduler\DataBinding\DataBindingWalkthrough.vb region=Rebind}} +20\. Use the __Rebind__ method of the __SchedulerBindingDataSource__ object if the dataset is filled after applying the event provider data source: -````C# -schedulerBindingDataSource1.Rebind(); +#### Rebind the Binding Source -```` -````VB.NET -SchedulerBindingDataSource1.Rebind() + + -```` -{{endregion}} 21\. Run the project. diff --git a/controls/scheduler/data-binding/data-binding-walkthrough.md b/controls/scheduler/data-binding/data-binding-walkthrough.md index 7740182bd..753d65e8d 100644 --- a/controls/scheduler/data-binding/data-binding-walkthrough.md +++ b/controls/scheduler/data-binding/data-binding-walkthrough.md @@ -62,51 +62,10 @@ When you do so, a dialog will appear letting you choose the field of the data so In order to programatically map the fields of your data source to the correct properties of scheduler’s objects, you need to setup two mapping info instances: one of type AppointmentMappingInfo and one of type ResourceMappingInfo and assign them to the SchedulerBindingDataSource instance as it is demonstrated below. -{{source=..\SamplesCS\Scheduler\DataBinding\DataBindingWalkthrough.cs region=creatingMappings}} -{{source=..\SamplesVB\Scheduler\DataBinding\DataBindingWalkthrough.vb region=creatingMappings}} - -````C# -AppointmentMappingInfo appointmentMappingInfo = new AppointmentMappingInfo(); -appointmentMappingInfo.BackgroundId = "BackgroundID"; -appointmentMappingInfo.Description = "Description"; -appointmentMappingInfo.End = "End"; -appointmentMappingInfo.Location = "Location"; -appointmentMappingInfo.MasterEventId = "ParentID"; -appointmentMappingInfo.RecurrenceRule = "RecurrenceRule"; -appointmentMappingInfo.ResourceId = "ResourceID"; -appointmentMappingInfo.Resources = "Appointments_AppointmentsResources"; -appointmentMappingInfo.Start = "Start"; -appointmentMappingInfo.StatusId = "StatusID"; -appointmentMappingInfo.Summary = "Summary"; -schedulerBindingDataSource1.EventProvider.Mapping = appointmentMappingInfo; -ResourceMappingInfo resourceMappingInfo = new ResourceMappingInfo(); -resourceMappingInfo.Id = "ID"; -resourceMappingInfo.Name = "ResourceName"; -this.schedulerBindingDataSource1.ResourceProvider.Mapping = resourceMappingInfo; - -```` -````VB.NET -Dim appointmentMappingInfo As New AppointmentMappingInfo() -appointmentMappingInfo.BackgroundId = "BackgroundID" -appointmentMappingInfo.Description = "Description" -appointmentMappingInfo.[End] = "End" -appointmentMappingInfo.Location = "Location" -appointmentMappingInfo.MasterEventId = "ParentID" -appointmentMappingInfo.RecurrenceRule = "RecurrenceRule" -appointmentMappingInfo.ResourceId = "ResourceID" -appointmentMappingInfo.Resources = "Appointments_AppointmentsResources" -appointmentMappingInfo.Start = "Start" -appointmentMappingInfo.StatusId = "StatusID" -appointmentMappingInfo.Summary = "Summary" -SchedulerBindingDataSource1.EventProvider.Mapping = appointmentMappingInfo -Dim resourceMappingInfo As New ResourceMappingInfo() -resourceMappingInfo.Id = "ID" -resourceMappingInfo.Name = "ResourceName" -Me.SchedulerBindingDataSource1.ResourceProvider.Mapping = resourceMappingInfo - -```` - -{{endregion}} + + + + >important As of **R1 2021** the EditAppointmentDialog provides UI for selecting multiple resources per appointment. In certain cases (e.g. unbound mode), the *Resource* **RadDropDownList** is replaced with a **RadCheckedDropDownList**. Otherwise, the default drop down with single selection for resources is shown. To enable the multiple resources selection in bound mode, it is necessary to specify the AppointmentMappingInfo. **Resources** property. The **Resources** property should be set to the name of the relation that connects the **Appointments** and the **AppointmentsResources** tables. @@ -118,62 +77,29 @@ Me.SchedulerBindingDataSource1.ResourceProvider.Mapping = resourceMappingInfo To retrieve the data, first we need to fill the data set: -{{source=..\SamplesCS\Scheduler\DataBinding\DataBindingWalkthrough.cs region=fillingAdapters}} -{{source=..\SamplesVB\Scheduler\DataBinding\DataBindingWalkthrough.vb region=fillingAdapters}} - -````C# -this.resourcesTableAdapter.Fill(this.schedulerDataDataSet.Resources); -this.appointmentsResourcesTableAdapter.Fill(this.schedulerDataDataSet.AppointmentsResources); -this.appointmentsTableAdapter.Fill(this.schedulerDataDataSet.Appointments); + + -```` -````VB.NET -Me.ResourcesTableAdapter.Fill(Me.SchedulerDataDataSet.Resources) -Me.AppointmentsResourcesTableAdapter.Fill(Me.SchedulerDataDataSet.AppointmentsResources) -Me.AppointmentsTableAdapter.Fill(Me.SchedulerDataDataSet.Appointments) -```` - -{{endregion}} >note You should fill the tables in the exact same order if you have already set the DataSource property of __RadScheduler__. Alternatively, you can just call the __DataBind__ method of __RadScheduler__ after you fill the tables. > Now we need to assign the Appointments and Resources tables from the data set to our SchedulerBindingDataSource (the following can also be set at design time through the Smart Tag of your SchedulerBindingDataSource instance as you can see on the previous image): -{{source=..\SamplesCS\Scheduler\DataBinding\DataBindingWalkthrough.cs region=AssignAppointmentsAndResources}} -{{source=..\SamplesVB\Scheduler\DataBinding\DataBindingWalkthrough.vb region=AssignAppointmentsAndResources}} - -````C# -schedulerBindingDataSource1.ResourceProvider.DataSource = schedulerDataDataSet.Resources; -schedulerBindingDataSource1.EventProvider.DataSource = schedulerDataDataSet.Appointments; + + -```` -````VB.NET -SchedulerBindingDataSource1.ResourceProvider.DataSource = SchedulerDataDataSet.Resources -SchedulerBindingDataSource1.EventProvider.DataSource = SchedulerDataDataSet.Appointments -```` - -{{endregion}} Finally, we assign our SchedulerBindingDataSource instance to __RadScheduler__ as its DataSource. This can be achieved either through the Smart Tag of __RadScheduler__ or via code: ![WinForms RadScheduler SchedulerBindingDataSource](images/scheduler-data-binding-data-binding-walkthrough008.png) -{{source=..\SamplesCS\Scheduler\DataBinding\DataBindingWalkthrough.cs region=dataSource}} -{{source=..\SamplesVB\Scheduler\DataBinding\DataBindingWalkthrough.vb region=dataSource}} - -````C# -radScheduler1.DataSource = schedulerBindingDataSource1; - -```` -````VB.NET -RadScheduler1.DataSource = SchedulerBindingDataSource1 + + -```` -{{endregion}} >note If the above steps are not performed in the same order, __RadScheduler__ might not display the appointments. In this case you can try calling the __DataBind__ method of __RadScheduler__ or the __Rebind__ method of __SchedulerBindingDataSource__. > @@ -182,157 +108,10 @@ RadScheduler1.DataSource = SchedulerBindingDataSource1 Add the following code to the Click event handler for an "Update" button, which will update the data source. (for more information on saving data, see MSDN:[How to: Update Data by Using a TableAdapter](http://msdn.microsoft.com/en-us/library/ms171933.aspx)).Note that we need to update the added, modified and deleted records in a certain order because of the relations between our tables.We also need to use the two dictionaries to keep track of the automatically generated IDs before and after calling Update. This is due to a synchronization problem between the database and the data set, where the data adapter could not update correctly the ID of the added row. This happens because the IDs generated locally might differ from the IDs generated from the database(for example when multiple users work simultaneously) and we use this IDs to store the relation between appointments and resources. (Here is an MSDN article which describes this limitation:[Retrieving Identity or Autonumber Values](http://msdn.microsoft.com/en-us/library/ks9f57t0%28VS.71%29.aspx)) -{{source=..\SamplesCS\Scheduler\DataBinding\DataBindingWalkthrough.cs region=update}} -{{source=..\SamplesVB\Scheduler\DataBinding\DataBindingWalkthrough.vb region=update}} - -````C# -private void btnUpdate_Click(object sender, EventArgs e) -{ - appointmentsResourcesTableAdapter.Adapter.AcceptChangesDuringUpdate = false; - SchedulerDataDataSet.AppointmentsResourcesDataTable deletedRelationRecords = - this.schedulerDataDataSet.AppointmentsResources.GetChanges(DataRowState.Deleted) - as SchedulerDataDataSet.AppointmentsResourcesDataTable; - SchedulerDataDataSet.AppointmentsResourcesDataTable newRelationRecords = - this.schedulerDataDataSet.AppointmentsResources.GetChanges(DataRowState.Added) - as SchedulerDataDataSet.AppointmentsResourcesDataTable; - SchedulerDataDataSet.AppointmentsResourcesDataTable modifiedRelationRecords = - this.schedulerDataDataSet.AppointmentsResources.GetChanges(DataRowState.Modified) - as SchedulerDataDataSet.AppointmentsResourcesDataTable; - SchedulerDataDataSet.AppointmentsDataTable newAppointmentRecords = - this.schedulerDataDataSet.Appointments.GetChanges(DataRowState.Added) as SchedulerDataDataSet.AppointmentsDataTable; - SchedulerDataDataSet.AppointmentsDataTable deletedAppointmentRecords = - this.schedulerDataDataSet.Appointments.GetChanges(DataRowState.Deleted) as SchedulerDataDataSet.AppointmentsDataTable; - SchedulerDataDataSet.AppointmentsDataTable modifiedAppointmentRecords = - this.schedulerDataDataSet.Appointments.GetChanges(DataRowState.Modified) as SchedulerDataDataSet.AppointmentsDataTable; - try - { - if (newAppointmentRecords != null) - { - Dictionary newAppointmentIds = new Dictionary(); - Dictionary oldAppointmentIds = new Dictionary(); - for (int i = 0; i < newAppointmentRecords.Count; i++) - { - oldAppointmentIds.Add(newAppointmentRecords[i], newAppointmentRecords[i].ID); - } - appointmentsTableAdapter.Update(newAppointmentRecords); - for (int i = 0; i < newAppointmentRecords.Count; i++) - { - newAppointmentIds.Add(oldAppointmentIds[newAppointmentRecords[i]], newAppointmentRecords[i].ID); - } - if (newRelationRecords!=null) - { - for (int i = 0; i < newRelationRecords.Count; i++) - { - newRelationRecords[i].AppointmentID = newAppointmentIds[newRelationRecords[i].AppointmentID]; - } - } - } - if (deletedRelationRecords != null) - { - appointmentsResourcesTableAdapter.Update(deletedRelationRecords); - } - if (deletedAppointmentRecords != null) - { - appointmentsTableAdapter.Update(deletedAppointmentRecords); - } - if (modifiedAppointmentRecords != null) - { - appointmentsTableAdapter.Update(modifiedAppointmentRecords); - } - if (newRelationRecords != null) - { - appointmentsResourcesTableAdapter.Update(newRelationRecords); - } - if (modifiedRelationRecords != null) - { - appointmentsResourcesTableAdapter.Update(modifiedRelationRecords); - } - this.schedulerDataDataSet.AcceptChanges(); - } - catch (Exception ex) - { - MessageBox.Show(string.Format("An error occurred during the update process:\n{0}", ex.Message)); - } - finally - { - if (deletedRelationRecords != null) - { - deletedRelationRecords.Dispose(); - } - if (newRelationRecords != null) - { - newRelationRecords.Dispose(); - } - if (modifiedRelationRecords != null) - { - modifiedRelationRecords.Dispose(); - } - } - lblStatus.Text = "Updated scheduler at " + DateTime.Now.ToString(); -} - -```` -````VB.NET -Private Sub btnUpdate_Click(ByVal sender As Object, ByVal e As EventArgs) - AppointmentsResourcesTableAdapter.Adapter.AcceptChangesDuringUpdate = False - Dim deletedRelationRecords As SchedulerDataDataSet.AppointmentsResourcesDataTable = TryCast(Me.SchedulerDataDataSet.AppointmentsResources.GetChanges(DataRowState.Deleted), SchedulerDataDataSet.AppointmentsResourcesDataTable) - Dim newRelationRecords As SchedulerDataDataSet.AppointmentsResourcesDataTable = TryCast(Me.SchedulerDataDataSet.AppointmentsResources.GetChanges(DataRowState.Added), SchedulerDataDataSet.AppointmentsResourcesDataTable) - Dim modifiedRelationRecords As SchedulerDataDataSet.AppointmentsResourcesDataTable = TryCast(Me.SchedulerDataDataSet.AppointmentsResources.GetChanges(DataRowState.Modified), SchedulerDataDataSet.AppointmentsResourcesDataTable) - Dim newAppointmentRecords As SchedulerDataDataSet.AppointmentsDataTable = TryCast(Me.SchedulerDataDataSet.Appointments.GetChanges(DataRowState.Added), SchedulerDataDataSet.AppointmentsDataTable) - Dim deletedAppointmentRecords As SchedulerDataDataSet.AppointmentsDataTable = TryCast(Me.SchedulerDataDataSet.Appointments.GetChanges(DataRowState.Deleted), SchedulerDataDataSet.AppointmentsDataTable) - Dim modifiedAppointmentRecords As SchedulerDataDataSet.AppointmentsDataTable = TryCast(Me.SchedulerDataDataSet.Appointments.GetChanges(DataRowState.Modified), SchedulerDataDataSet.AppointmentsDataTable) - Try - If newAppointmentRecords IsNot Nothing Then - Dim newAppointmentIds As New Dictionary(Of Integer, Integer)() - Dim oldAppointmentIds As New Dictionary(Of Object, Integer)() - For i As Integer = 0 To newAppointmentRecords.Count - 1 - oldAppointmentIds.Add(newAppointmentRecords(i), newAppointmentRecords(i).ID) - Next - AppointmentsTableAdapter.Update(newAppointmentRecords) - For i As Integer = 0 To newAppointmentRecords.Count - 1 - newAppointmentIds.Add(oldAppointmentIds(newAppointmentRecords(i)), newAppointmentRecords(i).ID) - Next - If newRelationRecords IsNot Nothing Then - For i As Integer = 0 To newRelationRecords.Count - 1 - newRelationRecords(i).AppointmentID = newAppointmentIds(newRelationRecords(i).AppointmentID) - Next - End If - End If - If deletedRelationRecords IsNot Nothing Then - AppointmentsResourcesTableAdapter.Update(deletedRelationRecords) - End If - If deletedAppointmentRecords IsNot Nothing Then - AppointmentsTableAdapter.Update(deletedAppointmentRecords) - End If - If modifiedAppointmentRecords IsNot Nothing Then - AppointmentsTableAdapter.Update(modifiedAppointmentRecords) - End If - If newRelationRecords IsNot Nothing Then - AppointmentsResourcesTableAdapter.Update(newRelationRecords) - End If - If modifiedRelationRecords IsNot Nothing Then - AppointmentsResourcesTableAdapter.Update(modifiedRelationRecords) - End If - Me.SchedulerDataDataSet.AcceptChanges() - Catch ex As Exception - MessageBox.Show(String.Format("An error occurred during the update process:" & vbLf & "{0}", ex.Message)) - Finally - If deletedRelationRecords IsNot Nothing Then - deletedRelationRecords.Dispose() - End If - If newRelationRecords IsNot Nothing Then - newRelationRecords.Dispose() - End If - If modifiedRelationRecords IsNot Nothing Then - modifiedRelationRecords.Dispose() - End If - End Try - lblStatus.Text = "Updated scheduler at " + DateTime.Now.ToString() -End Sub - -```` - -{{endregion}} + + + + >caption Figure 1: Data Bound RadScheduler ![WinForms RadScheduler Data Bound RadScheduler](images/scheduler-data-binding-data-binding-walkthrough009.png) diff --git a/controls/scheduler/data-binding/scheduler-mapping.md b/controls/scheduler/data-binding/scheduler-mapping.md index 247fad31b..a42b072d1 100644 --- a/controls/scheduler/data-binding/scheduler-mapping.md +++ b/controls/scheduler/data-binding/scheduler-mapping.md @@ -1,305 +1,89 @@ ---- -title: Scheduler Mapping -page_title: Scheduler Mapping - WinForms Scheduler Control -description: WinForms SchedulerMapping class is responsible for mapping a single property from the data source to a scheduler property, which allows you to specify convert callback methods in order to convert values to and from the data source if needed. -slug: winforms/scheduler/data-binding/scheduler-mapping -tags: scheduler,mapping -published: True -position: 11 -previous_url: scheduler-data-binding-scheduler-mapping ---- - -# Scheduler Mapping - -The __SchedulerMapping__ class is responsible for mapping a single property from the data source to a scheduler property, which allows you to specify convert callback methods in order to convert values to and from the data source if needed. - -## Overview - -To associate a field with a different type than the scheduler type, for example, a background id that is written as a string in the database: - -1\. Create two methods with the following signatures: - -{{source=..\SamplesCS\Scheduler\DataBinding\SchedulerMapping1.cs region=backgroundCallback}} -{{source=..\SamplesVB\Scheduler\DataBinding\SchedulerMapping1.vb region=backgroundCallback}} - -````C# -object ConvertBackgrounIdToScheduler(object obj) -{ - if (!(obj is DBNull)) - { - string appointmentBackground = (string)obj; - switch (appointmentBackground) - { - case "Business": - return AppointmentBackground.Business; - case "Important": - return AppointmentBackground.Important; - case "MustAttend": - return AppointmentBackground.MustAttend; - case "PhoneCall": - return AppointmentBackground.PhoneCall; - //TO DO other backgrounds - } - } - return AppointmentBackground.None; -} -object ConvertBackgrounIdToDataSource(object obj) -{ - AppointmentBackground appointmentBackground = (AppointmentBackground)obj; - switch (appointmentBackground) - { - case AppointmentBackground.Business: - return "Business"; - case AppointmentBackground.Important: - return "Important"; - case AppointmentBackground.MustAttend: - return "MustAttend"; - case AppointmentBackground.PhoneCall: - return "PhoneCall"; - //TO DO other backgrounds - } - return "None"; -} - -```` -````VB.NET -Private Function ConvertBackgrounIdToScheduler(ByVal obj As Object) As Object - If Not (TypeOf obj Is DBNull) Then - Dim appointmentBackground As String = CStr(obj) - Select Case appointmentBackground - Case "Business" - Return Telerik.WinControls.UI.AppointmentBackground.Business - Case "Important" - Return Telerik.WinControls.UI.AppointmentBackground.Important - Case "MustAttend" - Return Telerik.WinControls.UI.AppointmentBackground.MustAttend - Case "PhoneCall" - Return Telerik.WinControls.UI.AppointmentBackground.PhoneCall - 'TO DO other backgrounds - End Select - End If - Return AppointmentBackground.None -End Function -Private Function ConvertBackgrounIdToDataSource(ByVal obj As Object) As Object - Dim appointmentBackground As AppointmentBackground = CType(obj, AppointmentBackground) - Select Case appointmentBackground - Case appointmentBackground.Business - Return "Business" - Case appointmentBackground.Important - Return "Important" - Case appointmentBackground.MustAttend - Return "MustAttend" - Case appointmentBackground.PhoneCall - Return "PhoneCall" - 'TO DO other backgrounds - End Select - Return "None" -End Function - -```` - -{{endregion}} - -2\. Apply settings of the __BackgroundId__ mapping in the __AppointmentMappingInfo__: - -{{source=..\SamplesCS\Scheduler\DataBinding\SchedulerMapping1.cs region=background}} -{{source=..\SamplesVB\Scheduler\DataBinding\SchedulerMapping1.vb region=background}} - -````C# -SchedulerMapping backgroundIdSchedulerMapping = appointmentMappingInfo.FindBySchedulerProperty("BackgroundId"); -backgroundIdSchedulerMapping.ConvertToScheduler = new ConvertCallback(this.ConvertBackgrounIdToScheduler); -backgroundIdSchedulerMapping.ConvertToDataSource = new ConvertCallback(this.ConvertBackgrounIdToDataSource); - -```` -````VB.NET -Dim backgroundIdSchedulerMapping As SchedulerMapping = appointmentMappingInfo.FindBySchedulerProperty("BackgroundId") -backgroundIdSchedulerMapping.ConvertToScheduler = New ConvertCallback(AddressOf Me.ConvertBackgrounIdToScheduler) -backgroundIdSchedulerMapping.ConvertToDataSource = New ConvertCallback(AddressOf Me.ConvertBackgrounIdToDataSource) - -```` - -{{endregion}} - -## Null Fields in the Data Base - -If the database has fields that can be Null then you need to add converters for those fields. For example, let's suppose that the database has a field "Location", which is a string and you wish to check whether its value is DBNull. If it is DBNull you would want to convert it to null. Here are the steps: - -1\. Create a conversion method with the following signature: - -{{source=..\SamplesCS\Scheduler\DataBinding\SchedulerMapping1.cs region=locationCallback}} -{{source=..\SamplesVB\Scheduler\DataBinding\SchedulerMapping1.vb region=locationCallback}} - -````C# -object ConvertLocationToScheduler(object obj) -{ - if (obj is DBNull) - { - return null; - } - return obj; -} - -```` -````VB.NET -Private Function ConvertLocationToScheduler(ByVal obj As Object) As Object - If TypeOf obj Is DBNull Then - Return Nothing - End If - Return obj -End Function - -```` - -{{endregion}} - -2\. Apply the Location mapping settings in the AppointmentMappingInfo: - -{{source=..\SamplesCS\Scheduler\DataBinding\SchedulerMapping1.cs region=location}} -{{source=..\SamplesVB\Scheduler\DataBinding\SchedulerMapping1.vb region=location}} - -````C# -AppointmentMappingInfo appointmentMappingInfo = new AppointmentMappingInfo(); -appointmentMappingInfo.Location = "Location"; -SchedulerMapping locationSchedulerMapping = appointmentMappingInfo.FindBySchedulerProperty("Location"); -locationSchedulerMapping.ConvertToScheduler = new ConvertCallback(this.ConvertLocationToScheduler); - -```` -````VB.NET -Dim appointmentMappingInfo As New AppointmentMappingInfo() -appointmentMappingInfo.Location = "Location" -Dim locationSchedulerMapping As SchedulerMapping = appointmentMappingInfo.FindBySchedulerProperty("Location") -locationSchedulerMapping.ConvertToScheduler = New ConvertCallback(AddressOf Me.ConvertLocationToScheduler) - -```` - -{{endregion}} - -## Not Read-Only Id Field Other than Guid - -If the Id field type is different than a Guid, and/or it is not read only in the data table, then you will need to add a converter to convert the type to a Guid. This case holds true for __Resources__ and __Appointments__. - -If Id is read only in the data set, then the Scheduler will rely on the way the data set handles read only Id's. - -1\. Create a methods with the following signatures - -{{source=..\SamplesCS\Scheduler\DataBinding\SchedulerMapping1.cs region=NullFieldsInTheDataBase}} -{{source=..\SamplesVB\Scheduler\DataBinding\SchedulerMapping1.vb region=NullFieldsInTheDataBase}} - -````C# -object ConvertUniqueIdToScheduler(object obj) -{ - return new EventId(obj); -} -object ConvertUniqueIdToDataSource(object obj) -{ - EventId eventId = obj as EventId; - //if the appointment is added from the scheduler the eventId.KeyValue is Guid - if (eventId.KeyValue is Guid) - { - //return the value that is in your object/dataset - } - //if the appointment is loaded from an object/dataset the eventId.KeyValue is its representation in the object/datase - return eventId.KeyValue; -} - -```` -````VB.NET -Private Function ConvertUniqueIdToScheduler(ByVal obj As Object) As Object - Return New EventId(obj) -End Function -Private Function ConvertUniqueIdToDataSource(ByVal obj As Object) As Object - Dim eventId As EventId = TryCast(obj, EventId) - 'if the appointment is added from the scheduler the eventId.KeyValue is Guid - If TypeOf eventId.KeyValue Is Guid Then - 'return the value that is in your object/dataset - End If - 'if the appointment is loaded from an object/dataset the eventId.KeyValue is its representation in the object/datase - Return eventId.KeyValue -End Function - -```` - -{{endregion}} - -2\. Apply the settings of the UniqueId mapping in the AppointmentMappingInfo: - -{{source=..\SamplesCS\Scheduler\DataBinding\SchedulerMapping1.cs region=ApplyUniqueId}} -{{source=..\SamplesVB\Scheduler\DataBinding\SchedulerMapping1.vb region=ApplyUniqueId}} - -````C# -SchedulerMapping uniqueIdSchedulerMapping = appointmentMappingInfo.FindBySchedulerProperty("UniqueId"); -uniqueIdSchedulerMapping.ConvertToScheduler = new ConvertCallback(this.ConvertUniqueIdToScheduler); -uniqueIdSchedulerMapping.ConvertToDataSource = new ConvertCallback(this.ConvertUniqueIdToDataSource); - -```` -````VB.NET -Dim uniqueIdSchedulerMapping As SchedulerMapping = appointmentMappingInfo.FindBySchedulerProperty("UniqueId") -uniqueIdSchedulerMapping.ConvertToScheduler = New ConvertCallback(AddressOf Me.ConvertUniqueIdToScheduler) -uniqueIdSchedulerMapping.ConvertToDataSource = New ConvertCallback(AddressOf Me.ConvertUniqueIdToDataSource) - -```` - -{{endregion}} - -## ConvertValueToScheduler and ConvertValueToDataSource Events - -Similar to the **ConvertToScheduler** and **ConvertToDataSource** callbacks of the **SchedulerMapping**, in **R1 2018** we introduced the **ConvertValueToScheduler** and **ConvertValueToDataSource** events to handle the conversion from a value coming from the DataSource to the **RadScheduler**'s respective type and vice versa. - -#### Conversion Events - -{{source=..\SamplesCS\Scheduler\DataBinding\SchedulerMapping1.cs region=EventsMapping}} -{{source=..\SamplesVB\Scheduler\DataBinding\SchedulerMapping1.vb region=EventsMapping}} - -````C# -public void EventSubscriptions() -{ - AppointmentMappingInfo appointmentMapping = new AppointmentMappingInfo(); - //other code for the AppointmentMappingInfo setup - appointmentMapping.FindBySchedulerProperty("ResourceId").ConvertValueToScheduler += ConvertValueToScheduler; - appointmentMapping.FindBySchedulerProperty("ResourceId").ConvertValueToDataSource += ConvertValueToDataSource; -} -private void ConvertValueToDataSource(object sender, ConvertFromToSchedulerEventArgs e) -{ - if (e.PropertyName == "ResourceId") - { - e.Value = (int)((EventId)e.Value).KeyValue; - } -} -private void ConvertValueToScheduler(object sender, ConvertFromToSchedulerEventArgs e) -{ - if (e.PropertyName == "ResourceId") - { - e.Value = new EventId((int)e.Value); - } -} - -```` -````VB.NET -Public Sub EventSubscriptions() - Dim appointmentMapping As AppointmentMappingInfo = New AppointmentMappingInfo - 'other code for the AppointmentMappingInfo setup - AddHandler appointmentMapping.FindBySchedulerProperty("ResourceId").ConvertValueToScheduler, AddressOf ConvertValueToScheduler - AddHandler appointmentMapping.FindBySchedulerProperty("ResourceId").ConvertValueToDataSource, AddressOf ConvertValueToDataSource -End Sub -Private Sub ConvertValueToDataSource(ByVal sender As Object, ByVal e As ConvertFromToSchedulerEventArgs) - If (e.PropertyName = "ResourceId") Then - e.Value = CType(CType(e.Value, EventId).KeyValue, Integer) - End If -End Sub -Private Sub ConvertValueToScheduler(ByVal sender As Object, ByVal e As ConvertFromToSchedulerEventArgs) - If (e.PropertyName = "ResourceId") Then - e.Value = New EventId(CType(e.Value, Integer)) - End If -End Sub - -```` - -{{endregion}} - -# See Also - -* [Design Time]({%slug winforms/scheduler/design-time/smart-tag%}) -* [Views]({%slug winforms/scheduler/views/overview-and-structure%}) -* [Scheduler Mapping]({%slug winforms/scheduler/data-binding/scheduler-mapping%}) -* [Working with Resources]({%slug winforms/scheduler/data-binding/working-with-resources%}) -* [Setting Appointments and Resources Relations]({%slug winforms/scheduler/data-binding/setting-appointment-and-resource-relations%}) +--- +title: Scheduler Mapping +page_title: Scheduler Mapping - WinForms Scheduler Control +description: WinForms SchedulerMapping class is responsible for mapping a single property from the data source to a scheduler property, which allows you to specify convert callback methods in order to convert values to and from the data source if needed. +slug: winforms/scheduler/data-binding/scheduler-mapping +tags: scheduler,mapping +published: True +position: 11 +previous_url: scheduler-data-binding-scheduler-mapping +--- + +# Scheduler Mapping + +The __SchedulerMapping__ class is responsible for mapping a single property from the data source to a scheduler property, which allows you to specify convert callback methods in order to convert values to and from the data source if needed. + +## Overview + +To associate a field with a different type than the scheduler type, for example, a background id that is written as a string in the database: + +1\. Create two methods with the following signatures: + + + + + + +2\. Apply settings of the __BackgroundId__ mapping in the __AppointmentMappingInfo__: + + + + + + +## Null Fields in the Data Base + +If the database has fields that can be Null then you need to add converters for those fields. For example, let's suppose that the database has a field "Location", which is a string and you wish to check whether its value is DBNull. If it is DBNull you would want to convert it to null. Here are the steps: + +1\. Create a conversion method with the following signature: + + + + + + +2\. Apply the Location mapping settings in the AppointmentMappingInfo: + + + + + + +## Not Read-Only Id Field Other than Guid + +If the Id field type is different than a Guid, and/or it is not read only in the data table, then you will need to add a converter to convert the type to a Guid. This case holds true for __Resources__ and __Appointments__. + +If Id is read only in the data set, then the Scheduler will rely on the way the data set handles read only Id's. + +1\. Create a methods with the following signatures + + + + + + +2\. Apply the settings of the UniqueId mapping in the AppointmentMappingInfo: + + + + + + +## ConvertValueToScheduler and ConvertValueToDataSource Events + +Similar to the **ConvertToScheduler** and **ConvertToDataSource** callbacks of the **SchedulerMapping**, in **R1 2018** we introduced the **ConvertValueToScheduler** and **ConvertValueToDataSource** events to handle the conversion from a value coming from the DataSource to the **RadScheduler**'s respective type and vice versa. + +#### Conversion Events + + + + + + +# See Also + +* [Design Time]({%slug winforms/scheduler/design-time/smart-tag%}) +* [Views]({%slug winforms/scheduler/views/overview-and-structure%}) +* [Scheduler Mapping]({%slug winforms/scheduler/data-binding/scheduler-mapping%}) +* [Working with Resources]({%slug winforms/scheduler/data-binding/working-with-resources%}) +* [Setting Appointments and Resources Relations]({%slug winforms/scheduler/data-binding/setting-appointment-and-resource-relations%}) diff --git a/controls/scheduler/data-binding/setting-appointment-and-resource-relations.md b/controls/scheduler/data-binding/setting-appointment-and-resource-relations.md index 6edf46e87..d4c6f572a 100644 --- a/controls/scheduler/data-binding/setting-appointment-and-resource-relations.md +++ b/controls/scheduler/data-binding/setting-appointment-and-resource-relations.md @@ -23,95 +23,10 @@ Additionally, since the type of the __ResourceId__ property in the __Appointment #### Convert Methods -{{source=..\SamplesCS\Scheduler\DataBinding\SettingAppointmentAndResourceRelations.cs region=sample}} -{{source=..\SamplesVB\Scheduler\DataBinding\SettingAppointmentAndResourceRelations.vb region=sample}} - -````C# -private void SettingAppointmentAndResourceRelations_Load(object sender, EventArgs e) -{ - // TODO: This line of code loads data into the 'schedulerDataOneToManyDataSet.Resources' table. You can move, or remove it, as needed. - this.resourcesTableAdapter.Fill(this.schedulerDataOneToManyDataSet.Resources); - // TODO: This line of code loads data into the 'schedulerDataOneToManyDataSet.Appointments' table. You can move, or remove it, as needed. - this.appointmentsTableAdapter.Fill(this.schedulerDataOneToManyDataSet.Appointments); - AppointmentMappingInfo appointmentMapping = new AppointmentMappingInfo(); - ResourceMappingInfo resourceMapping = new ResourceMappingInfo(); - appointmentMapping.Start = "Start"; - appointmentMapping.End = "End"; - appointmentMapping.Summary = "Summary"; - appointmentMapping.Description = "Description"; - appointmentMapping.Location = "Location"; - appointmentMapping.BackgroundId = "BackgroundID"; - appointmentMapping.StatusId = "StatusID"; - appointmentMapping.RecurrenceRule = "RecurrenceRule"; - appointmentMapping.ResourceId = "ResourceID"; - appointmentMapping.FindBySchedulerProperty("ResourceId").ConvertToDataSource = ConvertResourceToDataSource; - appointmentMapping.FindBySchedulerProperty("ResourceId").ConvertToScheduler = ConvertResourceToScheduler; - resourceMapping.Name = "ResourceName"; - resourceMapping.Id = "ID"; - this.schedulerBindingDataSource1.ResourceProvider.Mapping = resourceMapping; - this.schedulerBindingDataSource1.ResourceProvider.DataSource = this.schedulerDataOneToManyDataSet.Resources; - this.schedulerBindingDataSource1.EventProvider.Mapping = appointmentMapping; - this.schedulerBindingDataSource1.EventProvider.DataSource = this.schedulerDataOneToManyDataSet.Appointments; - this.radScheduler1.DataSource = this.schedulerBindingDataSource1; - this.radScheduler1.GroupType = GroupType.Resource; -} -private object ConvertResourceToScheduler(object item) -{ - return new EventId(item); -} -private object ConvertResourceToDataSource(object item) -{ - EventId resourceId = item as EventId; - if (item != null && resourceId.KeyValue is int) - { - return resourceId.KeyValue; - } - return DBNull.Value; -} - -```` -````VB.NET -Private Sub SettingAppointmentAndResourceRelations_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load - 'TODO: This line of code loads data into the 'SchedulerDataOneToManyDataSet.Resources' table. You can move, or remove it, as needed. - Me.ResourcesTableAdapter.Fill(Me.SchedulerDataOneToManyDataSet.Resources) - 'TODO: This line of code loads data into the 'SchedulerDataOneToManyDataSet.Appointments' table. You can move, or remove it, as needed. - Me.AppointmentsTableAdapter.Fill(Me.SchedulerDataOneToManyDataSet.Appointments) - Dim appointmentMapping As New AppointmentMappingInfo() - Dim resourceMapping As New ResourceMappingInfo() - appointmentMapping.Start = "Start" - appointmentMapping.[End] = "End" - appointmentMapping.Summary = "Summary" - appointmentMapping.Description = "Description" - appointmentMapping.Location = "Location" - appointmentMapping.BackgroundId = "BackgroundID" - appointmentMapping.StatusId = "StatusID" - appointmentMapping.RecurrenceRule = "RecurrenceRule" - appointmentMapping.ResourceId = "ResourceID" - appointmentMapping.FindBySchedulerProperty("ResourceId").ConvertToDataSource = AddressOf ConvertResourceToDataSource - appointmentMapping.FindBySchedulerProperty("ResourceId").ConvertToScheduler = AddressOf ConvertResourceToScheduler - resourceMapping.Name = "ResourceName" - resourceMapping.Id = "ID" - Me.SchedulerBindingDataSource1.ResourceProvider.Mapping = resourceMapping - Me.SchedulerBindingDataSource1.ResourceProvider.DataSource = Me.SchedulerDataOneToManyDataSet.Resources - Me.SchedulerBindingDataSource1.EventProvider.Mapping = appointmentMapping - Me.SchedulerBindingDataSource1.EventProvider.DataSource = Me.SchedulerDataOneToManyDataSet.Appointments - Me.RadScheduler1.DataSource = Me.SchedulerBindingDataSource1 - Me.RadScheduler1.GroupType = GroupType.Resource -End Sub -Private Function ConvertResourceToScheduler(ByVal item As Object) As Object - Return New EventId(item) -End Function -Private Function ConvertResourceToDataSource(ByVal item As Object) As Object - Dim resourceId As EventId = TryCast(item, EventId) - If Not item Is Nothing AndAlso TypeOf resourceId.KeyValue Is Integer Then - Return resourceId.KeyValue - End If - Return DBNull.Value -End Function - -```` - -{{endregion}} + + + + >important A common case is that the resource_id field is stored as an integer field in your DataSource. But **RadScheduler** needs **EventId** type. You can have a look at the Appointment.**ResourceId** property which expects **EventId** value, not an integer. That is why it is necessary to use a **SchedulerMapping** in this case and convert the integer value to **EventId** used by **RadScheduler** and convert the **EventId** to an integer used by your **DataSource**. This conversion is performed by the **ConvertToDataSource** and **ConvertToScheduler** callbacks. Additional information for the **SchedulerMapping** is available [here]({%slug winforms/scheduler/data-binding/scheduler-mapping%}) diff --git a/controls/scheduler/data-binding/using-a-data-provider.md b/controls/scheduler/data-binding/using-a-data-provider.md index 61b7bd171..9f7d32803 100644 --- a/controls/scheduler/data-binding/using-a-data-provider.md +++ b/controls/scheduler/data-binding/using-a-data-provider.md @@ -21,321 +21,26 @@ This example shows how to bind __RadScheduler__ to a collection of custom object #### Custom Appointment Class -{{source=..\SamplesCS\Scheduler\DataBinding\MyAppointment.cs region=myAppointment}} -{{source=..\SamplesVB\Scheduler\DataBinding\MyAppointment.vb region=myAppointment}} + + -````C# -public class MyAppointment : INotifyPropertyChanged -{ - private DateTime start = DateTime.Now; - private DateTime end = DateTime.Now; - private string subject = string.Empty; - private string description = string.Empty; - private string location = string.Empty; - private Guid id = Guid.NewGuid(); - public MyAppointment() - { - } - public MyAppointment(DateTime start, DateTime end, string subject, string description, string location) - { - this.start = start; - this.end = end; - this.subject = subject; - this.description = description; - this.location = location; - } - public Guid Id - { - get - { - return this.id; - } - set - { - if (this.id != value) - { - this.id = value; - this.OnPropertyChanged("Id"); - } - } - } - public DateTime Start - { - get - { - return this.start; - } - set - { - if (this.start != value) - { - this.start = value; - this.OnPropertyChanged("Start"); - } - } - } - public DateTime End - { - get - { - return this.end; - } - set - { - if (this.end != value) - { - this.end = value; - this.OnPropertyChanged("End"); - } - } - } - public string Subject - { - get - { - return this.subject; - } - set - { - if (this.subject != value) - { - this.subject = value; - this.OnPropertyChanged("Subject"); - } - } - } - public string Description - { - get - { - return this.description; - } - set - { - if (this.description != value) - { - this.description = value; - this.OnPropertyChanged("Description"); - } - } - } - public string Location - { - get - { - return this.location; - } - set - { - if (this.location != value) - { - this.location = value; - this.OnPropertyChanged("Location"); - } - } - } - public event PropertyChangedEventHandler PropertyChanged; - protected virtual void OnPropertyChanged(string propertyName) - { - if (this.PropertyChanged != null) - { - this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); - } - } -} -```` -````VB.NET -Public Class MyAppointment - Implements INotifyPropertyChanged - Private _start As Date = Date.Now - Private _end As Date = Date.Now - Private _subject As String = String.Empty - Private _description As String = String.Empty - Private _location As String = String.Empty - Private _id As Guid = Guid.NewGuid() - Public Sub New() - End Sub - Public Sub New(ByVal start As Date, ByVal [end] As Date, ByVal subject As String, ByVal description As String, ByVal location As String) - Me._start = start - Me._end = [end] - Me._subject = subject - Me._description = description - Me._location = location - End Sub - Public Property Id() As Guid - Get - Return Me._id - End Get - Set(ByVal value As Guid) - If Me._id <> value Then - Me._id = value - Me.OnPropertyChanged("Id") - End If - End Set - End Property - Public Property Start() As Date - Get - Return Me._start - End Get - Set(ByVal value As Date) - If Me._start <> value Then - Me._start = value - Me.OnPropertyChanged("Start") - End If - End Set - End Property - Public Property [End]() As Date - Get - Return Me._end - End Get - Set(ByVal value As Date) - If Me._end <> value Then - Me._end = value - Me.OnPropertyChanged("End") - End If - End Set - End Property - Public Property Subject() As String - Get - Return Me._subject - End Get - Set(ByVal value As String) - If Me._subject <> value Then - Me._subject = value - Me.OnPropertyChanged("Subject") - End If - End Set - End Property - Public Property Description() As String - Get - Return Me._description - End Get - Set(ByVal value As String) - If Me._description <> value Then - Me._description = value - Me.OnPropertyChanged("Description") - End If - End Set - End Property - Public Property Location() As String - Get - Return Me._location - End Get - Set(ByVal value As String) - If Me._location <> value Then - Me._location = value - Me.OnPropertyChanged("Location") - End If - End Set - End Property - Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged - Protected Overridable Sub OnPropertyChanged(ByVal propertyName As String) - If Me.PropertyChangedEvent IsNot Nothing Then - RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName)) - End If - End Sub -End Class - -```` - -{{endregion}} We will use a list to store our appointment data. For the purpose of this example we will populate the appointments collection with some dummy data in the OnLoad override of our form: #### Create Appointments -{{source=..\SamplesCS\Scheduler\DataBinding\UsingDataProvider.cs region=creatingAppointment}} -{{source=..\SamplesVB\Scheduler\DataBinding\UsingDataProvider.vb region=creatingAppointment}} - -````C# -private List appointments = new List(); -protected override void OnLoad(EventArgs e) -{ - base.OnLoad(e); - DateTime baseDate = DateTime.Today; - DateTime[] start = new DateTime[] { baseDate.AddHours(14.0), baseDate.AddDays(1.0).AddHours(9.0), baseDate.AddDays(2.0).AddHours(13.0) }; - DateTime[] end = new DateTime[] { baseDate.AddHours(16.0), baseDate.AddDays(1.0).AddHours(15.0), baseDate.AddDays(2.0).AddHours(17.0) }; - string[] summaries = new string[] { "Mr. Brown", "Mr. White", "Mrs. Green" }; - string[] descriptions = new string[] { "", "", "" }; - string[] locations = new string[] { "City", "Out of town", "Service Center" }; - MyAppointment appointment = null; - for (int i = 0; i < summaries.Length; i++) - { - appointment = new MyAppointment(start[i], end[i], summaries[i], - descriptions[i], locations[i]); - this.appointments.Add(appointment); - } -} + + -```` -````VB.NET -Private appointments As New List(Of MyAppointment)() -Protected Overrides Sub OnLoad(ByVal e As EventArgs) - MyBase.OnLoad(e) - Dim baseDate As Date = Date.Today - Dim start() As Date = {baseDate.AddHours(14.0), baseDate.AddDays(1.0).AddHours(9.0), baseDate.AddDays(2.0).AddHours(13.0)} - Dim [end]() As Date = {baseDate.AddHours(16.0), baseDate.AddDays(1.0).AddHours(15.0), baseDate.AddDays(2.0).AddHours(17.0)} - Dim summaries() As String = {"Mr. Brown", "Mr. White", "Mrs. Green"} - Dim descriptions() As String = {"", "", ""} - Dim locations() As String = {"City", "Out of town", "Service Center"} - Dim appointment As MyAppointment = Nothing - For i As Integer = 0 To summaries.Length - 1 - appointment = New MyAppointment(start(i), [end](i), summaries(i), descriptions(i), locations(i)) - Me.appointments.Add(appointment) - Next i -End Sub -```` - -{{endregion}} And finally we will bind our RadScheduler instance to tha collection in the Click event handler of a button: -{{source=..\SamplesCS\Scheduler\DataBinding\UsingDataProvider.cs region=bindClick}} -{{source=..\SamplesVB\Scheduler\DataBinding\UsingDataProvider.vb region=bindClick}} - -````C# -private void btnBind_Click(object sender, EventArgs e) -{ - SchedulerBindingDataSource dataSource = new SchedulerBindingDataSource(); - AppointmentMappingInfo appointmentMappingInfo = new AppointmentMappingInfo(); - appointmentMappingInfo.Start = "Start"; - appointmentMappingInfo.End = "End"; - appointmentMappingInfo.Summary = "Subject"; - appointmentMappingInfo.Description = "Description"; - appointmentMappingInfo.Location = "Location"; - appointmentMappingInfo.UniqueId = "Id"; - SchedulerMapping idMapping = appointmentMappingInfo.FindByDataSourceProperty("Id"); - idMapping.ConvertToDataSource = new ConvertCallback(this.ConvertIdToDataSource); - idMapping.ConvertToScheduler = new ConvertCallback(this.ConvertIdToScheduler); - dataSource.EventProvider.Mapping = appointmentMappingInfo; - dataSource.EventProvider.DataSource = this.appointments; - this.radScheduler1.DataSource = dataSource; -} - -```` -````VB.NET -Private Sub btnBind_Click(ByVal sender As Object, ByVal e As EventArgs) - Dim dataSource As New SchedulerBindingDataSource() - Dim appointmentMappingInfo As New AppointmentMappingInfo() - appointmentMappingInfo.Start = "Start" - appointmentMappingInfo.End = "End" - appointmentMappingInfo.Summary = "Subject" - appointmentMappingInfo.Description = "Description" - appointmentMappingInfo.Location = "Location" - appointmentMappingInfo.UniqueId = "Id" - Dim idMapping As SchedulerMapping = appointmentMappingInfo.FindByDataSourceProperty("Id") - idMapping.ConvertToDataSource = New ConvertCallback(AddressOf Me.ConvertIdToDataSource) - idMapping.ConvertToScheduler = New ConvertCallback(AddressOf Me.ConvertIdToScheduler) - dataSource.EventProvider.Mapping = appointmentMappingInfo - dataSource.EventProvider.DataSource = Me.appointments - Me.RadScheduler1.DataSource = dataSource -End Sub + + -```` -{{endregion}} In the above code we create a __SchedulerBindingDataSource__ component. Then create a __AppointmentMappingInfo__ in order to “tell” the appointment provider how the properties of objects from the data source (in our case the appointments collection) corresponds to properties of the __IEvent__ interface. diff --git a/controls/scheduler/data-binding/using-datasource-property.md b/controls/scheduler/data-binding/using-datasource-property.md index 68bb57812..10f1274de 100644 --- a/controls/scheduler/data-binding/using-datasource-property.md +++ b/controls/scheduler/data-binding/using-datasource-property.md @@ -46,73 +46,19 @@ RadScheduler works from a provider model so that in the future, custom appointme #### Create Mapping -{{source=..\SamplesCS\Scheduler\DataBinding\UsingDataSourceProperty.cs region=creatingAppointment}} -{{source=..\SamplesVB\Scheduler\DataBinding\UsingDataSourceProperty.vb region=creatingAppointment}} - -````C# -AppointmentMappingInfo appointmentMappingInfo = new AppointmentMappingInfo(); -appointmentMappingInfo.Start = "Start"; -appointmentMappingInfo.End = "End"; -appointmentMappingInfo.Summary = "Summary"; -appointmentMappingInfo.Description = "Description"; -appointmentMappingInfo.Location = "Location"; -appointmentMappingInfo.BackgroundId = "BackgroundID"; -appointmentMappingInfo.StatusId = "StatusID"; -appointmentMappingInfo.RecurrenceRule = "RecurrenceRule"; -appointmentMappingInfo.Resources = "Appointments_AppointmentsResources"; -appointmentMappingInfo.ResourceId = "ResourceID"; -appointmentMappingInfo.Exceptions = "Appointments_Appointments"; -appointmentMappingInfo.MasterEventId = "ParentID"; -schedulerBindingDataSource1.EventProvider.Mapping = appointmentMappingInfo; - -```` -````VB.NET -Dim appointmentMappingInfo As New AppointmentMappingInfo() -appointmentMappingInfo.Start = "Start" -appointmentMappingInfo.End = "End" -appointmentMappingInfo.Summary = "Summary" -appointmentMappingInfo.Description = "Description" -appointmentMappingInfo.Location = "Location" -appointmentMappingInfo.BackgroundId = "BackgroundID" -appointmentMappingInfo.StatusId = "StatusID" -appointmentMappingInfo.RecurrenceRule = "RecurrenceRule" -appointmentMappingInfo.Resources = "Appointments_AppointmentsResources" -appointmentMappingInfo.ResourceId = "ResourceID" -appointmentMappingInfo.Exceptions = "Appointments_Appointments" -appointmentMappingInfo.MasterEventId = "ParentID" -SchedulerBindingDataSource1.EventProvider.Mapping = appointmentMappingInfo - -```` - -{{endregion}} + + + + The resource mapping has fewer columns and doesn't need any information about joining to the appointments table. #### Set Mapping -{{source=..\SamplesCS\Scheduler\DataBinding\UsingDataSourceProperty.cs region=creatingResource}} -{{source=..\SamplesVB\Scheduler\DataBinding\UsingDataSourceProperty.vb region=creatingResource}} - -````C# -ResourceMappingInfo resourceMappingInfo = new ResourceMappingInfo(); -resourceMappingInfo.Id = "ID"; -resourceMappingInfo.Name = "ResourceName"; -schedulerBindingDataSource1.ResourceProvider.Mapping = resourceMappingInfo; -schedulerBindingDataSource1.EventProvider.DataSource = this.schedulerDataDataSet.Appointments; -schedulerBindingDataSource1.ResourceProvider.DataSource = this.schedulerDataDataSet.Resources; - -```` -````VB.NET -Dim resourceMappingInfo As New ResourceMappingInfo() -resourceMappingInfo.Id = "ID" -resourceMappingInfo.Name = "ResourceName" -SchedulerBindingDataSource1.ResourceProvider.Mapping = resourceMappingInfo -SchedulerBindingDataSource1.EventProvider.DataSource = Me.schedulerDataDataSet.Appointments -SchedulerBindingDataSource1.ResourceProvider.DataSource = Me.schedulerDataDataSet.Resources - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/scheduler/data-binding/working-with-resources.md b/controls/scheduler/data-binding/working-with-resources.md index 75aa725de..4f6324f9c 100644 --- a/controls/scheduler/data-binding/working-with-resources.md +++ b/controls/scheduler/data-binding/working-with-resources.md @@ -32,34 +32,10 @@ To add resources to RadScheduler's Resource drop down (visible in the appointmen #### Adding Resources -{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\WorkingWithResources.cs region=loadResources}} -{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\WorkingWithResources.vb region=loadResources}} - -````C# -private void LoadResources() -{ - string[] descriptions = { "Conference Room 112", "Conference Room 113", "Meeting Hall A2" }; - int count = 1; - foreach (string description in descriptions) - { - this.radScheduler1.Resources.Add(new Resource(count++, description)); - } -} - -```` -````VB.NET -Private Sub LoadResources() - Dim descriptions() As String = {"Conference Room 112", "Conference Room 113", "Meeting Hall A2"} - Dim count As Integer = 1 - For Each description As String In descriptions - Me.RadScheduler1.Resources.Add(New Telerik.WinControls.UI.Resource(count, description)) - count += 1 - Next description -End Sub - -```` - -{{endregion}} + + + + >caption Figure 1: Added Resources diff --git a/controls/scheduler/dialogs/deleterecurringappointmentdialog.md b/controls/scheduler/dialogs/deleterecurringappointmentdialog.md index c51ff9184..1d79dd752 100644 --- a/controls/scheduler/dialogs/deleterecurringappointmentdialog.md +++ b/controls/scheduler/dialogs/deleterecurringappointmentdialog.md @@ -39,117 +39,15 @@ In the following example, we will create a derivative of the **DeleteRecurringAp ![WinForms RadScheduler Custom DeleteRecurringAppointmentDialog](images/scheduler-winforms-scheduler-dialogs-deleterecurringappointmentdialog003.png) -{{source=..\SamplesCS\Scheduler\Dialogs\CustomDeleteRecurringAppointmentDialog.cs region=MyDeleteRecurringAppointmentDialog}} -{{source=..\SamplesVB\Scheduler\Dialogs\CustomDeleteRecurringAppointmentDialog.vb region=MyDeleteRecurringAppointmentDialog}} - -````C# -public partial class CustomDeleteRecurringAppointmentDialog : DeleteRecurringAppointmentDialog -{ - Telerik.WinControls.UI.Localization.RadSchedulerLocalizationProvider localizationProvider; - RadDropDownList deleteSelection; - public CustomDeleteRecurringAppointmentDialog() - { - InitializeComponent(); - this.Text = localizationProvider.GetLocalizedString(Telerik.WinControls.UI.Localization.RadSchedulerStringId.DeleteRecurrenceDialogTitle); - } - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - this.radioDeleteOccurrence.Visible = false; - this.radioDeleteSeries.Visible = false; - if (deleteSelection == null) - { - deleteSelection = new RadDropDownList(); - deleteSelection.Width = 150; - this.Controls.Add(deleteSelection); - deleteSelection.Items.Add(this.radioDeleteOccurrence.Text); - deleteSelection.Items.Add(this.radioDeleteSeries.Text); - deleteSelection.SelectedIndex = 0; - deleteSelection.Location = this.radioDeleteOccurrence.Location; - } - } - public override bool DeleteSeries - { - get - { - return this.deleteSelection.SelectedIndex == 1; - } - } - protected override void LocalizeDialog(Telerik.WinControls.UI.Localization.RadSchedulerLocalizationProvider localizationProvider) - { - base.LocalizeDialog(localizationProvider); - this.localizationProvider = localizationProvider; - } -} - -```` -````VB.NET -Partial Public Class CustomDeleteRecurringAppointmentDialog - Inherits DeleteRecurringAppointmentDialog - Private localizationProvider As Telerik.WinControls.UI.Localization.RadSchedulerLocalizationProvider - Private deleteSelection As RadDropDownList - Public Sub New() - InitializeComponent() - Me.Text = localizationProvider.GetLocalizedString(Telerik.WinControls.UI.Localization.RadSchedulerStringId.DeleteRecurrenceDialogTitle) - End Sub - Protected Overrides Sub OnLoad(ByVal e As EventArgs) - MyBase.OnLoad(e) - Me.radioDeleteOccurrence.Visible = False - Me.radioDeleteSeries.Visible = False - If deleteSelection Is Nothing Then - deleteSelection = New RadDropDownList() - deleteSelection.Width = 150 - Me.Controls.Add(deleteSelection) - deleteSelection.Items.Add(Me.radioDeleteOccurrence.Text) - deleteSelection.Items.Add(Me.radioDeleteSeries.Text) - deleteSelection.SelectedIndex = 0 - deleteSelection.Location = Me.radioDeleteOccurrence.Location - End If - End Sub - Public Overrides ReadOnly Property DeleteSeries As Boolean - Get - Return Me.deleteSelection.SelectedIndex = 1 - End Get - End Property - Protected Overrides Sub LocalizeDialog(ByVal localizationProvider As Telerik.WinControls.UI.Localization.RadSchedulerLocalizationProvider) - MyBase.LocalizeDialog(localizationProvider) - Me.localizationProvider = localizationProvider - End Sub -End Class - -```` - -{{endregion}} + + + + Now, you can replace the default **DeleteRecurringAppointmentDialog** with the custom one by using the RadScheduler.**RecurrenceDeleteDialogShowing** event: -{{source=..\SamplesCS\Scheduler\Dialogs\SchedulerCustomDialogs.cs region=ReplaceDefaultDeleteRecurringAppointmentDialog}} -{{source=..\SamplesVB\Scheduler\Dialogs\SchedulerCustomDialogs.vb region=ReplaceDefaultDeleteRecurringAppointmentDialog}} - -````C# -CustomDeleteRecurringAppointmentDialog myDialog; - -private void radScheduler1_RecurrenceDeleteDialogShowing(object sender, RecurrenceDeleteDialogShowingEventArgs e) -{ - if (myDialog == null) - { - myDialog = new CustomDeleteRecurringAppointmentDialog(); - } - myDialog.EventName = e.Appointment.Summary; - e.DeleteDialog = myDialog; -} - -```` -````VB.NET -Private myDialog As CustomDeleteRecurringAppointmentDialog -Private Sub RadScheduler1_RecurrenceDeleteDialogShowing(sender As Object, e As Telerik.WinControls.UI.RecurrenceDeleteDialogShowingEventArgs) - If myDialog Is Nothing Then - myDialog = New CustomDeleteRecurringAppointmentDialog() - End If - myDialog.EventName = e.Appointment.Summary - e.DeleteDialog = myDialog -End Sub - -```` - -{{endregion}} + + + + + diff --git a/controls/scheduler/dialogs/editappointmentdialog.md b/controls/scheduler/dialogs/editappointmentdialog.md index f4b649a99..77068e322 100644 --- a/controls/scheduler/dialogs/editappointmentdialog.md +++ b/controls/scheduler/dialogs/editappointmentdialog.md @@ -41,333 +41,18 @@ As a derivative of **RadSchedulerDialog** which inherits **RadForm**, the **Show ![WinForms RadScheduler Custom edit dialog](images/scheduler-winforms-scheduler-dialogs-editappointmentdialog002.png) -{{source=..\SamplesCS\Scheduler\Dialogs\CustomEditForm.cs region=CustomEditDialog}} -{{source=..\SamplesVB\Scheduler\Dialogs\CustomEditForm.vb region=CustomEditDialog}} - -````C# - -public partial class CustomEditForm : RadSchedulerDialog, IEditAppointmentDialog -{ - public CustomEditForm() - { - InitializeComponent(); - } - - bool editOccurrence = false; - IOpenRecurringAppointmentDialog openRecurringAppointmentDialog = null; - IEvent appointment; - ISchedulerData schedulerData; - IEvent recurringAppointment; - bool saveRecurringAppointment = false; - - public bool EditAppointment(Telerik.WinControls.UI.IEvent appointment, Telerik.WinControls.UI.ISchedulerData schedulerData) - { - this.editOccurrence = false; - this.schedulerData = schedulerData; - this.appointment = appointment; - - if (appointment != null && appointment.MasterEvent != null) - { - if (this.openRecurringAppointmentDialog == null) - { - this.openRecurringAppointmentDialog = new OpenRecurringAppointmentDialog(); - } - this.openRecurringAppointmentDialog.ThemeName = this.ThemeName; - this.openRecurringAppointmentDialog.EventName = appointment.Summary; - - DialogResult result = this.openRecurringAppointmentDialog.ShowDialog(); - if (result != DialogResult.OK) - { - return false; - } - - this.editOccurrence = this.openRecurringAppointmentDialog.EditOccurrence; - if (!this.editOccurrence) - { - //if you edit the entire series, modify the master event, not the occurence - this.appointment = appointment.MasterEvent; - } - } - - return true; - } - - private bool RecurrenceSettingsShouldBeSaved() - { - return this.saveRecurringAppointment && this.recurringAppointment != null; - } - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - //load the data to the respective controls - this.saveRecurringAppointment = false; - this.recurrenceButton.Enabled = this.appointment.MasterEvent == null; - this.dateStart.Value = appointment.Start; - this.dateEnd.Value = appointment.End; - this.timeStart.Value = appointment.Start; - this.timeEnd.Value = appointment.End; - this.summaryTextBox.Text = this.appointment.Summary; - } - - public void ShowRecurrenceDialog() - { - RadScheduler scheduler = this.schedulerData as RadScheduler; - if (this.recurringAppointment == null) - { - this.recurringAppointment = scheduler != null ? scheduler.AppointmentFactory.CreateNewAppointment() : new Appointment(); - } - - DateTime targetEventStart = this.GetAppointmentStart(); - DateTime targetEventEnd = this.GetAppointmentEnd(); - - if (scheduler != null) - { - targetEventStart = scheduler.SystemTimeZone.OffsetTime(targetEventStart, scheduler.ActiveView.DefaultTimeZone); - targetEventEnd = scheduler.SystemTimeZone.OffsetTime(targetEventEnd, scheduler.ActiveView.DefaultTimeZone); - } - - this.recurringAppointment.Start = targetEventStart; - this.recurringAppointment.End = targetEventEnd; - this.recurringAppointment.AllDay = this.appointment.AllDay; - - if (!this.RecurrenceSettingsShouldBeSaved() && this.appointment.RecurrenceRule != null) - { - this.recurringAppointment.RecurrenceRule = this.appointment.RecurrenceRule.Clone(); - } - IEditRecurrenceDialog editRecurrenceDialog = new EditRecurrenceDialog(recurringAppointment, this.schedulerData); - DialogResult result = editRecurrenceDialog.ShowDialog(); - if (result == DialogResult.OK) - { - this.saveRecurringAppointment = true; - DateTime recurringAppointmentStart = this.recurringAppointment.Start; - DateTime recurringAppointmentEnd = this.recurringAppointment.End; - if (scheduler != null) - { - recurringAppointmentStart = scheduler.ActiveView.DefaultTimeZone.OffsetTime(recurringAppointmentStart, scheduler.SystemTimeZone); - recurringAppointmentEnd = scheduler.ActiveView.DefaultTimeZone.OffsetTime(recurringAppointmentEnd, scheduler.SystemTimeZone); - } - } - } - - private DateTime GetAppointmentStart() - { - DateTime startDate = this.dateStart.Value.Date; - - if (!(this.appointment.AllDay)) - { - TimeSpan startTime = this.timeStart.Value.Value.TimeOfDay; - startDate = startDate.Add(startTime); - } - - return startDate; - } - - private DateTime GetAppointmentEnd() - { - DateTime endDate = this.dateEnd.Value.Date; - TimeSpan endTime = !this.appointment.AllDay ? this.timeEnd.Value.Value.TimeOfDay : TimeSpan.Zero; - endDate = endDate.Add(endTime); - return endDate; - } - - private void recurrenceButton_Click(object sender, EventArgs e) - { - this.ShowRecurrenceDialog(); - } - - private void okButton_Click(object sender, EventArgs e) - { - if (this.RecurrenceSettingsShouldBeSaved()) - { - this.appointment.RecurrenceRule = this.recurringAppointment.RecurrenceRule; - if (this.appointment.RecurrenceRule == null) - { - this.appointment.Exceptions.Clear(); - } - } - - if (this.editOccurrence) - { - if (this.appointment.MasterEvent != null) - { - this.appointment.MasterEvent.AddOccurrenceException(appointment, true); - } - } - - this.appointment.Summary = this.summaryTextBox.Text; - this.appointment.Start = GetAppointmentStart(); - this.appointment.End = GetAppointmentEnd(); - this.DialogResult = DialogResult.OK; - this.Close(); - } - - private void cancelButton_Click(object sender, EventArgs e) - { - this.DialogResult = DialogResult.Cancel; - this.Close(); - } -} + + -```` -````VB.NET -Public Class CustomEditForm - Inherits RadSchedulerDialog - Implements IEditAppointmentDialog - Sub New() - InitializeComponent() - End Sub - Private editOccurrence As Boolean = False - Private openRecurringAppointmentDialog As IOpenRecurringAppointmentDialog = Nothing - Private appointment As IEvent - Private schedulerData As ISchedulerData - Private recurringAppointment As IEvent - Public Event Shown As EventHandler Implements IEditAppointmentDialog.Shown - Private saveRecurringAppointment As Boolean = False - Public Function EditAppointment(appointment As Telerik.WinControls.UI.IEvent, schedulerData As Telerik.WinControls.UI.ISchedulerData) As Boolean _ - Implements IEditAppointmentDialog.EditAppointment - Me.editOccurrence = False - Me.schedulerData = schedulerData - Me.appointment = appointment - If appointment IsNot Nothing AndAlso appointment.MasterEvent IsNot Nothing Then - If Me.openRecurringAppointmentDialog Is Nothing Then - Me.openRecurringAppointmentDialog = New OpenRecurringAppointmentDialog() - End If - Me.openRecurringAppointmentDialog.ThemeName = Me.ThemeName - Me.openRecurringAppointmentDialog.EventName = appointment.Summary - Dim result As DialogResult = Me.openRecurringAppointmentDialog.ShowDialog() - If result <> DialogResult.OK Then - Return False - End If - Me.editOccurrence = Me.openRecurringAppointmentDialog.EditOccurrence - If Not Me.editOccurrence Then - 'if you edit the entire series, modify the master event, not the occurence - Me.appointment = appointment.MasterEvent - End If - End If - Return True - End Function - Private Function RecurrenceSettingsShouldBeSaved() As Boolean - Return Me.saveRecurringAppointment AndAlso Me.recurringAppointment IsNot Nothing - End Function - Protected Overrides Sub OnLoad(e As EventArgs) - MyBase.OnLoad(e) - 'load the data to the respective controls - Me.saveRecurringAppointment = False - Me.recurrenceButton.Enabled = Me.appointment.MasterEvent Is Nothing - Me.dateStart.Value = appointment.Start - Me.dateEnd.Value = appointment.[End] - Me.timeStart.Value = appointment.Start - Me.timeEnd.Value = appointment.[End] - Me.summaryTextBox.Text = Me.appointment.Summary - End Sub - Public Sub ShowRecurrenceDialog() Implements IEditAppointmentDialog.ShowRecurrenceDialog - Dim scheduler As RadScheduler = TryCast(Me.schedulerData, RadScheduler) - If Me.recurringAppointment Is Nothing Then - Me.recurringAppointment = If(scheduler IsNot Nothing, scheduler.AppointmentFactory.CreateNewAppointment(), New Appointment()) - End If - Dim targetEventStart As DateTime = Me.GetAppointmentStart() - Dim targetEventEnd As DateTime = Me.GetAppointmentEnd() - If scheduler IsNot Nothing Then - targetEventStart = scheduler.SystemTimeZone.OffsetTime(targetEventStart, scheduler.ActiveView.DefaultTimeZone) - targetEventEnd = scheduler.SystemTimeZone.OffsetTime(targetEventEnd, scheduler.ActiveView.DefaultTimeZone) - End If - Me.recurringAppointment.Start = targetEventStart - Me.recurringAppointment.[End] = targetEventEnd - Me.recurringAppointment.AllDay = Me.appointment.AllDay - If Not Me.RecurrenceSettingsShouldBeSaved() AndAlso Me.appointment.RecurrenceRule IsNot Nothing Then - Me.recurringAppointment.RecurrenceRule = Me.appointment.RecurrenceRule.Clone() - End If - Dim editRecurrenceDialog As IEditRecurrenceDialog = New EditRecurrenceDialog(recurringAppointment, Me.schedulerData) - Dim result As DialogResult = editRecurrenceDialog.ShowDialog() - If result = DialogResult.OK Then - Me.saveRecurringAppointment = True - Dim recurringAppointmentStart As DateTime = Me.recurringAppointment.Start - Dim recurringAppointmentEnd As DateTime = Me.recurringAppointment.[End] - If scheduler IsNot Nothing Then - recurringAppointmentStart = scheduler.ActiveView.DefaultTimeZone.OffsetTime(recurringAppointmentStart, scheduler.SystemTimeZone) - recurringAppointmentEnd = scheduler.ActiveView.DefaultTimeZone.OffsetTime(recurringAppointmentEnd, scheduler.SystemTimeZone) - End If - End If - End Sub - Public Function ShowDialog() As DialogResult Implements IEditAppointmentDialog.ShowDialog - Return MyBase.ShowDialog() - End Function - Private Function GetAppointmentStart() As DateTime - Dim startDate As DateTime = Me.dateStart.Value.[Date] - If Not (Me.appointment.AllDay) Then - Dim startTime As TimeSpan = Me.timeStart.Value.Value.TimeOfDay - startDate = startDate.Add(startTime) - End If - Return startDate - End Function - Private Function GetAppointmentEnd() As DateTime - Dim endDate As DateTime = Me.dateEnd.Value.[Date] - Dim endTime As TimeSpan = If(Not Me.appointment.AllDay, Me.timeEnd.Value.Value.TimeOfDay, TimeSpan.Zero) - endDate = endDate.Add(endTime) - Return endDate - End Function - Private Sub recurrenceButton_Click(sender As Object, e As EventArgs) - Me.ShowRecurrenceDialog() - End Sub - Private Sub okButton_Click(sender As Object, e As EventArgs) - If Me.RecurrenceSettingsShouldBeSaved() Then - Me.appointment.RecurrenceRule = Me.recurringAppointment.RecurrenceRule - If Me.appointment.RecurrenceRule Is Nothing Then - Me.appointment.Exceptions.Clear() - End If - End If - If Me.editOccurrence Then - If Me.appointment.MasterEvent IsNot Nothing Then - Me.appointment.MasterEvent.AddOccurrenceException(appointment, True) - End If - End If - Me.appointment.Summary = Me.summaryTextBox.Text - Me.appointment.Start = GetAppointmentStart() - Me.appointment.[End] = GetAppointmentEnd() - Me.DialogResult = DialogResult.OK - Me.Close() - End Sub - Private Sub cancelButton_Click(sender As Object, e As EventArgs) - Me.DialogResult = DialogResult.Cancel - Me.Close() - End Sub -```` - -{{endregion}} Now, you can replace the default edit dialog with the custom one by using the RadScheduler.**AppointmentEditDialogShowing** event: -{{source=..\SamplesCS\Scheduler\Dialogs\SchedulerCustomDialogs.cs region=ReplaceDefaultDialog}} -{{source=..\SamplesVB\Scheduler\Dialogs\SchedulerCustomDialogs.vb region=ReplaceDefaultDialog}} - -````C# -CustomEditForm editDialog = null; - -private void radScheduler1_AppointmentEditDialogShowing(object sender, AppointmentEditDialogShowingEventArgs e) -{ - if (editDialog == null) - { - editDialog = new CustomEditForm(); - } - e.AppointmentEditDialog = editDialog; -} + + -```` -````VB.NET -Private editDialog As CustomEditForm = Nothing -Private Sub radScheduler1_AppointmentEditDialogShowing(sender As Object, e As Telerik.WinControls.UI.AppointmentEditDialogShowingEventArgs) - If editDialog Is Nothing Then - editDialog = New CustomEditForm() - End If - e.AppointmentEditDialog = editDialog -End Sub -```` -{{endregion}} - # See Also * [Adding a Custom Field to the EditAppointment Dialog]({%slug winforms/scheduler/appointments-and-dialogs/adding-a-custom-field-to-the-editappointment-dialog%}) diff --git a/controls/scheduler/dialogs/editrecurrencedialog.md b/controls/scheduler/dialogs/editrecurrencedialog.md index 49885353f..47d587fea 100644 --- a/controls/scheduler/dialogs/editrecurrencedialog.md +++ b/controls/scheduler/dialogs/editrecurrencedialog.md @@ -30,233 +30,15 @@ In the following example, we will create a completely new dialog which will repl 3\. Manage the recurrence rule of the appointment by the added controls on the form: -{{source=..\SamplesCS\Scheduler\Dialogs\MyEditRecurrenceDialog.cs region=CustomEditRecurrenceDialog}} -{{source=..\SamplesVB\Scheduler\Dialogs\MyEditRecurrenceDialog.vb region=CustomEditRecurrenceDialog}} - -````C# -public partial class MyEditRecurrenceDialog : RadSchedulerDialog, IEditRecurrenceDialog -{ - private IEvent Appointment; - RecurrenceRule recurrenceRule = null; - public MyEditRecurrenceDialog() - { - InitializeComponent(); - this.radButton1.Click += radButton1_Click; - this.radButton2.Click += radButton2_Click; - this.radButton3.Click += radButton3_Click; - } - public MyEditRecurrenceDialog(IEvent targetEvent) - : this() - { - this.Appointment = targetEvent; - this.radDropDownList1.DropDownStyle = RadDropDownStyle.DropDownList; - this.radDropDownList1.Items.Add(new RadListDataItem() - { - Text = "Hourly", - Value = new HourlyRecurrenceRule(this.Appointment.Start, 1) - }); - this.radDropDownList1.Items.Add(new RadListDataItem() - { - Text = "Daily", - Value = new DailyRecurrenceRule(this.Appointment.Start, 1, 5) - }); - this.radDropDownList1.SelectedIndexChanged += radDropDownList1_SelectedIndexChanged; - this.radDropDownList1.SelectedIndex = 0; - this.radSpinEditor1.ValueChanged += radSpinEditor1_ValueChanged; - this.radSpinEditor2.ValueChanged += radSpinEditor2_ValueChanged; - this.radSpinEditor1.Maximum = this.radSpinEditor2.Maximum = int.MaxValue; - this.LoadSettingsFromEvent(this.Appointment); - } - private void radButton3_Click(object sender, EventArgs e) - { - if (this.Appointment.RecurrenceRule != null) - { - this.Appointment.RecurrenceRule = null; - } - else if (this.Appointment.MasterEvent != null) - { - this.Appointment.MasterEvent.RecurrenceRule = null; - } - this.DialogResult = DialogResult.OK; - this.Close(); - } - private void radButton2_Click(object sender, EventArgs e) - { - this.DialogResult = DialogResult.Cancel; - this.Close(); - } - private void radSpinEditor2_ValueChanged(object sender, EventArgs e) - { - this.recurrenceRule.Count = (int)this.radSpinEditor2.Value; - } - private void radSpinEditor1_ValueChanged(object sender, EventArgs e) - { - this.recurrenceRule.Interval = (int)this.radSpinEditor1.Value; - } - private void radDropDownList1_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e) - { - this.recurrenceRule = this.radDropDownList1.SelectedItem.Value as RecurrenceRule; - } - private void LoadSettingsFromEvent(IEvent targetEvent) - { - if (targetEvent.RecurrenceRule != null) - { - this.recurrenceRule = targetEvent.RecurrenceRule; - HourlyRecurrenceRule hourlyRecurrenceRule = targetEvent as HourlyRecurrenceRule; - DailyRecurrenceRule dailyRecurrenceRule = targetEvent as DailyRecurrenceRule; - if (hourlyRecurrenceRule != null) - { - this.radDropDownList1.SelectedIndex = 0; - } - else if (dailyRecurrenceRule != null) - { - this.radDropDownList1.SelectedIndex = 1; - } - this.radSpinEditor1.Value = targetEvent.RecurrenceRule.Interval; - this.radSpinEditor2.Value = targetEvent.RecurrenceRule.Count; - } - } - private void radButton1_Click(object sender, EventArgs e) - { - this.ApplySettingsToEvent(this.Appointment); - this.DialogResult = DialogResult.OK; - this.Close(); - } - protected override void LocalizeDialog(Telerik.WinControls.UI.Localization.RadSchedulerLocalizationProvider localizationProvider) - { - base.LocalizeDialog(localizationProvider); - this.Text = localizationProvider.GetLocalizedString(Telerik.WinControls.UI.Localization.RadSchedulerStringId.RecurrenceDialogTitle); - this.radButton1.Text = localizationProvider.GetLocalizedString(Telerik.WinControls.UI.Localization.RadSchedulerStringId.RecurrenceDialogOK); - this.radButton2.Text = localizationProvider.GetLocalizedString(Telerik.WinControls.UI.Localization.RadSchedulerStringId.RecurrenceDialogCancel); - this.radButton3.Text = localizationProvider.GetLocalizedString(Telerik.WinControls.UI.Localization.RadSchedulerStringId.RecurrenceDialogRemoveRecurrence); - this.radLabel1.Text = "Interval:"; - this.radLabel2.Text = "Count:"; - } - public void ApplySettingsToEvent(IEvent targetEvent) - { - this.recurrenceRule.Interval = (int)this.radSpinEditor1.Value; - this.recurrenceRule.Count = (int)this.radSpinEditor2.Value; - this.Appointment.RecurrenceRule = this.recurrenceRule; - } -} + + -```` -````VB.NET -Public Class MyEditRecurrenceDialog -Inherits RadSchedulerDialog -Implements IEditRecurrenceDialog - Private Appointment As IEvent - Private recurrenceRule As RecurrenceRule = Nothing - Public Sub New() - InitializeComponent() - AddHandler Me.radButton1.Click, AddressOf radButton1_Click - AddHandler Me.radButton2.Click, AddressOf radButton2_Click - AddHandler Me.radButton3.Click, AddressOf radButton3_Click - End Sub - Public Property ThemeName() As String Implements IEditRecurrenceDialog.ThemeName - Get - Return MyBase.ThemeName - End Get - Set(value As String) - MyBase.ThemeName = Value - End Set - End Property - Public Function ShowDialog() As DialogResult Implements IEditRecurrenceDialog.ShowDialog - Return MyBase.ShowDialog() - End Function - Public Sub New(ByVal targetEvent As IEvent) - Me.New() - Me.Appointment = targetEvent - Me.radDropDownList1.DropDownStyle = RadDropDownStyle.DropDownList - Me.radDropDownList1.Items.Add(New RadListDataItem() With {.Text = "Hourly", .Value = New HourlyRecurrenceRule(Me.Appointment.Start, 1)}) - Me.radDropDownList1.Items.Add(New RadListDataItem() With {.Text = "Daily", .Value = New DailyRecurrenceRule(Me.Appointment.Start, 1, 5)}) - AddHandler Me.radDropDownList1.SelectedIndexChanged, AddressOf radDropDownList1_SelectedIndexChanged - Me.radDropDownList1.SelectedIndex = 0 - AddHandler Me.radSpinEditor1.ValueChanged, AddressOf radSpinEditor1_ValueChanged - AddHandler Me.radSpinEditor2.ValueChanged, AddressOf radSpinEditor2_ValueChanged - Me.radSpinEditor1.Maximum = Integer.MaxValue - Me.radSpinEditor2.Maximum = Integer.MaxValue - Me.LoadSettingsFromEvent(Me.Appointment) - End Sub - Private Sub radButton3_Click(ByVal sender As Object, ByVal e As EventArgs) - If Me.Appointment.RecurrenceRule IsNot Nothing Then - Me.Appointment.RecurrenceRule = Nothing - ElseIf Me.Appointment.MasterEvent IsNot Nothing Then - Me.Appointment.MasterEvent.RecurrenceRule = Nothing - End If - Me.DialogResult = Windows.Forms.DialogResult.OK - Me.Close() - End Sub - Private Sub radButton2_Click(ByVal sender As Object, ByVal e As EventArgs) - Me.DialogResult = Windows.Forms.DialogResult.Cancel - Me.Close() - End Sub - Private Sub radSpinEditor2_ValueChanged(ByVal sender As Object, ByVal e As EventArgs) - Me.recurrenceRule.Count = CInt(Me.radSpinEditor2.Value) - End Sub - Private Sub radSpinEditor1_ValueChanged(ByVal sender As Object, ByVal e As EventArgs) - Me.recurrenceRule.Interval = CInt(Me.radSpinEditor1.Value) - End Sub - Private Sub radDropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.Data.PositionChangedEventArgs) - Me.recurrenceRule = TryCast(Me.radDropDownList1.SelectedItem.Value, RecurrenceRule) - End Sub - Private Sub LoadSettingsFromEvent(ByVal targetEvent As IEvent) - If targetEvent.RecurrenceRule IsNot Nothing Then - Me.recurrenceRule = targetEvent.RecurrenceRule - Dim hourlyRecurrenceRule As HourlyRecurrenceRule = TryCast(targetEvent, HourlyRecurrenceRule) - Dim dailyRecurrenceRule As DailyRecurrenceRule = TryCast(targetEvent, DailyRecurrenceRule) - If hourlyRecurrenceRule IsNot Nothing Then - Me.radDropDownList1.SelectedIndex = 0 - ElseIf dailyRecurrenceRule IsNot Nothing Then - Me.radDropDownList1.SelectedIndex = 1 - End If - Me.radSpinEditor1.Value = targetEvent.RecurrenceRule.Interval - Me.radSpinEditor2.Value = targetEvent.RecurrenceRule.Count - End If - End Sub - Private Sub radButton1_Click(ByVal sender As Object, ByVal e As EventArgs) - Me.ApplySettingsToEvent(Me.Appointment) - Me.DialogResult = Windows.Forms.DialogResult.OK - Me.Close() - End Sub - Protected Overrides Sub LocalizeDialog(ByVal localizationProvider As Telerik.WinControls.UI.Localization.RadSchedulerLocalizationProvider) - MyBase.LocalizeDialog(localizationProvider) - Me.Text = localizationProvider.GetLocalizedString(Telerik.WinControls.UI.Localization.RadSchedulerStringId.RecurrenceDialogTitle) - Me.radButton1.Text = localizationProvider.GetLocalizedString(Telerik.WinControls.UI.Localization.RadSchedulerStringId.RecurrenceDialogOK) - Me.radButton2.Text = localizationProvider.GetLocalizedString(Telerik.WinControls.UI.Localization.RadSchedulerStringId.RecurrenceDialogCancel) - Me.radButton3.Text = localizationProvider.GetLocalizedString(Telerik.WinControls.UI.Localization.RadSchedulerStringId.RecurrenceDialogRemoveRecurrence) - Me.radLabel1.Text = "Interval:" - Me.radLabel2.Text = "Count:" - End Sub - Public Sub ApplySettingsToEvent(ByVal targetEvent As IEvent) - Me.recurrenceRule.Interval = CInt(Me.radSpinEditor1.Value) - Me.recurrenceRule.Count = CInt(Me.radSpinEditor2.Value) - Me.Appointment.RecurrenceRule = Me.recurrenceRule - End Sub -End Class -```` - -{{endregion}} 4\. Now, you can replace the default **EditRecurrenceDialog** with the custom one by using the RadScheduler.**RecurrenceEditDialogShowing** event: -{{source=..\SamplesCS\Scheduler\Dialogs\SchedulerCustomDialogs.cs region=ReplaceDefaultRecurrenceEditDialog}} -{{source=..\SamplesVB\Scheduler\Dialogs\SchedulerCustomDialogs.vb region=ReplaceDefaultRecurrenceEditDialog}} - -````C# - -private void radScheduler1_RecurrenceEditDialogShowing(object sender, RecurrenceEditDialogShowingEventArgs e) -{ - e.RecurrenceEditDialog = new MyEditRecurrenceDialog(e.Appointment); -} + + -```` -````VB.NET -Private Sub radScheduler1_RecurrenceEditDialogShowing(ByVal sender As Object, ByVal e As RecurrenceEditDialogShowingEventArgs) - e.RecurrenceEditDialog = New MyEditRecurrenceDialog(e.Appointment) -End Sub -```` -{{endregion}} diff --git a/controls/scheduler/drag-and-drop/combining-raddragdropservice-and-ole-drag-and-drop.md b/controls/scheduler/drag-and-drop/combining-raddragdropservice-and-ole-drag-and-drop.md index c62c93891..03bdde9e5 100644 --- a/controls/scheduler/drag-and-drop/combining-raddragdropservice-and-ole-drag-and-drop.md +++ b/controls/scheduler/drag-and-drop/combining-raddragdropservice-and-ole-drag-and-drop.md @@ -21,162 +21,10 @@ To implement drag and drop functionality for this scenario, we will use the Sche #### Behavior PreviewDragOver -{{source=..\SamplesCS\Scheduler\DragDrop\SchedulerToListControl.cs region=RadSchedulerToRadListControl}} -{{source=..\SamplesVB\Scheduler\DragDrop\SchedulerToListControl.vb region=RadSchedulerToRadListControl}} + + -````C# - -private void DragDropBehavior_PreviewDragOver(object sender, Telerik.WinControls.RadDragOverEventArgs e) -{ - e.CanDrop = e.HitTarget is RadListElement; -} - -private void DragDropBehavior_PreviewDragDrop(object sender, Telerik.WinControls.RadDropEventArgs e) -{ - DragFeedbackElement draggedInstance = e.DragInstance as DragFeedbackElement; - if (draggedInstance == null) - { - return; - } - RadListElement listElement = e.HitTarget as RadListElement; - if (listElement == null) - { - return; - } - e.Handled = true; - RadListControl listControl = listElement.ElementTree.Control as RadListControl; - RadListVisualItem targetItem = listControl.ElementTree.GetElementAtPoint(e.DropLocation) as RadListVisualItem; - int indexToInsert; - if (targetItem != null) - { - indexToInsert = targetItem.Data.RowIndex; - } - else - { - indexToInsert = listControl.Items.Count; - } - Appointment draggedAppointment = draggedInstance.AssociatedAppointment as Appointment; - SchedulerUIHelper.DeleteAppointment(draggedAppointment, this.radScheduler1); - RadListDataItem newItem = new RadListDataItem(draggedAppointment.Summary); - listControl.Items.Insert(indexToInsert, newItem); - //save changes to data base - SaveChanges(); -} -public void SaveChanges() -{ - appointmentsResourcesTableAdapter.Adapter.AcceptChangesDuringUpdate = false; - SchedulerDataDataSet.AppointmentsResourcesDataTable deletedChildRecords = - this.schedulerDataDataSet.AppointmentsResources.GetChanges(DataRowState.Deleted) - as SchedulerDataDataSet.AppointmentsResourcesDataTable; - SchedulerDataDataSet.AppointmentsResourcesDataTable newChildRecords = - this.schedulerDataDataSet.AppointmentsResources.GetChanges(DataRowState.Added) - as SchedulerDataDataSet.AppointmentsResourcesDataTable; - SchedulerDataDataSet.AppointmentsResourcesDataTable modifiedChildRecords = - this.schedulerDataDataSet.AppointmentsResources.GetChanges(DataRowState.Modified) - as SchedulerDataDataSet.AppointmentsResourcesDataTable; - try - { - if (deletedChildRecords != null) - { - appointmentsResourcesTableAdapter.Update(deletedChildRecords); - } - appointmentsTableAdapter.Update(this.schedulerDataDataSet.Appointments); - if (newChildRecords != null) - { - appointmentsResourcesTableAdapter.Update(newChildRecords); - } - if (modifiedChildRecords != null) - { - appointmentsResourcesTableAdapter.Update(modifiedChildRecords); - } - this.schedulerDataDataSet.AcceptChanges(); - } - catch (Exception ex) - { - MessageBox.Show(string.Format("An error occurred during the update process:\n{0}", ex.Message)); - } - finally - { - if (deletedChildRecords != null) - { - deletedChildRecords.Dispose(); - } - if (newChildRecords != null) - { - newChildRecords.Dispose(); - } - if (modifiedChildRecords != null) - { - modifiedChildRecords.Dispose(); - } - } -} -```` -````VB.NET -Private Sub DragDropBehavior_PreviewDragOver(sender As Object, e As Telerik.WinControls.RadDragOverEventArgs) - e.CanDrop = TypeOf e.HitTarget Is RadListElement -End Sub -Private Sub DragDropBehavior_PreviewDragDrop(sender As Object, e As Telerik.WinControls.RadDropEventArgs) - Dim draggedInstance As DragFeedbackElement = TryCast(e.DragInstance, DragFeedbackElement) - If draggedInstance Is Nothing Then - Return - End If - Dim listElement As RadListElement = TryCast(e.HitTarget, RadListElement) - If listElement Is Nothing Then - Return - End If - e.Handled = True - Dim listControl As RadListControl = TryCast(listElement.ElementTree.Control, RadListControl) - Dim targetItem As RadListVisualItem = TryCast(listControl.ElementTree.GetElementAtPoint(e.DropLocation), RadListVisualItem) - Dim indexToInsert As Integer - If targetItem IsNot Nothing Then - indexToInsert = targetItem.Data.RowIndex - Else - indexToInsert = listControl.Items.Count - End If - Dim draggedAppointment As Appointment = TryCast(draggedInstance.AssociatedAppointment, Appointment) - SchedulerUIHelper.DeleteAppointment(draggedAppointment, Me.RadScheduler1) - Dim newItem As New RadListDataItem(draggedAppointment.Summary) - listControl.Items.Insert(indexToInsert, newItem) - 'save changes to data base - SaveChanges() -End Sub -Public Sub SaveChanges() - AppointmentsResourcesTableAdapter.Adapter.AcceptChangesDuringUpdate = False - Dim deletedChildRecords As SchedulerDataDataSet.AppointmentsResourcesDataTable = TryCast(Me.SchedulerDataDataSet.AppointmentsResources.GetChanges(DataRowState.Deleted), SchedulerDataDataSet.AppointmentsResourcesDataTable) - Dim newChildRecords As SchedulerDataDataSet.AppointmentsResourcesDataTable = TryCast(Me.SchedulerDataDataSet.AppointmentsResources.GetChanges(DataRowState.Added), SchedulerDataDataSet.AppointmentsResourcesDataTable) - Dim modifiedChildRecords As SchedulerDataDataSet.AppointmentsResourcesDataTable = TryCast(Me.SchedulerDataDataSet.AppointmentsResources.GetChanges(DataRowState.Modified), SchedulerDataDataSet.AppointmentsResourcesDataTable) - Try - If deletedChildRecords IsNot Nothing Then - AppointmentsResourcesTableAdapter.Update(deletedChildRecords) - End If - AppointmentsTableAdapter.Update(Me.SchedulerDataDataSet.Appointments) - If newChildRecords IsNot Nothing Then - AppointmentsResourcesTableAdapter.Update(newChildRecords) - End If - If modifiedChildRecords IsNot Nothing Then - AppointmentsResourcesTableAdapter.Update(modifiedChildRecords) - End If - Me.SchedulerDataDataSet.AcceptChanges() - Catch ex As Exception - MessageBox.Show(String.Format("An error occurred during the update process:" & vbLf & "{0}", ex.Message)) - Finally - If deletedChildRecords IsNot Nothing Then - deletedChildRecords.Dispose() - End If - If newChildRecords IsNot Nothing Then - newChildRecords.Dispose() - End If - If modifiedChildRecords IsNot Nothing Then - modifiedChildRecords.Dispose() - End If - End Try -End Sub - -```` - -{{endregion}} >caption Figure 1: Using RadDragDropService ![WinForms RadScheduler Using RadDragDropService](images/scheduler-drag-and-drop-combining-raddragdropservice-and-ole-drag-and-drop001.gif) @@ -188,286 +36,24 @@ End Sub 1. Firstly, we should start the drag and drop operation using the RadListControl.__MouseMove__ event when the left mouse button is pressed. Afterwards, allow dragging over the __RadScheduler__ via the __Effect__ argument of the __DragEventArgs__ in the RadScheduler.__DragEnter__ event handler: -{{source=..\SamplesCS\Scheduler\DragDrop\SchedulerToListControl.cs region=StartDragDrop}} -{{source=..\SamplesVB\Scheduler\DragDrop\SchedulerToListControl.vb region=StartDragDrop}} - -````C# - -private Point mouseDownPosition; -private bool isDragging; - -private void radListControl1_MouseMove(object sender, MouseEventArgs e) -{ - if (e.Button != MouseButtons.Left) - { - this.isDragging = false; - return; - } - - if (this.isDragging) - return; - - Point currentPosition = e.Location; - if ((Math.Abs((currentPosition.X - this.mouseDownPosition.X)) >= SystemInformation.DragSize.Width) || - (Math.Abs((currentPosition.Y - this.mouseDownPosition.Y)) >= SystemInformation.DragSize.Height)) - { - this.isDragging = true; - DragObject dragObject = new DragObject(); - RadListVisualItem draggedItem = this.radListControl1.ElementTree.GetElementAtPoint(currentPosition) as RadListVisualItem; - if (draggedItem != null) - { - string itemText = draggedItem.Text; - - if (itemText != string.Empty) - { - dragObject.Values.Add(AppointmentFields.Summary, itemText); - dragObject.Status = AppointmentFields.Summary; - //start the drag and drop operation - (sender as RadListControl).DoDragDrop(dragObject, DragDropEffects.Copy); - } - } - } -} - -private void radScheduler1_DragEnter(object sender, DragEventArgs e) -{ - DragObject dragObject = e.Data.GetData(typeof(DragObject)) as DragObject; - //allow dragging over the RadScheduler - e.Effect = dragObject == null ? DragDropEffects.None : DragDropEffects.Copy; -} - -```` -````VB.NET -Private mouseDownPosition As Point -Private isDragging As Boolean -Private Sub radListControl1_MouseMove(sender As Object, e As MouseEventArgs) - If e.Button <> MouseButtons.Left Then - Me.isDragging = False - Return - End If - If Me.isDragging Then - Return - End If - Dim currentPosition As Point = e.Location - If (Math.Abs((currentPosition.X - Me.mouseDownPosition.X)) >= SystemInformation.DragSize.Width) OrElse (Math.Abs((currentPosition.Y - Me.mouseDownPosition.Y)) >= SystemInformation.DragSize.Height) Then - Me.isDragging = True - Dim dragObject As New DragObject() - Dim draggedItem As RadListVisualItem = TryCast(Me.RadListControl1.ElementTree.GetElementAtPoint(currentPosition), RadListVisualItem) - If draggedItem IsNot Nothing Then - Dim itemText As String = draggedItem.Text - If itemText <> String.Empty Then - dragObject.Values.Add(AppointmentFields.Summary, itemText) - dragObject.Status = AppointmentFields.Summary - 'start the drag and drop operation - TryCast(sender, RadListControl).DoDragDrop(dragObject, DragDropEffects.Copy) - End If - End If - End If -End Sub -Private Sub radScheduler1_DragEnter(sender As Object, e As DragEventArgs) - Dim dragObject As DragObject = TryCast(e.Data.GetData(GetType(DragObject)), DragObject) - 'allow dragging over the RadScheduler - e.Effect = If(dragObject Is Nothing, DragDropEffects.None, DragDropEffects.Copy) -End Sub + + -```` -{{endregion}} 2\. In the RadScheduler.__DragDrop__ event you need to get the location of the mouse and convert it to a point that the scheduler can use to get the cell element underneath the mouse. This __MonthCellElement__ is passed to a private method __GetCellAppointment__ that we will write next: -{{source=..\SamplesCS\Scheduler\DragDrop\SchedulerToListControl.cs region=DoDragDrop}} -{{source=..\SamplesVB\Scheduler\DragDrop\SchedulerToListControl.vb region=DoDragDrop}} + + -````C# - -private void radScheduler1_DragDrop(object sender, DragEventArgs e) -{ - Point point = this.radScheduler1.PointToClient(new Point(e.X, e.Y)); - SchedulerCellElement schedulerCell = SchedulerUIHelper.GetCellAtPoint(point, this.radScheduler1); - - if (schedulerCell != null) - { - DragObject dragObject = e.Data.GetData(typeof(DragObject)) as DragObject; - if (dragObject != null) - { - Appointment appointment = CreateAppointment(schedulerCell.Date, dragObject); - this.radScheduler1.Appointments.Add(appointment); - - int indexToRemove = this.radListControl1.Items.IndexOf(appointment.Summary); - if (indexToRemove > -1) - { - this.radListControl1.Items.RemoveAt(indexToRemove); - } - } - } - - this.mouseDownPosition = Point.Empty; - this.isDragging = false; - //save changes to database - SaveChanges(); -} -```` -````VB.NET -Private Sub radScheduler1_DragDrop(sender As Object, e As DragEventArgs) - Dim point__1 As Point = Me.RadScheduler1.PointToClient(New Point(e.X, e.Y)) - Dim schedulerCell As SchedulerCellElement = SchedulerUIHelper.GetCellAtPoint(point__1, Me.RadScheduler1) - If schedulerCell IsNot Nothing Then - Dim dragObject As DragObject = TryCast(e.Data.GetData(GetType(DragObject)), DragObject) - If dragObject IsNot Nothing Then - Dim appointment As Appointment = CreateAppointment(schedulerCell.[Date], dragObject) - Me.RadScheduler1.Appointments.Add(appointment) - Dim indexToRemove As Integer = Me.RadListControl1.Items.IndexOf(appointment.Summary) - If indexToRemove > -1 Then - Me.RadListControl1.Items.RemoveAt(indexToRemove) - End If - End If - End If - Me.mouseDownPosition = Point.Empty - Me.isDragging = False - 'save changes to database - SaveChanges() -End Sub - -```` - -{{endregion}} 3\. The helper method __CreateAppointment()__ creates an appointment, starting at the cell where the __RadListControl__ item is dropped. This appointment gets its data from the dragged item. -{{source=..\SamplesCS\Scheduler\DragDrop\SchedulerToListControl.cs region=DragHelper}} -{{source=..\SamplesVB\Scheduler\DragDrop\SchedulerToListControl.vb region=DragHelper}} - -````C# - -private Appointment CreateAppointment(DateTime currentDate, DragObject dragObject) -{ - Appointment appointment = new Appointment(); - DateTime startDate = currentDate; - DateTime endDate = currentDate.AddHours(1); - switch (dragObject.Status) - { - case AppointmentFields.Summary: - appointment.Summary = dragObject.Values[dragObject.Status] as string; - break; - case AppointmentFields.Row: - appointment.Summary = dragObject.Values[AppointmentFields.Summary] as string; - appointment.Description = dragObject.Values[AppointmentFields.Description] as string; - appointment.BackgroundId = (int)dragObject.Values[AppointmentFields.Background]; - appointment.StatusId = (int)dragObject.Values[AppointmentFields.Status]; - appointment.Location = dragObject.Values[AppointmentFields.Location] as string; - - startDate = (DateTime)dragObject.Values[AppointmentFields.Start]; - endDate = (DateTime)dragObject.Values[AppointmentFields.End]; - - TimeSpan range = endDate - startDate; - endDate = currentDate + range; - startDate = currentDate; - - break; - } - appointment.Start = startDate; - appointment.End = endDate; - return appointment; -} - -private enum AppointmentFields -{ - Row, - Summary, - Location, - Description, - Start, - End, - Background, - Status -} - -private class DragObject -{ - private AppointmentFields status; - private Dictionary values = new Dictionary(); - - public AppointmentFields Status - { - get - { - return this.status; - } - set - { - this.status = value; - } - } - - public Dictionary Values - { - get - { - return this.values; - } - } -} - -```` -````VB.NET -Private Function CreateAppointment(currentDate As DateTime, dragObject As DragObject) As Appointment - Dim appointment As New Appointment() - Dim startDate As DateTime = currentDate - Dim endDate As DateTime = currentDate.AddHours(1) - Select Case dragObject.Status - Case AppointmentFields.Summary - appointment.Summary = TryCast(dragObject.Values(dragObject.Status), String) - Exit Select - Case AppointmentFields.Row - appointment.Summary = TryCast(dragObject.Values(AppointmentFields.Summary), String) - appointment.Description = TryCast(dragObject.Values(AppointmentFields.Description), String) - appointment.BackgroundId = CInt(dragObject.Values(AppointmentFields.Background)) - appointment.StatusId = CInt(dragObject.Values(AppointmentFields.Status)) - appointment.Location = TryCast(dragObject.Values(AppointmentFields.Location), String) - startDate = DirectCast(dragObject.Values(AppointmentFields.Start), DateTime) - endDate = DirectCast(dragObject.Values(AppointmentFields.[End]), DateTime) - Dim range As TimeSpan = endDate - startDate - endDate = currentDate + range - startDate = currentDate - Exit Select - End Select - appointment.Start = startDate - appointment.[End] = endDate - Return appointment -End Function -Private Enum AppointmentFields - Row - Summary - Location - Description - Start - [End] - Background - Status -End Enum -Private Class DragObject - Private m_status As AppointmentFields - Private m_values As New Dictionary(Of AppointmentFields, Object)() - Public Property Status() As AppointmentFields - Get - Return Me.m_status - End Get - Set(value As AppointmentFields) - Me.m_status = value - End Set - End Property - Public ReadOnly Property Values() As Dictionary(Of AppointmentFields, Object) - Get - Return Me.m_values - End Get - End Property -End Class + + -```` -{{endregion}} >caption Figure 2: OLE Drag and Drop ![WinForms RadScheduler OLE Drag and Drop](images/scheduler-drag-and-drop-combining-raddragdropservice-and-ole-drag-and-drop002.gif) diff --git a/controls/scheduler/drag-and-drop/drag-and-drop-from-another-control.md b/controls/scheduler/drag-and-drop/drag-and-drop-from-another-control.md index 1aca33ef7..397b3f216 100644 --- a/controls/scheduler/drag-and-drop/drag-and-drop-from-another-control.md +++ b/controls/scheduler/drag-and-drop/drag-and-drop-from-another-control.md @@ -22,82 +22,10 @@ Firstly, we should start the drag and drop operation using the ListBox.__MouseMo #### Handle ListBox MouseMove -{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\DragDropFromControl.cs region=ListBoxToSchedulerStart}} -{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\DragDropFromControl.vb region=ListBoxToSchedulerStart}} - -````C# - -void listBox1_MouseMove(object sender, MouseEventArgs e) -{ - if (e.Button != MouseButtons.Left) - return; - - if (this.isDragging) - return; - - Point currentPosition = e.Location; - if ((Math.Abs((currentPosition.X - this.mouseDownPosition.X)) >= SystemInformation.DragSize.Width) || - (Math.Abs((currentPosition.Y - this.mouseDownPosition.Y)) >= SystemInformation.DragSize.Height)) - { - this.isDragging = true; - DragObject dragObject = new DragObject(); - int index = this.listBox1.IndexFromPoint(e.X, e.Y); - if (index > -1 && index < this.listBox1.Items.Count) - { - string itemText = this.listBox1.Items[index].ToString(); - - if (itemText != string.Empty) - { - dragObject.Values.Add(AppointmentFields.Summary, itemText); - dragObject.Status = AppointmentFields.Summary; - //start the drag and drop operation - (sender as ListBox).DoDragDrop(dragObject, DragDropEffects.Copy); - } - } - } -} - -private void radScheduler1_DragEnter(object sender, DragEventArgs e) -{ - DragObject dragObject = e.Data.GetData(typeof(DragObject)) as DragObject; - //allow dragging over the RadScheduler - e.Effect = dragObject == null ? DragDropEffects.None : DragDropEffects.Copy; -} - -```` -````VB.NET -Private Sub listBox1_MouseMove(sender As Object, e As MouseEventArgs) - If e.Button <> MouseButtons.Left Then - Return - End If - If Me.isDragging Then - Return - End If - Dim currentPosition As Point = e.Location - If (Math.Abs((currentPosition.X - Me.mouseDownPosition.X)) >= SystemInformation.DragSize.Width) OrElse (Math.Abs((currentPosition.Y - Me.mouseDownPosition.Y)) >= SystemInformation.DragSize.Height) Then - Me.isDragging = True - Dim dragObject As New DragObject() - Dim index As Integer = Me.ListBox1.IndexFromPoint(e.X, e.Y) - If index > -1 AndAlso index < Me.ListBox1.Items.Count Then - Dim itemText As String = Me.ListBox1.Items(index).ToString() - If itemText <> String.Empty Then - dragObject.Values.Add(AppointmentFields.Summary, itemText) - dragObject.Status = AppointmentFields.Summary - 'start the drag and drop operation - TryCast(sender, ListBox).DoDragDrop(dragObject, DragDropEffects.Copy) - End If - End If - End If -End Sub -Private Sub radScheduler1_DragEnter(sender As Object, e As DragEventArgs) - Dim dragObject As DragObject = TryCast(e.Data.GetData(GetType(DragObject)), DragObject) - 'allow dragging over the RadScheduler - e.Effect = If(dragObject Is Nothing, DragDropEffects.None, DragDropEffects.Copy) -End Sub - -```` - -{{endregion}} + + + + In order to use this feature, we will need to find the scheduler cell when the item is dropped onto the scheduler surface. Once you have the scheduler cell you can get the date and create an appointment for it. @@ -108,130 +36,19 @@ In the RadScheduler __DragDrop__ event handler you need to get the location of t #### Handle RadScheduler DragDrop -{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\DragDropFromControl.cs region=dropToCell}} -{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\DragDropFromControl.vb region=dropToCell}} - -````C# - -private Point mouseDownPosition; -private bool isDragging; - -private void radScheduler1_DragDrop(object sender, DragEventArgs e) -{ - Point point = this.radScheduler1.PointToClient(new Point(e.X, e.Y)); - SchedulerCellElement schedulerCell = SchedulerUIHelper.GetCellAtPoint(point, this.radScheduler1); - - if (schedulerCell != null) - { - DragObject dragObject = e.Data.GetData(typeof(DragObject)) as DragObject; - if (dragObject != null) - { - this.radScheduler1.Appointments.BeginUpdate(); - Appointment appointment = CreateAppointment(schedulerCell.Date, dragObject); - this.radScheduler1.Appointments.Add(appointment); - this.radScheduler1.Appointments.EndUpdate(); - } - } - - this.mouseDownPosition = Point.Empty; - this.isDragging = false; -} - -```` -````VB.NET -Private mouseDownPosition As Point -Private isDragging As Boolean -Private Sub radScheduler1_DragDrop(sender As Object, e As DragEventArgs) - Dim point As Point = Me.RadScheduler1.PointToClient(New Point(e.X, e.Y)) - Dim schedulerCell As SchedulerCellElement = SchedulerUIHelper.GetCellAtPoint(point, Me.RadScheduler1) - If schedulerCell IsNot Nothing Then - Dim dragObject As DragObject = TryCast(e.Data.GetData(GetType(DragObject)), DragObject) - If dragObject IsNot Nothing Then - Me.RadScheduler1.Appointments.BeginUpdate() - Dim appointment As Appointment = CreateAppointment(schedulerCell.[Date], dragObject) - Me.RadScheduler1.Appointments.Add(appointment) - Me.RadScheduler1.Appointments.EndUpdate() - End If - End If - Me.mouseDownPosition = Point.Empty - Me.isDragging = False -End Sub - -```` - -{{endregion}} + + + + The helper method __CreateAppointment()__ creates an appontment starting at the cell where the ListBox item is dropped. This appointment gets its data from the dragged item. #### Create Appointment -{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\DragDropFromControl.cs region=createAppointment}} -{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\DragDropFromControl.vb region=createAppointment}} - -````C# - -private Appointment CreateAppointment(DateTime currentDate, DragObject dragObject) -{ - Appointment appointment = new Appointment(); - DateTime startDate = currentDate; - DateTime endDate = currentDate.AddHours(1); - switch (dragObject.Status) - { - case AppointmentFields.Summary: - appointment.Summary = dragObject.Values[dragObject.Status] as string; - break; - case AppointmentFields.Row: - appointment.Summary = dragObject.Values[AppointmentFields.Summary] as string; - appointment.Description = dragObject.Values[AppointmentFields.Description] as string; - appointment.BackgroundId = (int)dragObject.Values[AppointmentFields.Background]; - appointment.StatusId = (int)dragObject.Values[AppointmentFields.Status]; - appointment.Location = dragObject.Values[AppointmentFields.Location] as string; - - startDate = (DateTime)dragObject.Values[AppointmentFields.Start]; - endDate = (DateTime)dragObject.Values[AppointmentFields.End]; - - TimeSpan range = endDate - startDate; - endDate = currentDate + range; - startDate = currentDate; - - break; - } - appointment.Start = startDate; - appointment.End = endDate; - return appointment; -} - -```` -````VB.NET -Private Function CreateAppointment(currentDate As DateTime, dragObject As DragObject) As Appointment - Dim appointment As New Appointment() - Dim startDate As DateTime = currentDate - Dim endDate As DateTime = currentDate.AddHours(1) - Select Case dragObject.Status - Case AppointmentFields.Summary - appointment.Summary = TryCast(dragObject.Values(dragObject.Status), String) - Exit Select - Case AppointmentFields.Row - appointment.Summary = TryCast(dragObject.Values(AppointmentFields.Summary), String) - appointment.Description = TryCast(dragObject.Values(AppointmentFields.Description), String) - appointment.BackgroundId = CInt(dragObject.Values(AppointmentFields.Background)) - appointment.StatusId = CInt(dragObject.Values(AppointmentFields.Status)) - appointment.Location = TryCast(dragObject.Values(AppointmentFields.Location), String) - startDate = DirectCast(dragObject.Values(AppointmentFields.Start), DateTime) - endDate = DirectCast(dragObject.Values(AppointmentFields.[End]), DateTime) - Dim range As TimeSpan = endDate - startDate - endDate = currentDate + range - startDate = currentDate - Exit Select - End Select - appointment.Start = startDate - appointment.[End] = endDate - Return appointment -End Function - -```` - -{{endregion}} + + + + ## Drag and Drop from RadScheduler to ListBox @@ -239,124 +56,19 @@ In order to enable dragging an appointment from __RadScheduler__ and dropping it #### Handle RadScheduler MouseMove -{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\DragDropFromControl.cs region=SchedulerToListBoxStart}} -{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\DragDropFromControl.vb region=SchedulerToListBoxStart}} - -````C# - -private void radScheduler1_MouseMove(object sender, MouseEventArgs e) -{ - if (e.Button != MouseButtons.Left) - return; - - if (this.isDragging) - return; - - AppointmentElement appointmentElement = this.radScheduler1.ElementTree.GetElementAtPoint(e.Location) as AppointmentElement; - if (appointmentElement == null) - { - return; - } - - this.isDragging = true; - DragObject dragObject = new DragObject(); - dragObject.Values.Add(AppointmentFields.Summary, appointmentElement.Appointment.Summary); - dragObject.Status = AppointmentFields.Summary; - //start drag and drop operation - (sender as RadScheduler).DoDragDrop(dragObject, DragDropEffects.Copy); -} - -private void listBox1_DragOver(object sender, DragEventArgs e) -{ - DragObject dragObject = e.Data.GetData(typeof(DragObject)) as DragObject; - //allow dragging over the ListBox - e.Effect = dragObject == null ? DragDropEffects.None : DragDropEffects.Copy; -} - -```` -````VB.NET -Private Sub radScheduler1_MouseMove(sender As Object, e As MouseEventArgs) - If e.Button <> MouseButtons.Left Then - Return - End If - If Me.isDragging Then - Return - End If - Dim appointmentElement As AppointmentElement = TryCast(Me.RadScheduler1.ElementTree.GetElementAtPoint(e.Location), AppointmentElement) - If appointmentElement Is Nothing Then - Return - End If - Me.isDragging = True - Dim dragObject As New DragObject() - dragObject.Values.Add(AppointmentFields.Summary, appointmentElement.Appointment.Summary) - dragObject.Status = AppointmentFields.Summary - 'start drag and drop operation - TryCast(sender, RadScheduler).DoDragDrop(dragObject, DragDropEffects.Copy) -End Sub -Private Sub listBox1_DragOver(sender As Object, e As DragEventArgs) - Dim dragObject As DragObject = TryCast(e.Data.GetData(GetType(DragObject)), DragObject) - 'allow dragging over the ListBox - e.Effect = If(dragObject Is Nothing, DragDropEffects.None, DragDropEffects.Copy) -End Sub - -```` - -{{endregion}} + + + + Finally, perform the exact drag and drop operation via inserting a new item in the ListBox in the __DragDrop__ event: #### Handle ListBox MouseMove -{{source=..\SamplesCS\Scheduler\AppointmentsAndDialogues\DragDropFromControl.cs region=SchedulerToListBoxDrop}} -{{source=..\SamplesVB\Scheduler\AppointmentsAndDialogues\DragDropFromControl.vb region=SchedulerToListBoxDrop}} - -````C# -private void listBox1_DragDrop(object sender, DragEventArgs e) -{ - Point point = this.listBox1.PointToClient(new Point(e.X, e.Y)); - DragObject dragObject = e.Data.GetData(typeof(DragObject)) as DragObject; - if (dragObject != null) - { - string itemText = dragObject.Values[AppointmentFields.Summary] as string; - if (!this.listBox1.Items.Contains(itemText)) - { - int index = this.listBox1.IndexFromPoint(point); - if (index > -1 && index < this.listBox1.Items.Count) - { - this.listBox1.Items.Insert(index, itemText); - } - else - { - this.listBox1.Items.Add(itemText); - } - } - } - - this.isDragging = false; -} - -```` -````VB.NET -Private Sub listBox1_DragDrop(sender As Object, e As DragEventArgs) - Dim point As Point = Me.ListBox1.PointToClient(New Point(e.X, e.Y)) - Dim dragObject As DragObject = TryCast(e.Data.GetData(GetType(DragObject)), DragObject) - If dragObject IsNot Nothing Then - Dim itemText As String = TryCast(dragObject.Values(AppointmentFields.Summary), String) - If Not Me.ListBox1.Items.Contains(itemText) Then - Dim index As Integer = Me.ListBox1.IndexFromPoint(point) - If index > -1 AndAlso index < Me.ListBox1.Items.Count Then - Me.ListBox1.Items.Insert(index, itemText) - Else - Me.ListBox1.Items.Add(itemText) - End If - End If - End If - Me.isDragging = False -End Sub - -```` - -{{endregion}} + + + + >caption Figure 2: Dragging from a RadScheduler ![WinForms RadScheduler Dragging from a RadScheduler](images/scheduler-drag-and-drop-drag-and-drop-from-another-control002.gif) diff --git a/controls/scheduler/drag-and-drop/drag-and-drop-using-raddragdropservice.md b/controls/scheduler/drag-and-drop/drag-and-drop-using-raddragdropservice.md index 6dd9e6c1b..fd3cc3065 100644 --- a/controls/scheduler/drag-and-drop/drag-and-drop-using-raddragdropservice.md +++ b/controls/scheduler/drag-and-drop/drag-and-drop-using-raddragdropservice.md @@ -19,206 +19,29 @@ Let’s assume that our __RadScheduler__ is in unbound mode and the __RadGridVie 1. The first thing we need to do is to start the __RadGridView__’s drag and drop service when a user clicks on a row with the left mouse down. For this purpose we should create a custom [grid behavior]({%slug winforms/gridview/rows/row-behaviors%}): -{{source=..\SamplesCS\Scheduler\DragDrop\SchedulerToGrid.cs region=CustomRowGridBehavior}} -{{source=..\SamplesVB\Scheduler\DragDrop\SchedulerToGrid.vb region=CustomRowGridBehavior}} + + -````C# - -//initiates drag and drop service for clicked rows -public class CustomRowGridBehavior : GridDataRowBehavior -{ - protected override bool OnMouseDownLeft(MouseEventArgs e) - { - GridDataRowElement row = this.GetRowAtPoint(e.Location) as GridDataRowElement; - if (row != null) - { - RadGridViewDragDropService svc = this.GridViewElement.GetService(); - svc.Start(row); - } - return base.OnMouseDownLeft(e); - } -} -```` -````VB.NET -'initiates drag and drop service for clicked rows -Public Class CustomRowGridBehavior -Inherits GridDataRowBehavior - Protected Overrides Function OnMouseDownLeft(e As MouseEventArgs) As Boolean - Dim row As GridDataRowElement = TryCast(Me.GetRowAtPoint(e.Location), GridDataRowElement) - If row IsNot Nothing Then - Dim svc As RadGridViewDragDropService = Me.GridViewElement.GetService(Of RadGridViewDragDropService)() - svc.Start(row) - End If - Return MyBase.OnMouseDownLeft(e) - End Function -End Class - -```` - -{{endregion}} 2\. Next, we should register this behavior in our grid: -{{source=..\SamplesCS\Scheduler\DragDrop\SchedulerToGrid.cs region=RegisterGridBehavior}} -{{source=..\SamplesVB\Scheduler\DragDrop\SchedulerToGrid.vb region=RegisterGridBehavior}} - -````C# - -//register the custom row behavior -BaseGridBehavior gridBehavior = this.radGridView1.GridBehavior as BaseGridBehavior; -gridBehavior.UnregisterBehavior(typeof(GridViewDataRowInfo)); -gridBehavior.RegisterBehavior(typeof(GridViewDataRowInfo), new CustomRowGridBehavior()); + + -```` -````VB.NET -'register the custom row behavior -Dim gridBehavior As BaseGridBehavior = TryCast(Me.RadGridView1.GridBehavior, BaseGridBehavior) -gridBehavior.UnregisterBehavior(GetType(GridViewDataRowInfo)) -gridBehavior.RegisterBehavior(GetType(GridViewDataRowInfo), New CustomRowGridBehavior()) -```` - -{{endregion}} 3\. It is necessary to subscribe to the __PreviewDragStart__, __PreviewDragOver__ and __PreviewDragDrop__ events of the grid’s __RadDragDropService__. The __PreviewDragStart__ event is fired once the drag and drop service on the grid is started. We should notify the service that the drag and drop operation can move forward. In the __PreviewDragOver__ event you can control on what targets to allow dropping the dragged row. The __PreviewDragDrop__ event performs the actual move of the row from the __RadGridView__ to the __RadScheduler__. -{{source=..\SamplesCS\Scheduler\DragDrop\SchedulerToGrid.cs region=RadDragDropService}} -{{source=..\SamplesVB\Scheduler\DragDrop\SchedulerToGrid.vb region=RadDragDropService}} - -````C# - -//handle drag and drop events for the grid through the DragDrop service -RadDragDropService svc = this.radGridView1.GridViewElement.GetService(); -svc.PreviewDragStart += svc_PreviewDragStart; -svc.PreviewDragDrop += svc_PreviewDragDrop; -svc.PreviewDragOver += svc_PreviewDragOver; + + -```` -````VB.NET -'handle drag and drop events for the grid through the DragDrop service -Dim svc As RadDragDropService = Me.RadGridView1.GridViewElement.GetService(Of RadDragDropService)() -AddHandler svc.PreviewDragStart, AddressOf svc_PreviewDragStart -AddHandler svc.PreviewDragDrop, AddressOf svc_PreviewDragDrop -AddHandler svc.PreviewDragOver, AddressOf svc_PreviewDragOver -```` -{{endregion}} + + -{{source=..\SamplesCS\Scheduler\DragDrop\SchedulerToGrid.cs region=PerformGridToSchedulerDragDrop}} -{{source=..\SamplesVB\Scheduler\DragDrop\SchedulerToGrid.vb region=PerformGridToSchedulerDragDrop}} -````C# - -//required to initiate drag and drop when grid is in bound mode -private void svc_PreviewDragStart(object sender, PreviewDragStartEventArgs e) -{ - e.CanStart = true; -} - -private void svc_PreviewDragOver(object sender, RadDragOverEventArgs e) -{ - if (e.DragInstance is GridDataRowElement) - { - e.CanDrop = e.HitTarget is SchedulerCellElement; - } -} - -private void svc_PreviewDragDrop(object sender, RadDropEventArgs e) -{ - SchedulerCellElement schedulerCell = e.HitTarget as SchedulerCellElement; - if (schedulerCell == null) - { - DayViewAllDayHeader allDay = (this.radScheduler1.SchedulerElement.ViewElement as SchedulerDayViewElement).AllDayHeaderElement; - schedulerCell = SchedulerUIHelper.GetCellAtPoint(e.DropLocation, allDay.Children); - } - if (schedulerCell == null) - { - return; - } - GridDataRowElement draggedRow = e.DragInstance as GridDataRowElement; - if (draggedRow == null) - { - return; - } - - DataRowView dataRowView = draggedRow.Data.DataBoundItem as DataRowView; - if (dataRowView != null) - { - if (draggedRow.GridControl.DataSource != null && typeof(BindingSource).IsAssignableFrom(draggedRow.GridControl.DataSource.GetType())) - { - Appointment appointment = new Appointment(); - appointment.Start = (DateTime)draggedRow.RowInfo.Cells["Start"].Value; - appointment.End = (DateTime)draggedRow.RowInfo.Cells["End"].Value; - //adjust start/end according to target cell - appointment.End = schedulerCell.Date.AddMinutes(appointment.Duration.TotalMinutes); - appointment.Start = schedulerCell.Date; - appointment.Summary = string.Empty + draggedRow.RowInfo.Cells["Summary"].Value; - appointment.Description = string.Empty + draggedRow.RowInfo.Cells["Description"].Value; - appointment.Location = string.Empty + draggedRow.RowInfo.Cells["Location"].Value; - appointment.StatusId = (int)draggedRow.RowInfo.Cells["StatusId"].Value; - appointment.BackgroundId = (int)draggedRow.RowInfo.Cells["BackgroundId"].Value; - this.radScheduler1.Appointments.Add(appointment); - - dataRowView.Row.Table.Rows.Remove(dataRowView.Row); - } - else - { - throw new ApplicationException("Unhandled Scenario"); - } - } -} - -```` -````VB.NET -'required to initiate drag and drop when grid is in bound mode -Private Sub svc_PreviewDragStart(sender As Object, e As PreviewDragStartEventArgs) - e.CanStart = True -End Sub -Private Sub svc_PreviewDragOver(sender As Object, e As RadDragOverEventArgs) - If TypeOf e.DragInstance Is GridDataRowElement Then - e.CanDrop = TypeOf e.HitTarget Is SchedulerCellElement - End If -End Sub -Private Sub svc_PreviewDragDrop(sender As Object, e As RadDropEventArgs) - Dim schedulerCell As SchedulerCellElement = TryCast(e.HitTarget, SchedulerCellElement) - If schedulerCell Is Nothing Then - Dim allDay As DayViewAllDayHeader = TryCast(Me.RadScheduler1.SchedulerElement.ViewElement, SchedulerDayViewElement).AllDayHeaderElement - schedulerCell = SchedulerUIHelper.GetCellAtPoint(e.DropLocation, allDay.Children) - End If - If schedulerCell Is Nothing Then - Return - End If - Dim draggedRow As GridDataRowElement = TryCast(e.DragInstance, GridDataRowElement) - If draggedRow Is Nothing Then - Return - End If - Dim dataRowView As DataRowView = TryCast(draggedRow.Data.DataBoundItem, DataRowView) - If dataRowView IsNot Nothing Then - If draggedRow.GridControl.DataSource IsNot Nothing AndAlso GetType(BindingSource).IsAssignableFrom(draggedRow.GridControl.DataSource.[GetType]()) Then - Dim appointment As New Appointment() - appointment.Start = DirectCast(draggedRow.RowInfo.Cells("Start").Value, DateTime) - appointment.[End] = DirectCast(draggedRow.RowInfo.Cells("End").Value, DateTime) - 'adjust start/end according to target cell - appointment.[End] = schedulerCell.[Date].AddMinutes(appointment.Duration.TotalMinutes) - appointment.Start = schedulerCell.[Date] - appointment.Summary = String.Empty + draggedRow.RowInfo.Cells("Summary").Value - appointment.Description = String.Empty + draggedRow.RowInfo.Cells("Description").Value - appointment.Location = String.Empty + draggedRow.RowInfo.Cells("Location").Value - appointment.StatusId = CInt(draggedRow.RowInfo.Cells("StatusId").Value) - appointment.BackgroundId = CInt(draggedRow.RowInfo.Cells("BackgroundId").Value) - Me.RadScheduler1.Appointments.Add(appointment) - dataRowView.Row.Table.Rows.Remove(dataRowView.Row) - Else - Throw New ApplicationException("Unhandled Scenario") - End If - End If -End Sub - -```` - -{{endregion}} >note The start date of the created appointment is in correspondence with the cell where the row is dropped. The appointment’s duration is relevant to the original duration. > @@ -230,157 +53,10 @@ End Sub To implement drag and drop functionality for this scenario, we will use the SchedulerElement.__DragDropBehavior__, which is a derivative of the __RadDragDropService__. Subscribe to its __PreviewDragOver__ and __PreviewDragDrop__ events. In the __PreviewDragOver__ event allow dropping over a row element or over the table element. The __PreviewDragDrop__ event performs the actual inserting of the dragged appointment into the __RadGridView__’s data source: -{{source=..\SamplesCS\Scheduler\DragDrop\SchedulerToGrid.cs region=SchedulerToGrid}} -{{source=..\SamplesVB\Scheduler\DragDrop\SchedulerToGrid.vb region=SchedulerToGrid}} - -````C# - -private void DragDropBehavior_PreviewDragOver(object sender, Telerik.WinControls.RadDragOverEventArgs e) -{ - e.CanDrop = e.HitTarget is GridTableElement || - e.HitTarget is GridDataRowElement; -} - -private void DragDropBehavior_PreviewDragDrop(object sender, Telerik.WinControls.RadDropEventArgs e) -{ - DragFeedbackElement draggedInstance = e.DragInstance as DragFeedbackElement; - if (draggedInstance == null) - { - return; - } - GridDataRowElement rowElement = e.HitTarget as GridDataRowElement; - GridTableElement tableElement = e.HitTarget as GridTableElement; - RadGridView targetGrid; - if (rowElement == null && tableElement == null) - { - return; - } - if (rowElement != null) - { - targetGrid = rowElement.GridViewElement.GridControl; - } - else - { - targetGrid = tableElement.GridViewElement.GridControl; - } - - if (targetGrid == null) - { - return; - } - e.Handled = true; - - int index = rowElement != null ? this.GetTargetRowIndex(rowElement, e.DropLocation) : targetGrid.RowCount; - Appointment draggedAppointment = draggedInstance.AssociatedAppointment as Appointment; - this.MoveRows(targetGrid, draggedAppointment, index); -} - -private int GetTargetRowIndex(GridDataRowElement row, Point dropLocation) -{ - int halfHeight = row.Size.Height / 2; - int index = row.RowInfo.Index; - if (dropLocation.Y > halfHeight) - { - index++; - } - return index; -} - -private void MoveRows(RadGridView dragGrid, - Appointment draggedAppointment, int index) -{ - dragGrid.BeginUpdate(); - - if (dragGrid.DataSource != null && typeof(BindingSource).IsAssignableFrom(dragGrid.DataSource.GetType())) - { - //bound to a BindingSource scenario - BindingSource sourceCollection = (BindingSource)dragGrid.DataSource; - this.radScheduler1.Appointments.Remove(draggedAppointment); - - DataRowView newDataRowView = sourceCollection.AddNew() as DataRowView; - if (newDataRowView != null) - { - newDataRowView["Start"] = draggedAppointment.Start; - newDataRowView["End"] = draggedAppointment.End ; - newDataRowView["Summary"] = draggedAppointment.Summary; - newDataRowView["Description"] = draggedAppointment.Description ; - newDataRowView["Location"] = draggedAppointment.Location; - newDataRowView["StatusId"] = draggedAppointment.StatusId; - newDataRowView["BackgroundId"] = draggedAppointment.BackgroundId ; - } - newDataRowView.Row.Table.Rows.InsertAt(newDataRowView.Row, index); - } - else - { - throw new ApplicationException("Unhandled Scenario"); - } - - dragGrid.EndUpdate(true); -} - -```` -````VB.NET -Private Sub DragDropBehavior_PreviewDragOver(sender As Object, e As Telerik.WinControls.RadDragOverEventArgs) - e.CanDrop = TypeOf e.HitTarget Is GridTableElement OrElse TypeOf e.HitTarget Is GridDataRowElement -End Sub -Private Sub DragDropBehavior_PreviewDragDrop(sender As Object, e As Telerik.WinControls.RadDropEventArgs) - Dim draggedInstance As DragFeedbackElement = TryCast(e.DragInstance, DragFeedbackElement) - If draggedInstance Is Nothing Then - Return - End If - Dim rowElement As GridDataRowElement = TryCast(e.HitTarget, GridDataRowElement) - Dim tableElement As GridTableElement = TryCast(e.HitTarget, GridTableElement) - Dim targetGrid As RadGridView - If rowElement Is Nothing AndAlso tableElement Is Nothing Then - Return - End If - If rowElement IsNot Nothing Then - targetGrid = rowElement.GridViewElement.GridControl - Else - targetGrid = tableElement.GridViewElement.GridControl - End If - If targetGrid Is Nothing Then - Return - End If - e.Handled = True - Dim index As Integer = If(rowElement IsNot Nothing, Me.GetTargetRowIndex(rowElement, e.DropLocation), targetGrid.RowCount) - Dim draggedAppointment As Appointment = TryCast(draggedInstance.AssociatedAppointment, Appointment) - Me.MoveRows(targetGrid, draggedAppointment, index) -End Sub -Private Function GetTargetRowIndex(row As GridDataRowElement, dropLocation As Point) As Integer - Dim halfHeight As Integer = row.Size.Height / 2 - Dim index As Integer = row.RowInfo.Index - If dropLocation.Y > halfHeight Then - index += 1 - End If - Return index -End Function -Private Sub MoveRows(dragGrid As RadGridView, draggedAppointment As Appointment, index As Integer) - dragGrid.BeginUpdate() - If dragGrid.DataSource IsNot Nothing AndAlso GetType(BindingSource).IsAssignableFrom(dragGrid.DataSource.[GetType]()) Then - 'bound to a BindingSource scenario - Dim sourceCollection As BindingSource = DirectCast(dragGrid.DataSource, BindingSource) - Me.RadScheduler1.Appointments.Remove(draggedAppointment) - Dim newDataRowView As DataRowView = TryCast(sourceCollection.AddNew(), DataRowView) - If newDataRowView IsNot Nothing Then - newDataRowView("Start") = draggedAppointment.Start - newDataRowView("End") = draggedAppointment.[End] - newDataRowView("Summary") = draggedAppointment.Summary - newDataRowView("Description") = draggedAppointment.Description - newDataRowView("Location") = draggedAppointment.Location - newDataRowView("StatusId") = draggedAppointment.StatusId - newDataRowView("BackgroundId") = draggedAppointment.BackgroundId - End If - newDataRowView.Row.Table.Rows.InsertAt(newDataRowView.Row, index) - Else - Throw New ApplicationException("Unhandled Scenario") - End If - dragGrid.EndUpdate(True) -End Sub + + -```` -{{endregion}} >caption Figure 2: Drag and Drop from RadScheduler to RadGridView ![WinForms RadScheduler Drag and Drop from RadScheduler to RadGridView](images/scheduler-drag-and-drop-drag-and-drop-using-raddragdropservice002.gif) diff --git a/controls/scheduler/end-user-functionality/copy-paste-cut.md b/controls/scheduler/end-user-functionality/copy-paste-cut.md index 4423f74f2..a17bcfc4e 100644 --- a/controls/scheduler/end-user-functionality/copy-paste-cut.md +++ b/controls/scheduler/end-user-functionality/copy-paste-cut.md @@ -46,34 +46,10 @@ Ctrl+V is the key combination performing the paste behavior in scheduler. The Ra #### Pasting Appointment -{{source=..\SamplesCS\Scheduler\EndUserFunctionality\EditingAppointments.cs region=Pasting}} -{{source=..\SamplesVB\Scheduler\EndUserFunctionality\EditingAppointments.vb region=Pasting}} - -````C# - -private void radScheduler1_AppointmentsPasting(object sender, SchedulerClipboardEventArgs e) -{ - if (e.Format == "ICal") - { - string iCalData = e.DataObject.GetData(RadScheduler.ICalendarDataFormat) + ""; - string newiCalData = iCalData.Replace("SUMMARY:", "SUMMARY: pasted "); - System.Windows.Forms.Clipboard.SetData(RadScheduler.ICalendarDataFormat, newiCalData); - } -} - -```` -````VB.NET -Private Sub radScheduler1_AppointmentsPasting(sender As Object, e As SchedulerClipboardEventArgs) - If e.Format = "ICal" Then - Dim iCalData As String = e.DataObject.GetData(RadScheduler.ICalendarDataFormat) + "" - Dim newiCalData As String = iCalData.Replace("SUMMARY:", "SUMMARY: pasted ") - System.Windows.Forms.Clipboard.SetData(RadScheduler.ICalendarDataFormat, newiCalData) - End If -End Sub - -```` - -{{endregion}} + + + + >caption Figure 1: Pasting Appointment ![WinForms RadScheduler Pasting Appointment](images/scheduler-end-user-functionality-copy-paste-cut001.gif) diff --git a/controls/scheduler/end-user-functionality/editing-appointments-.md b/controls/scheduler/end-user-functionality/editing-appointments-.md index 24d55c953..04f1b13a6 100644 --- a/controls/scheduler/end-user-functionality/editing-appointments-.md +++ b/controls/scheduler/end-user-functionality/editing-appointments-.md @@ -54,19 +54,10 @@ In-place editors provide a quick and easy way to edit a small number of the appo #### Setting a Simple Editor -{{source=..\SamplesCS\Scheduler\EndUserFunctionality\EditingAppointments.cs region=editorViewModeEditor}} -{{source=..\SamplesVB\Scheduler\EndUserFunctionality\EditingAppointments.vb region=editorViewModeEditor}} + + -````C# -this.radScheduler1.SchedulerElement.EditorManager.EditorViewMode = SchedulerEditorViewMode.Editor; -```` -````VB.NET -Me.RadScheduler1.SchedulerElement.EditorManager.EditorViewMode = SchedulerEditorViewMode.Editor - -```` - -{{endregion}} >caption Figure 1: Simple Editor ![WinForms RadScheduler Simple Editor](images/scheduler-end-user-functionality-editing-appointments006.png) @@ -75,38 +66,20 @@ Me.RadScheduler1.SchedulerElement.EditorManager.EditorViewMode = SchedulerEditor #### Setting an Editor Dialog -{{source=..\SamplesCS\Scheduler\EndUserFunctionality\EditingAppointments.cs region=editorViewModeEditorDialog}} -{{source=..\SamplesVB\Scheduler\EndUserFunctionality\EditingAppointments.vb region=editorViewModeEditorDialog}} - -````C# -this.radScheduler1.SchedulerElement.EditorManager.EditorViewMode = SchedulerEditorViewMode.EditorDialog; + + -```` -````VB.NET -Me.RadScheduler1.SchedulerElement.EditorManager.EditorViewMode = SchedulerEditorViewMode.EditorDialog -```` - -{{endregion}} >caption Figure 2: Dialog Editor ![WinForms RadScheduler Dialog Editor](images/scheduler-end-user-functionality-editing-appointments002.png) * All in-place editors are disabled. This is the default behavior. -{{source=..\SamplesCS\Scheduler\EndUserFunctionality\EditingAppointments.cs region=editorViewModeEditorNone}} -{{source=..\SamplesVB\Scheduler\EndUserFunctionality\EditingAppointments.vb region=editorViewModeEditorNone}} - -````C# -this.radScheduler1.SchedulerElement.EditorManager.EditorViewMode = SchedulerEditorViewMode.None; + + -```` -````VB.NET -Me.RadScheduler1.SchedulerElement.EditorManager.EditorViewMode = SchedulerEditorViewMode.None -```` - -{{endregion}} ## Customizing the In-place Editors @@ -114,79 +87,19 @@ You are able to change the default editors in the EditorRequired event of the Ra #### Custom TextBox Editor -{{source=..\SamplesCS\Scheduler\EndUserFunctionality\CustomSchedulerTextBoxEditor.cs region=customSchedulerTextBoxEditor}} -{{source=..\SamplesVB\Scheduler\EndUserFunctionality\CustomSchedulerTextBoxEditor.vb region=customSchedulerTextBoxEditor}} - -````C# -public class CustomSchedulerTextBoxEditor : RadSchedulerTextBoxEditor -{ - public override void BeginEditorEdit(IEditorManager editorManager, IEvent appointment) - { - base.BeginEditorEdit(editorManager, appointment); - this.Value = this.Value = appointment.Description; - } - public override void Save() - { - if (this.appointment.Description == this.Value.ToString()) - { - return; - } - this.appointment.Description = this.Value.ToString(); - if (this.appointment.MasterEvent != null && - !this.appointment.MasterEvent.Exceptions.Contains(this.appointment)) - { - this.appointment.MasterEvent.Exceptions.Add(this.appointment); - } - } -} - -```` -````VB.NET -Public Class CustomSchedulerTextBoxEditor - Inherits RadSchedulerTextBoxEditor - Public Overrides Sub BeginEditorEdit(ByVal editorManager As IEditorManager, ByVal appointment As IEvent) - MyBase.BeginEditorEdit(editorManager, appointment) - Me.Value = appointment.Description - Me.Value = Me.Value - End Sub - Public Overrides Sub Save() - If Me.appointment.Description = Me.Value.ToString() Then - Return - End If - Me.appointment.Description = Me.Value.ToString() - If Me.appointment.MasterEvent IsNot Nothing AndAlso (Not Me.appointment.MasterEvent.Exceptions.Contains(Me.appointment)) Then - Me.appointment.MasterEvent.Exceptions.Add(Me.appointment) - End If - End Sub -End Class - -```` - -{{endregion}} + + -After creating the custom editor that edits Description property of the appointment, you should replace the default editor. This has to be done on EditorRequired event of RadScheduler. -#### Replacing Editor -{{source=..\SamplesCS\Scheduler\EndUserFunctionality\EditingAppointments.cs region=editorRequired}} -{{source=..\SamplesVB\Scheduler\EndUserFunctionality\EditingAppointments.vb region=editorRequired}} +After creating the custom editor that edits Description property of the appointment, you should replace the default editor. This has to be done on EditorRequired event of RadScheduler. -````C# - -void radScheduler1_EditorRequired(object sender, SchedulerEditorRequiredArgs e) -{ - e.Editor = new CustomSchedulerTextBoxEditor(); -} +#### Replacing Editor -```` -````VB.NET -Private Sub radScheduler1_EditorRequired(ByVal sender As Object, ByVal e As SchedulerEditorRequiredArgs) - e.Editor = New CustomSchedulerTextBoxEditor() -End Sub + + -```` -{{endregion}} The result is shown on the screenshot below: diff --git a/controls/scheduler/fundamentals/appointment-title-formatter.md b/controls/scheduler/fundamentals/appointment-title-formatter.md index 04993f7a8..8e31a566f 100644 --- a/controls/scheduler/fundamentals/appointment-title-formatter.md +++ b/controls/scheduler/fundamentals/appointment-title-formatter.md @@ -38,47 +38,17 @@ RadScheduler offers the **AppointmentTitleFormat** property allowing you to spec ![WinForms RadScheduler Appointment Title Format](images/appointment-title-formatter001.png) -{{source=..\SamplesCS\Scheduler\Fundamentals\TitleFormatter.cs region=Example1}} -{{source=..\SamplesVB\Scheduler\Fundamentals\TitleFormatter.vb region=Example1}} + + -````C# -Appointment a = new Appointment(); -a.Start = DateTime.Now; -a.End = a.Start.AddHours(3); -a.Summary = "Release planning"; -a.Description = "List the tasks for the roadmap"; -a.Location = "Sofia"; -this.radScheduler1.Appointments.Add(a); - -```` -````VB.NET - -Dim a As Appointment = New Appointment() -a.Start = DateTime.Now -a.[End] = a.Start.AddHours(3) -a.Summary = "Release planning" -a.Description = "List the tasks for the roadmap" -a.Location = "Sofia" -Me.radScheduler1.Appointments.Add(a) - -```` Specify the title format according to the required information: -{{source=..\SamplesCS\Scheduler\Fundamentals\TitleFormatter.cs region=Example2}} -{{source=..\SamplesVB\Scheduler\Fundamentals\TitleFormatter.vb region=Example2}} - -````C# + + -this.radScheduler1.AppointmentTitleFormat = "{6}{0:dd-MM-yyyy h:mm tt} - {1:dd-MM-yyyy h:mm tt}{7} {3} {8} {2}"; -```` -````VB.NET - -Me.radScheduler1.AppointmentTitleFormat = "{6}{0:dd-MM-yyyy h:mm tt} - {1:dd-MM-yyyy h:mm tt}{7} {3} {8} {2}" - -```` ![WinForms RadScheduler Custom Format](images/appointment-title-formatter003.png) @@ -86,24 +56,10 @@ Me.radScheduler1.AppointmentTitleFormat = "{6}{0:dd-MM-yyyy h:mm tt} - {1:dd-MM- The AppointmentElement.**ShowAppointmentDescription** property controls whether the description will be drawn. By default, it is set to *false*. It can be set in the **AppointmentFormatting** event: -{{source=..\SamplesCS\Scheduler\Fundamentals\TitleFormatter.cs region=Example3}} -{{source=..\SamplesVB\Scheduler\Fundamentals\TitleFormatter.vb region=Example3}} - -````C# - -private void RadScheduler1_AppointmentFormatting(object sender, SchedulerAppointmentEventArgs e) -{ - e.AppointmentElement.ShowAppointmentDescription = true; -} + + -```` -````VB.NET -Private Sub RadScheduler1_AppointmentFormatting(ByVal sender As Object, ByVal e As SchedulerAppointmentEventArgs) - e.AppointmentElement.ShowAppointmentDescription = True -End Sub - -```` ![WinForms RadScheduler Appointment Description](images/appointment-title-formatter002.png) @@ -131,47 +87,10 @@ When the **SchedulerViewType** is *Timeline* a TimelineViewAppointmentTitleForma A common requirement is to use different colors for the different text parts, e.g. color the *time* part in blue and the *summary* in red. This can be achieved by creating a custom [AppointmentElement]({%slug winforms/scheduler/appointments-and-dialogs/custom-appointment-element%}) and overriding its **CreateAppointmentText** method which is expected to return the [HTML-like formatted]({%slug winforms/telerik-presentation-framework/html-like-text-formatting%}) text for the appointment. -{{source=..\SamplesCS\Scheduler\Fundamentals\TitleFormatter.cs region=Example4}} -{{source=..\SamplesVB\Scheduler\Fundamentals\TitleFormatter.vb region=Example4}} - -````C# - -public class MyAppointmentElement : AppointmentElement -{ - public MyAppointmentElement(RadScheduler scheduler, SchedulerView view, IEvent appointment) - : base(scheduler, view, appointment) - { - } - - protected override string CreateAppointmentText() - { - string text = "" + this.Appointment.Summary + "
" + - "" + string.Format("{0:dd-MM-yyyy hh:mm}", this.Appointment.Start) + " - " + - "" + string.Format("{0:dd-MM-yyyy hh:mm}", this.Appointment.End); - - return text; - } -} - -```` -````VB.NET - -Public Class MyAppointmentElement - Inherits AppointmentElement - - Public Sub New(ByVal scheduler As RadScheduler, ByVal view As SchedulerView, ByVal appointment As IEvent) - MyBase.New(scheduler, view, appointment) - End Sub + + - Protected Overrides Function CreateAppointmentText() As String - Dim text As String = "" & Me.Appointment.Summary & "
" & - "" & String.Format("{0:dd-MM-yyyy hh:mm}", - Me.Appointment.Start) & " - " & "" & String.Format("{0:dd-MM-yyyy hh:mm}", Me.Appointment.[End]) - Return text - End Function -End Class -```` Do not forget to replace the custom AppointmentElement with the help of a [SchedulerElementProvider]({%slug winforms/scheduler/appointments-and-dialogs/custom-appointment-element%}). diff --git a/controls/scheduler/fundamentals/input-behavior.md b/controls/scheduler/fundamentals/input-behavior.md index b6a2aee3d..050790e48 100644 --- a/controls/scheduler/fundamentals/input-behavior.md +++ b/controls/scheduler/fundamentals/input-behavior.md @@ -39,81 +39,19 @@ Each of these methods can be overridden and the instance of the __SchedulerInput #### Custom Input Behavior -{{source=..\SamplesCS\Scheduler\Fundamentals\InputBehavior.cs region=Behavior}} -{{source=..\SamplesVB\Scheduler\Fundamentals\InputBehavior.vb region=Behavior}} - -````C# -public class MySchedulerInputBehavior : SchedulerInputBehavior -{ - public MySchedulerInputBehavior(RadScheduler scheduler) - : base(scheduler) - { - } - public override bool HandleKeyDown(KeyEventArgs args) - { - bool isControl = (args.Modifiers & Keys.Control) == Keys.Control; - IEvent selectedAppointment = this.Scheduler.SelectionBehavior.SelectedAppointment; - if (isControl && selectedAppointment != null) - { - if ((args.KeyData & Keys.Up) == Keys.Up) - { - selectedAppointment.Start = selectedAppointment.Start.AddHours(-1); - selectedAppointment.End = selectedAppointment.End.AddHours(-1); - } - else if ((args.KeyData & Keys.Down) == Keys.Down) - { - selectedAppointment.Start = selectedAppointment.Start.AddHours(1); - selectedAppointment.End = selectedAppointment.End.AddHours(1); - } - } - return base.HandleKeyDown(args); - } -} - -```` -````VB.NET -Public Class MySchedulerInputBehavior - Inherits SchedulerInputBehavior - Public Sub New(scheduler As RadScheduler) - MyBase.New(scheduler) - End Sub - Public Overrides Function HandleKeyDown(args As KeyEventArgs) As Boolean - Dim isControl As Boolean = (args.Modifiers And Keys.Control) = Keys.Control - Dim selectedAppointment As IEvent = Me.Scheduler.SelectionBehavior.SelectedAppointment - If isControl AndAlso selectedAppointment IsNot Nothing Then - If (args.KeyData And Keys.Up) = Keys.Up Then - selectedAppointment.Start = selectedAppointment.Start.AddHours(-1) - selectedAppointment.[End] = selectedAppointment.[End].AddHours(-1) - ElseIf (args.KeyData And Keys.Down) = Keys.Down Then - selectedAppointment.Start = selectedAppointment.Start.AddHours(1) - selectedAppointment.[End] = selectedAppointment.[End].AddHours(1) - End If - End If - Return MyBase.HandleKeyDown(args) - End Function -End Class - -```` - -{{endregion}} + + -Now we need to assign this new input behavior to the __SchedulerInputBehavior__ property of __RadScheduler__: -#### Set Behavior -{{source=..\SamplesCS\Scheduler\Fundamentals\InputBehavior.cs region=SetBehavior}} -{{source=..\SamplesVB\Scheduler\Fundamentals\InputBehavior.vb region=SetBehavior}} +Now we need to assign this new input behavior to the __SchedulerInputBehavior__ property of __RadScheduler__: -````C# -scheduler.SchedulerInputBehavior = new MySchedulerInputBehavior(scheduler); +#### Set Behavior -```` -````VB.NET -scheduler.SchedulerInputBehavior = New MySchedulerInputBehavior(scheduler) + + -```` -{{endregion}} You can see the result below: diff --git a/controls/scheduler/fundamentals/scheduler-element-provider-.md b/controls/scheduler/fundamentals/scheduler-element-provider-.md index eb87f55fb..79854d63f 100644 --- a/controls/scheduler/fundamentals/scheduler-element-provider-.md +++ b/controls/scheduler/fundamentals/scheduler-element-provider-.md @@ -20,145 +20,19 @@ If you need to customize any of the __RadSheduler__ elements you can use the __ #### Custom Element Provider -{{source=..\SamplesCS\Scheduler\Fundamentals\SchedulerElementProviderSample.cs region=SchedulerElementProvider}} -{{source=..\SamplesVB\Scheduler\Fundamentals\SchedulerElementProviderSample.vb region=SchedulerElementProvider}} - -````C# -public class MyElementProvider : SchedulerElementProvider -{ - public MyElementProvider(RadScheduler scheduler) - : base(scheduler) - { - } - protected override T CreateElement(SchedulerView view, object context) - { - if (typeof(T) == typeof(AppointmentElement)) - { - return new MyAppointmentElement(this.Scheduler, view, (IEvent)context) as T; - } - if (typeof(T) == typeof(SchedulerCellElement)) - { - return new MySchedulerCellElement(this.Scheduler, view) as T; - } - return base.CreateElement(view, context); - } - public override RulerPrimitive CreateRulerPrimitive(DayViewAppointmentsArea area, SchedulerTimeZone timeZone) - { - return new MyRulerPrimitive(this.Scheduler, area); - } -} - -```` -````VB.NET -Public Class MyElementProvider - Inherits SchedulerElementProvider - Public Sub New(scheduler As RadScheduler) - MyBase.New(scheduler) - End Sub - Protected Overrides Function CreateElement(Of T As SchedulerVisualElement)(view As SchedulerView, context As Object) As T - If GetType(T) = GetType(AppointmentElement) Then - Return TryCast(New MyAppointmentElement(Me.Scheduler, view, DirectCast(context, IEvent)), T) - End If - If GetType(T) = GetType(SchedulerCellElement) Then - Return TryCast(New MySchedulerCellElement(Me.Scheduler, view), T) - End If - Return MyBase.CreateElement(Of T)(view, context) - End Function - Public Overrides Function CreateRulerPrimitive(area As DayViewAppointmentsArea, timeZone As SchedulerTimeZone) As RulerPrimitive - Return New MyRulerPrimitive(Me.Scheduler, area) - End Function -End Class - -```` - -{{endregion}} + + + + Your custom elements should be inherit of the default ones. For example, you can create custom elements and override some of their default properties. #### Custom Cells -{{source=..\SamplesCS\Scheduler\Fundamentals\SchedulerElementProviderSample.cs region=elements}} -{{source=..\SamplesVB\Scheduler\Fundamentals\SchedulerElementProviderSample.vb region=elements}} - -````C# -public class MySchedulerCellElement : SchedulerCellElement -{ - public MySchedulerCellElement(RadScheduler scheduler, SchedulerView view) - : base(scheduler, view) - { - } - protected override void InitializeFields() - { - base.InitializeFields(); - this.BorderWidth = 2; - this.BackColor = ColorTranslator.FromHtml("#f5e020"); - this.Text = "Text"; - } -} -public class MyAppointmentElement : AppointmentElement -{ - public MyAppointmentElement(RadScheduler scheduler, SchedulerView view, IEvent appointment) - : base(scheduler, view, appointment) - { - } - protected override void InitializeAppointment() - { - base.InitializeAppointment(); - this.BackColor = ColorTranslator.FromHtml("#91c930"); - this.BackColor2 = ColorTranslator.FromHtml("#51ab2e"); - this.SelectedBorderColor = ColorTranslator.FromHtml("#005Bbc"); - } -} -public class MyRulerPrimitive : RulerPrimitive -{ - public MyRulerPrimitive(RadScheduler scheduler, DayViewAppointmentsArea area) - : base(scheduler, area) - { - this.BackColor = ColorTranslator.FromHtml("#91c930"); - this.Font = new Font("Segoe Script", 12, FontStyle.Underline); - this.ForeColor = ColorTranslator.FromHtml("#bb2525"); - } -} - -```` -````VB.NET -Public Class MySchedulerCellElement - Inherits SchedulerCellElement - Public Sub New(scheduler As RadScheduler, view As SchedulerView) - MyBase.New(scheduler, view) - End Sub - Protected Overrides Sub InitializeFields() - MyBase.InitializeFields() - Me.BorderWidth = 2 - Me.BackColor = ColorTranslator.FromHtml("#f5e020") - Me.Text = "Text" - End Sub -End Class -Public Class MyAppointmentElement - Inherits AppointmentElement - Public Sub New(scheduler As RadScheduler, view As SchedulerView, appointment As IEvent) - MyBase.New(scheduler, view, appointment) - End Sub - Protected Overrides Sub InitializeAppointment() - MyBase.InitializeAppointment() - Me.BackColor = ColorTranslator.FromHtml("#91c930") - Me.BackColor2 = ColorTranslator.FromHtml("#51ab2e") - Me.SelectedBorderColor = ColorTranslator.FromHtml("#005Bbc") - End Sub -End Class -Public Class MyRulerPrimitive - Inherits RulerPrimitive - Public Sub New(scheduler As RadScheduler, area As DayViewAppointmentsArea) - MyBase.New(scheduler, area) - Me.BackColor = ColorTranslator.FromHtml("#91c930") - Me.Font = New Font("Segoe Script", 12, FontStyle.Underline) - Me.ForeColor = ColorTranslator.FromHtml("#bb2525") - End Sub -End Class - -```` - -{{endregion}} + + + + The following __RadSheduler__ elements can be substituted in the __CreateElement__ method. diff --git a/controls/scheduler/fundamentals/scheduler-ruler.md b/controls/scheduler/fundamentals/scheduler-ruler.md index bb1870675..f2af6489d 100644 --- a/controls/scheduler/fundamentals/scheduler-ruler.md +++ b/controls/scheduler/fundamentals/scheduler-ruler.md @@ -15,178 +15,82 @@ The ruler in __RadScheduler__ is used to show the time intervals of the current The ruler has various properties which can be used to modify its appearance. The examples below demonstrate the various behaviors of the ruler. The ruler can be accessed as follows: -{{source=..\SamplesCS\Scheduler\Fundamentals\Ruler.cs region=GetRuller}} -{{source=..\SamplesVB\Scheduler\Fundamentals\Ruler.vb region=GetRuller}} + + -````C# -RulerPrimitive ruler = (this.scheduler.SchedulerElement.ViewElement as SchedulerDayViewElement).DataAreaElement.Ruler; -```` -````VB.NET -Dim ruler As RulerPrimitive = TryCast(Me.scheduler.SchedulerElement.ViewElement, SchedulerDayViewElement).DataAreaElement.Ruler - -```` - -{{endregion}} >caption Figure 1: RadScheduler Ruler ![WinForms RadScheduler RadScheduler Ruler](images/scheduler-fundamentals-ruler001.png) * __TimePointerStyle__ - Sets the style of the pointer which shows the current time. Can be *Arrow, Line or SimpleLine*. -{{source=..\SamplesCS\Scheduler\Fundamentals\Ruler.cs region=TimePointerStyle}} -{{source=..\SamplesVB\Scheduler\Fundamentals\Ruler.vb region=TimePointerStyle}} - -````C# -ruler.TimePointerStyle = RulerCurrentTimePointer.Arrow; + + -```` -````VB.NET -ruler.TimePointerStyle = RulerCurrentTimePointer.Arrow -```` - -{{endregion}} >caption Figure 2: Time Pointer Style ![WinForms RadScheduler Time Pointer Style](images/scheduler-fundamentals-ruler002.png) * __Start__ and __EndScale__ - Sets the time when the ruler starts and ends. -{{source=..\SamplesCS\Scheduler\Fundamentals\Ruler.cs region=StartEndScale}} -{{source=..\SamplesVB\Scheduler\Fundamentals\Ruler.vb region=StartEndScale}} - -````C# -ruler.StartScale = 2; -ruler.EndScale = 9; + + -```` -````VB.NET -ruler.StartScale = 2 -ruler.EndScale = 9 -```` - -{{endregion}} >caption Figure 3: Start and End Scales ![WinForms RadScheduler Start and End Scales](images/scheduler-fundamentals-ruler003.png) * __RangeFactor__ - The range factor determines whether the units in the ruler will be devided in *FiveMinutes, HalfHour, Hour, QuarterHour, SixMinutes or TenMinutes*. -{{source=..\SamplesCS\Scheduler\Fundamentals\Ruler.cs region=RangeFactor}} -{{source=..\SamplesVB\Scheduler\Fundamentals\Ruler.vb region=RangeFactor}} - -````C# -ruler.RangeFactor = ScaleRange.FiveMinutes; - -```` -````VB.NET -ruler.RangeFactor = ScaleRange.FiveMinutes + + -```` -{{endregion}} >caption Figure 4: Ruler Range ![WinForms RadScheduler Ruler Range](images/scheduler-fundamentals-ruler004.png) * __CurrentTimePointerWidth__ and __CurrentTimePointerColor__ - Sets the size and the color of the pointer which shows the current time. -{{source=..\SamplesCS\Scheduler\Fundamentals\Ruler.cs region=CurrentTimePointerWidthAndColor}} -{{source=..\SamplesVB\Scheduler\Fundamentals\Ruler.vb region=CurrentTimePointerWidthAndColor}} - -````C# -ruler.CurrentTimePointerWidth = 10; -ruler.CurrentTimePointerColor = Color.Red; - -```` -````VB.NET -ruler.CurrentTimePointerWidth = 10 -ruler.CurrentTimePointerColor = Color.Red + + -```` -{{endregion}} >caption Figure 5: Time Pointer Width ![WinForms RadScheduler Time Pointer Width](images/scheduler-fundamentals-ruler005.png) * __RulerFormatStrings__ and the __RulerTextFormatting__ event - They are used to format the text in the ruler. For example here is how to display the hours in a 12 hours format: -{{source=..\SamplesCS\Scheduler\Fundamentals\Ruler.cs region=FormatStrings}} -{{source=..\SamplesVB\Scheduler\Fundamentals\Ruler.vb region=FormatStrings}} + + -````C# -ruler.FormatStrings = new RulerFormatStrings("hh", "mm", "hh", "mm"); -```` -````VB.NET -ruler.FormatStrings = New RulerFormatStrings("hh", "mm", "hh", "mm") - -```` - -{{endregion}} >caption Figure 6: Ruler Format String ![WinForms RadScheduler Ruler Format String](images/scheduler-fundamentals-ruler006.png) The RulerTextFormatting event can be used to manually format the text. You can prepend a "0" in front of the text if it contains only one digit: -{{source=..\SamplesCS\Scheduler\Fundamentals\Ruler.cs region=RulerFormattingSubscribe}} -{{source=..\SamplesVB\Scheduler\Fundamentals\Ruler.vb region=RulerFormattingSubscribe}} - -````C# -this.scheduler.RulerTextFormatting += Scheduler_RulerTextFormatting; - -```` -````VB.NET -AddHandler Me.scheduler.RulerTextFormatting, AddressOf Scheduler_RulerTextFormatting - -```` + + -{{endregion}} -{{source=..\SamplesCS\Scheduler\Fundamentals\Ruler.cs region=RulerFormattingHandler}} -{{source=..\SamplesVB\Scheduler\Fundamentals\Ruler.vb region=RulerFormattingHandler}} + + -````C# -void Scheduler_RulerTextFormatting(object sender, RulerTextFormattingEventArgs e) -{ - if (e.Text.Length == 1) - { - e.Text = "0" + e.Text; - } -} -```` -````VB.NET -Private Sub Scheduler_RulerTextFormatting(sender As Object, e As RulerTextFormattingEventArgs) - If e.Text.Length = 1 Then - e.Text = "0" & e.Text - End If -End Sub - -```` - -{{endregion}} * __RulerWidth__ - Sets the width of the ruler. -{{source=..\SamplesCS\Scheduler\Fundamentals\Ruler.cs region=RulerWidth}} -{{source=..\SamplesVB\Scheduler\Fundamentals\Ruler.vb region=RulerWidth}} - -````C# -ruler.RulerWidth = 100; - -```` -````VB.NET -ruler.RulerWidth = 100 + + -```` -{{endregion}} >caption Figure 7: Ruler Width ![WinForms RadScheduler Ruler Width](images/scheduler-fundamentals-ruler007.png) diff --git a/controls/scheduler/fundamentals/scheduler-selection.md b/controls/scheduler/fundamentals/scheduler-selection.md index 5f0f0dac8..8356801b5 100644 --- a/controls/scheduler/fundamentals/scheduler-selection.md +++ b/controls/scheduler/fundamentals/scheduler-selection.md @@ -55,83 +55,28 @@ The default behavior of the __RadScheduler__ selection can be modified programm #### Custom Selection Class -{{source=..\SamplesCS\Scheduler\Fundamentals\SelectionBehavior.cs region=SchedulerSelectionBehavior}} -{{source=..\SamplesVB\Scheduler\Fundamentals\SelectionBehavior.vb region=SchedulerSelectionBehavior}} + + + -````C# - -public class CustomSchedulerSelectionBehavior : SchedulerSelectionBehavior -{ - public CustomSchedulerSelectionBehavior(RadScheduler scheduler) : base(scheduler) - { - } -} - -```` -````VB.NET -Public Class CustomSchedulerSelectionBehavior -Inherits SchedulerSelectionBehavior - Public Sub New(scheduler As RadScheduler) - MyBase.New(scheduler) - End Sub -End Class - -```` - -{{endregion}} 2\. Override the __SelectAppointment__ method and allow selection only for appointments off work hours: #### Override Method -{{source=..\SamplesCS\Scheduler\Fundamentals\SelectionBehavior.cs region=SelectAppointment}} -{{source=..\SamplesVB\Scheduler\Fundamentals\SelectionBehavior.vb region=SelectAppointment}} + + + -````C# - -public override void SelectAppointment(IEvent appointment, bool extend) -{ - SchedulerDayView dayView = this.Scheduler.GetDayView(); - - if (dayView.IsWorkTime(appointment.Start)) - { - return; - } - base.SelectAppointment(appointment, extend); -} - -```` -````VB.NET -Public Overrides Sub SelectAppointment(appointment As IEvent, extend As Boolean) - Dim dayView As SchedulerDayView = Me.Scheduler.GetDayView() - If dayView.IsWorkTime(appointment.Start) Then - Return - End If - MyBase.SelectAppointment(appointment, extend) -End Sub - -```` - -{{endregion}} 3\. Apply this behavior to the __RadScheduler__: #### Set Behavior -{{source=..\SamplesCS\Scheduler\Fundamentals\SelectionBehavior.cs region=ReplaceSelectionBehavior}} -{{source=..\SamplesVB\Scheduler\Fundamentals\SelectionBehavior.vb region=ReplaceSelectionBehavior}} - -````C# - -this.radScheduler1.SelectionBehavior = new CustomSchedulerSelectionBehavior(this.radScheduler1); - -```` -````VB.NET -Me.RadScheduler1.SelectionBehavior = New CustomSchedulerSelectionBehavior(Me.RadScheduler1) + + -```` -{{endregion}} # See Also diff --git a/controls/scheduler/holidays.md b/controls/scheduler/holidays.md index 0ac7e9d7e..b213ca8fb 100644 --- a/controls/scheduler/holidays.md +++ b/controls/scheduler/holidays.md @@ -40,76 +40,24 @@ The following code snippet demonstrates how to add a holiday. The passed Boolean #### Add a holiday programmatically -{{source=..\SamplesCS\Scheduler\SchedulerHolidays.cs region=AddHolidayProgrammatically}} -{{source=..\SamplesVB\Scheduler\SchedulerHolidays.vb region=AddHolidayProgrammatically}} - -````C# -Holiday holiday = new Holiday(); -holiday.Date = new DateTime(2018, 5, 24); -holiday.HolidayName = "Saints Cyril and Methodius Day"; -holiday.Location = "Bulgaria"; -bool generateAppointment = true; -this.radScheduler1.Holidays.AddHoliday(holiday, generateAppointment); - -```` -````VB.NET -Dim holiday As Holiday = New Holiday() -holiday.Date = New DateTime(2018, 5, 24) -holiday.HolidayName = "Saints Cyril and Methodius Day" -holiday.Location = "Bulgaria" -Dim generateAppointment As Boolean = True -Me.radScheduler1.Holidays.AddHoliday(holiday, generateAppointment) - -```` - -{{endregion}} + + -## Load Holidays from a File -{{source=..\SamplesCS\Scheduler\SchedulerHolidays.cs region=LoadFile}} -{{source=..\SamplesVB\Scheduler\SchedulerHolidays.vb region=LoadFile}} -````C# - -string fileName = @".hol file location"; -bool createAppointment = true; -this.radScheduler1.Holidays.ReadHolidays(fileName, createAppointment); +## Load Holidays from a File -```` -````VB.NET -Dim fileName As String = ".hol file location" -Dim createAppointment As Boolean = True -Me.radScheduler1.Holidays.ReadHolidays(fileName, createAppointment) + + -```` -{{endregion}} ## Load Holidays from a Stream -{{source=..\SamplesCS\Scheduler\SchedulerHolidays.cs region=LoadStream}} -{{source=..\SamplesVB\Scheduler\SchedulerHolidays.vb region=LoadStream}} - -````C# - -string fileToRead = @".hol file location"; -bool generateAppointment = true; -using (System.IO.Stream fileStream = File.OpenRead(fileToRead)) -{ - this.radScheduler1.Holidays.ReadHolidays(fileStream, generateAppointment); -} - -```` -````VB.NET -Dim fileToRead As String = ".hol file location" -Dim generateAppointment As Boolean = True -Using fileStream As System.IO.Stream = File.OpenRead(fileToRead) - Me.radScheduler1.Holidays.ReadHolidays(fileStream, generateAppointment) -End Using + + -```` -{{endregion}} ## Formatting Holidays @@ -121,70 +69,8 @@ End Using #### Formatting the holidays -{{source=..\SamplesCS\Scheduler\SchedulerHolidays.cs region=HolidaysFormatting}} -{{source=..\SamplesVB\Scheduler\SchedulerHolidays.vb region=HolidaysFormatting}} - -````C# -private void radScheduler1_CellFormatting(object sender, SchedulerCellEventArgs e) -{ - if (!(e.CellElement is SchedulerHeaderCellElement)) - { - if (this.radScheduler1.Holidays.IsHoliday(e.CellElement.Date)) - { - string s = string.Empty; - foreach (var item in radScheduler1.Holidays.GetHolidays(e.CellElement.Date).OrderBy(ae => ae.HolidayName)) - { - if (!s.Contains(item.HolidayName)) - s += item.HolidayName + Environment.NewLine; - } - e.CellElement.DrawText = true; - e.CellElement.Text = s.ToString(); - e.CellElement.TextWrap = true; - e.CellElement.TextAlignment = ContentAlignment.BottomCenter; - Padding padding = e.CellElement.Padding; - if (this.radScheduler1.ActiveViewType == SchedulerViewType.Month) - padding.Bottom = 22; - e.CellElement.Padding = padding; - if (radScheduler1.Holidays.GetHolidays(e.CellElement.Date).Where(l => l.Location == "Bulgaria").Any()) - e.CellElement.BackColor = Color.LightGreen; - else - e.CellElement.BackColor = Color.Orange; - } - else - { - e.CellElement.DrawText = false; - e.CellElement.ResetValue(RadItem.BackColorProperty, ValueResetFlags.Local); - } - } -} - -```` -````VB.NET -Private Sub radScheduler1_CellFormatting(ByVal sender As Object, ByVal e As SchedulerCellEventArgs) - If Not (TypeOf e.CellElement Is SchedulerHeaderCellElement) Then - If Me.radScheduler1.Holidays.IsHoliday(e.CellElement.Date) Then - Dim s As String = String.Empty - For Each item In radScheduler1.Holidays.GetHolidays(e.CellElement.Date).OrderBy(Function(ae) ae.HolidayName) - If Not s.Contains(item.HolidayName) Then s += item.HolidayName + Environment.NewLine - Next - e.CellElement.DrawText = True - e.CellElement.Text = s.ToString() - e.CellElement.TextWrap = True - e.CellElement.TextAlignment = ContentAlignment.BottomCenter - Dim padding As Padding = e.CellElement.Padding - If Me.radScheduler1.ActiveViewType = SchedulerViewType.Month Then padding.Bottom = 22 - e.CellElement.Padding = padding - If radScheduler1.Holidays.GetHolidays(e.CellElement.Date).Where(Function(l) l.Location = "Bulgaria").Any() Then e.CellElement.BackColor = Color.LightGreen Else e.CellElement.BackColor = Color.Orange - Else - e.CellElement.DrawText = False - e.CellElement.ResetValue(RadItem.BackColorProperty, ValueResetFlags.Local) - End If - End If -End Sub - -```` - -{{endregion}} + + diff --git a/controls/scheduler/how-to/loading-data-for-selected-day-only.md b/controls/scheduler/how-to/loading-data-for-selected-day-only.md index 536565df7..3ee6f90f4 100644 --- a/controls/scheduler/how-to/loading-data-for-selected-day-only.md +++ b/controls/scheduler/how-to/loading-data-for-selected-day-only.md @@ -18,38 +18,10 @@ The article provides an example how data for the selected day when loading RadSc 1. Check in it whether the __StartDate__ property has changed. If the __PropertyName__ property of the argument is the name of the __StartDate__ property, load the data: -{{source=..\SamplesCS\Scheduler\HowTo\LoadingData.cs region=propertyChanged}} -{{source=..\SamplesVB\Scheduler\HowTo\LoadingData.vb region=propertyChanged}} - -````C# -public LoadingData() -{ - InitializeComponent(); - this.radScheduler1.ActiveView.PropertyChanged += new PropertyChangedEventHandler(ActiveView_PropertyChanged); -} -void ActiveView_PropertyChanged(object sender, PropertyChangedEventArgs e) -{ - if (e.PropertyName == "StartDate") - { - //load the data here - } -} - -```` -````VB.NET -Public Sub New() - InitializeComponent() - AddHandler Me.RadScheduler1.ActiveView.PropertyChanged, AddressOf ActiveView_PropertyChanged -End Sub -Sub ActiveView_PropertyChanged(ByVal sender As Object, ByVal e As PropertyChangedEventArgs) - 'load the data here - If e.PropertyName = "StartDate" Then - End If -End Sub - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/scheduler/importing-and-exporting-appointments/export-to-a-custom-file.md b/controls/scheduler/importing-and-exporting-appointments/export-to-a-custom-file.md index 99f0784e9..54e458ef5 100644 --- a/controls/scheduler/importing-and-exporting-appointments/export-to-a-custom-file.md +++ b/controls/scheduler/importing-and-exporting-appointments/export-to-a-custom-file.md @@ -15,101 +15,17 @@ In order to import/export the scheduler appointments to a custom file you should 1\. Create custom classes for import and export: -{{source=..\SamplesCS\Scheduler\ImportExport\CustomImporterExporter.cs region=importExport}} -{{source=..\SamplesVB\Scheduler\ImportExport\CustomImporterExporter.vb region=importExport}} + + -````C# -public class CustomImporter : ISchedulerImporter -{ - public void Import(ISchedulerData data, string stringData) - { - //TODO Parse the string data and fill - //data.GetEventStorage().Add( created event ); - } - public void Import(ISchedulerData data, System.IO.Stream stream) - { - //TODO Read stream - //data.GetEventStorage().Add( created event ); - } -} -public class CustomExporter : ISchedulerExporter -{ - public string Export(ISchedulerData data) - { - string result = string.Empty; - //Save events to string value - //data.GetEventStorage(); - return all events - return result; - } - public void Export(ISchedulerData data, System.IO.Stream stream) - { - //Save events to the stream - //data.GetEventStorage(); - return all events - } -} -```` -````VB.NET -Public Class CustomImporter - Implements ISchedulerImporter - Public Sub Import(ByVal data As ISchedulerData, ByVal stringData As String) Implements ISchedulerImporter.Import - 'TODO Parse the string data and fill - 'data.GetEventStorage().Add( created event ); - End Sub - Public Sub Import(ByVal data As ISchedulerData, ByVal stream As System.IO.Stream) Implements ISchedulerImporter.Import - 'TODO Read stream - 'data.GetEventStorage().Add( created event ); - End Sub -End Class -Public Class CustomExporter - Implements ISchedulerExporter - Public Function Export(ByVal data As ISchedulerData) As String Implements ISchedulerExporter.Export - Dim result As String = String.Empty - 'Save events to string value - 'data.GetEventStorage(); - return all events - Return result - End Function - Public Sub Export(ByVal data As ISchedulerData, ByVal stream As System.IO.Stream) Implements ISchedulerExporter.Export - 'Save events to the stream - 'data.GetEventStorage(); - return all events - End Sub -End Class - -```` - -{{endregion}} 2\. Then you need to pass the instances of these classes to the Import and Export methods of the scheduler: -{{source=..\SamplesCS\Scheduler\ImportExport\ImEx.cs region=imEx}} -{{source=..\SamplesVB\Scheduler\ImportExport\ImEx.vb region=imEx}} - -````C# -//Import -using (FileStream fileStream = File.Create("file name")) -{ - this.radScheduler1.Import(fileStream, new CustomImporter()); -} -//Export -using (FileStream fileStream = File.Create("file name")) -{ - this.radScheduler1.Export(fileStream, new CustomExporter()); -} - -```` -````VB.NET -'Import -Using fileStream As FileStream = File.Create("file name") - Me.RadScheduler1.Import(fileStream, New CustomImporter()) -End Using -'Export -Using fileStream As FileStream = File.Create("file name") - Me.RadScheduler1.Export(fileStream, New CustomExporter()) -End Using + + -```` -{{endregion}} # See Also diff --git a/controls/scheduler/importing-and-exporting-appointments/export-to-icalendar.md b/controls/scheduler/importing-and-exporting-appointments/export-to-icalendar.md index 16268c0ec..ee4edc062 100644 --- a/controls/scheduler/importing-and-exporting-appointments/export-to-icalendar.md +++ b/controls/scheduler/importing-and-exporting-appointments/export-to-icalendar.md @@ -15,42 +15,19 @@ __RadScheduler__ allows you to export appointments in the industry-standard ICal #### Export to String -{{source=..\SamplesCS\Scheduler\ImportExport\ImEx.cs region=iCalExport}} -{{source=..\SamplesVB\Scheduler\ImportExport\ImEx.vb region=iCalExport}} + + -````C# -string exportResult = this.radScheduler1.Export(new SchedulerICalendarExporter()); -```` -````VB.NET -Dim exportResult As String = Me.RadScheduler1.Export(New SchedulerICalendarExporter) - -```` - -{{endregion}} Another override of the __Export__ method allows writing the appointment data to a Stream. The following example demonstrates how easy it is to export the appointment data contained in a RadScheduler instance to a file: #### Export to Stream -{{source=..\SamplesCS\Scheduler\ImportExport\ImEx.cs region=iCalEFile}} -{{source=..\SamplesVB\Scheduler\ImportExport\ImEx.vb region=iCalEFile}} - -````C# -using (FileStream stream = File.Create("schedule.ics")) -{ - this.radScheduler1.Export(stream, new SchedulerICalendarExporter()); -} - -```` -````VB.NET -Using stream As FileStream = File.Create("schedule.ics") - Me.RadScheduler1.Export(stream, New SchedulerICalendarExporter) -End Using + + -```` -{{endregion}} # See Also diff --git a/controls/scheduler/importing-and-exporting-appointments/import-from-icalendar.md b/controls/scheduler/importing-and-exporting-appointments/import-from-icalendar.md index 4195fc566..1926fbbb6 100644 --- a/controls/scheduler/importing-and-exporting-appointments/import-from-icalendar.md +++ b/controls/scheduler/importing-and-exporting-appointments/import-from-icalendar.md @@ -15,44 +15,19 @@ __RadScheduler__ allows you to import appointments from the industry-standard IC #### Import with String -{{source=..\SamplesCS\Scheduler\ImportExport\ImEx.cs region=iCalImport}} -{{source=..\SamplesVB\Scheduler\ImportExport\ImEx.vb region=iCalImport}} + + -````C# -string importString = "ICalendar string format"; -this.radScheduler1.Import(importString, new SchedulerICalendarImporter()); -```` -````VB.NET -Dim importResult As String = "ICalendar string format" -Me.RadScheduler1.Import(importResult, New SchedulerICalendarImporter) - -```` - -{{endregion}} Another override of the __Import__ method allows you to read appointment data from a Stream: #### Import with Stream -{{source=..\SamplesCS\Scheduler\ImportExport\ImEx.cs region=iCalIFile}} -{{source=..\SamplesVB\Scheduler\ImportExport\ImEx.vb region=iCalIFile}} - -````C# -using (FileStream stream = File.OpenRead("schedule.ics")) -{ - this.radScheduler1.Import(stream, new SchedulerICalendarImporter()); -} - -```` -````VB.NET -Using stream As FileStream = File.OpenRead("schedule.ics") - Me.RadScheduler1.Import(stream, New SchedulerICalendarImporter) -End Using + + -```` -{{endregion}} # See Also diff --git a/controls/scheduler/localization/localizing-dialog-strings.md b/controls/scheduler/localization/localizing-dialog-strings.md index 2c7e6df08..7fd917d86 100644 --- a/controls/scheduler/localization/localizing-dialog-strings.md +++ b/controls/scheduler/localization/localizing-dialog-strings.md @@ -15,56 +15,10 @@ __RadScheduler__ has a built-in LocalizationProvider. You can use it in order to #### Localizing the EditAppointmentDialog -{{source=..\SamplesCS\Scheduler\Localization\LocAppointmentEditForm.cs region=localizeDialog}} -{{source=..\SamplesVB\Scheduler\Localization\LocAppointmentEditForm.vb region=localizeDialog}} + + -````C# -public class LocAppointmentEditForm : EditAppointmentDialog -{ - protected override void LocalizeDialog(RadSchedulerLocalizationProvider localizationProvider) - { - this.Text = localizationProvider.GetLocalizedString(RadSchedulerStringId.AppointmentDialogTitle); - this.labelSubject.Text = localizationProvider.GetLocalizedString(RadSchedulerStringId.AppointmentDialogSubject); - this.labelLocation.Text = localizationProvider.GetLocalizedString(RadSchedulerStringId.AppointmentDialogLocation); - this.labelBackground.Text = localizationProvider.GetLocalizedString(RadSchedulerStringId.AppointmentDialogBackground); - this.labelStartTime.Text = localizationProvider.GetLocalizedString(RadSchedulerStringId.AppointmentDialogStartTime); - this.labelEndTime.Text = localizationProvider.GetLocalizedString(RadSchedulerStringId.AppointmentDialogEndTime); - this.chkAllDay.Text = localizationProvider.GetLocalizedString(RadSchedulerStringId.AppointmentDialogAllDay); - this.labelResource.Text = localizationProvider.GetLocalizedString(RadSchedulerStringId.AppointmentDialogResource); - this.labelStatus.Text = localizationProvider.GetLocalizedString(RadSchedulerStringId.AppointmentDialogStatus); - this.buttonOK.Text = localizationProvider.GetLocalizedString(RadSchedulerStringId.AppointmentDialogOK); - this.buttonCancel.Text = localizationProvider.GetLocalizedString(RadSchedulerStringId.AppointmentDialogCancel); - this.buttonDelete.Text = localizationProvider.GetLocalizedString(RadSchedulerStringId.AppointmentDialogDelete); - this.buttonRecurrence.Text = localizationProvider.GetLocalizedString(RadSchedulerStringId.AppointmentDialogRecurrence); - this.radLabelReminder.Text = localizationProvider.GetLocalizedString(RadSchedulerStringId.Reminder); - } -} -```` -````VB.NET -Public Class LocAppointmentEditForm - Inherits EditAppointmentDialog - Protected Overloads Overrides Sub LocalizeDialog(ByVal localizationProvider As RadSchedulerLocalizationProvider) - Me.Text = localizationProvider.GetLocalizedString(RadSchedulerStringId.AppointmentDialogTitle) - Me.labelSubject.Text = localizationProvider.GetLocalizedString(RadSchedulerStringId.AppointmentDialogSubject) - Me.labelLocation.Text = localizationProvider.GetLocalizedString(RadSchedulerStringId.AppointmentDialogLocation) - Me.labelBackground.Text = localizationProvider.GetLocalizedString(RadSchedulerStringId.AppointmentDialogBackground) - Me.labelStartTime.Text = localizationProvider.GetLocalizedString(RadSchedulerStringId.AppointmentDialogStartTime) - Me.labelEndTime.Text = localizationProvider.GetLocalizedString(RadSchedulerStringId.AppointmentDialogEndTime) - Me.chkAllDay.Text = localizationProvider.GetLocalizedString(RadSchedulerStringId.AppointmentDialogAllDay) - Me.labelResource.Text = localizationProvider.GetLocalizedString(RadSchedulerStringId.AppointmentDialogResource) - Me.labelStatus.Text = localizationProvider.GetLocalizedString(RadSchedulerStringId.AppointmentDialogStatus) - Me.buttonOK.Text = localizationProvider.GetLocalizedString(RadSchedulerStringId.AppointmentDialogOK) - Me.buttonCancel.Text = localizationProvider.GetLocalizedString(RadSchedulerStringId.AppointmentDialogCancel) - Me.buttonDelete.Text = localizationProvider.GetLocalizedString(RadSchedulerStringId.AppointmentDialogDelete) - Me.buttonRecurrence.Text = localizationProvider.GetLocalizedString(RadSchedulerStringId.AppointmentDialogRecurrence) - Me.radLabelReminder.Text = localizationProvider.GetLocalizedString(RadSchedulerStringId.Reminder) - End Sub -End Class - -```` - -{{endregion}} # See Also diff --git a/controls/scheduler/localization/localizing-scheduler-navigator.md b/controls/scheduler/localization/localizing-scheduler-navigator.md index 85abd908c..e083a4947 100644 --- a/controls/scheduler/localization/localizing-scheduler-navigator.md +++ b/controls/scheduler/localization/localizing-scheduler-navigator.md @@ -15,113 +15,19 @@ The __RadSchedulerNavigator__ control uses the __SchedulerNavigatorLocalizationP #### Custom Localization Provider -{{source=..\SamplesCS\Scheduler\Localization\CustomNavigatorLocalizationProvider.cs region=navigatorProvider}} -{{source=..\SamplesVB\Scheduler\Localization\CustomNavigatorLocalizationProvider.vb region=navigatorProvider}} + + -````C# -public class CustomSchedulerNavigatorLocalizationProvider : SchedulerNavigatorLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case SchedulerNavigatorStringId.DayViewButtonCaption: - { - return "Day View"; - } - case SchedulerNavigatorStringId.WeekViewButtonCaption: - { - return "Week View"; - } - case SchedulerNavigatorStringId.MonthViewButtonCaption: - { - return "Month View"; - } - case SchedulerNavigatorStringId.TimelineViewButtonCaption: - { - return "Timeline View"; - } - case SchedulerNavigatorStringId.AgendaViewButtonCaption: - { - return "Agenda View"; - } - case SchedulerNavigatorStringId.ShowWeekendCheckboxCaption: - { - return "Show Weekend"; - } - case SchedulerNavigatorStringId.TodayButtonCaptionToday: - { - return "Today"; - } - case SchedulerNavigatorStringId.TodayButtonCaptionThisWeek: - { - return "This week"; - } - case SchedulerNavigatorStringId.TodayButtonCaptionThisMonth: - { - return "This month"; - } - case SchedulerNavigatorStringId.SearchInAppointments: - { - return "Search In Appointments"; - } - } - return String.Empty; - } -} -```` -````VB.NET -Public Class CustomSchedulerNavigatorLocalizationProvider - Inherits SchedulerNavigatorLocalizationProvider - Public Overrides Function GetLocalizedString(ByVal id As String) As String - Select Case id - Case SchedulerNavigatorStringId.DayViewButtonCaption - Return "Day View" - Case SchedulerNavigatorStringId.WeekViewButtonCaption - Return "Week View" - Case SchedulerNavigatorStringId.MonthViewButtonCaption - Return "Month View" - Case SchedulerNavigatorStringId.TimelineViewButtonCaption - Return "Timeline View" - Case SchedulerNavigatorStringId.AgendaViewButtonCaption - Return "Agenda View" - Case SchedulerNavigatorStringId.ShowWeekendCheckboxCaption - Return "Show Weekend" - Case SchedulerNavigatorStringId.TodayButtonCaptionToday - Return "Today" - Case SchedulerNavigatorStringId.TodayButtonCaptionThisWeek - Return "This week" - Case SchedulerNavigatorStringId.TodayButtonCaptionThisMonth - Return "This month" - Case SchedulerNavigatorStringId.SearchInAppointments - Return "Search In Appointments" - End Select - Return String.Empty - End Function -End Class - -```` - -{{endregion}} In order to utilize the new Localization Provider, you should create an instance of the new provider and assign it to the static __CurrentProvider__ property of __SchedulerNavigatorLocalizationProvider__ class: #### Change the Current Provider -{{source=..\SamplesCS\Scheduler\Localization\AssignProviders.cs region=assignNavigatorProvider}} -{{source=..\SamplesVB\Scheduler\Localization\AssignProviders.vb region=assignNavigatorProvider}} - -````C# -SchedulerNavigatorLocalizationProvider.CurrentProvider = new CustomSchedulerNavigatorLocalizationProvider(); - -```` -````VB.NET -SchedulerNavigatorLocalizationProvider.CurrentProvider = New CustomSchedulerNavigatorLocalizationProvider() + + -```` -{{endregion}} # See Also diff --git a/controls/scheduler/localization/right-to-left-support.md b/controls/scheduler/localization/right-to-left-support.md index 6867c44b6..4304daf86 100644 --- a/controls/scheduler/localization/right-to-left-support.md +++ b/controls/scheduler/localization/right-to-left-support.md @@ -15,19 +15,10 @@ Enabling the RightToLeft mode of RadScheduler is achieved by setting the __Right #### Right-to-Left Layout -{{source=..\SamplesCS\Scheduler\Localization\SchedulerRightToLeft.cs region=RTL}} -{{source=..\SamplesVB\Scheduler\Localization\SchedulerRightToLeft.vb region=RTL}} + + -````C# -radScheduler1.RightToLeft = System.Windows.Forms.RightToLeft.Yes; -```` -````VB.NET -RadScheduler1.RightToLeft = System.Windows.Forms.RightToLeft.Yes - -```` - -{{endregion}} Here is how your scheduler will look like in this mode: diff --git a/controls/scheduler/localization/translating-strings.md b/controls/scheduler/localization/translating-strings.md index 488dfa3c5..bb657b575 100644 --- a/controls/scheduler/localization/translating-strings.md +++ b/controls/scheduler/localization/translating-strings.md @@ -1,605 +1,45 @@ ---- -title: Localizing RadScheduler -page_title: Localizing RadScheduler - WinForms Scheduler Control -description: To localize WinForms Scheduler to display control text and messages in a specific language create a descendant of the RadSchedulerLocalizationProvider class. -slug: winforms/scheduler/localization/translating-strings -tags: translating,strings -published: True -position: 0 -previous_url: scheduler-localization-translating-strings ---- - -# Localizing RadScheduler - -To localize __RadScheduler__ to display control text and messages in a specific language: - -* All required classes for localization are defined in __Telerik.WinControls.UI.Localization__ namespace. - -* Start by creating a descendant of the __RadSchedulerLocalizationProvider__ class. - -* Override the __GetLocalizedString(string id)__ method and provide a translation for the messages. If a translation is not provided, the default value will be returned. This behavior is guaranteed by the call to the base __GetLocalizedString__ method in the default clause of the switch statement in the example. - -Below is a sample implementation of a custom localization provider: - -#### Custom Localization Provider - -{{source=..\SamplesCS\Scheduler\Localization\CustomSchedulerLocalizationProvider.cs region=schedulerProvider}} -{{source=..\SamplesVB\Scheduler\Localization\CustomSchedulerLocalizationProvider.vb region=schedulerProvider}} - -````C# -public class CustomSchedulerLocalizationProvider : RadSchedulerLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case RadSchedulerStringId.NextAppointment: return "Next Appointment"; - case RadSchedulerStringId.PreviousAppointment: return "Previous Appointment"; - case RadSchedulerStringId.AppointmentDialogTitle: return "Edit Appointment"; - case RadSchedulerStringId.AppointmentDialogSubject: return "Subject:"; - case RadSchedulerStringId.AppointmentDialogLocation: return "Location:"; - case RadSchedulerStringId.AppointmentDialogBackground: return "Background:"; - case RadSchedulerStringId.AppointmentDialogDescription: return "Description:"; - case RadSchedulerStringId.AppointmentDialogStartTime: return "Start time:"; - case RadSchedulerStringId.AppointmentDialogEndTime: return "End time:"; - case RadSchedulerStringId.AppointmentDialogAllDay: return "All day event"; - case RadSchedulerStringId.AppointmentDialogResource: return "Resource:"; - case RadSchedulerStringId.AppointmentDialogStatus: return "Show time as:"; - case RadSchedulerStringId.AppointmentDialogOK: return "OK"; - case RadSchedulerStringId.AppointmentDialogCancel: return "Cancel"; - case RadSchedulerStringId.AppointmentDialogDelete: return "Delete"; - case RadSchedulerStringId.AppointmentDialogRecurrence: return "Recurrence"; - case RadSchedulerStringId.OpenRecurringDialogTitle: return "Open Recurring Item"; - case RadSchedulerStringId.DeleteRecurrenceDialogOK: return "OK"; - case RadSchedulerStringId.OpenRecurringDialogOK: return "OK"; - case RadSchedulerStringId.DeleteRecurrenceDialogCancel: return "Cancel"; - case RadSchedulerStringId.OpenRecurringDialogCancel: return "Cancel"; - case RadSchedulerStringId.OpenRecurringDialogLabel: return "\"{0}\" is a recurring\nappointment. Do you want to open\nonly this occurrence or the series?"; - case RadSchedulerStringId.OpenRecurringDialogRadioOccurrence: return "Open this occurrence."; - case RadSchedulerStringId.OpenRecurringDialogRadioSeries: return "Open the series."; - case RadSchedulerStringId.DeleteRecurrenceDialogTitle: return "Confirm Delete"; - case RadSchedulerStringId.DeleteRecurrenceDialogRadioOccurrence: return "Delete this occurrence."; - case RadSchedulerStringId.DeleteRecurrenceDialogRadioSeries: return "Delete the series."; - case RadSchedulerStringId.DeleteRecurrenceDialogLabel: return "Do you want to delete all occurrences of the recurring appointment \"{0}\", or just this one?"; - case RadSchedulerStringId.RecurrenceDragDropCreateExceptionDialogText: return "You changed the date of a single occurrence of a recurring appointment. To change all the dates, open the series.\nDo you want to change just this one?"; - case RadSchedulerStringId.RecurrenceDragDropValidationSameDateText: return "Two occurrences of the same series cannot occur on the same day."; - case RadSchedulerStringId.RecurrenceDragDropValidationSkipOccurrenceText: return "Cannot reschedule an occurrence of a recurring appointment if it skips over a later occurrence of the same appointment."; - case RadSchedulerStringId.RecurrenceDialogMessageBoxText: return "Start date should be before EndBy date."; - case RadSchedulerStringId.RecurrenceDialogMessageBoxWrongRecurrenceRuleText: return "The recurrence pattern is not valid."; - case RadSchedulerStringId.RecurrenceDialogMessageBoxTitle: return "Validation error"; - case RadSchedulerStringId.RecurrenceDialogTitle: return "Edit Recurrence"; - case RadSchedulerStringId.RecurrenceDialogAppointmentTimeGroup: return "Appointment time"; - case RadSchedulerStringId.RecurrenceDialogDuration: return "Duration:"; - case RadSchedulerStringId.RecurrenceDialogAppointmentEnd: return "End:"; - case RadSchedulerStringId.RecurrenceDialogAppointmentStart: return "Start:"; - case RadSchedulerStringId.RecurrenceDialogRecurrenceGroup: return "Recurrence pattern"; - case RadSchedulerStringId.RecurrenceDialogRangeGroup: return "Range of recurrence"; - case RadSchedulerStringId.RecurrenceDialogOccurrences: return "occurrences"; - case RadSchedulerStringId.RecurrenceDialogRecurrenceStart: return "Start:"; - case RadSchedulerStringId.RecurrenceDialogYearly: return "Yearly"; - case RadSchedulerStringId.RecurrenceDialogHourly: return "Hourly"; - case RadSchedulerStringId.RecurrenceDialogMonthly: return "Monthly"; - case RadSchedulerStringId.RecurrenceDialogWeekly: return "Weekly"; - case RadSchedulerStringId.RecurrenceDialogDaily: return "Daily"; - case RadSchedulerStringId.RecurrenceDialogEndBy: return "End by:"; - case RadSchedulerStringId.RecurrenceDialogEndAfter: return "End after:"; - case RadSchedulerStringId.RecurrenceDialogNoEndDate: return "No end date"; - case RadSchedulerStringId.RecurrenceDialogAllDay: return "All day event"; - case RadSchedulerStringId.RecurrenceDialogDurationDropDown1Day: return "1 day"; - case RadSchedulerStringId.RecurrenceDialogDurationDropDown2Days: return "2 days"; - case RadSchedulerStringId.RecurrenceDialogDurationDropDown3Days: return "3 days"; - case RadSchedulerStringId.RecurrenceDialogDurationDropDown4Days: return "4 days"; - case RadSchedulerStringId.RecurrenceDialogDurationDropDown1Week: return "1 week"; - case RadSchedulerStringId.RecurrenceDialogDurationDropDown2Weeks: return "2 weeks"; - case RadSchedulerStringId.RecurrenceDialogOK: return "OK"; - case RadSchedulerStringId.RecurrenceDialogCancel: return "Cancel"; - case RadSchedulerStringId.RecurrenceDialogRemoveRecurrence: return "Remove Recurrence"; - case RadSchedulerStringId.HourlyRecurrenceEvery: return "Every"; - case RadSchedulerStringId.HourlyRecurrenceHours: return "hour(s)"; - case RadSchedulerStringId.DailyRecurrenceEveryDay: return "Every"; - case RadSchedulerStringId.DailyRecurrenceEveryWeekday: return "Every weekday"; - case RadSchedulerStringId.DailyRecurrenceDays: return "day(s)"; - case RadSchedulerStringId.WeeklyRecurrenceRecurEvery: return "Recur every"; - case RadSchedulerStringId.WeeklyRecurrenceWeeksOn: return "week(s) on:"; - case RadSchedulerStringId.WeeklyRecurrenceSunday: return "Sunday"; - case RadSchedulerStringId.WeeklyRecurrenceMonday: return "Monday"; - case RadSchedulerStringId.WeeklyRecurrenceTuesday: return "Tuesday"; - case RadSchedulerStringId.WeeklyRecurrenceWednesday: return "Wednesday"; - case RadSchedulerStringId.WeeklyRecurrenceThursday: return "Thursday"; - case RadSchedulerStringId.WeeklyRecurrenceFriday: return "Friday"; - case RadSchedulerStringId.WeeklyRecurrenceSaturday: return "Saturday"; - case RadSchedulerStringId.WeeklyRecurrenceDay: return "Day"; - case RadSchedulerStringId.WeeklyRecurrenceWeekday: return "Weekday"; - case RadSchedulerStringId.WeeklyRecurrenceWeekendDay: return "Weekend day"; - case RadSchedulerStringId.MonthlyRecurrenceDay: return "Day"; - case RadSchedulerStringId.MonthlyRecurrenceWeek: return "The"; - case RadSchedulerStringId.MonthlyRecurrenceDayOfMonth: return "of every"; - case RadSchedulerStringId.MonthlyRecurrenceMonths: return "month(s)"; - case RadSchedulerStringId.MonthlyRecurrenceWeekOfMonth: return "of every"; - case RadSchedulerStringId.MonthlyRecurrenceFirst: return "First"; - case RadSchedulerStringId.MonthlyRecurrenceSecond: return "Second"; - case RadSchedulerStringId.MonthlyRecurrenceThird: return "Third"; - case RadSchedulerStringId.MonthlyRecurrenceFourth: return "Fourth"; - case RadSchedulerStringId.MonthlyRecurrenceLast: return "Last"; - case RadSchedulerStringId.YearlyRecurrenceDayOfMonth: return "Every"; - case RadSchedulerStringId.YearlyRecurrenceWeekOfMonth: return "The"; - case RadSchedulerStringId.YearlyRecurrenceOfMonth: return "of"; - case RadSchedulerStringId.YearlyRecurrenceJanuary: return "January"; - case RadSchedulerStringId.YearlyRecurrenceFebruary: return "February"; - case RadSchedulerStringId.YearlyRecurrenceMarch: return "March"; - case RadSchedulerStringId.YearlyRecurrenceApril: return "April"; - case RadSchedulerStringId.YearlyRecurrenceMay: return "May"; - case RadSchedulerStringId.YearlyRecurrenceJune: return "June"; - case RadSchedulerStringId.YearlyRecurrenceJuly: return "July"; - case RadSchedulerStringId.YearlyRecurrenceAugust: return "August"; - case RadSchedulerStringId.YearlyRecurrenceSeptember: return "September"; - case RadSchedulerStringId.YearlyRecurrenceOctober: return "October"; - case RadSchedulerStringId.YearlyRecurrenceNovember: return "November"; - case RadSchedulerStringId.YearlyRecurrenceDecember: return "December"; - case RadSchedulerStringId.BackgroundNone: return "None"; - case RadSchedulerStringId.BackgroundImportant: return "Important"; - case RadSchedulerStringId.BackgroundBusiness: return "Business"; - case RadSchedulerStringId.BackgroundPersonal: return "Personal"; - case RadSchedulerStringId.BackgroundVacation: return "Vacation"; - case RadSchedulerStringId.BackgroundMustAttend: return "Must Attend"; - case RadSchedulerStringId.BackgroundTravelRequired: return "Travel Required"; - case RadSchedulerStringId.BackgroundNeedsPreparation: return "Needs Preparation"; - case RadSchedulerStringId.BackgroundBirthday: return "Birthday"; - case RadSchedulerStringId.BackgroundAnniversary: return "Anniversary"; - case RadSchedulerStringId.BackgroundPhoneCall: return "Phone Call"; - case RadSchedulerStringId.StatusBusy: return "Busy"; - case RadSchedulerStringId.StatusFree: return "Free"; - case RadSchedulerStringId.StatusTentative: return "Tentative"; - case RadSchedulerStringId.StatusUnavailable: return "Unavailable"; - case RadSchedulerStringId.ReminderNone: return "None"; - case RadSchedulerStringId.ReminderOneMinute: return "1 minute"; - case RadSchedulerStringId.ReminderMinutes: return " minutes"; - case RadSchedulerStringId.ReminderOneSecond: return "1 second"; - case RadSchedulerStringId.ReminderSeconds: return " seconds"; - case RadSchedulerStringId.ReminderDays: return " days"; - case RadSchedulerStringId.ReminderWeeks: return " weeks"; - case RadSchedulerStringId.ReminderHours: return " hours"; - case RadSchedulerStringId.ReminderZeroMinutes: return "0 minutes"; - case RadSchedulerStringId.ReminderFiveMinutes: return "5 minutes"; - case RadSchedulerStringId.ReminderTenMinutes: return "10 minutes"; - case RadSchedulerStringId.ReminderFifteenMinutes: return "15 minutes"; - case RadSchedulerStringId.ReminderThirtyMinutes: return "30 minutes"; - case RadSchedulerStringId.ReminderOneHour: return "1 hour"; - case RadSchedulerStringId.ReminderTwoHours: return "2 hours"; - case RadSchedulerStringId.ReminderThreeHours: return "3 hours"; - case RadSchedulerStringId.ReminderFourHours: return "4 hours"; - case RadSchedulerStringId.ReminderFiveHours: return "5 hours"; - case RadSchedulerStringId.ReminderSixHours: return "6 hours"; - case RadSchedulerStringId.ReminderSevenHours: return "7 hours"; - case RadSchedulerStringId.ReminderEightHours: return "8 hours"; - case RadSchedulerStringId.ReminderNineHours: return "9 hours"; - case RadSchedulerStringId.ReminderTenHours: return "10 hours"; - case RadSchedulerStringId.ReminderElevenHours: return "11 hours"; - case RadSchedulerStringId.ReminderTwelveHours: return "12 hours"; - case RadSchedulerStringId.ReminderEighteenHours: return "18 hours"; - case RadSchedulerStringId.ReminderOneDay: return "1 day"; - case RadSchedulerStringId.ReminderTwoDays: return "2 days"; - case RadSchedulerStringId.ReminderThreeDays: return "3 days"; - case RadSchedulerStringId.ReminderFourDays: return "4 days"; - case RadSchedulerStringId.ReminderOneWeek: return "1 week"; - case RadSchedulerStringId.ReminderTwoWeeks: return "2 weeks"; - case RadSchedulerStringId.Reminder: return "Reminder"; - case RadSchedulerStringId.ContextMenuNewAppointment: return "New Appointment"; - case RadSchedulerStringId.ContextMenuEditAppointment: return "Edit Appointment"; - case RadSchedulerStringId.ContextMenuNewRecurringAppointment: return "New Recurring Appointment"; - case RadSchedulerStringId.ContextMenu60Minutes: return "60 Minutes"; - case RadSchedulerStringId.ContextMenu30Minutes: return "30 Minutes"; - case RadSchedulerStringId.ContextMenu15Minutes: return "15 Minutes"; - case RadSchedulerStringId.ContextMenu10Minutes: return "10 Minutes"; - case RadSchedulerStringId.ContextMenu6Minutes: return "6 Minutes"; - case RadSchedulerStringId.ContextMenu5Minutes: return "5 Minutes"; - case RadSchedulerStringId.ContextMenuNavigateToNextView: return "Next View"; - case RadSchedulerStringId.ContextMenuNavigateToPreviousView: return "Previous View"; - case RadSchedulerStringId.ContextMenuTimescales: return "Time Scales"; - case RadSchedulerStringId.ContextMenuTimescalesYear: return "Year"; - case RadSchedulerStringId.ContextMenuTimescalesMonth: return "Month"; - case RadSchedulerStringId.ContextMenuTimescalesWeek: return "Week"; - case RadSchedulerStringId.ContextMenuTimescalesDay: return "Day"; - case RadSchedulerStringId.ContextMenuTimescalesHour: return "Hour"; - case RadSchedulerStringId.ContextMenuTimescalesHalfHour: return "30 minutes"; - case RadSchedulerStringId.ContextMenuTimescalesFifteenMinutes: return "15 minutes"; - case RadSchedulerStringId.ErrorProviderWrongAppointmentDates: return "Appointment end time is less or equal to start time!"; - case RadSchedulerStringId.ErrorProviderWrongExceptionDuration: return "Recurrence interval must be greater or equal to appointment duration!"; - case RadSchedulerStringId.ErrorProviderExceptionSameDate: return "Two occurrences of the same series cannot occur on the same day."; - case RadSchedulerStringId.ErrorProviderExceptionSkipOverDate: return "Recurrence exception cannot skip over a later occurrence of the same appointment."; - case RadSchedulerStringId.TimeZoneLocal: return "Local"; - } - return string.Empty; - } -} - -```` -````VB.NET -Public Class CustomSchedulerLocalizationProvider - Inherits RadSchedulerLocalizationProvider - - Public Overrides Function GetLocalizedString(id As String) As String - Select Case id - Case RadSchedulerStringId.NextAppointment - Return "Next Appointment" - Case RadSchedulerStringId.PreviousAppointment - Return "Previous Appointment" - Case RadSchedulerStringId.AppointmentDialogTitle - Return "Edit Appointment" - Case RadSchedulerStringId.AppointmentDialogSubject - Return "Subject:" - Case RadSchedulerStringId.AppointmentDialogLocation - Return "Location:" - Case RadSchedulerStringId.AppointmentDialogBackground - Return "Background:" - Case RadSchedulerStringId.AppointmentDialogDescription - Return "Description:" - Case RadSchedulerStringId.AppointmentDialogStartTime - Return "Start time:" - Case RadSchedulerStringId.AppointmentDialogEndTime - Return "End time:" - Case RadSchedulerStringId.AppointmentDialogAllDay - Return "All day event" - Case RadSchedulerStringId.AppointmentDialogResource - Return "Resource:" - Case RadSchedulerStringId.AppointmentDialogStatus - Return "Show time as:" - Case RadSchedulerStringId.AppointmentDialogOK - Return "OK" - Case RadSchedulerStringId.AppointmentDialogCancel - Return "Cancel" - Case RadSchedulerStringId.AppointmentDialogDelete - Return "Delete" - Case RadSchedulerStringId.AppointmentDialogRecurrence - Return "Recurrence" - Case RadSchedulerStringId.OpenRecurringDialogTitle - Return "Open Recurring Item" - Case RadSchedulerStringId.DeleteRecurrenceDialogOK - Return "OK" - Case RadSchedulerStringId.OpenRecurringDialogOK - Return "OK" - Case RadSchedulerStringId.DeleteRecurrenceDialogCancel - Return "Cancel" - Case RadSchedulerStringId.OpenRecurringDialogCancel - Return "Cancel" - Case RadSchedulerStringId.OpenRecurringDialogLabel - Return """{0}"" is a recurring" & vbLf & "appointment. Do you want to open" & vbLf & "only this occurrence or the series?" - Case RadSchedulerStringId.OpenRecurringDialogRadioOccurrence - Return "Open this occurrence." - Case RadSchedulerStringId.OpenRecurringDialogRadioSeries - Return "Open the series." - Case RadSchedulerStringId.DeleteRecurrenceDialogTitle - Return "Confirm Delete" - Case RadSchedulerStringId.DeleteRecurrenceDialogRadioOccurrence - Return "Delete this occurrence." - Case RadSchedulerStringId.DeleteRecurrenceDialogRadioSeries - Return "Delete the series." - Case RadSchedulerStringId.DeleteRecurrenceDialogLabel - Return "Do you want to delete all occurrences of the recurring appointment ""{0}"", or just this one?" - Case RadSchedulerStringId.RecurrenceDragDropCreateExceptionDialogText - Return "You changed the date of a single occurrence of a recurring appointment. To change all the dates, open the series." & vbLf & "Do you want to change just this one?" - Case RadSchedulerStringId.RecurrenceDragDropValidationSameDateText - Return "Two occurrences of the same series cannot occur on the same day." - Case RadSchedulerStringId.RecurrenceDragDropValidationSkipOccurrenceText - Return "Cannot reschedule an occurrence of a recurring appointment if it skips over a later occurrence of the same appointment." - Case RadSchedulerStringId.RecurrenceDialogMessageBoxText - Return "Start date should be before EndBy date." - Case RadSchedulerStringId.RecurrenceDialogMessageBoxWrongRecurrenceRuleText - Return "The recurrence pattern is not valid." - Case RadSchedulerStringId.RecurrenceDialogMessageBoxTitle - Return "Validation error" - Case RadSchedulerStringId.RecurrenceDialogTitle - Return "Edit Recurrence" - Case RadSchedulerStringId.RecurrenceDialogAppointmentTimeGroup - Return "Appointment time" - Case RadSchedulerStringId.RecurrenceDialogDuration - Return "Duration:" - Case RadSchedulerStringId.RecurrenceDialogAppointmentEnd - Return "End:" - Case RadSchedulerStringId.RecurrenceDialogAppointmentStart - Return "Start:" - Case RadSchedulerStringId.RecurrenceDialogRecurrenceGroup - Return "Recurrence pattern" - Case RadSchedulerStringId.RecurrenceDialogRangeGroup - Return "Range of recurrence" - Case RadSchedulerStringId.RecurrenceDialogOccurrences - Return "occurrences" - Case RadSchedulerStringId.RecurrenceDialogRecurrenceStart - Return "Start:" - Case RadSchedulerStringId.RecurrenceDialogYearly - Return "Yearly" - Case RadSchedulerStringId.RecurrenceDialogHourly - Return "Hourly" - Case RadSchedulerStringId.RecurrenceDialogMonthly - Return "Monthly" - Case RadSchedulerStringId.RecurrenceDialogWeekly - Return "Weekly" - Case RadSchedulerStringId.RecurrenceDialogDaily - Return "Daily" - Case RadSchedulerStringId.RecurrenceDialogEndBy - Return "End by:" - Case RadSchedulerStringId.RecurrenceDialogEndAfter - Return "End after:" - Case RadSchedulerStringId.RecurrenceDialogNoEndDate - Return "No end date" - Case RadSchedulerStringId.RecurrenceDialogAllDay - Return "All day event" - Case RadSchedulerStringId.RecurrenceDialogDurationDropDown1Day - Return "1 day" - Case RadSchedulerStringId.RecurrenceDialogDurationDropDown2Days - Return "2 days" - Case RadSchedulerStringId.RecurrenceDialogDurationDropDown3Days - Return "3 days" - Case RadSchedulerStringId.RecurrenceDialogDurationDropDown4Days - Return "4 days" - Case RadSchedulerStringId.RecurrenceDialogDurationDropDown1Week - Return "1 week" - Case RadSchedulerStringId.RecurrenceDialogDurationDropDown2Weeks - Return "2 weeks" - Case RadSchedulerStringId.RecurrenceDialogOK - Return "OK" - Case RadSchedulerStringId.RecurrenceDialogCancel - Return "Cancel" - Case RadSchedulerStringId.RecurrenceDialogRemoveRecurrence - Return "Remove Recurrence" - Case RadSchedulerStringId.HourlyRecurrenceEvery - Return "Every" - Case RadSchedulerStringId.HourlyRecurrenceHours - Return "hour(s)" - Case RadSchedulerStringId.DailyRecurrenceEveryDay - Return "Every" - Case RadSchedulerStringId.DailyRecurrenceEveryWeekday - Return "Every weekday" - Case RadSchedulerStringId.DailyRecurrenceDays - Return "day(s)" - Case RadSchedulerStringId.WeeklyRecurrenceRecurEvery - Return "Recur every" - Case RadSchedulerStringId.WeeklyRecurrenceWeeksOn - Return "week(s) on:" - Case RadSchedulerStringId.WeeklyRecurrenceSunday - Return "Sunday" - Case RadSchedulerStringId.WeeklyRecurrenceMonday - Return "Monday" - Case RadSchedulerStringId.WeeklyRecurrenceTuesday - Return "Tuesday" - Case RadSchedulerStringId.WeeklyRecurrenceWednesday - Return "Wednesday" - Case RadSchedulerStringId.WeeklyRecurrenceThursday - Return "Thursday" - Case RadSchedulerStringId.WeeklyRecurrenceFriday - Return "Friday" - Case RadSchedulerStringId.WeeklyRecurrenceSaturday - Return "Saturday" - Case RadSchedulerStringId.WeeklyRecurrenceDay - Return "Day" - Case RadSchedulerStringId.WeeklyRecurrenceWeekday - Return "Weekday" - Case RadSchedulerStringId.WeeklyRecurrenceWeekendDay - Return "Weekend day" - Case RadSchedulerStringId.MonthlyRecurrenceDay - Return "Day" - Case RadSchedulerStringId.MonthlyRecurrenceWeek - Return "The" - Case RadSchedulerStringId.MonthlyRecurrenceDayOfMonth - Return "of every" - Case RadSchedulerStringId.MonthlyRecurrenceMonths - Return "month(s)" - Case RadSchedulerStringId.MonthlyRecurrenceWeekOfMonth - Return "of every" - Case RadSchedulerStringId.MonthlyRecurrenceFirst - Return "First" - Case RadSchedulerStringId.MonthlyRecurrenceSecond - Return "Second" - Case RadSchedulerStringId.MonthlyRecurrenceThird - Return "Third" - Case RadSchedulerStringId.MonthlyRecurrenceFourth - Return "Fourth" - Case RadSchedulerStringId.MonthlyRecurrenceLast - Return "Last" - Case RadSchedulerStringId.YearlyRecurrenceDayOfMonth - Return "Every" - Case RadSchedulerStringId.YearlyRecurrenceWeekOfMonth - Return "The" - Case RadSchedulerStringId.YearlyRecurrenceOfMonth - Return "of" - Case RadSchedulerStringId.YearlyRecurrenceJanuary - Return "January" - Case RadSchedulerStringId.YearlyRecurrenceFebruary - Return "February" - Case RadSchedulerStringId.YearlyRecurrenceMarch - Return "March" - Case RadSchedulerStringId.YearlyRecurrenceApril - Return "April" - Case RadSchedulerStringId.YearlyRecurrenceMay - Return "May" - Case RadSchedulerStringId.YearlyRecurrenceJune - Return "June" - Case RadSchedulerStringId.YearlyRecurrenceJuly - Return "July" - Case RadSchedulerStringId.YearlyRecurrenceAugust - Return "August" - Case RadSchedulerStringId.YearlyRecurrenceSeptember - Return "September" - Case RadSchedulerStringId.YearlyRecurrenceOctober - Return "October" - Case RadSchedulerStringId.YearlyRecurrenceNovember - Return "November" - Case RadSchedulerStringId.YearlyRecurrenceDecember - Return "December" - Case RadSchedulerStringId.BackgroundNone - Return "None" - Case RadSchedulerStringId.BackgroundImportant - Return "Important" - Case RadSchedulerStringId.BackgroundBusiness - Return "Business" - Case RadSchedulerStringId.BackgroundPersonal - Return "Personal" - Case RadSchedulerStringId.BackgroundVacation - Return "Vacation" - Case RadSchedulerStringId.BackgroundMustAttend - Return "Must Attend" - Case RadSchedulerStringId.BackgroundTravelRequired - Return "Travel Required" - Case RadSchedulerStringId.BackgroundNeedsPreparation - Return "Needs Preparation" - Case RadSchedulerStringId.BackgroundBirthday - Return "Birthday" - Case RadSchedulerStringId.BackgroundAnniversary - Return "Anniversary" - Case RadSchedulerStringId.BackgroundPhoneCall - Return "Phone Call" - Case RadSchedulerStringId.StatusBusy - Return "Busy" - Case RadSchedulerStringId.StatusFree - Return "Free" - Case RadSchedulerStringId.StatusTentative - Return "Tentative" - Case RadSchedulerStringId.StatusUnavailable - Return "Unavailable" - Case RadSchedulerStringId.ReminderNone - Return "None" - Case RadSchedulerStringId.ReminderOneMinute - Return "1 minute" - Case RadSchedulerStringId.ReminderMinutes - Return " minutes" - Case RadSchedulerStringId.ReminderOneSecond - Return "1 second" - Case RadSchedulerStringId.ReminderSeconds - Return " seconds" - Case RadSchedulerStringId.ReminderDays - Return " days" - Case RadSchedulerStringId.ReminderWeeks - Return " weeks" - Case RadSchedulerStringId.ReminderHours - Return " hours" - Case RadSchedulerStringId.ReminderZeroMinutes - Return "0 minutes" - Case RadSchedulerStringId.ReminderFiveMinutes - Return "5 minutes" - Case RadSchedulerStringId.ReminderTenMinutes - Return "10 minutes" - Case RadSchedulerStringId.ReminderFifteenMinutes - Return "15 minutes" - Case RadSchedulerStringId.ReminderThirtyMinutes - Return "30 minutes" - Case RadSchedulerStringId.ReminderOneHour - Return "1 hour" - Case RadSchedulerStringId.ReminderTwoHours - Return "2 hours" - Case RadSchedulerStringId.ReminderThreeHours - Return "3 hours" - Case RadSchedulerStringId.ReminderFourHours - Return "4 hours" - Case RadSchedulerStringId.ReminderFiveHours - Return "5 hours" - Case RadSchedulerStringId.ReminderSixHours - Return "6 hours" - Case RadSchedulerStringId.ReminderSevenHours - Return "7 hours" - Case RadSchedulerStringId.ReminderEightHours - Return "8 hours" - Case RadSchedulerStringId.ReminderNineHours - Return "9 hours" - Case RadSchedulerStringId.ReminderTenHours - Return "10 hours" - Case RadSchedulerStringId.ReminderElevenHours - Return "11 hours" - Case RadSchedulerStringId.ReminderTwelveHours - Return "12 hours" - Case RadSchedulerStringId.ReminderEighteenHours - Return "18 hours" - Case RadSchedulerStringId.ReminderOneDay - Return "1 day" - Case RadSchedulerStringId.ReminderTwoDays - Return "2 days" - Case RadSchedulerStringId.ReminderThreeDays - Return "3 days" - Case RadSchedulerStringId.ReminderFourDays - Return "4 days" - Case RadSchedulerStringId.ReminderOneWeek - Return "1 week" - Case RadSchedulerStringId.ReminderTwoWeeks - Return "2 weeks" - Case RadSchedulerStringId.Reminder - Return "Reminder" - Case RadSchedulerStringId.ContextMenuNewAppointment - Return "New Appointment" - Case RadSchedulerStringId.ContextMenuEditAppointment - Return "Edit Appointment" - Case RadSchedulerStringId.ContextMenuNewRecurringAppointment - Return "New Recurring Appointment" - Case RadSchedulerStringId.ContextMenu60Minutes - Return "60 Minutes" - Case RadSchedulerStringId.ContextMenu30Minutes - Return "30 Minutes" - Case RadSchedulerStringId.ContextMenu15Minutes - Return "15 Minutes" - Case RadSchedulerStringId.ContextMenu10Minutes - Return "10 Minutes" - Case RadSchedulerStringId.ContextMenu6Minutes - Return "6 Minutes" - Case RadSchedulerStringId.ContextMenu5Minutes - Return "5 Minutes" - Case RadSchedulerStringId.ContextMenuNavigateToNextView - Return "Next View" - Case RadSchedulerStringId.ContextMenuNavigateToPreviousView - Return "Previous View" - Case RadSchedulerStringId.ContextMenuTimescales - Return "Time Scales" - Case RadSchedulerStringId.ContextMenuTimescalesYear - Return "Year" - Case RadSchedulerStringId.ContextMenuTimescalesMonth - Return "Month" - Case RadSchedulerStringId.ContextMenuTimescalesWeek - Return "Week" - Case RadSchedulerStringId.ContextMenuTimescalesDay - Return "Day" - Case RadSchedulerStringId.ContextMenuTimescalesHour - Return "Hour" - Case RadSchedulerStringId.ContextMenuTimescalesHalfHour - Return "30 minutes" - Case RadSchedulerStringId.ContextMenuTimescalesFifteenMinutes - Return "15 minutes" - Case RadSchedulerStringId.ErrorProviderWrongAppointmentDates - Return "Appointment end time is less or equal to start time!" - Case RadSchedulerStringId.ErrorProviderWrongExceptionDuration - Return "Recurrence interval must be greater or equal to appointment duration!" - Case RadSchedulerStringId.ErrorProviderExceptionSameDate - Return "Two occurrences of the same series cannot occur on the same day." - Case RadSchedulerStringId.ErrorProviderExceptionSkipOverDate - Return "Recurrence exception cannot skip over a later occurrence of the same appointment." - Case RadSchedulerStringId.TimeZoneLocal - Return "Local" - End Select - Return String.Empty - End Function -End Class - -```` - -{{endregion}} - -To apply the custom localization provider, instantiate and assign it to the current localization provider: - -#### Change the Current Provider - -{{source=..\SamplesCS\Scheduler\Localization\AssignProviders.cs region=assignSchedulerProvider}} -{{source=..\SamplesVB\Scheduler\Localization\AssignProviders.vb region=assignSchedulerProvider}} - -````C# -RadSchedulerLocalizationProvider.CurrentProvider = new CustomSchedulerLocalizationProvider(); - -```` -````VB.NET -RadSchedulerLocalizationProvider.CurrentProvider = New CustomSchedulerLocalizationProvider() - -```` - -{{endregion}} - -# See Also - -* [Right-to-Left Support]({%slug winforms/scheduler/localization/right-to-left-support%}) -* [Views]({%slug winforms/scheduler/views/overview-and-structure%}) -* [Themes and Appearance]({%slug winforms/scheduler/appearance/themes-and-appearance%}) - +--- +title: Localizing RadScheduler +page_title: Localizing RadScheduler - WinForms Scheduler Control +description: To localize WinForms Scheduler to display control text and messages in a specific language create a descendant of the RadSchedulerLocalizationProvider class. +slug: winforms/scheduler/localization/translating-strings +tags: translating,strings +published: True +position: 0 +previous_url: scheduler-localization-translating-strings +--- + +# Localizing RadScheduler + +To localize __RadScheduler__ to display control text and messages in a specific language: + +* All required classes for localization are defined in __Telerik.WinControls.UI.Localization__ namespace. + +* Start by creating a descendant of the __RadSchedulerLocalizationProvider__ class. + +* Override the __GetLocalizedString(string id)__ method and provide a translation for the messages. If a translation is not provided, the default value will be returned. This behavior is guaranteed by the call to the base __GetLocalizedString__ method in the default clause of the switch statement in the example. + +Below is a sample implementation of a custom localization provider: + +#### Custom Localization Provider + + + + + + +To apply the custom localization provider, instantiate and assign it to the current localization provider: + +#### Change the Current Provider + + + + + + +# See Also + +* [Right-to-Left Support]({%slug winforms/scheduler/localization/right-to-left-support%}) +* [Views]({%slug winforms/scheduler/views/overview-and-structure%}) +* [Themes and Appearance]({%slug winforms/scheduler/appearance/themes-and-appearance%}) + diff --git a/controls/scheduler/print-support/events-and-customization.md b/controls/scheduler/print-support/events-and-customization.md index 2287b1451..48cf49faf 100644 --- a/controls/scheduler/print-support/events-and-customization.md +++ b/controls/scheduler/print-support/events-and-customization.md @@ -36,129 +36,10 @@ Here is an example. The comments are inline: #### Handle Formatting and Paint Events -{{source=..\SamplesCS\Scheduler\Print support\SchedulerEventsAndCustomization.cs region=Customize}} -{{source=..\SamplesVB\Scheduler\Print support\SchedulerEventsAndCustomization.vb region=Customize}} - -````C# -void radScheduler1_CellPrintElementPaint(object sender, PrintSchedulerCellPaintEventArgs e) -{ - //draw a hatch in the cell if it is 12 o'clock (lunch break) - if (e.CellElement.Date.Hour == 12) - { - Brush b = new HatchBrush(HatchStyle.BackwardDiagonal, Color.White, Color.Transparent); - e.Graphics.FillRectangle(b, e.Bounds); - } -} -void radScheduler1_AppointmentPrintElementPaint(object sender, PrintAppointmentPaintEventArgs e) -{ - //draw an image in the bottom right corner of each appointment - Image img = Resources.telerikLogo1; - int imgWidth = (int)((double)img.Size.Width * 100 / (double)Graphics.FromImage(img).DpiX); - int imgheight = (int)((double)img.Size.Height * 100 / (double)Graphics.FromImage(img).DpiX); - e.Graphics.DrawImage(img, new Point(e.Bounds.Right - imgWidth, e.Bounds.Bottom - imgheight)); -} -void radScheduler1_PrintElementPaint(object sender, PrintElementPaintEventArgs e) -{ - if (!(e.PrintElement is CalendarPrintElement)) - { - //draw an image in the main element - e.Graphics.DrawImage(Resources.telerikLogo, new Point(e.Bounds.X +1, e.Bounds.Y)); - } -} -void radScheduler1_PrintElementFormatting(object sender, PrintElementEventArgs e) -{ - //allow paint of the main element - e.PrintElement.DrawFill = true; - //set the calendar backcolor - if (e.PrintElement is CalendarPrintElement) - { - e.PrintElement.BackColor = Color.Yellow; - } - else - { - //set the main element backcolor and change its text position - e.PrintElement.BackColor = Color.LightSeaGreen; - e.PrintElement.TextAlignment = ContentAlignment.BottomLeft; - } -} -Font appointmentFont = new Font("Consolas", 20); -void radScheduler1_AppointmentPrintElementFormatting(object sender, PrintAppointmentEventArgs e) -{ - //customize the appointment appearance - e.AppointmentElement.DrawFill = true; - e.AppointmentElement.BackColor = Color.Moccasin; - e.AppointmentElement.ForeColor = Color.Red; - e.AppointmentElement.Font = appointmentFont; -} -void radScheduler1_CellPrintElementFormatting(object sender, Telerik.WinControls.UI.PrintSchedulerCellEventArgs e) -{ - //set different colors for cells with even and odd hours - e.CellElement.DrawFill = true; - if (e.CellElement.Date.Hour % 2 == 0) - { - e.CellElement.BackColor = Color.YellowGreen; - } - else - { - e.CellElement.BackColor = Color.CornflowerBlue; - } -} - -```` -````VB.NET -Private Sub radScheduler1_CellPrintElementPaint(sender As Object, e As PrintSchedulerCellPaintEventArgs) - 'draw a hatch in the cell if it is 12 o'clock (lunch break) - If e.CellElement.[Date].Hour = 12 Then - Dim b As Brush = New HatchBrush(HatchStyle.BackwardDiagonal, Color.White, Color.Transparent) - e.Graphics.FillRectangle(b, e.Bounds) - End If -End Sub -Private Sub radScheduler1_AppointmentPrintElementPaint(sender As Object, e As PrintAppointmentPaintEventArgs) - 'draw an image in the bottom right corner of each appointment - Dim img As Image = My.Resources.telerikLogo1 - Dim imgWidth As Integer = CInt(CDbl(img.Size.Width) * 100 / CDbl(Graphics.FromImage(img).DpiX)) - Dim imgheight As Integer = CInt(CDbl(img.Size.Height) * 100 / CDbl(Graphics.FromImage(img).DpiX)) - e.Graphics.DrawImage(img, New Point(e.Bounds.Right - imgWidth, e.Bounds.Bottom - imgheight)) -End Sub -Private Sub radScheduler1_PrintElementPaint(sender As Object, e As PrintElementPaintEventArgs) - If Not (TypeOf e.PrintElement Is CalendarPrintElement) Then - 'draw an image in the main element - e.Graphics.DrawImage(My.Resources.telerikLogo, New Point(e.Bounds.X + 1, e.Bounds.Y)) - End If -End Sub -Private Sub radScheduler1_PrintElementFormatting(sender As Object, e As PrintElementEventArgs) - 'allow paint of the main element - e.PrintElement.DrawFill = True - 'set the calendar backcolor - If TypeOf e.PrintElement Is CalendarPrintElement Then - e.PrintElement.BackColor = Color.Yellow - Else - 'et the main element backcolor and change its text position - e.PrintElement.BackColor = Color.LightSeaGreen - e.PrintElement.TextAlignment = ContentAlignment.BottomLeft - End If -End Sub -Private appointmentFont As New Font("Consolas", 20) -Private Sub radScheduler1_AppointmentPrintElementFormatting(sender As Object, e As PrintAppointmentEventArgs) - 'customize the appointment appearance - e.AppointmentElement.DrawFill = True - e.AppointmentElement.BackColor = Color.Moccasin - e.AppointmentElement.ForeColor = Color.Red - e.AppointmentElement.Font = appointmentFont -End Sub -Private Sub radScheduler1_CellPrintElementFormatting(sender As Object, e As Telerik.WinControls.UI.PrintSchedulerCellEventArgs) - 'set different colors for cells with even and odd hours - e.CellElement.DrawFill = True - If e.CellElement.[Date].Hour Mod 2 = 0 Then - e.CellElement.BackColor = Color.YellowGreen - Else - e.CellElement.BackColor = Color.CornflowerBlue - End If -End Sub - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/scheduler/print-support/print-support-overview.md b/controls/scheduler/print-support/print-support-overview.md index b171b1fcf..f00f85799 100644 --- a/controls/scheduler/print-support/print-support-overview.md +++ b/controls/scheduler/print-support/print-support-overview.md @@ -35,21 +35,10 @@ The RadScheduler has two public methods available for printing – __Print()__ a #### Initiate Printing -{{source=..\SamplesCS\Scheduler\Print support\SchedulerPrintSupport.cs region=print}} -{{source=..\SamplesVB\Scheduler\Print support\SchedulerPrintSupport.vb region=print}} + + -````C# -this.radScheduler1.Print(); -this.radScheduler1.Print(true); -```` -````VB.NET -Me.RadScheduler1.Print() -Me.RadScheduler1.Print(True) - -```` - -{{endregion}} >caption Figure 1: RadScheduler Printing ![WinForms RadScheduler Printing](images/scheduler-print-support001.png) @@ -58,19 +47,10 @@ The other available method is __PrintPreview()__. It opens a new RadPrintPreview #### Show Print Preview -{{source=..\SamplesCS\Scheduler\Print support\SchedulerPrintSupport.cs region=PrintPreview}} -{{source=..\SamplesVB\Scheduler\Print support\SchedulerPrintSupport.vb region=PrintPreview}} - -````C# -this.radScheduler1.PrintPreview(); - -```` -````VB.NET -Me.RadScheduler1.PrintPreview() + + -```` -{{endregion}} >caption Figure 2: RadScheduler Print Preview ![WinForms RadScheduler Print Preview](images/scheduler-print-support002.png) diff --git a/controls/scheduler/print-support/schedulerprintstyles.md b/controls/scheduler/print-support/schedulerprintstyles.md index 84d60604a..4133dfe39 100644 --- a/controls/scheduler/print-support/schedulerprintstyles.md +++ b/controls/scheduler/print-support/schedulerprintstyles.md @@ -21,21 +21,10 @@ To set a __RadScheduler__ with a print style: #### Daily Print Style -{{source=..\SamplesCS\Scheduler\Print support\SchedulerPrintStyle1.cs region=SetPrintStyle}} -{{source=..\SamplesVB\Scheduler\Print support\SchedulerPrintStyle1.vb region=SetPrintStyle}} + + -````C# -SchedulerPrintStyle schedulerPrintStyle = new SchedulerDailyPrintStyle(); -this.radScheduler1.PrintStyle = schedulerPrintStyle; -```` -````VB.NET -Dim schedulerPrintStyle As New SchedulerDailyPrintStyle() -Me.RadScheduler1.PrintStyle = schedulerPrintStyle - -```` - -{{endregion}} __SchedulerPrintStyle__ has the following properties: @@ -43,107 +32,46 @@ __SchedulerPrintStyle__ has the following properties: #### Specify Date Range -{{source=..\SamplesCS\Scheduler\Print support\SchedulerPrintStyle1.cs region=SpeficyDateRange}} -{{source=..\SamplesVB\Scheduler\Print support\SchedulerPrintStyle1.vb region=SpeficyDateRange}} - -````C# -schedulerPrintStyle.DateStartRange = DateTime.Today; -schedulerPrintStyle.DateEndRange = DateTime.Today.AddDays(6); + + -```` -````VB.NET -schedulerPrintStyle.DateStartRange = DateTime.Today -schedulerPrintStyle.DateEndRange = DateTime.Today.AddDays(6) -```` - -{{endregion}} * __TimeStartRange__ and __TimeEndRange__: Allows you to specify the time frame which for every day in the date range - i.e. the time frame which will be printed for each date in the date range period: #### Specify Time Frame -{{source=..\SamplesCS\Scheduler\Print support\SchedulerPrintStyle1.cs region=SpecifyTimeFrame}} -{{source=..\SamplesVB\Scheduler\Print support\SchedulerPrintStyle1.vb region=SpecifyTimeFrame}} - -````C# -schedulerPrintStyle.TimeStartRange = TimeSpan.FromHours(7); -schedulerPrintStyle.TimeEndRange = TimeSpan.FromHours(19); - -```` -````VB.NET -schedulerPrintStyle.TimeStartRange = TimeSpan.FromHours(7) -schedulerPrintStyle.TimeEndRange = TimeSpan.FromHours(19) + + -```` -{{endregion}} * __AppointmentFont__, __DateHeadingFont__ and __PageHeadingFont__ allow you to specify the fonts for the appointments, dates and page headers respectively: #### Set Font -{{source=..\SamplesCS\Scheduler\Print support\SchedulerPrintStyle1.cs region=SetFonts}} -{{source=..\SamplesVB\Scheduler\Print support\SchedulerPrintStyle1.vb region=SetFonts}} + + -````C# -schedulerPrintStyle.AppointmentFont = new Font("Segoe UI Light", 8, FontStyle.Regular); -schedulerPrintStyle.DateHeadingFont = new Font("Segoe UI Light", 12, FontStyle.Regular); -schedulerPrintStyle.PageHeadingFont = new Font("Segoe UI Light", 16, FontStyle.Regular); -```` -````VB.NET -schedulerPrintStyle.AppointmentFont = New Font("Segoe UI Light", 8, FontStyle.Regular) -schedulerPrintStyle.DateHeadingFont = New Font("Segoe UI Light", 12, FontStyle.Regular) -schedulerPrintStyle.PageHeadingFont = New Font("Segoe UI Light", 16, FontStyle.Regular) - -```` - -{{endregion}} * You can also specify which __visual parts__ of the page to be printed - page title, calendar in the page title, notes area, etc: #### Specify Visual Parts -{{source=..\SamplesCS\Scheduler\Print support\SchedulerPrintStyle1.cs region=SpeficyVisualElements}} -{{source=..\SamplesVB\Scheduler\Print support\SchedulerPrintStyle1.vb region=SpeficyVisualElements}} - -````C# -schedulerPrintStyle.DrawPageTitle = true; -schedulerPrintStyle.DrawPageTitleCalendar = true; -schedulerPrintStyle.ShowLinedNotesArea = true; -schedulerPrintStyle.ShowNotesArea = true; + + -```` -````VB.NET -schedulerPrintStyle.DrawPageTitle = True -schedulerPrintStyle.DrawPageTitleCalendar = True -schedulerPrintStyle.ShowLinedNotesArea = True -schedulerPrintStyle.ShowNotesArea = True -```` - -{{endregion}} * To modify the size of the visual areas use: #### Area Size -{{source=..\SamplesCS\Scheduler\Print support\SchedulerPrintStyle1.cs region=ModifyVisualElements}} -{{source=..\SamplesVB\Scheduler\Print support\SchedulerPrintStyle1.vb region=ModifyVisualElements}} - -````C# -schedulerPrintStyle.NotesAreaWidth = 200; -schedulerPrintStyle.HeadingAreaHeight = 100; + + -```` -````VB.NET -schedulerPrintStyle.NotesAreaWidth = 200 -schedulerPrintStyle.HeadingAreaHeight = 100 -```` - -{{endregion}} ## DailyStyle @@ -154,27 +82,10 @@ The __SchedulerDailyPrintStyle__ class defines printing of RadScheduler in a dai #### Set SchedulerDailyPrintStyle -{{source=..\SamplesCS\Scheduler\Print support\SchedulerPrintStyle1.cs region=DailyStyle}} -{{source=..\SamplesVB\Scheduler\Print support\SchedulerPrintStyle1.vb region=DailyStyle}} - -````C# -SchedulerDailyPrintStyle dailyStyle = new SchedulerDailyPrintStyle(); -dailyStyle.HoursColumnWidth = 100; -dailyStyle.MaxAllDayAreaHeight = 100; -dailyStyle.AllDayAppointmentHeight = 20; -dailyStyle.TwoPagesPerDay = true; - -```` -````VB.NET -Dim dailyStyle As New SchedulerDailyPrintStyle() -dailyStyle.HoursColumnWidth = 100 -dailyStyle.MaxAllDayAreaHeight = 100 -dailyStyle.AllDayAppointmentHeight = 20 -dailyStyle.TwoPagesPerDay = True + + -```` -{{endregion}} ## WeeklyCalendarStyle @@ -195,25 +106,10 @@ In the WeeklyCalendarPrintStyle the appointments are arranged in a grid where ea #### Set SchedulerWeeklyCalendarPrintStyle -{{source=..\SamplesCS\Scheduler\Print support\SchedulerPrintStyle1.cs region=WeeklyCalendarStyle}} -{{source=..\SamplesVB\Scheduler\Print support\SchedulerPrintStyle1.vb region=WeeklyCalendarStyle}} + + -````C# -SchedulerWeeklyCalendarPrintStyle weeklyCalendarStyle = new SchedulerWeeklyCalendarPrintStyle(); -weeklyCalendarStyle.AppointmentFont = new System.Drawing.Font("Segoe UI", 12, FontStyle.Regular); -weeklyCalendarStyle.HeadingAreaHeight = 120; -weeklyCalendarStyle.HoursColumnWidth = 30; -```` -````VB.NET -Dim weeklyCalendarStyle As New SchedulerWeeklyCalendarPrintStyle() -weeklyCalendarStyle.AppointmentFont = New System.Drawing.Font("Segoe UI", 12, FontStyle.Regular) -weeklyCalendarStyle.HeadingAreaHeight = 120 -weeklyCalendarStyle.HoursColumnWidth = 30 - -```` - -{{endregion}} ## WeeklyStyle @@ -230,25 +126,10 @@ The SchedulerWeeklyPrintStyle class defines printing of RadScheduler in a weekly #### Set SchedulerWeeklyPrintStyle -{{source=..\SamplesCS\Scheduler\Print support\SchedulerPrintStyle1.cs region=WeeklyStyle}} -{{source=..\SamplesVB\Scheduler\Print support\SchedulerPrintStyle1.vb region=WeeklyStyle}} - -````C# -SchedulerWeeklyPrintStyle weeklyStyle = new SchedulerWeeklyPrintStyle(); -weeklyStyle.ExcludeNonWorkingDays = true; -weeklyStyle.DaysLayout = WeeklyStyleLayout.TopToBottom; -weeklyStyle.TwoPagesPerWeek = true; + + -```` -````VB.NET -Dim weeklyStyle As New SchedulerWeeklyPrintStyle() -weeklyStyle.ExcludeNonWorkingDays = True -weeklyStyle.DaysLayout = WeeklyStyleLayout.TopToBottom -weeklyStyle.TwoPagesPerWeek = True -```` - -{{endregion}} ## MonthlyStyle @@ -275,33 +156,10 @@ In this mode you can take advantage of the following properties: #### Set SchedulerMonthlyPrintStyle -{{source=..\SamplesCS\Scheduler\Print support\SchedulerPrintStyle1.cs region=MonthlyStyle}} -{{source=..\SamplesVB\Scheduler\Print support\SchedulerPrintStyle1.vb region=MonthlyStyle}} - -````C# -SchedulerMonthlyPrintStyle monthlyStyle = new SchedulerMonthlyPrintStyle(); -monthlyStyle.ExcludeNonWorkingDays = true; -monthlyStyle.TwoPagesPerMonth = true; -monthlyStyle.PrintExactlyOneMonth = false; -monthlyStyle.WeeksPerPage = 4; -monthlyStyle.AppointmentHeight = 30; -monthlyStyle.CellHeaderHeight = 30; -monthlyStyle.VerticalHeaderWidth = 100; - -```` -````VB.NET -Dim monthlyStyle As New SchedulerMonthlyPrintStyle() -monthlyStyle.ExcludeNonWorkingDays = True -monthlyStyle.TwoPagesPerMonth = True -monthlyStyle.PrintExactlyOneMonth = False -monthlyStyle.WeeksPerPage = 4 -monthlyStyle.AppointmentHeight = 30 -monthlyStyle.CellHeaderHeight = 30 -monthlyStyle.VerticalHeaderWidth = 100 - -```` - -{{endregion}} + + + + ## DetailsStyle @@ -322,27 +180,10 @@ Similar to the previous modes, you can set properties that define the size of sp #### Set SchedulerDetailsPrintStyle -{{source=..\SamplesCS\Scheduler\Print support\SchedulerPrintStyle1.cs region=DetailsStyle}} -{{source=..\SamplesVB\Scheduler\Print support\SchedulerPrintStyle1.vb region=DetailsStyle}} - -````C# -SchedulerDetailsPrintStyle detailsStyle = new SchedulerDetailsPrintStyle(); -detailsStyle.AppointmentDateWidth = 200; -detailsStyle.AppointmentTitleHeight = 30; -detailsStyle.DayHeaderHeight = 60; -detailsStyle.PageBreakMode = PageBreakMode.Day; - -```` -````VB.NET -Dim detailsStyle As New SchedulerDetailsPrintStyle() -detailsStyle.AppointmentDateWidth = 200 -detailsStyle.AppointmentTitleHeight = 30 -detailsStyle.DayHeaderHeight = 60 -detailsStyle.PageBreakMode = PageBreakMode.Day + + -```` -{{endregion}} # See Also diff --git a/controls/scheduler/reminders/load-reminders.md b/controls/scheduler/reminders/load-reminders.md index 77bc94dde..3745daf70 100644 --- a/controls/scheduler/reminders/load-reminders.md +++ b/controls/scheduler/reminders/load-reminders.md @@ -15,19 +15,10 @@ __RadScheduler__ allows you to save and load the reminders set for appointments. #### Save Reminders -{{source=..\SamplesCS\Scheduler\Reminders\SaveLoadReminders.cs region=SaveReminders}} -{{source=..\SamplesVB\Scheduler\Reminders\SaveLoadReminders.vb region=SaveReminders}} + + -````C# -this.radScheduler1.SaveReminders(filePath); -```` -````VB.NET -Me.radScheduler1.SaveReminders(filePath) - -```` - -{{endregion}} >note When you load reminders you should first have the appointments loaded in __RadScheduler__ so the load mechanism can identify them and restore their reminders. > @@ -36,77 +27,26 @@ You can load saved reminders into __RadScheduler__ is by calling the __LoadRemin #### Load Reminders -{{source=..\SamplesCS\Scheduler\Reminders\SaveLoadReminders.cs region=LoadReminders}} -{{source=..\SamplesVB\Scheduler\Reminders\SaveLoadReminders.vb region=LoadReminders}} - -````C# -this.radScheduler1.LoadReminders(filePath); + + -```` -````VB.NET -Me.radScheduler1.LoadReminders(filePath) -```` - -{{endregion}} __SchedulerSaveLoadRemindersBehavior__ is the class that handles the saving and loading of reminders inside __RadScheduler__. You can inherit this class and provide your own custom logic for saving and loading appointments. After you have your custom implementation all you have to do is assign it to the __SaveLoadRemindersBehavior__ property of __RadScheduler__: #### Custom Save/Load Behavior -{{source=..\SamplesCS\Scheduler\Reminders\SaveLoadReminders.cs region=CustomSaveLoadRemindersBehavior}} -{{source=..\SamplesVB\Scheduler\Reminders\SaveLoadReminders.vb region=CustomSaveLoadRemindersBehavior}} - -````C# -public class CustomSaveLoadRemindersBehavior : SchedulerSaveLoadRemindersBehavior -{ - public CustomSaveLoadRemindersBehavior(RadScheduler scheduler) - : base(scheduler) - { } - public override void SaveReminders(string filePath) - { - //Custom save logic - } - public override void LoadReminders(string filePath) - { - //Custom load logic - } -} - -```` -````VB.NET -Public Class CustomSaveLoadRemindersBehavior - Inherits SchedulerSaveLoadRemindersBehavior - Public Sub New(scheduler As RadScheduler) - MyBase.New(scheduler) - End Sub - Public Overrides Sub SaveReminders(filePath As String) - 'Custom save logic - End Sub - Public Overrides Sub LoadReminders(filePath As String) - 'Custom load logic - End Sub -End Class - -```` - -{{endregion}} + + -#### Change the Current Save/Load Behavior -{{source=..\SamplesCS\Scheduler\Reminders\SaveLoadReminders.cs region=SetRemindersBehavior}} -{{source=..\SamplesVB\Scheduler\Reminders\SaveLoadReminders.vb region=SetRemindersBehavior}} -````C# -this.radScheduler1.SaveLoadRemindersBehavior = new CustomSaveLoadRemindersBehavior(this.radScheduler1); +#### Change the Current Save/Load Behavior -```` -````VB.NET -Me.radScheduler1.SaveLoadRemindersBehavior = New CustomSaveLoadRemindersBehavior(Me.radScheduler1) + + -```` -{{endregion}} # See Also diff --git a/controls/scheduler/reminders/localizing-reminder-strings.md b/controls/scheduler/reminders/localizing-reminder-strings.md index b2e7f403e..4f970b0cf 100644 --- a/controls/scheduler/reminders/localizing-reminder-strings.md +++ b/controls/scheduler/reminders/localizing-reminder-strings.md @@ -21,195 +21,19 @@ Below is a sample implementation of an English localization provider: #### Sample English Localization Provider -{{source=..\SamplesCS\Scheduler\Reminders\EnglishReminderLocalizationProvider.cs region=englishLocalizationProvider}} -{{source=..\SamplesVB\Scheduler\Reminders\EnglishReminderLocalizationProvider.vb region=englishLocalizationProvider}} - -````C# -public class EnglishReminderLocalizationProvider : RadReminderLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case RadReminderStringId.AlarmFormButtonDismiss: - return "Dismiss"; - case RadReminderStringId.AlarmFormButtonDismissAll: - return "Dismiss All"; - case RadReminderStringId.AlarmFormButtonOpenItem: - return "Open Item"; - case RadReminderStringId.AlarmFormButtonSnooze: - return "Snooze"; - case RadReminderStringId.AlarmFormColumnDueIn: - return "Due in"; - case RadReminderStringId.AlarmFormColumnSubject: - return "Subject"; - case RadReminderStringId.AlarmFormLabelSnooze: - return "Click Snooze to be reminded again in:"; - case RadReminderStringId.AlarmFormReminder: - return "Reminder"; - case RadReminderStringId.AlarmFormReminders: - return "Reminders"; - case RadReminderStringId.AlarmFormSnoozeOneMinute: - return "1 minute"; - case RadReminderStringId.AlarmFormSnoozeFiveMinutes: - return "5 minutes"; - case RadReminderStringId.AlarmFormSnoozeTenMinutes: - return "10 minutes"; - case RadReminderStringId.AlarmFormSnoozeFifteenMinutes: - return "15 minutes"; - case RadReminderStringId.AlarmFormSnoozeThirtyMinutes: - return "30 minutes"; - case RadReminderStringId.AlarmFormSnoozeOneHour: - return "1 hour"; - case RadReminderStringId.AlarmFormSnoozeTwoHours: - return "2 hours"; - case RadReminderStringId.AlarmFormSnoozeFourHours: - return "4 hours"; - case RadReminderStringId.AlarmFormSnoozeEightHours: - return "8 hours"; - case RadReminderStringId.AlarmFormSnoozeHalfDay: - return "0.5 days"; - case RadReminderStringId.AlarmFormSnoozeOneDay: - return "1 day"; - case RadReminderStringId.AlarmFormSnoozeTwoDays: - return "2 days"; - case RadReminderStringId.AlarmFormSnoozeThreeDays: - return "3 days"; - case RadReminderStringId.AlarmFormSnoozeFourDays: - return "4 days"; - case RadReminderStringId.AlarmFormSnoozeOneWeek: - return "1 week"; - case RadReminderStringId.AlarmFormSnoozeTwoWeeks: - return "2 weeks"; - case RadReminderStringId.DueInMinute: - return "minute"; - case RadReminderStringId.DueInMinutes: - return "minutes"; - case RadReminderStringId.DueInHour: - return "hour"; - case RadReminderStringId.DueInHours: - return "hours"; - case RadReminderStringId.DueInDay: - return "day"; - case RadReminderStringId.DueInDays: - return "days"; - case RadReminderStringId.DueInWeek: - return "week"; - case RadReminderStringId.DueInWeeks: - return "weeks"; - case RadReminderStringId.DueInNow: - return "now"; - case RadReminderStringId.DueInOverdue: - return "{0} overdue"; - case RadReminderStringId.AlarmFormSelectMoreRemindObjects: - return " reminders are selected."; - } - return string.Empty; - } -} - -```` -````VB.NET -Public Class EnglishReminderLocalizationProvider - Inherits RadReminderLocalizationProvider - Public Overrides Function GetLocalizedString(ByVal id As String) As String - Select Case id - Case RadReminderStringId.AlarmFormButtonDismiss - Return "Dismiss" - Case RadReminderStringId.AlarmFormButtonDismissAll - Return "Dismiss All" - Case RadReminderStringId.AlarmFormButtonOpenItem - Return "Open Item" - Case RadReminderStringId.AlarmFormButtonSnooze - Return "Snooze" - Case RadReminderStringId.AlarmFormColumnDueIn - Return "Due in" - Case RadReminderStringId.AlarmFormColumnSubject - Return "Subject" - Case RadReminderStringId.AlarmFormLabelSnooze - Return "Click Snooze to be reminded again in:" - Case RadReminderStringId.AlarmFormReminder - Return "Reminder" - Case RadReminderStringId.AlarmFormReminders - Return "Reminders" - Case RadReminderStringId.AlarmFormSnoozeEightHours - Return "8 hours" - Case RadReminderStringId.AlarmFormSnoozeFifteenMinutes - Return "15 minutes" - Case RadReminderStringId.AlarmFormSnoozeFiveMinutes - Return "5 minutes" - Case RadReminderStringId.AlarmFormSnoozeFourDays - Return "4 days" - Case RadReminderStringId.AlarmFormSnoozeFourHours - Return "4 hours" - Case RadReminderStringId.AlarmFormSnoozeHalfDay - Return "0.5 days" - Case RadReminderStringId.AlarmFormSnoozeOneDay - Return "1 day" - Case RadReminderStringId.AlarmFormSnoozeOneHour - Return "1 hour" - Case RadReminderStringId.AlarmFormSnoozeOneMinute - Return "1 minute" - Case RadReminderStringId.AlarmFormSnoozeOneWeek - Return "1 week" - Case RadReminderStringId.AlarmFormSnoozeTenMinutes - Return "10 minutes" - Case RadReminderStringId.AlarmFormSnoozeThirtyMinutes - Return "30 minutes" - Case RadReminderStringId.AlarmFormSnoozeThreeDays - Return "3 days" - Case RadReminderStringId.AlarmFormSnoozeTwoDays - Return "2 days" - Case RadReminderStringId.AlarmFormSnoozeTwoHours - Return "2 hours" - Case RadReminderStringId.AlarmFormSnoozeTwoWeeks - Return "2 weeks" - Case RadReminderStringId.DueInDay - Return "day" - Case RadReminderStringId.DueInDays - Return "days" - Case RadReminderStringId.DueInHour - Return "hour" - Case RadReminderStringId.DueInHours - Return "hours" - Case RadReminderStringId.DueInMinute - Return "minute" - Case RadReminderStringId.DueInWeek - Return "week" - Case RadReminderStringId.DueInWeeks - Return "weeks" - Case RadReminderStringId.DueInNow - Return "now" - Case RadReminderStringId.DueInOverdue - Return "{0} overdue" - Case RadReminderStringId.AlarmFormSelectMoreRemindObjects - Return " reminders are selected." - End Select - Return MyBase.GetLocalizedString(id) - End Function -End Class - -```` - -{{endregion}} + + -To apply the custom localization provider, instantiate and assign it to the current localization provider: -#### Change the Current Provider -{{source=..\SamplesCS\Scheduler\Reminders\SchedulerReminder.cs region=usingReminderLocalization}} -{{source=..\SamplesVB\Scheduler\Reminders\SchedulerReminder.vb region=usingReminderLocalization}} +To apply the custom localization provider, instantiate and assign it to the current localization provider: -````C# -RadReminderLocalizationProvider.CurrentProvider = new EnglishReminderLocalizationProvider(); +#### Change the Current Provider -```` -````VB.NET -RadReminderLocalizationProvider.CurrentProvider = New EnglishReminderLocalizationProvider() + + -```` -{{endregion}} The code provided above illustrates the approach to be used to localize the __RadReminder__ and is not intended as a full translation. diff --git a/controls/scheduler/reminders/radschedulerreminder.md b/controls/scheduler/reminders/radschedulerreminder.md index b479afa3c..8816910e9 100644 --- a/controls/scheduler/reminders/radschedulerreminder.md +++ b/controls/scheduler/reminders/radschedulerreminder.md @@ -24,78 +24,31 @@ __RadSchedulerReminder__ represents a special reminder object for the appointme In order to incorporate __RadSchedulerReminder__ in your application, please follow to the steps below. 1\. Initialize the RadSchedulerReminder from code or in the designer. -{{source=..\SamplesCS\Scheduler\Reminders\SchedulerReminder.cs region=creating}} -{{source=..\SamplesVB\Scheduler\Reminders\SchedulerReminder.vb region=creating}} + + -````C# -RadSchedulerReminder schedulerReminder = new RadSchedulerReminder(); -```` -````VB.NET -Dim schedulerReminder As New RadSchedulerReminder() - -```` - -{{endregion}} 2\. Set __AssociatedScheduler__ property. -{{source=..\SamplesCS\Scheduler\Reminders\SchedulerReminder.cs region=associatedScheduler}} -{{source=..\SamplesVB\Scheduler\Reminders\SchedulerReminder.vb region=associatedScheduler}} - -````C# -schedulerReminder.AssociatedScheduler = this.radScheduler1; - -```` -````VB.NET -schedulerReminder.AssociatedScheduler = Me.RadScheduler1 + + -```` -{{endregion}} 3\. Set StartReminderInterval and EndReminderInterval. -{{source=..\SamplesCS\Scheduler\Reminders\SchedulerReminder.cs region=interval}} -{{source=..\SamplesVB\Scheduler\Reminders\SchedulerReminder.vb region=interval}} + + -````C# -schedulerReminder.StartReminderInterval = DateTime.Now; -schedulerReminder.EndReminderInterval = DateTime.Now.AddDays(1); -```` -````VB.NET -schedulerReminder.StartReminderInterval = Date.Now -schedulerReminder.EndReminderInterval = Date.Now.AddDays(1) - -```` - -{{endregion}} 4\. You should set the reminder property of the appointment. This property indicates how much time before the appointment start, the reminder will be shown. For example you can initialize and add an appointment with the following code. -{{source=..\SamplesCS\Scheduler\Reminders\SchedulerReminder.cs region=reminder}} -{{source=..\SamplesVB\Scheduler\Reminders\SchedulerReminder.vb region=reminder}} - -````C# -DateTime dtStart = DateTime.Now.AddMinutes(1); -DateTime dtEnd = dtStart.AddHours(1); -Appointment appointment = new Appointment(dtStart, dtEnd, "Appointment description"); -this.radScheduler1.Appointments.Add(appointment); - -appointment.Reminder = new TimeSpan(10000); - -```` -````VB.NET -Dim dtStart As DateTime = DateTime.Now.AddMinutes(1) -Dim dtEnd As DateTime = dtStart.AddHours(1) -Dim appointment As New Appointment(dtStart, dtEnd, "Appointment description") -Me.RadScheduler1.Appointments.Add(appointment) -appointment.Reminder = New TimeSpan(10000) + + -```` -{{endregion}} Also you can set this in AppointmentEditDialog at runtime. diff --git a/controls/scheduler/views/agenda-view.md b/controls/scheduler/views/agenda-view.md index 8c5f260a8..ba7c1844f 100644 --- a/controls/scheduler/views/agenda-view.md +++ b/controls/scheduler/views/agenda-view.md @@ -20,42 +20,20 @@ Agenda View is a table, structured like a simple list, which lists appointments The Agenda View can be set to be the default view which the user sees by setting the RadScheduler.**ActiveViewType** property: -{{source=..\SamplesCS\Scheduler\Views\AgendaView.cs region=SetView}} -{{source=..\SamplesVB\Scheduler\Views\AgendaView.vb region=SetView}} + + -````C# -this.radScheduler1.ActiveViewType = Telerik.WinControls.UI.SchedulerViewType.Agenda; -```` -````VB.NET -Me.radScheduler1.ActiveViewType = Telerik.WinControls.UI.SchedulerViewType.Agenda - -```` - -{{endregion}} ## Get Agenda View To get the instance of the **SchedulerAgendaView** from the **RadScheduler** object, you can either use the **GetAgendaView** method or get the **ActiveView** property: -{{source=..\SamplesCS\Scheduler\Views\AgendaView.cs region=GetAgendaView}} -{{source=..\SamplesVB\Scheduler\Views\AgendaView.vb region=GetAgendaView}} - -````C# -SchedulerAgendaView agendaView = this.radScheduler1.ActiveView as SchedulerAgendaView; -//or -agendaView = this.radScheduler1.GetAgendaView(); - -```` -````VB.NET -Dim agendaView As SchedulerAgendaView = TryCast(Me.radScheduler1.ActiveView, SchedulerAgendaView) -'or -agendaView = Me.radScheduler1.GetAgendaView() + + -```` -{{endregion}} >note This method returns *null* if the active view of the **RadScheduler** is not **SchedulerAgendaView**. @@ -63,21 +41,10 @@ agendaView = Me.radScheduler1.GetAgendaView() **SchedulerAgendaView** internally uses a [RadGridView]({%slug winforms/gridview%}) to display the available records. It can be accessed through the SchedulerAgendaViewElement.**Grid** property. Feel free to use the whole API that **RadGridView** offers to achieve any custom requirements that you have. -{{source=..\SamplesCS\Scheduler\Views\AgendaView.cs region=GetGrid}} -{{source=..\SamplesVB\Scheduler\Views\AgendaView.vb region=GetGrid}} + + -````C# -SchedulerAgendaViewElement agendaViewElement = this.radScheduler1.SchedulerElement.ViewElement as SchedulerAgendaViewElement; -RadGridView agendaGrid = agendaViewElement.Grid; -```` -````VB.NET -Dim agendaViewElement As SchedulerAgendaViewElement = TryCast(Me.radScheduler1.SchedulerElement.ViewElement, SchedulerAgendaViewElement) -Dim agendaGrid As RadGridView = agendaViewElement.Grid - -```` - -{{endregion}} ## SchedulerAgendaView Properties @@ -104,23 +71,10 @@ Since **SchedulerAgendaView** uses a **RadGridView**, it supports grouping by di In order to group the **SchedulerAgendaView** by resources programmatically it is necessary to add a [GroupDescriptor]({%slug winforms/gridview/grouping/setting-groups-programmatically%}) to the grid for the **Resource** property: -{{source=..\SamplesCS\Scheduler\Views\AgendaView.cs region=GroupByResources}} -{{source=..\SamplesVB\Scheduler\Views\AgendaView.vb region=GroupByResources}} - -````C# -GroupDescriptor descriptor = new GroupDescriptor(); -descriptor.GroupNames.Add("Resource", ListSortDirection.Ascending); -agendaViewElement.Grid.GroupDescriptors.Add(descriptor); - -```` -````VB.NET -Dim descriptor As GroupDescriptor = New GroupDescriptor() -descriptor.GroupNames.Add("Resource", ListSortDirection.Ascending) -agendaViewElement.Grid.GroupDescriptors.Add(descriptor) + + -```` -{{endregion}} >caption Figure 3: Agenda View Grouped by Resources diff --git a/controls/scheduler/views/common-visual-properties.md b/controls/scheduler/views/common-visual-properties.md index ec8c528f5..18aeafcd0 100644 --- a/controls/scheduler/views/common-visual-properties.md +++ b/controls/scheduler/views/common-visual-properties.md @@ -17,19 +17,10 @@ Some properties can modify the appearance of the appointments in __RadScheduler_ Exact Time Rendering increases readability of the appointments by rendering them at its exact Start and End time corresponding with the time slots around. When __ExactTimeRendering__ is enabled, appointments will not snap to the nearest cell border but will render exactly on the location where their Start and End dates are expected to be. To enable this functionality, use the __ExactTimeRendering__ property: -{{source=..\SamplesCS\Scheduler\Views\CommonProperties.cs region=exactTimeRendering}} -{{source=..\SamplesVB\Scheduler\Views\CommonProperties.vb region=exactTimeRendering}} + + -````C# -this.radScheduler1.EnableExactTimeRendering = true; -```` -````VB.NET -Me.RadScheduler1.EnableExactTimeRendering = True - -```` - -{{endregion}} >caption Figure 1: Exact Time Rendering ![WinForms RadScheduler Exact Time Rendering](images/scheduler-views-common-visual-properties001.png) @@ -38,19 +29,10 @@ Me.RadScheduler1.EnableExactTimeRendering = True When __AutoSizeAppointments__ is enabled, appointment elements will automatically adjust their height so that they can fully display their summary. This property will not have any effect in DayView and WeekView because the height in these views is determined by the appointment’s dates. -{{source=..\SamplesCS\Scheduler\Views\CommonProperties.cs region=autoSizeAppointments}} -{{source=..\SamplesVB\Scheduler\Views\CommonProperties.vb region=autoSizeAppointments}} - -````C# -this.radScheduler1.AutoSizeAppointments = true; - -```` -````VB.NET -Me.RadScheduler1.AutoSizeAppointments = True + + -```` -{{endregion}} >caption Figure 2: AutoSize Appointments ![WinForms RadScheduler AutoSize Appointments](images/scheduler-views-common-visual-properties002.png) @@ -59,39 +41,19 @@ Me.RadScheduler1.AutoSizeAppointments = True When __AutoSizeAppointments__ is disabled, the appointments in Month and Timeline views have a fixed height which can be modified by using the __AppointmentsHeight__ property. -{{source=..\SamplesCS\Scheduler\Views\CommonProperties.cs region=appointmentsHeight}} -{{source=..\SamplesVB\Scheduler\Views\CommonProperties.vb region=appointmentsHeight}} + + -````C# -((SchedulerMonthViewElement)this.radScheduler1.ViewElement).AppointmentHeight = 50; -((SchedulerTimelineViewElement)this.radScheduler1.ViewElement).AppointmentHeight = 50; -```` -````VB.NET -DirectCast(Me.RadScheduler1.ViewElement, SchedulerMonthViewElement).AppointmentHeight = 50 -DirectCast(Me.RadScheduler1.ViewElement, SchedulerTimelineViewElement).AppointmentHeight = 50 - -```` - -{{endregion}} ## Spacing Between Appointments Using the __AppointmentsMargin__ property, you can specify the spacing between the appointment elements: -{{source=..\SamplesCS\Scheduler\Views\CommonProperties.cs region=appointmentsMargin}} -{{source=..\SamplesVB\Scheduler\Views\CommonProperties.vb region=appointmentsMargin}} - -````C# -this.radScheduler1.ViewElement.AppointmentMargin = new Padding(5, 0, 10, 0); - -```` -````VB.NET -Me.RadScheduler1.ViewElement.AppointmentMargin = New Padding(5, 0, 10, 0) + + -```` -{{endregion}} >caption Figure 3: Appointments Spacing ![WinForms RadScheduler Appointments Spacing](images/scheduler-views-common-visual-properties003.png) diff --git a/controls/scheduler/views/day-view.md b/controls/scheduler/views/day-view.md index 5fe00c252..5a30610d4 100644 --- a/controls/scheduler/views/day-view.md +++ b/controls/scheduler/views/day-view.md @@ -24,19 +24,10 @@ The Day View is the default RadScheduler view, but you can explicitly set it to #### Set Day View -{{source=..\SamplesCS\Scheduler\Views\DayView.cs region=activeViewType1}} -{{source=..\SamplesVB\Scheduler\Views\DayView.vb region=activeViewType1}} + + -````C# -this.radScheduler1.ActiveViewType = SchedulerViewType.Day; -```` -````VB.NET -Me.RadScheduler1.ActiveViewType = SchedulerViewType.Day - -```` - -{{endregion}} ## Getting Day View @@ -45,19 +36,10 @@ To get the instance to the SchedulerDayView from the RadScheduler object, either #### GetDayView Method -{{source=..\SamplesCS\Scheduler\Views\DayView.cs region=getDayView}} -{{source=..\SamplesVB\Scheduler\Views\DayView.vb region=getDayView}} - -````C# -SchedulerDayView dayView = this.radScheduler1.GetDayView(); + + -```` -````VB.NET -Dim dayView As SchedulerDayView = Me.RadScheduler1.GetDayView() -```` - -{{endregion}} >note This method returns null if the active view of the scheduler is not SchedulerDayView. > @@ -66,24 +48,10 @@ Dim dayView As SchedulerDayView = Me.RadScheduler1.GetDayView() #### ActiveView Property -{{source=..\SamplesCS\Scheduler\Views\DayView.cs region=activeView2}} -{{source=..\SamplesVB\Scheduler\Views\DayView.vb region=activeView2}} - -````C# -if (this.radScheduler1.ActiveViewType == SchedulerViewType.Day) -{ - SchedulerDayView activeDayView = (SchedulerDayView)this.radScheduler1.ActiveView; -} + + -```` -````VB.NET -If Me.RadScheduler1.ActiveViewType = SchedulerViewType.Day Then - Dim activeDayView As SchedulerDayView = CType(Me.RadScheduler1.ActiveView, SchedulerDayView) -End If -```` - -{{endregion}} ## Changing the number of days visible @@ -91,19 +59,9 @@ The Day View can show a predefined number of days through the __DayCount__ prope #### Day Count -{{source=..\SamplesCS\Scheduler\Views\DayView.cs region=dayCount}} -{{source=..\SamplesVB\Scheduler\Views\DayView.vb region=dayCount}} - -````C# -dayView.DayCount = 3; - -```` -````VB.NET -dayView.DayCount = 3 + + -```` - -{{endregion}} ## Changing The Work Time @@ -112,19 +70,10 @@ The work time hours is a predefined range of hours, which can be specified withi #### Work Time -{{source=..\SamplesCS\Scheduler\Views\DayView.cs region=workTime}} -{{source=..\SamplesVB\Scheduler\Views\DayView.vb region=workTime}} - -````C# -dayView.WorkTime = TimeInterval.DefaultWorkTime; + + -```` -````VB.NET -dayView.WorkTime = TimeInterval.DefaultWorkTime -```` - -{{endregion}} Example when you set a 4 hour working day: @@ -135,21 +84,10 @@ Additionally, you can specify which week days are part of the working week. This #### Work Week Start and End -{{source=..\SamplesCS\Scheduler\Views\DayView.cs region=workWeek}} -{{source=..\SamplesVB\Scheduler\Views\DayView.vb region=workWeek}} - -````C# -dayView.WorkWeekStart = DayOfWeek.Thursday; -dayView.WorkWeekEnd = DayOfWeek.Saturday; - -```` -````VB.NET -dayView.WorkWeekStart = DayOfWeek.Thursday -dayView.WorkWeekEnd = DayOfWeek.Saturday + + -```` -{{endregion}} ## Showing and hiding the Day Headers @@ -157,19 +95,10 @@ Showing/hiding the day headers is done through the __ShowHeader__ property (the #### Show Day Headers -{{source=..\SamplesCS\Scheduler\Views\DayView.cs region=showHeader}} -{{source=..\SamplesVB\Scheduler\Views\DayView.vb region=showHeader}} - -````C# -dayView.ShowHeader = true; - -```` -````VB.NET -dayView.ShowHeader = True + + -```` -{{endregion}} ## Customizing the day header format @@ -177,19 +106,9 @@ RadScheduler uses the [.NET Standard DateTime Format Strings](http://msdn.micros #### Set Header Format -{{source=..\SamplesCS\Scheduler\Views\DayView.cs region=headerFormat}} -{{source=..\SamplesVB\Scheduler\Views\DayView.vb region=headerFormat}} + + -````C# -dayView.Scheduler.HeaderFormat = "MMMM dd"; - -```` -````VB.NET -dayView.Scheduler.HeaderFormat = "MMMM dd" - -```` - -{{endregion}} ## Ruler Scale @@ -210,19 +129,10 @@ The default __scale of the ruler__ can be set with a single property (__RangeFac #### Set Ruler Scale -{{source=..\SamplesCS\Scheduler\Views\DayView.cs region=rangeFactor}} -{{source=..\SamplesVB\Scheduler\Views\DayView.vb region=rangeFactor}} - -````C# -dayView.RangeFactor = ScaleRange.Hour; + + -```` -````VB.NET -dayView.RangeFactor = ScaleRange.Hour -```` - -{{endregion}} ## Ruler Height and Row Height @@ -230,19 +140,10 @@ The size of the ruler height (and row height respectively) is controlled by the #### Set Ruler Size -{{source=..\SamplesCS\Scheduler\Views\DayView.cs region=rulerScaleSize}} -{{source=..\SamplesVB\Scheduler\Views\DayView.vb region=rulerScaleSize}} - -````C# -dayView.RulerScaleSize = 50; - -```` -````VB.NET -dayView.RulerScaleSize = 50 + + -```` -{{endregion}} ## Start and End Times @@ -250,27 +151,10 @@ You can control which hours are visible in the view by using __RulerStartScale__ #### Ruler Start and End -{{source=..\SamplesCS\Scheduler\Views\DayView.cs region=rulerStartScale}} -{{source=..\SamplesVB\Scheduler\Views\DayView.vb region=rulerStartScale}} - -````C# -dayView.RangeFactor = ScaleRange.QuarterHour; -dayView.RulerStartScale = 9; -dayView.RulerStartScaleMinutes = 30; -dayView.RulerEndScale = 14; -dayView.RulerEndScaleMinutes = 45; - -```` -````VB.NET -dayView.RangeFactor = ScaleRange.QuarterHour -dayView.RulerStartScale = 9 -dayView.RulerStartScaleMinutes = 30 -dayView.RulerEndScale = 14 -dayView.RulerEndScaleMinutes = 45 + + -```` -{{endregion}} >caption Figure 3: Ruler Scaling ![WinForms RadScheduler Ruler Scaling](images/scheduler-views-day-view003.png) @@ -281,46 +165,20 @@ The __RulerFormatStrings__ property changes the time format in the ruler between #### Set 12 Hour Time Format -{{source=..\SamplesCS\Scheduler\Views\DayView.cs region=12rulerTimeFormat}} -{{source=..\SamplesVB\Scheduler\Views\DayView.vb region=12rulerTimeFormat}} + + -````C# -dayView.RulerStartScale = 9; -dayView.RulerEndScale = 14; -dayView.RulerFormatStrings = new RulerFormatStrings("%h", "mm", "", ""); -```` -````VB.NET -dayView.RulerStartScale = 9 -dayView.RulerEndScale = 14 -dayView.RulerFormatStrings = New RulerFormatStrings("%h", "mm", "", "") - -```` - -{{endregion}} >caption Figure 4: 12 Hour Time Format ![WinForms RadScheduler Hour Time Format](images/scheduler-views-day-view005.png) #### Set 24 Hour Time Format -{{source=..\SamplesCS\Scheduler\Views\DayView.cs region=24rulerTimeFormat}} -{{source=..\SamplesVB\Scheduler\Views\DayView.vb region=24rulerTimeFormat}} - -````C# -dayView.RulerStartScale = 9; -dayView.RulerEndScale = 14; -dayView.RulerFormatStrings = new RulerFormatStrings("%H", "mm", "", ""); + + -```` -````VB.NET -dayView.RulerStartScale = 9 -dayView.RulerEndScale = 14 -dayView.RulerFormatStrings = New RulerFormatStrings("%H", "mm", "", "") -```` - -{{endregion}} >caption Figure 5: 24 Hour Time Format ![WinForms RadScheduler 4 Hour Time Format](images/scheduler-views-day-view006.png) @@ -331,19 +189,10 @@ To show and hide the ruler, use the __ShowRuler__ property: #### Show Ruler -{{source=..\SamplesCS\Scheduler\Views\DayView.cs region=showRuler}} -{{source=..\SamplesVB\Scheduler\Views\DayView.vb region=showRuler}} - -````C# -dayView.ShowRuler = true; + + -```` -````VB.NET -dayView.ShowRuler = True -```` - -{{endregion}} ## Ruler Width  @@ -351,19 +200,10 @@ The width of the ruler is controlled from the __RulerWidth__ property, whereas t #### Set Ruler Width -{{source=..\SamplesCS\Scheduler\Views\DayView.cs region=rulerWidth}} -{{source=..\SamplesVB\Scheduler\Views\DayView.vb region=rulerWidth}} - -````C# -dayView.RulerWidth = 40; - -```` -````VB.NET -dayView.RulerWidth = 40 + + -```` -{{endregion}} ## Current Time Pointer @@ -371,25 +211,10 @@ The current time pointer is a thin line on the ruler and on the today’s column #### Time Pointer -{{source=..\SamplesCS\Scheduler\Views\DayView.cs region=currentTimePointer}} -{{source=..\SamplesVB\Scheduler\Views\DayView.vb region=currentTimePointer}} - -````C# -SchedulerDayViewElement dayViewElement = (SchedulerDayViewElement)this.radScheduler1.ViewElement; -dayViewElement.DataAreaElement.Ruler.TimePointerStyle = RulerCurrentTimePointer.Arrow; -dayViewElement.DataAreaElement.Ruler.CurrentTimePointerWidth = 3; -dayViewElement.DataAreaElement.Ruler.CurrentTimePointerColor = Color.Red; - -```` -````VB.NET -Dim dayViewElement As SchedulerDayViewElement = DirectCast(Me.RadScheduler1.ViewElement, SchedulerDayViewElement) -dayViewElement.DataAreaElement.Ruler.TimePointerStyle = RulerCurrentTimePointer.Arrow -dayViewElement.DataAreaElement.Ruler.CurrentTimePointerWidth = 3 -dayViewElement.DataAreaElement.Ruler.CurrentTimePointerColor = Color.Red + + -```` -{{endregion}} ## The All Day Area @@ -397,21 +222,10 @@ The AllDay area contains appointments that are either defined as AllDay appointm #### Modify All Day Area -{{source=..\SamplesCS\Scheduler\Views\DayView.cs region=allDayArea}} -{{source=..\SamplesVB\Scheduler\Views\DayView.vb region=allDayArea}} + + -````C# -dayViewElement.AllDayHeaderElement.HeaderHeight = 50; -dayViewElement.AllDayHeaderElement.MaxHeaderHeight = 200; -```` -````VB.NET -dayViewElement.AllDayHeaderElement.HeaderHeight = 50 -dayViewElement.AllDayHeaderElement.MaxHeaderHeight = 200 - -```` - -{{endregion}} ## Modifying The Size Of Day View Columns @@ -419,19 +233,10 @@ The __SchedulerDayViewElement__ allows you to specify different size for the dif #### Set Column Size -{{source=..\SamplesCS\Scheduler\Views\DayView.cs region=resizeColumns}} -{{source=..\SamplesVB\Scheduler\Views\DayView.vb region=resizeColumns}} - -````C# -dayViewElement.SetColumnWidth(2, 2); - -```` -````VB.NET -dayViewElement.SetColumnWidth(2, 2) + + -```` -{{endregion}} >caption Figure 6: Column Size ![WinForms RadScheduler Column Size](images/scheduler-views-day-view007.png) diff --git a/controls/scheduler/views/grouping-by-resources.md b/controls/scheduler/views/grouping-by-resources.md index 3836e171c..59058722b 100644 --- a/controls/scheduler/views/grouping-by-resources.md +++ b/controls/scheduler/views/grouping-by-resources.md @@ -24,58 +24,19 @@ If you want to group RadScheduler by resources you can use the __GroupType__ pr #### Group by Resources -{{source=..\SamplesCS\Scheduler\Views\GroupingByResources.cs region=groupType}} -{{source=..\SamplesVB\Scheduler\Views\GroupingByResources.vb region=groupType}} + + -````C# -this.radScheduler1.GroupType = GroupType.Resource; -```` -````VB.NET -Me.RadScheduler1.GroupType = GroupType.Resource - -```` - -{{endregion}} You can add/remove resources using the RadScheduler’s Resources collection. The resources in __RadScheduler__ for Winforms are represented by the Resource class and you can assign it text, color and image values. #### Resources Collection -{{source=..\SamplesCS\Scheduler\Views\GroupingByResources.cs region=addingResources}} -{{source=..\SamplesVB\Scheduler\Views\GroupingByResources.vb region=addingResources}} - -````C# -Color[] colors = new Color[]{Color.LightBlue, Color.LightGreen, Color.LightYellow, - Color.Red, Color.Orange, Color.Pink, Color.Purple, Color.Peru, Color.PowderBlue}; -string[] names = new string[]{"Alan Smith", "Anne Dodsworth", - "Boyan Mastoni", "Richard Duncan", "Maria Shnaider"}; -for (int i = 0; i < names.Length; i++) -{ - Resource resource = new Resource(); - resource.Id = new EventId(i); - resource.Name = names[i]; - resource.Color = colors[i]; - resource.Image = this.imageList1.Images[i]; - this.radScheduler1.Resources.Add(resource); -} - -```` -````VB.NET -Dim colors() As Color = {Color.LightBlue, Color.LightGreen, Color.LightYellow, Color.Red, Color.Orange, Color.Pink, Color.Purple, Color.Peru, Color.PowderBlue} -Dim names() As String = {"Alan Smith", "Anne Dodsworth", "Boyan Mastoni", "Richard Duncan", "Maria Shnaider"} -For i As Integer = 0 To names.Length - 1 - Dim resource As New Telerik.WinControls.UI.Resource() - resource.Id = New EventId(i) - resource.Name = names(i) - resource.Color = colors(i) - resource.Image = Me.imageList1.Images(i) - Me.RadScheduler1.Resources.Add(resource) -Next i - -```` - -{{endregion}} + + + + ## Setting the Number of Displayed Resources @@ -83,19 +44,10 @@ You can use the view’s __ResourcesPerView__ property to change the number of v #### Resources Count -{{source=..\SamplesCS\Scheduler\Views\GroupingByResources.cs region=getDayView}} -{{source=..\SamplesVB\Scheduler\Views\GroupingByResources.vb region=getDayView}} + + -````C# -this.radScheduler1.ActiveView.ResourcesPerView = 2; -```` -````VB.NET -Me.RadScheduler1.ActiveView.ResourcesPerView = 2 - -```` - -{{endregion}} ## Navigating Through Resources @@ -103,123 +55,35 @@ Navigating through resources To navigate to a specific resource you can use the #### Resource Start Index -{{source=..\SamplesCS\Scheduler\Views\GroupingByResources.cs region=resourceNavigation}} -{{source=..\SamplesVB\Scheduler\Views\GroupingByResources.vb region=resourceNavigation}} - -````C# -((SchedulerViewGroupedByResourceElementBase)this.radScheduler1.ViewElement).ResourceStartIndex = 2; - -```` -````VB.NET -CType(Me.RadScheduler1.ViewElement, SchedulerViewGroupedByResourceElementBase).ResourceStartIndex = 2 + + -```` -{{endregion}} To track when the resource index is changed, you can use the ResourceStartIndexChanging and ResourceStartIndexChanged events. The first one is fired before the index is actually changed and allows you to cancel the action. The second one is fired when the index has changed and the view was updated. #### Track Index Changes -{{source=..\SamplesCS\Scheduler\Views\GroupingByResources.cs region=resourceNavigationEvents}} -{{source=..\SamplesVB\Scheduler\Views\GroupingByResources.vb region=resourceNavigationEvents}} + + -````C# -this.radScheduler1.ResourceStartIndexChanging += radScheduler1_ResourceStartIndexChanging; -this.radScheduler1.ResourceStartIndexChanged += radScheduler1_ResourceStartIndexChanged; -```` -````VB.NET -AddHandler Me.RadScheduler1.ResourceStartIndexChanging, AddressOf radScheduler1_ResourceStartIndexChanging -AddHandler Me.RadScheduler1.ResourceStartIndexChanged, AddressOf radScheduler1_ResourceStartIndexChanged -```` +#### Handle Events -{{endregion}} + + -#### Handle Events -{{source=..\SamplesCS\Scheduler\Views\GroupingByResources.cs region=resourceNavigationHandlers}} -{{source=..\SamplesVB\Scheduler\Views\GroupingByResources.vb region=resourceNavigationHandlers}} - -````C# -void radScheduler1_ResourceStartIndexChanging(object sender, ResourceIndexChangingEventArgs e) -{ - if (e.NewStartIndex > 5) - { - e.Cancel = true; - } -} -void radScheduler1_ResourceStartIndexChanged(object sender, EventArgs e) -{ - RadMessageBox.Show("Resource Index has changed"); -} - -```` -````VB.NET -Private Sub radScheduler1_ResourceStartIndexChanging(sender As Object, e As ResourceIndexChangingEventArgs) - If e.NewStartIndex > 5 Then - e.Cancel = True - End If -End Sub -Private Sub radScheduler1_ResourceStartIndexChanged(sender As Object, e As EventArgs) - RadMessageBox.Show("Resource Index has changed") -End Sub - -```` - -{{endregion}} ## Setting a Header Width Depending on the currentlty active view the __SchedulerViewElement__ exposes a __ResourceHeaderHeight__ or __ResourceHeaderWidth__ properties which define the height or width of the header. A suitable place to listen to set these properties is the handler of the RadScheduler.__ActiveViewChanged__ event. -{{source=..\SamplesCS\Scheduler\Views\GroupingByResources.cs region=SetResourceHeader}} -{{source=..\SamplesVB\Scheduler\Views\GroupingByResources.vb region=SetResourceHeader}} -````C# -private void radScheduler1_ActiveViewChanged(object sender, SchedulerViewChangedEventArgs e) -{ - switch (e.NewView.ViewType) - { - case SchedulerViewType.Day: - case SchedulerViewType.Week: - SchedulerDayViewGroupedByResourceElement dayView = this.radScheduler1.SchedulerElement.ViewElement as SchedulerDayViewGroupedByResourceElement; - dayView.ResourceHeaderHeight = 80; - break; - case SchedulerViewType.Month: - SchedulerMonthViewGroupedByResourceElement monthView = this.radScheduler1.SchedulerElement.ViewElement as SchedulerMonthViewGroupedByResourceElement; - monthView.ResourceHeaderHeight = 50; - break; - case SchedulerViewType.Timeline: - TimelineGroupingByResourcesElement timelineElement = this.radScheduler1.SchedulerElement.ViewElement as TimelineGroupingByResourcesElement; - timelineElement.ResourceHeaderWidth = 150; - break; - } -} - -```` -````VB.NET -Private Sub RadScheduler1_ActiveViewChanged(sender As Object, e As SchedulerViewChangedEventArgs) - Select Case e.NewView.ViewType - Case SchedulerViewType.Day, SchedulerViewType.Week - Dim dayView As SchedulerDayViewGroupedByResourceElement = TryCast(Me.RadScheduler1.SchedulerElement.ViewElement, SchedulerDayViewGroupedByResourceElement) - dayView.ResourceHeaderHeight = 80 - Exit Select - Case SchedulerViewType.Month - Dim monthView As SchedulerMonthViewGroupedByResourceElement = TryCast(Me.RadScheduler1.SchedulerElement.ViewElement, SchedulerMonthViewGroupedByResourceElement) - monthView.ResourceHeaderHeight = 50 - Exit Select - Case SchedulerViewType.Timeline - Dim timelineElement As TimelineGroupingByResourcesElement = TryCast(Me.RadScheduler1.SchedulerElement.ViewElement, TimelineGroupingByResourcesElement) - timelineElement.ResourceHeaderWidth = 150 - Exit Select - End Select -End Sub - -```` - - -{{endregion}} + + + + ## Modifying the Size of the Resources @@ -227,19 +91,10 @@ __RadScheduler__ allows you to specify different size for the different resource #### Define Resource Size -{{source=..\SamplesCS\Scheduler\Views\GroupingByResources.cs region=resourceResizing}} -{{source=..\SamplesVB\Scheduler\Views\GroupingByResources.vb region=resourceResizing}} + + -````C# -((SchedulerViewGroupedByResourceElementBase)this.radScheduler1.ViewElement).SetResourceSize(1, 2); -```` -````VB.NET -CType(Me.RadScheduler1.ViewElement, SchedulerViewGroupedByResourceElementBase).SetResourceSize(1, 2) - -```` - -{{endregion}} >caption Figure 1: Resource Size @@ -261,129 +116,10 @@ The example below demonstrates how each of the child view elements can be access #### Customize Child Views -{{source=..\SamplesCS\Scheduler\Views\GroupingByResources.cs region=CustomizeChildViewElements}} -{{source=..\SamplesVB\Scheduler\Views\GroupingByResources.vb region=CustomizeChildViewElements}} -````C# -private void CustomizeChildViewElements(RadScheduler radScheduler) -{ - if (radScheduler.GroupType != GroupType.Resource) - { - return; - } - switch (radScheduler.ActiveViewType) - { - case SchedulerViewType.Day: - case SchedulerViewType.Week: - case SchedulerViewType.WorkWeek: - SchedulerDayViewGroupedByResourceElement dayViewGroupedElement = (SchedulerDayViewGroupedByResourceElement)radScheduler.ViewElement; - IList childDayElements = dayViewGroupedElement.GetChildViewElements(); - foreach (SchedulerDayViewElement dayViewElement in childDayElements) - { - IResource resource = dayViewElement.View.GetResources()[0]; - // Hide a particular day for a selected resource - int index = 2; - if (resource.Name == "Anne Dodsworth" && index < dayViewElement.GetDayViewBase().DayCount) - { - dayViewElement.SetColumnWidth(index, 0); - } - else - { - dayViewElement.SetColumnWidth(index, 1); - } - } - break; - case SchedulerViewType.Month: - SchedulerMonthViewGroupedByResourceElement monthViewGroupedElement = (SchedulerMonthViewGroupedByResourceElement)radScheduler.ViewElement; - IList childMonthElements = monthViewGroupedElement.GetChildViewElements(); - foreach (SchedulerMonthViewElement monthViewElement in childMonthElements) - { - IResource resource = monthViewElement.View.GetResources()[0]; - // Hide weekends for a particular resource - if (resource.Name == "Alan Smith") - { - monthViewElement.GetMonthView().ShowWeekend = false; - } - else - { - monthViewElement.GetMonthView().ShowWeekend = true; - } - } - break; - case SchedulerViewType.Timeline: - TimelineGroupingByResourcesElement timelineViewGroupedElement = (TimelineGroupingByResourcesElement)radScheduler.ViewElement; - IList childTimelineElements = timelineViewGroupedElement.GetChildViewElements(); - foreach (SchedulerTimelineViewElement timelineViewElement in childTimelineElements) - { - IResource resource = timelineViewElement.View.GetResources()[0]; - // Change appointment height for a selected resource - if (resource.Name == "Boyan Mastoni") - { - timelineViewElement.AppointmentHeight = 75; - } - else - { - timelineViewElement.AppointmentHeight = 25; - } - } - break; - } -} - -```` -````VB.NET -Private Sub CustomizeChildViewElements(radScheduler As RadScheduler) - If radScheduler.GroupType <> GroupType.Resource Then - Return - End If - Select Case radScheduler.ActiveViewType - Case SchedulerViewType.Day, SchedulerViewType.Week, SchedulerViewType.WorkWeek - Dim dayViewGroupedElement As SchedulerDayViewGroupedByResourceElement = DirectCast(radScheduler.ViewElement, SchedulerDayViewGroupedByResourceElement) - Dim childDayElements As IList(Of SchedulerDayViewElement) = dayViewGroupedElement.GetChildViewElements() - For Each dayViewElement As SchedulerDayViewElement In childDayElements - Dim resource As IResource = dayViewElement.View.GetResources()(0) - ' Hide a particular day for a selected resource - Dim index As Integer = 2 - If resource.Name = "Anne Dodsworth" AndAlso index < dayViewElement.GetDayViewBase().DayCount Then - dayViewElement.SetColumnWidth(index, 0) - Else - dayViewElement.SetColumnWidth(index, 1) - End If - Next - Exit Select - Case SchedulerViewType.Month - Dim monthViewGroupedElement As SchedulerMonthViewGroupedByResourceElement = DirectCast(radScheduler.ViewElement, SchedulerMonthViewGroupedByResourceElement) - Dim childMonthElements As IList(Of SchedulerMonthViewElement) = monthViewGroupedElement.GetChildViewElements() - For Each monthViewElement As SchedulerMonthViewElement In childMonthElements - Dim resource As IResource = monthViewElement.View.GetResources()(0) - ' Hide weekends for a particular resource - If resource.Name = "Alan Smith" Then - monthViewElement.GetMonthView().ShowWeekend = False - Else - monthViewElement.GetMonthView().ShowWeekend = True - End If - Next - Exit Select - Case SchedulerViewType.Timeline - Dim timelineViewGroupedElement As TimelineGroupingByResourcesElement = DirectCast(radScheduler.ViewElement, TimelineGroupingByResourcesElement) - Dim childTimelineElements As IList(Of SchedulerTimelineViewElement) = timelineViewGroupedElement.GetChildViewElements() - For Each timelineViewElement As SchedulerTimelineViewElement In childTimelineElements - Dim resource As IResource = timelineViewElement.View.GetResources()(0) - ' Change appointment height for a selected resource - If resource.Name = "Boyan Mastoni" Then - timelineViewElement.AppointmentHeight = 75 - Else - timelineViewElement.AppointmentHeight = 25 - End If - Next - Exit Select - End Select -End Sub - -```` - - - -{{endregion}} + + + + >note Due to the UI virtualization the logic for accessing a particular view element associated with a resource needs to reapplied when the current resource or selected view type changes. This can be performed in the handlers of the __ActiveViewChanged__ and __ResourceStartIndexChanged__ events. diff --git a/controls/scheduler/views/month-view.md b/controls/scheduler/views/month-view.md index 5958b3668..d824bcfb7 100644 --- a/controls/scheduler/views/month-view.md +++ b/controls/scheduler/views/month-view.md @@ -29,19 +29,10 @@ The Week View can be set it to be the default view which the user sees: #### ActiveViewType Property -{{source=..\SamplesCS\Scheduler\Views\MonthView.cs region=activeViewType}} -{{source=..\SamplesVB\Scheduler\Views\MonthView.vb region=activeViewType}} + + -````C# -this.radScheduler1.ActiveViewType = Telerik.WinControls.UI.SchedulerViewType.Month; -```` -````VB.NET -Me.RadScheduler1.ActiveViewType = Telerik.WinControls.UI.SchedulerViewType.Month - -```` - -{{endregion}} ## Get Month View @@ -51,20 +42,10 @@ To get the instance to the SchedulerMonthView from the RadScheduler object: #### GetMonthView Method -{{source=..\SamplesCS\Scheduler\Views\MonthView.cs region=getMonthView}} -{{source=..\SamplesVB\Scheduler\Views\MonthView.vb region=getMonthView}} - -````C# - -SchedulerMonthView monthView = this.radScheduler1.GetMonthView(); + + -```` -````VB.NET -Dim monthView As SchedulerMonthView = Me.RadScheduler1.GetMonthView() -```` - -{{endregion}} ## Showing/Hiding The Weekend @@ -72,39 +53,19 @@ By default the weekends are shown, but you can hide them by using the __ShowWee #### Show Weekend -{{source=..\SamplesCS\Scheduler\Views\MonthView.cs region=showWeekend}} -{{source=..\SamplesVB\Scheduler\Views\MonthView.vb region=showWeekend}} - -````C# -monthView.ShowWeekend = true; + + -```` -````VB.NET -monthView.ShowWeekend = False -```` - -{{endregion}} You can also specify which days to be considered weekends. The WorkWeekStart and WorkWeekEnd properties allow you to achieve this: #### Set Work Week Start -{{source=..\SamplesCS\Scheduler\Views\MonthView.cs region=workWeek}} -{{source=..\SamplesVB\Scheduler\Views\MonthView.vb region=workWeek}} - -````C# -monthView.WorkWeekStart = DayOfWeek.Tuesday; -monthView.WorkWeekEnd = DayOfWeek.Thursday; + + -```` -````VB.NET -monthView.WorkWeekStart = DayOfWeek.Tuesday -monthView.WorkWeekEnd = DayOfWeek.Thursday -```` - -{{endregion}} ## Change The Start/End Work Days @@ -112,21 +73,10 @@ The work days determine the start and end days for the work week. All days outsi #### Start/End Work Days -{{source=..\SamplesCS\Scheduler\Views\MonthView.cs region=workDays}} -{{source=..\SamplesVB\Scheduler\Views\MonthView.vb region=workDays}} - -````C# -monthView.WorkWeekStart = DayOfWeek.Wednesday; -monthView.WorkWeekEnd = DayOfWeek.Saturday; + + -```` -````VB.NET -monthView.WorkWeekStart = DayOfWeek.Wednesday -monthView.WorkWeekEnd = DayOfWeek.Saturday -```` - -{{endregion}} >caption Figure 2: Shown Weekends @@ -139,38 +89,19 @@ By default the Month view shows 3 weeks at a time, but this can be changed by  #### Set Number of Weeks -{{source=..\SamplesCS\Scheduler\Views\MonthView.cs region=weekCount}} -{{source=..\SamplesVB\Scheduler\Views\MonthView.vb region=weekCount}} - -````C# -monthView.WeekCount = 5; - -```` -````VB.NET -monthView.WeekCount = 5 + + -```` - -{{endregion}} ## Getting The Week Days Displayed #### Get Week Days -{{source=..\SamplesCS\Scheduler\Views\MonthView.cs region=weekDaysCount}} -{{source=..\SamplesVB\Scheduler\Views\MonthView.vb region=weekDaysCount}} - -````C# -int weekDaysCount = monthView.WeekDaysCount; + + -```` -````VB.NET -Dim weekDaysCount As Integer = monthView.WeekDaysCount -```` - -{{endregion}} ## Showing Full Month @@ -178,19 +109,10 @@ It is possible to indicate whether the month view should always display exactly #### Full Month -{{source=..\SamplesCS\Scheduler\Views\MonthView.cs region=showFullMonth}} -{{source=..\SamplesVB\Scheduler\Views\MonthView.vb region=showFullMonth}} - -````C# -monthView.ShowFullMonth = true; + + -```` -````VB.NET -monthView.ShowFullMonth = True -```` - -{{endregion}} >caption Figure 3: Show Full Month ![WinForms RadScheduler Show Full Month](images/scheduler-views-month-view003.png) @@ -199,39 +121,19 @@ monthView.ShowFullMonth = True #### Hiding The Vertical Indicator -{{source=..\SamplesCS\Scheduler\Views\MonthView.cs region=showVerticalNavigator}} -{{source=..\SamplesVB\Scheduler\Views\MonthView.vb region=showVerticalNavigator}} - -````C# -monthView.ShowVerticalNavigator = false; + + -```` -````VB.NET -monthView.ShowVerticalNavigator = False -```` - -{{endregion}} ## Setting The Vertical Navigator Range #### Navigator Range -{{source=..\SamplesCS\Scheduler\Views\MonthView.cs region=verticalNavigatorRange}} -{{source=..\SamplesVB\Scheduler\Views\MonthView.vb region=verticalNavigatorRange}} - -````C# -monthView.RangeStartDate = new DateTime(2016, 6, 10); -monthView.RangeEndDate = new DateTime(2016, 7, 20); - -```` -````VB.NET -monthView.RangeStartDate = New DateTime(2016, 6, 10) -monthView.RangeEndDate = New DateTime(2016, 7, 20) + + -```` -{{endregion}} >caption Figure 4: Navigator Range ![WinForms RadScheduler Navigator Range](images/scheduler-views-month-view004.gif) @@ -242,21 +144,10 @@ The week (row) headers display the date range presented by the respective row. B #### Showing Weeks Headers -{{source=..\SamplesCS\Scheduler\Views\MonthView.cs region=showWeeksHeader}} -{{source=..\SamplesVB\Scheduler\Views\MonthView.vb region=showWeeksHeader}} - -````C# -monthView.ShowWeeksHeader = true; -monthView.EnableWeeksHeader = false; - -```` -````VB.NET -monthView.ShowWeeksHeader = True -monthView.EnableWeeksHeader = True + + -```` -{{endregion}} ## Customizing The Week (Row) Header Format @@ -264,19 +155,10 @@ RadScheduler uses the [.NET Standard DateTime Format Strings](http://msdn.micros #### Setting A Header Format -{{source=..\SamplesCS\Scheduler\Views\MonthView.cs region=headerFormat}} -{{source=..\SamplesVB\Scheduler\Views\MonthView.vb region=headerFormat}} + + -````C# -radScheduler1.HeaderFormat = "MMMM dd"; -```` -````VB.NET -RadScheduler1.HeaderFormat = "MMMM dd" - -```` - -{{endregion}} ## Showing An Exact Month @@ -284,19 +166,10 @@ You can set the __ShowFullMonth__ property to force the __SchedulerMonthView__ t #### Full Month -{{source=..\SamplesCS\Scheduler\Views\MonthView.cs region=showFullMonth}} -{{source=..\SamplesVB\Scheduler\Views\MonthView.vb region=showFullMonth}} - -````C# -monthView.ShowFullMonth = true; - -```` -````VB.NET -monthView.ShowFullMonth = True + + -```` -{{endregion}} ## Vertical Scrolling @@ -304,23 +177,10 @@ The vertical scrollbar in __MonthView__ allows for quick navigation in large dat #### Verical Scrolling Range -{{source=..\SamplesCS\Scheduler\Views\MonthView.cs region=verticalScrolling}} -{{source=..\SamplesVB\Scheduler\Views\MonthView.vb region=verticalScrolling}} + + -````C# -monthView.ShowVerticalNavigator = true; -monthView.RangeStartDate = DateTime.Today.AddYears(-1); -monthView.RangeEndDate = DateTime.Today.AddYears(1); -```` -````VB.NET -monthView.ShowVerticalNavigator = True -monthView.RangeStartDate = DateTime.Today.AddYears(-1) -monthView.RangeEndDate = DateTime.Today.AddYears(1) - -```` - -{{endregion}} ## Handling Overflown Cells @@ -328,21 +188,10 @@ RadScheduler handles the overflown cells in month view in two ways. The first on #### Appointments Scrolling -{{source=..\SamplesCS\Scheduler\Views\MonthView.cs region=overflow}} -{{source=..\SamplesVB\Scheduler\Views\MonthView.vb region=overflow}} - -````C# -monthView.EnableCellOverflowButton = true; -monthView.EnableAppointmentsScrolling = true; - -```` -````VB.NET -monthView.EnableCellOverflowButton = True -monthView.EnableAppointmentsScrolling = True + + -```` -{{endregion}} >caption Figure 5: Appointments Scrolling ![WinForms RadScheduler Appointments Scrolling](images/scheduler-views-month-view005.png) @@ -353,23 +202,10 @@ The __SchedulerMonthViewElement__ allows you to specify different size for the d #### Setting Row Height -{{source=..\SamplesCS\Scheduler\Views\MonthView.cs region=columnRowResize}} -{{source=..\SamplesVB\Scheduler\Views\MonthView.vb region=columnRowResize}} + + -````C# -SchedulerMonthViewElement monthViewElement = (SchedulerMonthViewElement)this.radScheduler1.ViewElement; -monthViewElement.SetRowHeight(1, 2); -monthViewElement.SetColumnWidth(1, 2); -```` -````VB.NET -Dim monthViewElement As SchedulerMonthViewElement = DirectCast(Me.RadScheduler1.ViewElement, SchedulerMonthViewElement) -monthViewElement.SetRowHeight(1, 2) -monthViewElement.SetColumnWidth(1, 2) - -```` - -{{endregion}} >caption Figure 6: Row Height ![WinForms RadScheduler Row Height](images/scheduler-views-month-view006.png) @@ -380,21 +216,10 @@ The month view of RadScheduler contains two headers – the horizontal __MonthVi #### Headers Size -{{source=..\SamplesCS\Scheduler\Views\MonthView.cs region=headerResize}} -{{source=..\SamplesVB\Scheduler\Views\MonthView.vb region=headerResize}} - -````C# -monthViewElement.VerticalHeader.HeaderWidth = 50; -monthViewElement.Header.HeaderHeight = 50; - -```` -````VB.NET -monthViewElement.VerticalHeader.HeaderWidth = 50 -monthViewElement.Header.HeaderHeight = 50 + + -```` -{{endregion}} >caption Figure 7: Headers Size ![WinForms RadScheduler Headers Size](images/scheduler-views-month-view007.png) diff --git a/controls/scheduler/views/multiday-view.md b/controls/scheduler/views/multiday-view.md index 40d12e92d..678d50994 100644 --- a/controls/scheduler/views/multiday-view.md +++ b/controls/scheduler/views/multiday-view.md @@ -22,53 +22,19 @@ __MultidayView__ shows multiple date-time intervals with appointments arranged 1\. In order to set the current view of __RadScheduler__ to __MultidayView__, use the __ActiveViewType__ or __ActiveView__ properties: -{{source=..\SamplesCS\Scheduler\Views\MultiDayView.cs region=multiDay}} -{{source=..\SamplesVB\Scheduler\Views\MultiDayView.vb region=multiDay}} - -````C# -this.radScheduler1.ActiveViewType = SchedulerViewType.MultiDay; -//or -SchedulerMultiDayView multiDayView = new SchedulerMultiDayView(); -DateTime startDate = DateTime.Today; -multiDayView.Intervals.Add(startDate, 2); -multiDayView.Intervals.Add(startDate.AddDays(4), 3); -this.radScheduler1.ActiveView = multiDayView; - -```` -````VB.NET -Me.RadScheduler1.ActiveViewType = SchedulerViewType.MultiDay -'or -Dim multiDayView As New SchedulerMultiDayView() -Dim startDate As Date = Date.Today -multiDayView.Intervals.Add(startDate, 2) -multiDayView.Intervals.Add(startDate.AddDays(4), 3) -Me.RadScheduler1.ActiveView = multiDayView - -```` - -{{endregion}} + + -2\. To add, remove or modify a date-time __Interval__ in SchedulerMultiDayView instance use the __Intervals__ collection. -3\. To get all appointments in a particular interval, use the __GetAppointmentsInInterval__ helper method: -{{source=..\SamplesCS\Scheduler\Views\MultiDayView.cs region=interval}} -{{source=..\SamplesVB\Scheduler\Views\MultiDayView.vb region=interval}} +2\. To add, remove or modify a date-time __Interval__ in SchedulerMultiDayView instance use the __Intervals__ collection. -````C# -DateTimeInterval interval = new DateTimeInterval(); -interval.Duration = new TimeSpan(20, 5, 25); -multiDayView.GetAppointmentsInInterval(interval); +3\. To get all appointments in a particular interval, use the __GetAppointmentsInInterval__ helper method: -```` -````VB.NET -Dim interval As New DateTimeInterval() -interval.Duration = New TimeSpan(20, 5, 25) -multiDayView.GetAppointmentsInInterval(interval) + + -```` -{{endregion}} 4\. To get all appointments in the view, use the __Appointments__ collection. diff --git a/controls/scheduler/views/scheduler-cell-containers.md b/controls/scheduler/views/scheduler-cell-containers.md index f58707539..b80262fb7 100644 --- a/controls/scheduler/views/scheduler-cell-containers.md +++ b/controls/scheduler/views/scheduler-cell-containers.md @@ -19,59 +19,17 @@ The __InitializeCells__ and __InitializeAppointments__ methods are used to refre #### Initialize Elements -{{source=..\SamplesCS\Scheduler\Views\SchedulerCellContainers.cs region=initializeSchedulerChildren}} -{{source=..\SamplesVB\Scheduler\Views\SchedulerCellContainers.vb region=initializeSchedulerChildren}} - -````C# -DayViewAppointmentsTable table = ((SchedulerDayViewElement)this.radScheduler1.ViewElement).DataAreaElement.Table; -table.CellsRefreshed +=table_CellsRefreshed; -table.AppointmentsRefreshed +=table_AppointmentsRefreshed; -table.InitializeCells(); -table.InitializeAppointments(); -//or use the following method which calls both of the above methods -table.InitializeChildren(); - -```` -````VB.NET -Dim table As DayViewAppointmentsTable = DirectCast(Me.radScheduler1.ViewElement, SchedulerDayViewElement).DataAreaElement.Table -AddHandler table.CellsRefreshed, AddressOf table_CellsRefreshed -AddHandler table.AppointmentsRefreshed, AddressOf table_AppointmentsRefreshed -table.InitializeCells() -table.InitializeAppointments() -'or use the following method which calls both of the above methods -table.InitializeChildren() - -```` - -{{endregion}} + + -#### Handle Events -{{source=..\SamplesCS\Scheduler\Views\SchedulerCellContainers.cs region=cellContainerEvents}} -{{source=..\SamplesVB\Scheduler\Views\SchedulerCellContainers.vb region=cellContainerEvents}} -````C# -void table_AppointmentsRefreshed(object sender, EventArgs e) -{ - RadMessageBox.Show("Appointments were refreshed"); -} -void table_CellsRefreshed(object sender, EventArgs e) -{ - RadMessageBox.Show("Cells were refreshed"); -} +#### Handle Events -```` -````VB.NET -Private Sub table_AppointmentsRefreshed(sender As Object, e As EventArgs) - RadMessageBox.Show("Appointments were refreshed") -End Sub -Private Sub table_CellsRefreshed(sender As Object, e As EventArgs) - RadMessageBox.Show("Cells were refreshed") -End Sub + + -```` -{{endregion}} ## Updating The Elements @@ -79,23 +37,10 @@ The __UpdateCells__ and __UpdateAppointments__ are called to synchronize the exi #### Update Elements -{{source=..\SamplesCS\Scheduler\Views\SchedulerCellContainers.cs region=updateSchedulerChildren}} -{{source=..\SamplesVB\Scheduler\Views\SchedulerCellContainers.vb region=updateSchedulerChildren}} - -````C# -DayViewAppointmentsTable table = ((SchedulerDayViewElement)this.radScheduler1.ViewElement).DataAreaElement.Table; -table.UpdateCells(); -table.UpdateAppointments(); + + -```` -````VB.NET -Dim table As DayViewAppointmentsTable = DirectCast(Me.radScheduler1.ViewElement, SchedulerDayViewElement).DataAreaElement.Table -table.UpdateCells() -table.UpdateAppointments() -```` - -{{endregion}} ## Getting The Existing Elements @@ -103,33 +48,10 @@ You can access the cell element and the appointment elements from a SchedulerCel #### Access Elements -{{source=..\SamplesCS\Scheduler\Views\SchedulerCellContainers.cs region=cellContainerGetElements}} -{{source=..\SamplesVB\Scheduler\Views\SchedulerCellContainers.vb region=cellContainerGetElements}} - -````C# -DayViewAppointmentsTable table = ((SchedulerDayViewElement)this.radScheduler1.ViewElement).DataAreaElement.Table; -foreach (SchedulerCellElement cellElement in table.CellElements) -{ - cellElement.BackColor = Color.Red; -} -foreach (AppointmentElement appElement in table.AppointmentElements) -{ - appElement.BackColor = Color.Green; -} - -```` -````VB.NET -Dim table As DayViewAppointmentsTable = DirectCast(Me.radScheduler1.ViewElement, SchedulerDayViewElement).DataAreaElement.Table -For Each cellElement As SchedulerCellElement In table.CellElements - cellElement.BackColor = Color.Red -Next -For Each appElement As AppointmentElement In table.AppointmentElements - appElement.BackColor = Color.Green -Next - -```` - -{{endregion}} + + + + ## Accessing The Containers From The ViewElement @@ -137,74 +59,28 @@ The __SchedulerViewElement__ base type provides means for accessing the containe #### Update Elements In The Container -{{source=..\SamplesCS\Scheduler\Views\SchedulerCellContainers.cs region=viewElementUpdateCells}} -{{source=..\SamplesVB\Scheduler\Views\SchedulerCellContainers.vb region=viewElementUpdateCells}} + + -````C# -foreach (SchedulerCellContainer cellContainer in this.radScheduler1.ViewElement.GetCellContainers()) -{ - cellContainer.UpdateCells(); -} -```` -````VB.NET -For Each cellContainer As SchedulerCellContainer In Me.radScheduler1.ViewElement.GetCellContainers() - cellContainer.UpdateCells() -Next - -```` - -{{endregion}} For your convenience, there are the __InitializeCells__, __UpdateCells__, __InitializeAppointmentElements__, __UpdateAppointmentElements__ methods of the view element which you can use to perform the same operation over all of the child SchedulerCellContainers: #### Update Elements From The View Element -{{source=..\SamplesCS\Scheduler\Views\SchedulerCellContainers.cs region=viewElementUpdateCellsDirect}} -{{source=..\SamplesVB\Scheduler\Views\SchedulerCellContainers.vb region=viewElementUpdateCellsDirect}} - -````C# -this.radScheduler1.ViewElement.UpdateCells(); -this.radScheduler1.ViewElement.UpdateAppointmentElements(); + + -```` -````VB.NET -Me.radScheduler1.ViewElement.UpdateCells() -Me.radScheduler1.ViewElement.UpdateAppointmentElements() -```` - -{{endregion}} Additionally, there are the __GetCellEments__ and the __GetAppointmentElements__ methods which return a list of all cell or appointment elements from all containers in the view. #### Get Elements -{{source=..\SamplesCS\Scheduler\Views\SchedulerCellContainers.cs region=viewElementGetAllElements}} -{{source=..\SamplesVB\Scheduler\Views\SchedulerCellContainers.vb region=viewElementGetAllElements}} - -````C# -foreach (SchedulerCellElement cellElement in this.radScheduler1.ViewElement.GetCellElements()) -{ - cellElement.BackColor = Color.Red; -} -foreach (AppointmentElement appElement in this.radScheduler1.ViewElement.GetAppointmentElements()) -{ - appElement.BackColor = Color.Green; -} - -```` -````VB.NET -For Each cellElement As SchedulerCellElement In Me.radScheduler1.ViewElement.GetCellElements() - cellElement.BackColor = Color.Red -Next -For Each appElement As AppointmentElement In Me.radScheduler1.ViewElement.GetAppointmentElements() - appElement.BackColor = Color.Green -Next - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/scheduler/views/time-zones.md b/controls/scheduler/views/time-zones.md index cb80263a0..512f305ac 100644 --- a/controls/scheduler/views/time-zones.md +++ b/controls/scheduler/views/time-zones.md @@ -26,19 +26,10 @@ We provide an easy way to take all time zones from the Windows. To do this, you #### Get Time Zones -{{source=..\SamplesCS\Scheduler\Views\TimesZones.cs region=getAllZones}} -{{source=..\SamplesVB\Scheduler\Views\TimesZones.vb region=getAllZones}} + + -````C# -List allTimeZones = SchedulerTimeZone.GetSchedulerTimeZones(); -```` -````VB.NET -Dim allTimeZones As List(Of SchedulerTimeZone) = SchedulerTimeZone.GetSchedulerTimeZones() - -```` - -{{endregion}} >note The *bias* property represents the difference between the "UTC" time zone and the time zone that you want to set to RadScheduler in minutes multiplied by minus 1. For example, if the time zone that you want to set is "(UTC -05:00) Eastern Time (US and Canada)" the *bias* value would be -5 * 60 * -1 = 300 > @@ -49,42 +40,22 @@ All appointments in RadScheduler are stored/loaded according to the value of the 1\. Let's create an appointment from 10:00 AM to 11:00 AM: -{{source=..\SamplesCS\Scheduler\Views\TimesZones.cs region=creatingAppointment}} -{{source=..\SamplesVB\Scheduler\Views\TimesZones.vb region=creatingAppointment}} - -````C# -this.radScheduler1.Appointments.Add(new Appointment(DateTime.Now.Date.AddHours(1), new TimeSpan(1, 0, 0))); + + -```` -````VB.NET -Me.RadScheduler1.Appointments.Add(New Appointment(Date.Now.Date.AddHours(1), New TimeSpan(1, 0, 0))) -```` -{{endregion}} - - By default, this appointment will be shown from 10:00 AM to 11:00 AM: +By default, this appointment will be shown from 10:00 AM to 11:00 AM: >caption Figure 1: Default SystemTimeZone ![WinForms RadScheduler Default SystemTimeZone](images/scheduler-views-time-zones001.png) 2\. Let's now set the SystemTimeZone property to "UTC" time zone: -{{source=..\SamplesCS\Scheduler\Views\TimesZones.cs region=systemTimeZone}} -{{source=..\SamplesVB\Scheduler\Views\TimesZones.vb region=systemTimeZone}} + + -````C# -SchedulerTimeZone utcTimeZone = new SchedulerTimeZone(0, "UTC"); -this.radScheduler1.SystemTimeZone = utcTimeZone; -```` -````VB.NET -Dim utcTimeZone As New SchedulerTimeZone(0, "UTC") -Me.RadScheduler1.SystemTimeZone = utcTimeZone - -```` - -{{endregion}} This will change the representation of the appointment according to the time zone set to the client machine. Please note that the start time, end time and duration of the logical appointment are not changed. Only the representation of the appointment in the active view is changed. For example, if we start the RadScheduler on a client machine where the time zone is "UTC + 02:00", our appointment will look as shown on the screenshot below: @@ -99,19 +70,10 @@ All __RadScheduler__ views have the __DefaultTimeZone__ property. The active vie 1\. Let's create an appointment from 10:00 AM to 11:00 AM: -{{source=..\SamplesCS\Scheduler\Views\TimesZones.cs region=creatingAppointment}} -{{source=..\SamplesVB\Scheduler\Views\TimesZones.vb region=creatingAppointment}} - -````C# -this.radScheduler1.Appointments.Add(new Appointment(DateTime.Now.Date.AddHours(1), new TimeSpan(1, 0, 0))); + + -```` -````VB.NET -Me.RadScheduler1.Appointments.Add(New Appointment(Date.Now.Date.AddHours(1), New TimeSpan(1, 0, 0))) -```` - -{{endregion}} By default, this appointment will be shown from 10:00 AM to 11:00 AM: @@ -120,21 +82,10 @@ By default, this appointment will be shown from 10:00 AM to 11:00 AM: 2\. Let's now set the DefaultTimeZone property of the ActiveDayView to "UTC + 1" time zone: -{{source=..\SamplesCS\Scheduler\Views\TimesZones.cs region=defaultTimeZone}} -{{source=..\SamplesVB\Scheduler\Views\TimesZones.vb region=defaultTimeZone}} - -````C# -SchedulerTimeZone utcPlusOneTimeZone = new SchedulerTimeZone(-60, "UTC + 1"); -this.radScheduler1.GetDayView().DefaultTimeZone = utcPlusOneTimeZone; + + -```` -````VB.NET -Dim utcPlusOneTimeZone As New SchedulerTimeZone(-60, "UTC + 1") -Me.RadScheduler1.GetDayView().DefaultTimeZone = utcPlusOneTimeZone -```` - -{{endregion}} Again, this will change the representation of the appointment according to the time zone of the client machine. However, this time the appointment will be represented according to the time scale of the "UTC + 1" time zone. Since we are running the RadScheduler instance on a machine where the time zone set is "UTC + 2", an appointment starting at 10 o'clock will be represented as an appointment starting at 9: @@ -157,136 +108,31 @@ The way to handle this situation is to choose one time zone as the system time z This functionality can be achieved by setting the SystemTimeZone of RadScheduler. Let's say that the default time zone is "(UTC) Dublin, Edinburgh, Lisbon, London". We can get the time zone from the Windows registry and set it as SystemTimeZone as shown below: -{{source=..\SamplesCS\Scheduler\Views\TimesZones.cs region=london}} -{{source=..\SamplesVB\Scheduler\Views\TimesZones.vb region=london}} - -````C# -SchedulerTimeZone london = GetSpecificTimeZone("London", "London"); -this.radScheduler1.SystemTimeZone = london; - -```` -````VB.NET -Dim london As SchedulerTimeZone = GetSpecificTimeZone("London", "London") -Me.RadScheduler1.SystemTimeZone = london - -```` - -{{endregion}} - -{{source=..\SamplesCS\Scheduler\Views\TimesZones.cs region=insertingTimeZones}} -{{source=..\SamplesVB\Scheduler\Views\TimesZones.vb region=insertingTimeZones}} - -````C# -SchedulerTimeZone newYork = GetSpecificTimeZone("Eastern Time", "New York"); -if (!newYork.Equals(this.radScheduler1.GetDayView().DefaultTimeZone)) -{ - radScheduler1.GetDayView().TimeZones.Insert(0, newYork); -} -SchedulerTimeZone tokyo = GetSpecificTimeZone("Tokyo", "Tokyo"); -if (!tokyo.Equals(this.radScheduler1.GetDayView().DefaultTimeZone)) -{ - radScheduler1.GetDayView().TimeZones.Insert(0, tokyo); -} -SchedulerTimeZone paris = GetSpecificTimeZone("Paris", "Paris"); -if (!paris.Equals(this.radScheduler1.GetDayView().DefaultTimeZone)) -{ - radScheduler1.GetDayView().TimeZones.Insert(0, paris); -} -SchedulerTimeZone london = GetSpecificTimeZone("London", "London"); -if (!london.Equals(this.radScheduler1.GetDayView().DefaultTimeZone)) -{ - radScheduler1.GetDayView().TimeZones.Insert(0, london); -} - -```` -````VB.NET -Dim newYork As SchedulerTimeZone = GetSpecificTimeZone("Eastern Time", "New York") -If Not newYork.Equals(Me.RadScheduler1.GetDayView().DefaultTimeZone) Then - RadScheduler1.GetDayView().TimeZones.Insert(0, newYork) -End If -Dim tokyo As SchedulerTimeZone = GetSpecificTimeZone("Tokyo", "Tokyo") -If Not tokyo.Equals(Me.RadScheduler1.GetDayView().DefaultTimeZone) Then - RadScheduler1.GetDayView().TimeZones.Insert(0, tokyo) -End If -Dim paris As SchedulerTimeZone = GetSpecificTimeZone("Paris", "Paris") -If Not paris.Equals(Me.RadScheduler1.GetDayView().DefaultTimeZone) Then - RadScheduler1.GetDayView().TimeZones.Insert(0, paris) -End If -Dim london As SchedulerTimeZone = GetSpecificTimeZone("London", "London") -If Not london.Equals(Me.RadScheduler1.GetDayView().DefaultTimeZone) Then - RadScheduler1.GetDayView().TimeZones.Insert(0, london) -End If - -```` - -{{endregion}} + + + + + + + + + Further, we may want to show the four most commonly used time zones - Tokyo, New York, London and Paris. This can be achieved by getting the appropriate time zones from the Windows registry and adding them to RadScheduler: -{{source=..\SamplesCS\Scheduler\Views\TimesZones.cs region=insertingTimeZones}} -{{source=..\SamplesVB\Scheduler\Views\TimesZones.vb region=insertingTimeZones}} - -````C# -SchedulerTimeZone newYork = GetSpecificTimeZone("Eastern Time", "New York"); -if (!newYork.Equals(this.radScheduler1.GetDayView().DefaultTimeZone)) -{ - radScheduler1.GetDayView().TimeZones.Insert(0, newYork); -} -SchedulerTimeZone tokyo = GetSpecificTimeZone("Tokyo", "Tokyo"); -if (!tokyo.Equals(this.radScheduler1.GetDayView().DefaultTimeZone)) -{ - radScheduler1.GetDayView().TimeZones.Insert(0, tokyo); -} -SchedulerTimeZone paris = GetSpecificTimeZone("Paris", "Paris"); -if (!paris.Equals(this.radScheduler1.GetDayView().DefaultTimeZone)) -{ - radScheduler1.GetDayView().TimeZones.Insert(0, paris); -} -SchedulerTimeZone london = GetSpecificTimeZone("London", "London"); -if (!london.Equals(this.radScheduler1.GetDayView().DefaultTimeZone)) -{ - radScheduler1.GetDayView().TimeZones.Insert(0, london); -} - -```` -````VB.NET -Dim newYork As SchedulerTimeZone = GetSpecificTimeZone("Eastern Time", "New York") -If Not newYork.Equals(Me.RadScheduler1.GetDayView().DefaultTimeZone) Then - RadScheduler1.GetDayView().TimeZones.Insert(0, newYork) -End If -Dim tokyo As SchedulerTimeZone = GetSpecificTimeZone("Tokyo", "Tokyo") -If Not tokyo.Equals(Me.RadScheduler1.GetDayView().DefaultTimeZone) Then - RadScheduler1.GetDayView().TimeZones.Insert(0, tokyo) -End If -Dim paris As SchedulerTimeZone = GetSpecificTimeZone("Paris", "Paris") -If Not paris.Equals(Me.RadScheduler1.GetDayView().DefaultTimeZone) Then - RadScheduler1.GetDayView().TimeZones.Insert(0, paris) -End If -Dim london As SchedulerTimeZone = GetSpecificTimeZone("London", "London") -If Not london.Equals(Me.RadScheduler1.GetDayView().DefaultTimeZone) Then - RadScheduler1.GetDayView().TimeZones.Insert(0, london) -End If - -```` - -{{endregion}} + + + + It is important to Insert the zones, because this will make your local time zone the zone according to which the appointment will be represented. In addition, we should check if the DefaultTimeZone of RadScheduler(which is taken from the client machine where RadScheduler is started) is the equal to the time zone that we are going to insert. If this is so, we should not insert the zone, because we want to avoid having repetitive time zones. Finally, set the RulerWidth property to an appropriate value to show the entire labels: -{{source=..\SamplesCS\Scheduler\Views\TimesZones.cs region=rulerWidth}} -{{source=..\SamplesVB\Scheduler\Views\TimesZones.vb region=rulerWidth}} -````C# -this.radScheduler1.GetDayView().RulerWidth = 50; - -```` -````VB.NET -Me.RadScheduler1.GetDayView().RulerWidth = 50 + + -```` -{{endregion}} After all these steps are performed, let's try to create an appointment starting at 10 o'clock on Jan 12 on a client machine where the local time zone is "(UTC +09:00) Osaka, Sapporo, Tokyo". Here is how this appointment will look like on client machines having different local time zones set: diff --git a/controls/scheduler/views/timeline-view.md b/controls/scheduler/views/timeline-view.md index 405ba4677..8be8cba2a 100644 --- a/controls/scheduler/views/timeline-view.md +++ b/controls/scheduler/views/timeline-view.md @@ -27,20 +27,10 @@ The Timeline View can be set it to be the default view which the user sees: #### ActiveViewType Timeline -{{source=..\SamplesCS\Scheduler\Views\TimelineView.cs region=activeViewType1}} -{{source=..\SamplesVB\Scheduler\Views\TimelineView.vb region=activeViewType1}} + + -````C# - -this.radScheduler1.ActiveViewType = Telerik.WinControls.UI.SchedulerViewType.Timeline; -```` -````VB.NET -Me.RadScheduler1.ActiveViewType = Telerik.WinControls.UI.SchedulerViewType.Timeline - -```` - -{{endregion}} ## Get The Timeline View @@ -50,19 +40,10 @@ To get the instance to the scheduler timeline view from the __RadScheduler__ obj #### GetTimelineView Method -{{source=..\SamplesCS\Scheduler\Views\TimelineView.cs region=timelineView}} -{{source=..\SamplesVB\Scheduler\Views\TimelineView.vb region=timelineView}} - -````C# -SchedulerTimelineView timelineView = this.radScheduler1.GetTimelineView(); + + -```` -````VB.NET -Dim timelineView As SchedulerTimelineView = Me.RadScheduler1.GetTimelineView() -```` - -{{endregion}} >note This method returns null if the active view of the scheduler is not SchedulerTimelineView. > @@ -71,25 +52,10 @@ Dim timelineView As SchedulerTimelineView = Me.RadScheduler1.GetTimelineView() #### ActiveView Property -{{source=..\SamplesCS\Scheduler\Views\TimelineView.cs region=activeView2}} -{{source=..\SamplesVB\Scheduler\Views\TimelineView.vb region=activeView2}} - -````C# - -if (this.radScheduler1.ActiveViewType == SchedulerViewType.Timeline) -{ - SchedulerTimelineView activeTimelineView = (SchedulerTimelineView)this.radScheduler1.ActiveView; -} + + -```` -````VB.NET -If Me.RadScheduler1.ActiveViewType = SchedulerViewType.Timeline Then - Dim activeTimelineView As SchedulerTimelineView = CType(Me.RadScheduler1.ActiveView, SchedulerTimelineView) -End If -```` - -{{endregion}} ## Setting The Time Range and First Date @@ -99,43 +65,19 @@ The time range that the timeline shows can be set with the __RangeStartDate__ an The __StartDate__ property sets the first date that is shown in the timeline __RangeStartDate__ and __RangeEndDate__. -{{source=..\SamplesCS\Scheduler\Views\TimelineView.cs region=getTimelineView}} -{{source=..\SamplesVB\Scheduler\Views\TimelineView.vb region=getTimelineView}} - -````C# - -this.radScheduler1.GetTimelineView().RangeStartDate = new DateTime(2010, 1, 20); -this.radScheduler1.GetTimelineView().RangeEndDate = new DateTime(2010, 2, 20); -this.radScheduler1.GetTimelineView().StartDate = new DateTime(2010, 2, 1); - -```` -````VB.NET -Me.RadScheduler1.GetTimelineView().RangeStartDate = New Date(2010, 1, 20) -Me.RadScheduler1.GetTimelineView().RangeEndDate = New Date(2010, 2, 20) -Me.RadScheduler1.GetTimelineView().StartDate = New Date(2010, 2, 1) + + -```` -{{endregion}} To get the duration between __RangeStartDate__ and __RangeEndDate__ you can use the duration __property__: #### Timeline View Duration -{{source=..\SamplesCS\Scheduler\Views\TimelineView.cs region=duration}} -{{source=..\SamplesVB\Scheduler\Views\TimelineView.vb region=duration}} - -````C# - -TimeSpan duration = timelineView.Duration; - -```` -````VB.NET -Dim duration As TimeSpan = timelineView.Duration + + -```` -{{endregion}} ## Setting The Default Time Scale @@ -152,22 +94,10 @@ To change the time scaling to *Hours*, for example, you need to use the __ShowTi #### Set Time Scale -{{source=..\SamplesCS\Scheduler\Views\TimelineView.cs region=showTimescale}} -{{source=..\SamplesVB\Scheduler\Views\TimelineView.vb region=showTimescale}} + + -````C# - -Timescales scale = Timescales.Hours; -timelineView.ShowTimescale(scale); -```` -````VB.NET -Dim scale As Timescales = Timescales.Hours -timelineView.ShowTimescale(scale) - -```` - -{{endregion}} ## Getting The Scale @@ -175,24 +105,10 @@ To get the currently selected scale, use the __GetScaling__ method. After this y #### Current Scaling -{{source=..\SamplesCS\Scheduler\Views\TimelineView.cs region=getTimescale}} -{{source=..\SamplesVB\Scheduler\Views\TimelineView.vb region=getTimescale}} - -````C# - -SchedulerTimescale currentScaling = timelineView.GetScaling(); -currentScaling.Format = "dd MMM"; -currentScaling.DisplayedCellsCount = 8; + + -```` -````VB.NET -Dim currentScaling As SchedulerTimescale = timelineView.GetScaling() -currentScaling.Format = "dd MMM" -currentScaling.DisplayedCellsCount = 8 -```` - -{{endregion}} ## Navigation and Scrolling @@ -200,22 +116,10 @@ In TimelineView there are two scrollbars which stand for navigation between date #### Navigation Element -{{source=..\SamplesCS\Scheduler\Views\TimelineView.cs region=navigationElements}} -{{source=..\SamplesVB\Scheduler\Views\TimelineView.vb region=navigationElements}} - -````C# - -timelineView.ShowNavigationElement = false; -timelineView.ShowVerticalScrollBar = false; + + -```` -````VB.NET -timelineView.ShowNavigationElement = False -timelineView.ShowVerticalScrollBar = False -```` - -{{endregion}} ## Modifying The Size of The Columns @@ -223,21 +127,10 @@ The SchedulerTimelineViewElement allows you to specify different size for the di #### Resizing Columns -{{source=..\SamplesCS\Scheduler\Views\TimelineView.cs region=resizeColumns}} -{{source=..\SamplesVB\Scheduler\Views\TimelineView.vb region=resizeColumns}} - -````C# -SchedulerTimelineViewElement viewElement = (SchedulerTimelineViewElement)this.radScheduler1.ViewElement; -viewElement.SetColumnWidth(1, 2); - -```` -````VB.NET -Dim viewElement As SchedulerTimelineViewElement = CType(RadScheduler1.ViewElement, SchedulerTimelineViewElement) -viewElement.SetColumnWidth(1, 2) + + -```` -{{endregion}} ## Modifying The Size of The Headers @@ -245,21 +138,10 @@ TimelineView contains two header rows. The first one displays the date range of #### Headers Size -{{source=..\SamplesCS\Scheduler\Views\TimelineView.cs region=headerSizing}} -{{source=..\SamplesVB\Scheduler\Views\TimelineView.vb region=headerSizing}} - -````C# -viewElement.ColumnHeaderHeight = 70; -viewElement.ViewHeaderHeight = 35; - -```` -````VB.NET -viewElement.ColumnHeaderHeight = 70 -viewElement.ViewHeaderHeight = 35 + + -```` -{{endregion}} The following picture demonstrates the result of setting the header sizes and resizing the column with index 1. diff --git a/controls/scheduler/views/views-walkthrough.md b/controls/scheduler/views/views-walkthrough.md index 5b0c3be8a..5562e8643 100644 --- a/controls/scheduler/views/views-walkthrough.md +++ b/controls/scheduler/views/views-walkthrough.md @@ -39,192 +39,38 @@ In this walkthrough (part of the [Telerik UI for WinForms Step-by-step Tutorial 1. Add code to the form load that will add values to the combo boxes in the tool strip for __SchedulerViewType__ and __ScaleRange__ enumerations. Also, add a simple range of integers to the "count" combo box. -{{source=..\SamplesCS\Scheduler\Views\ViewsWalkthrough.cs region=addingValues}} -{{source=..\SamplesVB\Scheduler\Views\ViewsWalkthrough.vb region=addingValues}} - -````C# -foreach (SchedulerViewType viewType in Enum.GetValues(typeof(SchedulerViewType))) -{ - RadListDataItem item = new RadListDataItem(); - item.Text = viewType.ToString(); - item.Value = viewType; - ddlActiveViewType.Items.Add(item); -} -foreach (ScaleRange range in Enum.GetValues(typeof(ScaleRange))) -{ - RadListDataItem item = new RadListDataItem(); - item.Text = range.ToString(); - item.Value = range; - ddlRange.Items.Add(item); -} -for (int i = 1; i < 10; i++) -{ - RadListDataItem item = new RadListDataItem(); - item.Text = i.ToString(); - item.Value = i; - ddlACount.Items.Add(item); -} - -```` -````VB.NET -For Each viewType As SchedulerViewType In System.Enum.GetValues(GetType(SchedulerViewType)) - Dim item As New RadListDataItem() - item.Text = viewType.ToString() - item.Value = viewType - ddlActiveViewType.Items.Add(item) -Next viewType -For Each range As ScaleRange In System.Enum.GetValues(GetType(ScaleRange)) - Dim item As New RadListDataItem() - item.Text = range.ToString() - item.Value = range - ddlRange.Items.Add(item) -Next range -For i As Integer = 1 To 9 - Dim item As New RadListDataItem() - item.Text = i.ToString() - item.Value = i - ddlCount.Items.Add(item) -Next i - -```` - -{{endregion}} + + -12\. Next add a SelectedIndexChanged event handler for the ddlActiveViewType combo box: -{{source=..\SamplesCS\Scheduler\Views\ViewsWalkthrough.cs region=selectedIndexChanged}} -{{source=..\SamplesVB\Scheduler\Views\ViewsWalkthrough.vb region=selectedIndexChanged}} -````C# -void ddlActiveViewType_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e) -{ - RadDropDownListElement dropDownList = sender as RadDropDownListElement; - radScheduler1.ActiveViewType = (SchedulerViewType)(dropDownList.SelectedValue); -} +12\. Next add a SelectedIndexChanged event handler for the ddlActiveViewType combo box: -```` -````VB.NET -Private Sub ddlActiveViewType_SelectedIndexChanged(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.Data.PositionChangedEventArgs) - Dim dropDownList As RadDropDownListElement = TryCast(sender, RadDropDownListElement) - RadScheduler1.ActiveViewType = CType(dropDownList.SelectedValue, SchedulerViewType) -End Sub + + -```` -{{endregion}} 13\. Add another SelectedIndexChanged event handler for the ddlRange combo box element: -{{source=..\SamplesCS\Scheduler\Views\ViewsWalkthrough.cs region=rangeChanged}} -{{source=..\SamplesVB\Scheduler\Views\ViewsWalkthrough.vb region=rangeChanged}} - -````C# -void ddlRange_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e) -{ - RadDropDownListElement dropDownList = sender as RadDropDownListElement; - ScaleRange range = (ScaleRange)(dropDownList.SelectedValue); - // set the appropriate range factor based on the type of view - switch (radScheduler1.ActiveViewType) - { - case SchedulerViewType.Day: - (radScheduler1.ActiveView as SchedulerDayView).RangeFactor = range; - break; - case SchedulerViewType.MultiDay: - (radScheduler1.ActiveView as SchedulerMultiDayView).RangeFactor = range; - break; - case SchedulerViewType.Week: - case SchedulerViewType.WorkWeek: - (radScheduler1.ActiveView as SchedulerWeekView).RangeFactor = range; - break; - } -} - -```` -````VB.NET -Private Sub ddlRange_SelectedIndexChanged(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.Data.PositionChangedEventArgs) - Dim dropDownList As RadDropDownListElement = TryCast(sender, RadDropDownListElement) - Dim range As ScaleRange = CType(dropDownList.SelectedValue, ScaleRange) - ' set the appropriate range factor based on the type of view - Select Case RadScheduler1.ActiveViewType - Case SchedulerViewType.Day - TryCast(RadScheduler1.ActiveView, SchedulerDayView).RangeFactor = range - Case SchedulerViewType.MultiDay - TryCast(RadScheduler1.ActiveView, SchedulerMultiDayView).RangeFactor = range - Case SchedulerViewType.Week, SchedulerViewType.WorkWeek - TryCast(RadScheduler1.ActiveView, SchedulerWeekView).RangeFactor = range - End Select -End Sub - -```` - -{{endregion}} + + + + 14\. Add another SelectedIndexChanged event handler for the ddlCount combo box element: -{{source=..\SamplesCS\Scheduler\Views\ViewsWalkthrough.cs region=countChanged}} -{{source=..\SamplesVB\Scheduler\Views\ViewsWalkthrough.vb region=countChanged}} - -````C# -void ddlCount_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e) -{ - RadDropDownListElement dropDownList = sender as RadDropDownListElement; - int count = (int)dropDownList.SelectedValue; - // set the Day or WeekCount based on the current view - switch (radScheduler1.ActiveViewType) - { - case SchedulerViewType.Day: - (radScheduler1.ActiveView as SchedulerDayView).DayCount = count; - break; - case SchedulerViewType.MultiDay: - (radScheduler1.ActiveView as SchedulerMultiDayView).DayCount = count; - break; - case SchedulerViewType.Month: - (radScheduler1.ActiveView as SchedulerMonthView).WeekCount = count; - break; - } -} - -```` -````VB.NET -Private Sub ddlCount_SelectedIndexChanged(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.Data.PositionChangedEventArgs) - Dim dropDownList As RadDropDownListElement = TryCast(sender, RadDropDownListElement) - Dim count As Integer = CInt(Fix(dropDownList.SelectedValue)) - ' set the Day or WeekCount based on the current view - Select Case RadScheduler1.ActiveViewType - Case SchedulerViewType.Day - TryCast(RadScheduler1.ActiveView, SchedulerDayView).DayCount = count - Case SchedulerViewType.MultiDay - TryCast(RadScheduler1.ActiveView, SchedulerMultiDayView).DayCount = count - Case SchedulerViewType.Month - TryCast(RadScheduler1.ActiveView, SchedulerMonthView).WeekCount = count - End Select -End Sub - -```` - -{{endregion}} + + -15\. Handle the RadScheduler ActiveViewChanging event. Use the SchedulerViewChangingEventArgs OldView and NewView to display in the status label. -{{source=..\SamplesCS\Scheduler\Views\ViewsWalkthrough.cs region=activeViewChanging}} -{{source=..\SamplesVB\Scheduler\Views\ViewsWalkthrough.vb region=activeViewChanging}} -````C# -void radScheduler1_ActiveViewChanging(object sender, SchedulerViewChangingEventArgs e) -{ - lblStatus.Text = String.Format("Old: {0} New: {1}", - e.OldView.ViewType.ToString(), e.NewView.ViewType.ToString()); -} +15\. Handle the RadScheduler ActiveViewChanging event. Use the SchedulerViewChangingEventArgs OldView and NewView to display in the status label. -```` -````VB.NET -Private Sub radScheduler1_ActiveViewChanging(ByVal sender As Object, ByVal e As SchedulerViewChangingEventArgs) - lblStatus.Text = String.Format("Old: {0} New: {1}", e.OldView.ViewType.ToString(), e.NewView.ViewType.ToString()) -End Sub + + -```` -{{endregion}} 16\. Run the application and test the various combinations of settings. diff --git a/controls/scheduler/views/week-view.md b/controls/scheduler/views/week-view.md index 710016c88..fc45c0aea 100644 --- a/controls/scheduler/views/week-view.md +++ b/controls/scheduler/views/week-view.md @@ -24,19 +24,10 @@ To explicitly set the Work Week to be the default view which the user sees on #### Set ActiveViewType -{{source=..\SamplesCS\Scheduler\Views\WeekView.cs region=ViewType}} -{{source=..\SamplesVB\Scheduler\Views\WeekView.vb region=ViewType}} + + -````C# -this.radScheduler1.ActiveViewType = SchedulerViewType.Week; -```` -````VB.NET -Me.RadScheduler1.ActiveViewType = SchedulerViewType.Week - -```` - -{{endregion}} ## Get Week View @@ -46,19 +37,10 @@ To get the instance to the SchedulerWeek view from the RadScheduler object, eith #### GetWeekView Method -{{source=..\SamplesCS\Scheduler\Views\WeekView.cs region=weekView}} -{{source=..\SamplesVB\Scheduler\Views\WeekView.vb region=weekView}} - -````C# -SchedulerWeekView weekView = this.radScheduler1.GetWeekView(); - -```` -````VB.NET -Dim weekView As SchedulerWeekView = Me.RadScheduler1.GetWeekView() + + -```` -{{endregion}} >note This method returns null if the active view of the scheduler is not SchedulerWeekView. > @@ -67,24 +49,10 @@ Dim weekView As SchedulerWeekView = Me.RadScheduler1.GetWeekView() #### ActiveView Property -{{source=..\SamplesCS\Scheduler\Views\WeekView.cs region=activeView}} -{{source=..\SamplesVB\Scheduler\Views\WeekView.vb region=activeView}} + + -````C# -if (this.radScheduler1.ActiveViewType == SchedulerViewType.Week) -{ - SchedulerWeekView activeWeekView = (SchedulerWeekView)this.radScheduler1.ActiveView; -} -```` -````VB.NET -If Me.RadScheduler1.ActiveViewType = SchedulerViewType.Week Then - Dim activeWeekView As SchedulerWeekView = CType(Me.RadScheduler1.ActiveView, SchedulerWeekView) -End If - -```` - -{{endregion}} ## Showing/Hiding The Weekend @@ -92,18 +60,10 @@ By default the weekends are shown, but you can hide them by using the __ShowWee #### Show Weekend -{{source=..\SamplesCS\Scheduler\Views\WeekView.cs region=Weekend}} -{{source=..\SamplesVB\Scheduler\Views\WeekView.vb region=Weekend}} -````C# -weekView.ShowWeekend = false; - -```` -````VB.NET -weekView.ShowWeekend = False + + -```` -{{endregion}} # See Also diff --git a/controls/scheduler/views/work-week-view.md b/controls/scheduler/views/work-week-view.md index 37440f0f6..36dfa6e22 100644 --- a/controls/scheduler/views/work-week-view.md +++ b/controls/scheduler/views/work-week-view.md @@ -24,19 +24,10 @@ The Week View can be set it to be the default view which the user sees: #### ActiveViewType Property -{{source=..\SamplesCS\Scheduler\Views\WorkWeekView.cs region=activeViewType}} -{{source=..\SamplesVB\Scheduler\Views\WorkWeekView.vb region=activeViewType}} + + -````C# -this.radScheduler1.ActiveViewType = Telerik.WinControls.UI.SchedulerViewType.WorkWeek; -```` -````VB.NET -Me.RadScheduler1.ActiveViewType = Telerik.WinControls.UI.SchedulerViewType.WorkWeek - -```` - -{{endregion}} ## Get Work Week View @@ -46,18 +37,10 @@ To get the instance to the SchedulerWeekView from the RadScheduler object,either #### GetWeekView Method -{{source=..\SamplesCS\Scheduler\Views\WorkWeekView.cs region=getWeekView}} -{{source=..\SamplesVB\Scheduler\Views\WorkWeekView.vb region=getWeekView}} -````C# -SchedulerWeekView weekView = this.radScheduler1.GetWeekView(); - -```` -````VB.NET -Dim weekView As SchedulerWeekView = Me.RadScheduler1.GetWeekView() + + -```` -{{endregion}} >note This method returns null if the active view of the scheduler is not SchedulerWeekView. > @@ -66,25 +49,10 @@ Dim weekView As SchedulerWeekView = Me.RadScheduler1.GetWeekView() #### ActiveView Property -{{source=..\SamplesCS\Scheduler\Views\WorkWeekView.cs region=activeWorkWeek}} -{{source=..\SamplesVB\Scheduler\Views\WorkWeekView.vb region=activeWorkWeek}} -````C# -if (this.radScheduler1.ActiveViewType == SchedulerViewType.WorkWeek) -{ - SchedulerWeekView activeWeekView = (SchedulerWeekView)this.radScheduler1.ActiveView; -} - -```` -````VB.NET -If Me.RadScheduler1.ActiveViewType = SchedulerViewType.WorkWeek Then - Dim activeWeekView As SchedulerWeekView = CType(Me.RadScheduler1.ActiveView, SchedulerWeekView) -End If - -```` - + + -{{endregion}} # See Also diff --git a/controls/scheduler/views/working-with-views.md b/controls/scheduler/views/working-with-views.md index 852b93356..35aef313d 100644 --- a/controls/scheduler/views/working-with-views.md +++ b/controls/scheduler/views/working-with-views.md @@ -21,23 +21,10 @@ At any one time the scheduler displays a view using a descendant of the __Schedu #### Get Day View -{{source=..\SamplesCS\Scheduler\Views\WorkingWithViews.cs region=getDayView}} -{{source=..\SamplesVB\Scheduler\Views\WorkingWithViews.vb region=getDayView}} + + -````C# -SchedulerDayView dayView = radScheduler1.GetDayView(); -dayView.RulerStartScale = 2; -dayView.RulerEndScale = 5; -```` -````VB.NET -Dim dayView As SchedulerDayView = RadScheduler1.GetDayView() -dayView.RulerStartScale = 2 -dayView.RulerEndScale = 5 - -```` - -{{endregion}} After running the code, the day view for the scheduler looks like this screenshot: @@ -48,64 +35,29 @@ Change between views by changing the __ActiveViewType__ property to one of the _ #### ActiveViewType Property -{{source=..\SamplesCS\Scheduler\Views\WorkingWithViews.cs region=activeViewType}} -{{source=..\SamplesVB\Scheduler\Views\WorkingWithViews.vb region=activeViewType}} - -````C# -radScheduler1.ActiveViewType = SchedulerViewType.Day; - -```` -````VB.NET -RadScheduler1.ActiveViewType = SchedulerViewType.Day + + -```` -{{endregion}} Retrieve the view that is currently being displayed by using the ActiveView property, cast it to be the ActiveViewType. #### ActiveView Property -{{source=..\SamplesCS\Scheduler\Views\WorkingWithViews.cs region=weekCount}} -{{source=..\SamplesVB\Scheduler\Views\WorkingWithViews.vb region=weekCount}} + + -````C# -radScheduler1.ActiveViewType = SchedulerViewType.Month; -(radScheduler1.ActiveView as SchedulerMonthView).WeekCount = 2; -```` -````VB.NET -RadScheduler1.ActiveViewType = SchedulerViewType.Month -TryCast(RadScheduler1.ActiveView, SchedulerMonthView).WeekCount = 2 - -```` - -{{endregion}} >caption Figure 2: Week Count ![WinForms RadScheduler Week Count](images/scheduler-views-working-with-views002.png) Detect changes to the view by handling the __ActiveViewChanging__ and __ActiveViewChanged__ events. As always, the "Changing" event arguments provide the ability to cancel the view change, but also the "old" and "new" views before and after the view changes transpires: -{{source=..\SamplesCS\Scheduler\Views\WorkingWithViews.cs region=activeViewChanging}} -{{source=..\SamplesVB\Scheduler\Views\WorkingWithViews.vb region=activeViewChanging}} - -````C# -void radScheduler1_ActiveViewChanging(object sender, SchedulerViewChangingEventArgs e) -{ - this.Text = String.Format("Old: {0} New: {1}", - e.OldView.ViewType.ToString(), e.NewView.ViewType.ToString()); -} - -```` -````VB.NET -Private Sub radScheduler1_ActiveViewChanging(ByVal sender As Object, ByVal e As SchedulerViewChangingEventArgs) - Me.Text = String.Format("Old: {0} New: {1}", e.OldView.ViewType.ToString(), e.NewView.ViewType.ToString()) -End Sub + + -```` -{{endregion}} # See Also diff --git a/controls/shortcuts/assigning-global-radshortcuts.md b/controls/shortcuts/assigning-global-radshortcuts.md index d2822a199..57accf4aa 100644 --- a/controls/shortcuts/assigning-global-radshortcuts.md +++ b/controls/shortcuts/assigning-global-radshortcuts.md @@ -15,8 +15,8 @@ previous_url: shortcuts-assigning-global-radshortcuts 1\. Implement a custom **IShortcutProvider**: -{{source=..\SamplesCS\Shortcuts\MyShortcutProvider.cs region=customProvider}} -{{source=..\SamplesVB\Shortcuts\MyShortcutProvider.vb region=customProvider}} + + ````C# @@ -125,12 +125,10 @@ End Class ```` -{{endregion}} - 2\. And here is how we utilize the custom shortcut provider: -{{source=..\SamplesCS\Shortcuts\Form2.cs region=globalShortcut}} -{{source=..\SamplesVB\Shortcuts\Form2.vb region=globalShortcut}} + + ````C# MyShortcutProvider provider; @@ -152,8 +150,6 @@ End Sub ```` -{{endregion}} - >caution The shortcut providers that implement **IShortcutProvider** interface are registered as WeakReferences. So, if you declare the **MyShortcutProvider** variable in the scope of the constructor or in another method (for example the Form.Load event) the Garbage collection may collect the shortcut provider reference at a certain moment. To prevent this from happening, you need to declare the **MyShortcutProvider** variable globally. # See Also diff --git a/controls/shortcuts/getting-started-(radbuttons).md b/controls/shortcuts/getting-started-(radbuttons).md index 896853d39..5b8ad734e 100644 --- a/controls/shortcuts/getting-started-(radbuttons).md +++ b/controls/shortcuts/getting-started-(radbuttons).md @@ -15,8 +15,8 @@ As stated in the [Overview]({%slug winforms/shortcuts%}) article, **RadShortcuts #### Assigning shortcuts -{{source=..\SamplesCS\Shortcuts\Form2.cs region=buttonsShortcuts}} -{{source=..\SamplesVB\Shortcuts\Form2.vb region=buttonsShortcuts}} + + ````C# this.radButton1.ButtonElement.Shortcuts.Add(new RadShortcut(Keys.Control, Keys.B)); @@ -33,8 +33,6 @@ Me.RadToggleButton1.ButtonElement.Shortcuts.Add(New RadShortcut(Keys.Control, Ke ```` -{{endregion}} - # See Also * [Getting Started (RadMenuItems)]({%slug winforms/shortcuts/getting-started-(radmenuitems)%}) diff --git a/controls/shortcuts/getting-started-(radmenuitems).md b/controls/shortcuts/getting-started-(radmenuitems).md index 6c52eabe4..6168fb6fd 100644 --- a/controls/shortcuts/getting-started-(radmenuitems).md +++ b/controls/shortcuts/getting-started-(radmenuitems).md @@ -48,8 +48,8 @@ The Telerik UI for WinForms assemblies can be install by using one of the availa 5\. Inside the event handlers add the following code: -{{source=..\SamplesCS\Shortcuts\Form2.cs region=handlingClickEvent}} -{{source=..\SamplesVB\Shortcuts\Form2.vb region=handlingClickEvent}} + + ````C# void radMenuItem1_Click(object sender, EventArgs e) @@ -72,12 +72,10 @@ End Sub ```` -{{endregion}} - 6\. Now, all you have to do is to add the shortcuts to the desired items -{{source=..\SamplesCS\Shortcuts\Form2.cs region=menuShortcuts}} -{{source=..\SamplesVB\Shortcuts\Form2.vb region=menuShortcuts}} + + ````C# this.radMenuItem1.Shortcuts.Add(new RadShortcut(Keys.Control, Keys.N)); @@ -90,8 +88,6 @@ Me.RadMenuItem2.Shortcuts.Add(New RadShortcut(Keys.Shift, Keys.F, Keys.K)) ```` -{{endregion}} - >note In the constructor of **RadShortcut**, you should first pass the key modifier as a parameter and then an array of the key mappings. > @@ -103,8 +99,8 @@ Interesting functionality to mention is the ability to set your own custom text #### Specifying HintText -{{source=..\SamplesCS\Shortcuts\Form2.cs region=SetHintText}} -{{source=..\SamplesVB\Shortcuts\Form2.vb region=SetHintText}} + + ````C# radMenuItem2.HintText = "Custom Text"; @@ -115,8 +111,6 @@ RadMenuItem2.HintText = "Custom Text" ```` -{{endregion}} - ![WinForms RadShortcuts Specifying HintText](images/shortcuts-getting-started-(radmenuitems)004.png) # See Also diff --git a/controls/slideview/animation.md b/controls/slideview/animation.md index 66905167a..59c5d4b29 100644 --- a/controls/slideview/animation.md +++ b/controls/slideview/animation.md @@ -26,32 +26,13 @@ The __AnimationStarted__ and __AnimationFinished__ events occur when the animati #### Customize the Default Animation -{{source=..\SamplesCS\SlideView\GettingStartedGallery.cs region=CustomizeAnimation}} -{{source=..\SamplesVB\SlideView\GettingStartedGallery.vb region=CustomizeAnimation}} + + -````C# -this.radSlideView1.AllowAnimation = true; -this.radSlideView1.AnimationInterval = 30; -this.radSlideView1.AnimationFrames = 30; -this.radSlideView1.AnimationType = AnimationType.Fade; -this.radSlideView1.AnimationEasingType = Telerik.WinControls.RadEasingType.InExponential; - -```` -````VB.NET - -Me.radSlideView1.AllowAnimation = True -Me.radSlideView1.AnimationInterval = 30 -Me.radSlideView1.AnimationFrames = 30 -Me.radSlideView1.AnimationType = AnimationType.Fade -Me.radSlideView1.AnimationEasingType = Telerik.WinControls.RadEasingType.InExponential - -```` - -{{endregion}} ![WinForms SlideView Animation](images/slideview-animation.gif) ## See Also -* [Structure]({%slug slideview-structure%}) \ No newline at end of file +* [Structure]({%slug slideview-structure%}) diff --git a/controls/slideview/data-binding.md b/controls/slideview/data-binding.md index 9d2e30e70..e904bade3 100644 --- a/controls/slideview/data-binding.md +++ b/controls/slideview/data-binding.md @@ -26,345 +26,10 @@ position: 3 >important When the types of the mapped property and the property of the visual element do not match the **MappedPropertyUpdating** event has to be used to convert the value type to the visual element property type. If not converted, the property will not be mapped. In the example below the mapped property is of type Integer(Id), but the visual element property is of type String(Text), and in the MappedPropertyUpdating event we convert the value to string type and format the string. -{{source=..\SamplesCS\SlideView\SlideViewBinding.cs region=DataBinding}} -{{source=..\SamplesVB\SlideView\SlideViewBinding.vb region=DataBinding}} + + -````C# - private void BindSlideView() - { - BindingList employees = new BindingList(); - employees.Add(new Employee(1, "Laura Callahan", "Inside Sales Coordinator", Properties.Resources.laura)); - employees.Add(new Employee(2, "Michael Suyama", "Sales Representative", Properties.Resources.michael)); - employees.Add(new Employee(1, "Anne Dodsworth", "Sales Manager", Properties.Resources.anne)); - BindingSource bs = new BindingSource(); - bs.DataSource = employees; - this.radSlideView1.BindingSource = bs; - - GalleryTemplate template = new GalleryTemplate(); - this.radSlideView1.Mappings.Add(new Mapping(template, LightVisualElement.BackgroundImageProperty, nameof(Employee.Photo))); - this.radSlideView1.Mappings.Add(new Mapping(template.LabelId, LightVisualElement.TextProperty, nameof(Employee.Id))); - this.radSlideView1.Mappings.Add(new Mapping(template.LabelName, LightVisualElement.TextProperty, nameof(Employee.Name))); - this.radSlideView1.Mappings.Add(new Mapping(template.LabelTitle, LightVisualElement.TextProperty, nameof(Employee.Title))); - this.radSlideView1.MappedPropertyUpdating += RadSlideView1_MappedPropertyUpdating; - this.radSlideView1.TemplateElement = template; - - } - - private void RadSlideView1_MappedPropertyUpdating(object sender, MappedPropertyUpdatingEventArgs e) - { - if (e.PropertyName == nameof(Employee.Id)) - { - e.Value = $"ID = {e.Value}"; - } - } - - internal class GalleryTemplate : LightVisualElement - { - public StackLayoutElement Panel { get; private set; } - - public StackLayoutElement LabelsPanel { get; private set; } - public LightVisualElement LabelId { get; private set; } - public LightVisualElement LabelName { get; private set; } - - public StackLayoutElement ButtonsPanel { get; private set; } - public LightVisualElement LabelTitle { get; private set; } - public GlyphButtonElement ButtonLike { get; private set; } - - protected override void CreateChildElements() - { - base.CreateChildElements(); - - this.BackgroundImageLayout = ImageLayout.Tile; - this.Panel = new StackLayoutElement() - { - Alignment = ContentAlignment.BottomCenter, - Orientation = Orientation.Vertical, - Margin = new Padding(30), - StretchHorizontally = false, - StretchVertically = false, - MinSize = new Size(150, 75) - }; - this.Children.Add(this.Panel); - - this.LabelsPanel = new StackLayoutElement { Orientation = Orientation.Vertical, DrawFill = true, - GradientStyle = GradientStyles.Solid, StretchHorizontally = true, Padding = new Padding(6, 4, 6, 4), - BackColor = Color.FromArgb(200, Color.White), - }; - this.Panel.Children.Add(this.LabelsPanel); - - Font font = new Font("Segoe UI Semibold", 10f); - this.LabelId = new LightVisualElement { Font = font, ForeColor = Color.Black, TextAlignment = ContentAlignment.BottomLeft }; - this.LabelName = new LightVisualElement() { Font = font, ForeColor = Color.Black, TextAlignment = ContentAlignment.TopLeft }; - this.LabelsPanel.Children.Add(this.LabelId); - this.LabelsPanel.Children.Add(this.LabelName); - - this.ButtonsPanel = new StackLayoutElement - { - Orientation = Orientation.Horizontal, - DrawFill = true, - GradientStyle = GradientStyles.Solid, - BackColor = Color.FromArgb(200, Color.DarkGray), - Padding = new Padding(10, 4, 10, 4), - ElementSpacing = 10, - StretchHorizontally = true, - StretchVertically = true, - }; - this.Panel.Children.Add(this.ButtonsPanel); - - this.LabelTitle = new LightVisualElement() { Alignment = ContentAlignment.MiddleLeft, - Padding = new Padding(6, 0, 6, 0), StretchHorizontally = false, StretchVertically = false, MinSize = new Size(0, 30) }; - this.LabelTitle.UnbindProperty(RadElement.StretchVerticallyProperty); - this.LabelTitle.StretchVertically = true; - this.ButtonsPanel.Children.Add(this.LabelTitle); - - this.ButtonLike = new GlyphButtonElement(TelerikWebUIFont.GlyphHeartOutline); - this.ButtonLike.Click += this.ButtonLike_Click; - this.ButtonsPanel.Children.Add(this.ButtonLike); - - } - - private void ButtonLike_Click(object sender, EventArgs e) - { - if (sender is RadButtonElement button) - { - if (button.Text == TelerikWebUIFont.GlyphHeart) - { - button.Text = TelerikWebUIFont.GlyphHeartOutline; - button.ResetLocalValue(ForeColorProperty); - } - else - { - button.Text = TelerikWebUIFont.GlyphHeart; - button.ForeColor = Color.FromArgb(225, 19, 20); - } - } - } - - internal class GlyphButtonElement : RadButtonElement - { - public GlyphButtonElement(string glyph, bool circleShape = false) : - base(glyph) - { - if (circleShape) - { - this.SetThemeValueOverride(ShapeProperty, new CircleShape(), string.Empty); - } - } - - - protected override void OnLoaded() - { - base.OnLoaded(); - - Font glyphFont = new Font(ThemeResolutionService.GetCustomFont(ThemeResolutionService.WebComponentsIconsFontName), 12f); - this.SetThemeValueOverride(FontProperty, glyphFont, string.Empty, typeof(TextPrimitive)); - this.Alignment = ContentAlignment.MiddleLeft; - this.Padding = new Padding(3, 6, 3, 4); - this.StretchHorizontally = false; - this.StretchVertically = false; - this.MinSize = new Size(30, 30); - this.MaxSize = new Size(30, 30); - if (this.Shape?.GetType() == typeof(CircleShape)) - { - this.EnableBorderHighlight = false; - this.ButtonFillElement.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; - } - } - - protected override Type ThemeEffectiveType - { - get { return typeof(RadButtonElement); } - } - } - } - - public class Employee - { - public Employee(int _id, string _name, string _title, Bitmap _photo) - { - Id = _id; - Name = _name; - Title = _title; - Photo = _photo; - } - - public int Id { get; set; } - public string Name { get; set; } - public string Title { get; set; } - public Image Photo { get; set; } - - } - -```` -````VB.NET - - Private Sub BindSlideView() - Dim employees As BindingList(Of Employee) = New BindingList(Of Employee)() - employees.Add(New Employee(1, "Laura Callahan", "Inside Sales Coordinator", My.Resources.laura)) - employees.Add(New Employee(2, "Michael Suyama", "Sales Representative", My.Resources.michael)) - employees.Add(New Employee(1, "Anne Dodsworth", "Sales Manager", My.Resources.anne)) - Dim bs As BindingSource = New BindingSource() - bs.DataSource = employees - Me.radSlideView1.BindingSource = bs - Dim template As GalleryTemplate = New GalleryTemplate() - Me.radSlideView1.Mappings.Add(New Mapping(template, LightVisualElement.BackgroundImageProperty, NameOf(Employee.Photo))) - Me.radSlideView1.Mappings.Add(New Mapping(template.LabelId, LightVisualElement.TextProperty, NameOf(Employee.Id))) - Me.radSlideView1.Mappings.Add(New Mapping(template.LabelName, LightVisualElement.TextProperty, NameOf(Employee.Name))) - Me.radSlideView1.Mappings.Add(New Mapping(template.LabelTitle, LightVisualElement.TextProperty, NameOf(Employee.Title))) - AddHandler Me.radSlideView1.MappedPropertyUpdating, AddressOf RadSlideView1_MappedPropertyUpdating - Me.radSlideView1.TemplateElement = template - End Sub - - Private Sub RadSlideView1_MappedPropertyUpdating(ByVal sender As Object, ByVal e As MappedPropertyUpdatingEventArgs) - If e.PropertyName = NameOf(Employee.Id) Then - e.Value = $"ID = {e.Value}" - End If - End Sub - - Friend Class GalleryTemplate - Inherits LightVisualElement - - Public Property Panel As StackLayoutElement - Public Property LabelsPanel As StackLayoutElement - Public Property LabelId As LightVisualElement - Public Property LabelName As LightVisualElement - Public Property ButtonsPanel As StackLayoutElement - Public Property LabelTitle As LightVisualElement - Public Property ButtonLike As GlyphButtonElement - - Protected Overrides Sub CreateChildElements() - MyBase.CreateChildElements() - Me.BackgroundImageLayout = ImageLayout.Tile - Me.Panel = New StackLayoutElement() With { - .Alignment = ContentAlignment.BottomCenter, - .Orientation = Orientation.Vertical, - .Margin = New Padding(30), - .StretchHorizontally = False, - .StretchVertically = False, - .MinSize = New Size(150, 75) - } - Me.Children.Add(Me.Panel) - Me.LabelsPanel = New StackLayoutElement With { - .Orientation = Orientation.Vertical, - .DrawFill = True, - .GradientStyle = GradientStyles.Solid, - .StretchHorizontally = True, - .Padding = New Padding(6, 4, 6, 4), - .BackColor = Color.FromArgb(200, Color.White) - } - Me.Panel.Children.Add(Me.LabelsPanel) - Dim font As Font = New Font("Segoe UI Semibold", 10.0F) - Me.LabelId = New LightVisualElement With { - .Font = font, - .ForeColor = Color.Black, - .TextAlignment = ContentAlignment.BottomLeft - } - Me.LabelName = New LightVisualElement() With { - .Font = font, - .ForeColor = Color.Black, - .TextAlignment = ContentAlignment.TopLeft - } - Me.LabelsPanel.Children.Add(Me.LabelId) - Me.LabelsPanel.Children.Add(Me.LabelName) - Me.ButtonsPanel = New StackLayoutElement With { - .Orientation = Orientation.Horizontal, - .DrawFill = True, - .GradientStyle = GradientStyles.Solid, - .BackColor = Color.FromArgb(200, Color.DarkGray), - .Padding = New Padding(10, 4, 10, 4), - .ElementSpacing = 10, - .StretchHorizontally = True, - .StretchVertically = True - } - Me.Panel.Children.Add(Me.ButtonsPanel) - Me.LabelTitle = New LightVisualElement() With { - .Alignment = ContentAlignment.MiddleLeft, - .Padding = New Padding(6, 0, 6, 0), - .StretchHorizontally = False, - .StretchVertically = False, - .MinSize = New Size(0, 30) - } - Me.LabelTitle.UnbindProperty(RadElement.StretchVerticallyProperty) - Me.LabelTitle.StretchVertically = True - Me.ButtonsPanel.Children.Add(Me.LabelTitle) - Me.ButtonLike = New GlyphButtonElement(TelerikWebUIFont.GlyphHeartOutline) - AddHandler Me.ButtonLike.Click, AddressOf Me.ButtonLike_Click - Me.ButtonsPanel.Children.Add(Me.ButtonLike) - End Sub - - Private Sub ButtonLike_Click(ByVal sender As Object, ByVal e As EventArgs) - Dim button As RadButtonElement = TryCast(sender, RadButtonElement) - - If button IsNot Nothing Then - - If button.Text = TelerikWebUIFont.GlyphHeart Then - button.Text = TelerikWebUIFont.GlyphHeartOutline - button.ResetLocalValue(ForeColorProperty) - Else - button.Text = TelerikWebUIFont.GlyphHeart - button.ForeColor = Color.FromArgb(225, 19, 20) - End If - End If - End Sub - - Friend Class GlyphButtonElement - Inherits RadButtonElement - - Public Sub New(ByVal glyph As String, ByVal Optional circleShape As Boolean = False) - MyBase.New(glyph) - - If circleShape Then - Me.SetThemeValueOverride(ShapeProperty, New CircleShape(), String.Empty) - End If - End Sub - - Protected Overrides Sub OnLoaded() - MyBase.OnLoaded() - Dim glyphFont As Font = New Font(ThemeResolutionService.GetCustomFont(ThemeResolutionService.WebComponentsIconsFontName), 12.0F) - Me.SetThemeValueOverride(FontProperty, glyphFont, String.Empty, GetType(TextPrimitive)) - Me.Alignment = ContentAlignment.MiddleLeft - Me.Padding = New Padding(3, 6, 3, 4) - Me.StretchHorizontally = False - Me.StretchVertically = False - Me.MinSize = New Size(30, 30) - Me.MaxSize = New Size(30, 30) - - If Me.Shape?.[GetType]() = GetType(CircleShape) Then - Me.EnableBorderHighlight = False - Me.ButtonFillElement.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias - End If - End Sub - - Protected Overrides ReadOnly Property ThemeEffectiveType As Type - Get - Return GetType(RadButtonElement) - End Get - End Property - - End Class - - End Class - - Public Class Employee - Public Sub New(ByVal _id As Integer, ByVal _name As String, ByVal _title As String, ByVal _photo As Bitmap) - Id = _id - Name = _name - Title = _title - Photo = _photo - End Sub - - Public Property Id As Integer - Public Property Name As String - Public Property Title As String - Public Property Photo As Image - End Class - -```` - -{{endregion}} - - ## See Also diff --git a/controls/slideview/getting-started.md b/controls/slideview/getting-started.md index 78f8fbbcb..72d8bd076 100644 --- a/controls/slideview/getting-started.md +++ b/controls/slideview/getting-started.md @@ -51,45 +51,10 @@ Follow the steps: 5\. Set the __BindingSource__ property of RadSlideView. -{{source=..\SamplesCS\SlideView\GettingStartedGallery.cs region=GettingStarted}} -{{source=..\SamplesVB\SlideView\GettingStartedGallery.vb region=GettingStarted}} - -````C# -BindingSource bs = new BindingSource(); -DataTable dt = new DataTable(); -dt.Columns.Add("Photo", typeof(Image)); -dt.Rows.Add(Properties.Resources.Burano1); -dt.Rows.Add(Properties.Resources.Burano2); -dt.Rows.Add(Properties.Resources.Burano3); -bs.DataSource = dt; - -LightVisualElement basicTemplate = new LightVisualElement(); -basicTemplate.Opacity = 0.5; -basicTemplate.ImageLayout = ImageLayout.Zoom; -this.radSlideView1.Mappings.Add(new Mapping(basicTemplate, LightVisualElement.ImageProperty, dt.Columns[0].ColumnName)); -this.radSlideView1.TemplateElement = basicTemplate; -this.radSlideView1.BindingSource = bs; - -```` -````VB.NET - -Dim bs As BindingSource = New BindingSource() -Dim dt As DataTable = New DataTable() -dt.Columns.Add("Photo", GetType(Image)) -dt.Rows.Add(My.Resources.Burano1) -dt.Rows.Add(My.Resources.Burano2) -dt.Rows.Add(My.Resources.Burano3) -bs.DataSource = dt -Dim basicTemplate As LightVisualElement = New LightVisualElement() -basicTemplate.Opacity = 0.5 -basicTemplate.ImageLayout = ImageLayout.Zoom -Me.radSlideView1.Mappings.Add(New Mapping(basicTemplate, LightVisualElement.ImageProperty, dt.Columns(0).ColumnName)) -Me.radSlideView1.TemplateElement = basicTemplate -Me.radSlideView1.BindingSource = bs - -```` - -{{endregion}} + + + + >note More advanced TemplateElement is demonstrated in the Demo application >> SlideView >> First look example which also shows the smooth integration between RadSlideView and [RadPipsPager]({%slug pipspager-overview%}). diff --git a/controls/slideview/infinite-scrolling.md b/controls/slideview/infinite-scrolling.md index 0568f8f79..f3ae28341 100644 --- a/controls/slideview/infinite-scrolling.md +++ b/controls/slideview/infinite-scrolling.md @@ -15,17 +15,9 @@ By default, when the user scrolls to the last slideview item the navigation butt #### Enable Infinite Scrolling -{{source=..\SamplesCS\SlideView\GettingStartedGallery.cs region=EnableInfiniteScrolling}} -{{source=..\SamplesCS\SlideView\GettingStartedGallery.vb region=EnableInfiniteScrolling}} + + -````C# -this.radSlideView1.IsInfiniteScrollingEnabled = true; - -```` -````VB.NET -Me.radSlideView1.IsInfiniteScrollingEnabled = True - -```` ![RadSlideView Infinite Scrolling](images/slideview-infinite-scrolling.gif) @@ -34,4 +26,4 @@ Me.radSlideView1.IsInfiniteScrollingEnabled = True * [Getting Started]({%slug slideview-getting-started%}) * [Structure]({%slug slideview-structure%}) -* [Structure]({%slug slideview-navigation-buttons%}) \ No newline at end of file +* [Structure]({%slug slideview-navigation-buttons%}) diff --git a/controls/slideview/navigation-buttons.md b/controls/slideview/navigation-buttons.md index a1b2b2c1f..fcce2224f 100644 --- a/controls/slideview/navigation-buttons.md +++ b/controls/slideview/navigation-buttons.md @@ -39,29 +39,14 @@ You can specify a time interval (in milliseconds), after which the navigation bu #### Customize the Navigation Buttons -{{source=..\SamplesCS\SlideView\GettingStartedGallery.cs region=NavigationButtons}} -{{source=..\SamplesVB\SlideView\GettingStartedGallery.vb region=NavigationButtons}} + + -````C# -this.radSlideView1.ButtonsVisibility = ButtonsVisibility.VisibleOnMouseOver; -this.radSlideView1.ShowButtonsOverContent = false; -this.radSlideView1.AutoHideButtonsDelay = 1000; - -```` -````VB.NET - -Me.radSlideView1.ButtonsVisibility = ButtonsVisibility.VisibleOnMouseOver -Me.radSlideView1.ShowButtonsOverContent = False -Me.radSlideView1.AutoHideButtonsDelay = 1000 - -```` - -{{endregion}} ![WinForms SlideView Customize Navigation Buttons](images/slideview-customize-navigation-buttons.gif) ## See Also -* [Structure]({%slug slideview-structure%}) \ No newline at end of file +* [Structure]({%slug slideview-structure%}) diff --git a/controls/slideview/template-element.md b/controls/slideview/template-element.md index 1580bdebe..36ebd7329 100644 --- a/controls/slideview/template-element.md +++ b/controls/slideview/template-element.md @@ -22,43 +22,10 @@ More advanced TemplateElement example is demonstrated in the Demo application >> ![WinForms SlideView TemplateElement](images/slideview-template-element.png) #### Setup template -{{source=..\SamplesCS\SlideView\GettingStartedGallery.cs region=SetupTemplate}} -{{source=..\SamplesVB\SlideView\GettingStartedGallery.vb region=SetupTemplate}} - -````C# -private void SetupTemplate() -{ - this.radSlideView1.NumberOfPages = 3; - this.radSlideView1.TemplateElement.DrawFill = true; - this.radSlideView1.TemplateElement.GradientStyle = GradientStyles.Solid; - this.radSlideView1.TemplateElement.BackColor = Color.White; -} -private void RadSlideView1_TemplateUpdated(object sender, TemplateUpdatedEventArgs e) -{ - Image image = images[this.radSlideView1.SelectedIndex]; - this.radSlideView1.TemplateElement.Image = image; - this.radSlideView1.TemplateElement.Text = $"Page {this.radSlideView1.SelectedIndex + 1} of {this.radSlideView1.NumberOfPages}"; - this.radSlideView1.TemplateElement.ForeColor = Color.Red; - this.radSlideView1.TemplateElement.Font = new Font("Segoe UI", 15, FontStyle.Bold); -} - -```` -````VB.NET - Private Sub SetupTemplate() - Me.radSlideView1.NumberOfPages = 3 - Me.radSlideView1.TemplateElement.DrawFill = True - Me.radSlideView1.TemplateElement.GradientStyle = GradientStyles.Solid - Me.radSlideView1.TemplateElement.BackColor = Color.White - End Sub - Private Sub RadSlideView1_TemplateUpdated(ByVal sender As Object, ByVal e As TemplateUpdatedEventArgs) - Dim image As Image = images(Me.radSlideView1.SelectedIndex) - Me.radSlideView1.TemplateElement.Image = image - Me.radSlideView1.TemplateElement.Text = $"Page {Me.radSlideView1.SelectedIndex + 1} of {Me.radSlideView1.NumberOfPages}" - Me.radSlideView1.TemplateElement.ForeColor = Color.Red - Me.radSlideView1.TemplateElement.Font = New Font("Segoe UI", 15, FontStyle.Bold) - End Sub - -```` + + + + >note For more detailed information please refer to [Unbound mode](#unbound-mode). diff --git a/controls/slideview/unbound-mode.md b/controls/slideview/unbound-mode.md index 2919e4cf3..0ab1615fe 100644 --- a/controls/slideview/unbound-mode.md +++ b/controls/slideview/unbound-mode.md @@ -22,39 +22,10 @@ Let's consider that we have a folder "Gallery" with 5 images. When navigating th ![WinForms SlideView UpdImages](images/slideview-images.png) -{{source=..\SamplesCS\SlideView\SlideViewBinding.cs region=UnboundMode}} -{{source=..\SamplesVB\SlideView\SlideViewBinding.vb region=UnboundMode}} + + -````C# - private void UnboundMode() - { - this.radSlideView1.TemplateUpdated += RadSlideView1_TemplateUpdated; - this.radSlideView1.NumberOfPages = 5; - } - - private void RadSlideView1_TemplateUpdated(object sender, Telerik.WinControls.UI.SlideView.TemplateUpdatedEventArgs e) - { - int imageIndex = this.radSlideView1.SelectedIndex + 1; - e.Template.Image = Image.FromFile(@"..\..\Gallery\Image" + imageIndex + ".png"); - } - -```` -````VB.NET - - Private Sub UnboundMode() - AddHandler Me.radSlideView1.TemplateUpdated, AddressOf RadSlideView1_TemplateUpdated - Me.radSlideView1.NumberOfPages = 5 - End Sub - - Private Sub RadSlideView1_TemplateUpdated(sender As Object, e As TemplateUpdatedEventArgs) - Dim imageIndex = Me.radSlideView1.SelectedIndex + 1 - e.Template.Image = Image.FromFile("..\..\Gallery\Image" & imageIndex & ".png") - End Sub - -```` - -{{endregion}} ![WinForms SlideView Update Pages](images/slideview-update-pages.gif) diff --git a/controls/sparkline/customizing-appearance/custom-painting.md b/controls/sparkline/customizing-appearance/custom-painting.md index fc6e1b06b..51dacd273 100644 --- a/controls/sparkline/customizing-appearance/custom-painting.md +++ b/controls/sparkline/customizing-appearance/custom-painting.md @@ -23,53 +23,10 @@ The following examples demonstrates how you can use the above events. #### Using the Paint Events -{{source=..\SamplesCS\Sparkline\SparklineCode.cs region=CustomPaint}} -{{source=..\SamplesVB\Sparkline\SparklineCode.vb region=CustomPaint}} -````C# -Font labelFont = new Font("Segoe UI", 8, FontStyle.Regular); -Image pointIcon = Image.FromFile(@"C:\img\pin.png").GetThumbnailImage(16, 16, null, IntPtr.Zero); -private void RadSparkline1_PaintSparkStroke(object sender, PaintSparkStrokeEventArgs e) -{ - if (e.Context is CategoricalSparkDataPoint) - { - e.Cancel = true; - var point = new PointF(e.Path.PathPoints[0].X - 16, e.Path.PathPoints[0].Y - 16); - e.Graphics.DrawImage(pointIcon, point); - } -} -private void RadSparkline1_PaintSparkFill(object sender, PaintSparkFillEventArgs e) -{ - if (e.Context is CategoricalSparkDataPoint) - { - e.Cancel = true; - var value = (e.Context as CategoricalSparkDataPoint).Value; - e.Graphics.DrawString(value.ToString(), labelFont, Brushes.Blue, e.Path.PathPoints[0].X, e.Path.PathPoints[0].Y); - } -} + + -```` -````VB.NET -Private labelFont As New Font("Segoe UI", 8, FontStyle.Regular) -Private pointIcon As Image = Image.FromFile("C:\img\pin.png").GetThumbnailImage(16, 16, Nothing, IntPtr.Zero) -Private Sub RadSparkline1_PaintSparkStroke(ByVal sender As Object, ByVal e As PaintSparkStrokeEventArgs) - If TypeOf e.Context Is CategoricalSparkDataPoint Then - e.Cancel = True - Dim point = New PointF(e.Path.PathPoints(0).X - 16, e.Path.PathPoints(0).Y - 16) - e.Graphics.DrawImage(pointIcon, point) - End If -End Sub -Private Sub RadSparkline1_PaintSparkFill(ByVal sender As Object, ByVal e As PaintSparkFillEventArgs) - If TypeOf e.Context Is CategoricalSparkDataPoint Then - e.Cancel = True - Dim value = (TryCast(e.Context, CategoricalSparkDataPoint)).Value - e.Graphics.DrawString(value.ToString(), labelFont, Brushes.Blue, e.Path.PathPoints(0).X, e.Path.PathPoints(0).Y) - End If -End Sub -```` - - -{{endregion}} >caption Figure 1: Custom Paint diff --git a/controls/sparkline/export-to-image.md b/controls/sparkline/export-to-image.md index 3d3c96f19..fe838cb9e 100644 --- a/controls/sparkline/export-to-image.md +++ b/controls/sparkline/export-to-image.md @@ -13,21 +13,8 @@ __RadSparkline__ supports exporting to image out of the box. This can be achieve #### Example 1: Export to a File -{{source=..\SamplesCS\Sparkline\SparklineCode.cs region=Export}} -{{source=..\SamplesVB\Sparkline\SparklineCode.vb region=Export}} -````C# -private void RadButton1_Click(object sender, EventArgs e) -{ - radSparkline1.ExportToImage(@"D:\MySpark1.png", new Size(200, 200)); -} + + -```` -````VB.NET -Private Sub RadButton1_Click(ByVal sender As Object, ByVal e As EventArgs) - radSparkline1.ExportToImage("D:\MySpark1.png", New Size(200, 200)) -End Sub -```` - -{{endregion}} \ No newline at end of file diff --git a/controls/sparkline/features/annotations.md b/controls/sparkline/features/annotations.md index 80a1cf30a..6a5b95440 100644 --- a/controls/sparkline/features/annotations.md +++ b/controls/sparkline/features/annotations.md @@ -34,50 +34,10 @@ The following example shows how you can create a Grid Line annotation. #### Add Plot Band Annotation -{{source=..\SamplesCS\Sparkline\SparklineCode.cs region=GridLineAnnotation}} -{{source=..\SamplesVB\Sparkline\SparklineCode.vb region=GridLineAnnotation}} -````C# -public void AddGridLineAnnotation() -{ - CartesianSparkGridLineAnnotation annotation1 = new CartesianSparkGridLineAnnotation(); - annotation1.Axis = this.radSparkline1.Axes[1] as SparkCartesianAxis; - annotation1.Value = 3; - annotation1.BorderColor = Color.Red; - annotation1.BorderDashStyle = DashStyle.Solid; - annotation1.BorderWidth = 1; - this.radSparkline1.Annotations.Add(annotation1); - CartesianSparkGridLineAnnotation annotation2 = new CartesianSparkGridLineAnnotation(); - annotation2.Axis = this.radSparkline1.Axes[0] as SparkCartesianAxis; - annotation2.Value = "Test"; - annotation2.BorderColor = Color.Blue; - annotation2.BorderDashStyle = DashStyle.Solid; - annotation2.BorderWidth = 1; - this.radSparkline1.Annotations.Add(annotation2); -} - -```` -````VB.NET -Public Sub AddGridLineAnnotation() - Dim annotation1 As New CartesianSparkGridLineAnnotation() - annotation1.Axis = TryCast(Me.radSparkline1.Axes(1), SparkCartesianAxis) - annotation1.Value = 3 - annotation1.BorderColor = Color.Red - annotation1.BorderDashStyle = DashStyle.Solid - annotation1.BorderWidth = 1 - Me.radSparkline1.Annotations.Add(annotation1) - Dim annotation2 As New CartesianSparkGridLineAnnotation() - annotation2.Axis = TryCast(Me.radSparkline1.Axes(0), SparkCartesianAxis) - annotation2.Value = "Test" - annotation2.BorderColor = Color.Blue - annotation2.BorderDashStyle = DashStyle.Solid - annotation2.BorderWidth = 1 - Me.radSparkline1.Annotations.Add(annotation2) -End Sub - -```` - - -{{endregion}} + + + + Properties specific to the Grid Line Annotations are: @@ -102,40 +62,11 @@ The following example shows how you can create a Plot Band annotation. #### Add Plot Band Annotation -{{source=..\SamplesCS\Sparkline\SparklineCode.cs region=PlotBandAnnotation}} -{{source=..\SamplesVB\Sparkline\SparklineCode.vb region=PlotBandAnnotation}} -````C# -public void AddPlotBandAnottation() -{ - CartesianSparkPlotBandAnnotation annotation1 = new CartesianSparkPlotBandAnnotation(); - annotation1.Axis = this.radSparkline1.Axes[1] as SparkCartesianAxis; - annotation1.From = -2; - annotation1.To = 2; - annotation1.BackColor = Color.FromArgb(100, Color.LightBlue); - annotation1.BorderColor = Color.Black; - annotation1.BorderWidth = 1; - this.radSparkline1.Annotations.Add(annotation1); -} - -```` -````VB.NET -Public Sub AddPlotBandAnottation() - Dim annotation1 As New CartesianSparkPlotBandAnnotation() - annotation1.Axis = TryCast(Me.radSparkline1.Axes(1), SparkCartesianAxis) - annotation1.From = -2 - annotation1.To = 2 - annotation1.BackColor = Color.FromArgb(100, Color.LightBlue) - annotation1.BorderColor = Color.Black - annotation1.BorderWidth = 1 - Me.radSparkline1.Annotations.Add(annotation1) -End Sub - -```` - - -{{endregion}} - - + + + + + Properties specific to the Plot Band Annotations are: * __Axis:__ The Cartesian plotBand annotation needs to be associated with horizontal or vertical axis explicitly. diff --git a/controls/sparkline/features/indicators.md b/controls/sparkline/features/indicators.md index 2e6f04534..b7897d14c 100644 --- a/controls/sparkline/features/indicators.md +++ b/controls/sparkline/features/indicators.md @@ -31,45 +31,10 @@ The below example shows how you can customize the indicators by setting some pro #### Customize Indicators Example -{{source=..\SamplesCS\Sparkline\SparklineCode.cs region=Indicators}} -{{source=..\SamplesVB\Sparkline\SparklineCode.vb region=Indicators}} -````C# -public void StyleIndicators() -{ - SparkLineSeries series = new SparkLineSeries(); - series.ShowHighPointIndicator = true; - series.ShowLowPointIndicator = true; - series.HighPointBackColor = Color.DarkRed; - series.HighPointBorderWidth = 3; - series.HighPointBorderColor = Color.Yellow; - series.HighPointSize = new SizeF(20, 20); - series.LowPointShape = new StarShape(5, 5); - series.LowPointBackColor = Color.DarkGreen; - series.DataPoints.AddRange(GetPoints()); - radSparkline1.Series = series; -} - -```` -````VB.NET -Public Sub StyleIndicators() - Dim series As New SparkLineSeries() - series.ShowHighPointIndicator = True - series.ShowLowPointIndicator = True - series.HighPointBackColor = Color.DarkRed - series.HighPointBorderWidth = 3 - series.HighPointBorderColor = Color.Yellow - series.HighPointSize = New SizeF(20, 20) - series.LowPointShape = New StarShape(5, 5) - series.LowPointBackColor = Color.DarkGreen - series.DataPoints.AddRange(GetPoints()) - radSparkline1.Series = series -End Sub - -```` - - - -{{endregion}} + + + + >caption Figure 2: Show and Customize Indicators diff --git a/controls/sparkline/features/null-values.md b/controls/sparkline/features/null-values.md index ee4ff8dd3..67e03f9dc 100644 --- a/controls/sparkline/features/null-values.md +++ b/controls/sparkline/features/null-values.md @@ -15,68 +15,9 @@ In __RadSparkline__ the __EmptyPointBehavior__ property controls what happens wi * __ShowAsZero:__ The null point will be considered as 0 on the Y axis. * __DoNotShow:__ The null point would not be painted on the chart. -{{source=..\SamplesCS\Sparkline\SparklineCode.cs region=SparklineNullValueSupport}} -{{source=..\SamplesVB\Sparkline\SparklineCode.vb region=SparklineNullValueSupport}} + + -````C# - -public void AddSeries() -{ - SparkLineSeries lineSeries = new SparkLineSeries(); - lineSeries.DataPoints.Add(new CategoricalSparkDataPoint(13)); - lineSeries.DataPoints.Add(new CategoricalSparkDataPoint(20)); - lineSeries.DataPoints.Add(new CategoricalSparkDataPoint(15)); - lineSeries.DataPoints.Add(new CategoricalSparkDataPoint(-5)); - lineSeries.DataPoints.Add(new CategoricalSparkDataPoint(null)); - lineSeries.DataPoints.Add(new CategoricalSparkDataPoint(8)); - lineSeries.DataPoints.Add(new CategoricalSparkDataPoint(-22)); - lineSeries.DataPoints.Add(new CategoricalSparkDataPoint(22)); - lineSeries.DataPoints.Add(new CategoricalSparkDataPoint(12)); - lineSeries.ShowMarkers = true; - lineSeries.ShowHighPointIndicator = true; - lineSeries.ShowLowPointIndicator = true; - radSparkline1.Series = lineSeries; - CartesianSparkGridLineAnnotation annotation1 = new CartesianSparkGridLineAnnotation(); - annotation1.Axis = this.radSparkline1.Axes[1] as SparkCartesianAxis; - annotation1.Value = 0; - annotation1.BorderColor = Color.Red; - annotation1.BorderDashStyle = DashStyle.Solid; - annotation1.BorderWidth = 1; - this.radSparkline1.Annotations.Add(annotation1); -} - - - -```` -````VB.NET - -Public Sub AddSeries() - Dim lineSeries As SparkLineSeries = New SparkLineSeries() - lineSeries.DataPoints.Add(New CategoricalSparkDataPoint(13)) - lineSeries.DataPoints.Add(New CategoricalSparkDataPoint(20)) - lineSeries.DataPoints.Add(New CategoricalSparkDataPoint(15)) - lineSeries.DataPoints.Add(New CategoricalSparkDataPoint(-5)) - lineSeries.DataPoints.Add(New CategoricalSparkDataPoint(Nothing)) - lineSeries.DataPoints.Add(New CategoricalSparkDataPoint(8)) - lineSeries.DataPoints.Add(New CategoricalSparkDataPoint(-22)) - lineSeries.DataPoints.Add(New CategoricalSparkDataPoint(22)) - lineSeries.DataPoints.Add(New CategoricalSparkDataPoint(12)) - lineSeries.ShowMarkers = True - lineSeries.ShowHighPointIndicator = True - lineSeries.ShowLowPointIndicator = True - radSparkline1.Series = lineSeries - Dim annotation1 As CartesianSparkGridLineAnnotation = New CartesianSparkGridLineAnnotation() - annotation1.Axis = TryCast(Me.radSparkline1.Axes(1), SparkCartesianAxis) - annotation1.Value = 0 - annotation1.BorderColor = Color.Red - annotation1.BorderDashStyle = DashStyle.Solid - annotation1.BorderWidth = 1 - Me.radSparkline1.Annotations.Add(annotation1) -End Sub - - - -```` >caption Figure 1: ShowAsBlank diff --git a/controls/sparkline/getting-started.md b/controls/sparkline/getting-started.md index 02e6f250c..678121a24 100644 --- a/controls/sparkline/getting-started.md +++ b/controls/sparkline/getting-started.md @@ -41,76 +41,19 @@ The Telerik UI for WinForms assemblies can be install by using one of the availa #### Adding SparkBarSeries to RadSparkline -{{source=..\SamplesCS\Sparkline\SparklineCode.cs region=GettingStarted}} -{{source=..\SamplesVB\Sparkline\SparklineCode.vb region=GettingStarted}} -````C# -private void SparklineCode_Load(object sender, EventArgs e) -{ - var series = new SparkBarSeries(); - series.CategoryMember = "Category"; - series.ValueMember = "Values"; - series.DataSource = GetData(); - series.ShowHighPointIndicator = true; - series.ShowLowPointIndicator = true; - radSparkline1.Series = series; -} - -```` -````VB.NET -Private Sub SparklineCode_Load(ByVal sender As Object, ByVal e As EventArgs) - Dim series = New SparkBarSeries() - series.CategoryMember = "Category" - series.ValueMember = "Values" - series.DataSource = GetData() - series.ShowHighPointIndicator = True - series.ShowLowPointIndicator = True - radSparkline1.Series = series -End Sub - -```` - - -{{endregion}} + + + 3\. Here is the method that returns the sample data as well. #### Sample Data -{{source=..\SamplesCS\Sparkline\SparklineCode.cs region=SampleData}} -{{source=..\SamplesVB\Sparkline\SparklineCode.vb region=SampleData}} -````C# -public static DataTable GetData() -{ - DataTable table = new DataTable(); - table.Columns.Add("Values"); - table.Columns.Add("Category"); - table.Rows.Add(1, "John"); - table.Rows.Add(3, "Adam"); - table.Rows.Add(5, "Peter"); - table.Rows.Add(12, "Sam"); - table.Rows.Add(6, "Paul"); - return table; -} - -```` -````VB.NET -Public Shared Function GetData() As DataTable - Dim table As New DataTable() - table.Columns.Add("Values") - table.Columns.Add("Category") - table.Rows.Add(1, "John") - table.Rows.Add(3, "Adam") - table.Rows.Add(5, "Peter") - table.Rows.Add(12, "Sam") - table.Rows.Add(6, "Paul") - Return table -End Function - -```` - - -{{endregion}} + + + + 4\. The RadSparkline now shows the data and indicates the high an low points. diff --git a/controls/sparkline/populating-with-data/data-binding.md b/controls/sparkline/populating-with-data/data-binding.md index 24cb788f0..ad29ffb4a 100644 --- a/controls/sparkline/populating-with-data/data-binding.md +++ b/controls/sparkline/populating-with-data/data-binding.md @@ -24,62 +24,10 @@ To bind the series you need to set the __ValueMember__ property. The following e #### Bind Series to a DataTable -{{source=..\SamplesCS\Sparkline\SparklineCode.cs region=BindToTable}} -{{source=..\SamplesVB\Sparkline\SparklineCode.vb region=BindToTable}} -````C# -DataTable table; -public void AddBoundSeries() -{ - table = new DataTable(); - table.Columns.Add("Value", typeof(double)); - table.Rows.Add(1); - table.Rows.Add(-3); - table.Rows.Add(5); - table.Rows.Add(1); - table.Rows.Add(6); - table.Rows.Add(-1); - table.Rows.Add(3); - table.Rows.Add(-5); - table.Rows.Add(1); - table.Rows.Add(6); - SparkLineSeries lineSeries = new SparkLineSeries(); - lineSeries.ValueMember = "Value"; - lineSeries.DataSource = table; - lineSeries.ShowMarkers = true; - lineSeries.ShowHighPointIndicator = true; - lineSeries.ShowLowPointIndicator = true; - radSparkline1.Series = lineSeries; -} + + -```` -````VB.NET -Private table As DataTable -Public Sub AddBoundSeries() - table = New DataTable() - table.Columns.Add("Value", GetType(Double)) - table.Rows.Add(1) - table.Rows.Add(-3) - table.Rows.Add(5) - table.Rows.Add(1) - table.Rows.Add(6) - table.Rows.Add(-1) - table.Rows.Add(3) - table.Rows.Add(-5) - table.Rows.Add(1) - table.Rows.Add(6) - Dim lineSeries As New SparkLineSeries() - lineSeries.ValueMember = "Value" - lineSeries.DataSource = table - lineSeries.ShowMarkers = True - lineSeries.ShowHighPointIndicator = True - lineSeries.ShowLowPointIndicator = True - radSparkline1.Series = lineSeries -End Sub -```` - - -{{endregion}} The bellow image show the result from the above code. diff --git a/controls/sparkline/populating-with-data/unbound-mode.md b/controls/sparkline/populating-with-data/unbound-mode.md index 7768f7fe5..5371e9b30 100644 --- a/controls/sparkline/populating-with-data/unbound-mode.md +++ b/controls/sparkline/populating-with-data/unbound-mode.md @@ -14,54 +14,10 @@ When using the unbound mode you need to create the series and manually add data #### Create Series Manually -{{source=..\SamplesCS\Sparkline\SparklineCode.cs region=Unbound}} -{{source=..\SamplesVB\Sparkline\SparklineCode.vb region=Unbound}} -````C# -var barSeries = new SparkBarSeries(); -barSeries.DataPoints.Add(new CategoricalSparkDataPoint(13)); -barSeries.DataPoints.Add(new CategoricalSparkDataPoint(20)); -barSeries.DataPoints.Add(new CategoricalSparkDataPoint(15)); -barSeries.DataPoints.Add(new CategoricalSparkDataPoint(-5)); -barSeries.DataPoints.Add(new CategoricalSparkDataPoint(29)); -barSeries.DataPoints.Add(new CategoricalSparkDataPoint(8)); -barSeries.DataPoints.Add(new CategoricalSparkDataPoint(-22)); -barSeries.DataPoints.Add(new CategoricalSparkDataPoint(22)); -barSeries.DataPoints.Add(new CategoricalSparkDataPoint(12)); -barSeries.ShowHighPointIndicator = true; -barSeries.ShowLowPointIndicator = true; -barSeries.ShowFirstPointIndicator = true; -barSeries.ShowLastPointIndicator = true; -barSeries.ShowNegativePointIndicators = true; - -this.radSparkline1.ShowAxis = true; -this.radSparkline1.AxisDrawMode = AxisDrawMode.AboveSeries; -this.radSparkline1.Series = barSeries; - -```` -````VB.NET -Dim barSeries = New SparkBarSeries() -barSeries.DataPoints.Add(New CategoricalSparkDataPoint(13)) -barSeries.DataPoints.Add(New CategoricalSparkDataPoint(20)) -barSeries.DataPoints.Add(New CategoricalSparkDataPoint(15)) -barSeries.DataPoints.Add(New CategoricalSparkDataPoint(-5)) -barSeries.DataPoints.Add(New CategoricalSparkDataPoint(29)) -barSeries.DataPoints.Add(New CategoricalSparkDataPoint(8)) -barSeries.DataPoints.Add(New CategoricalSparkDataPoint(-22)) -barSeries.DataPoints.Add(New CategoricalSparkDataPoint(22)) -barSeries.DataPoints.Add(New CategoricalSparkDataPoint(12)) -barSeries.ShowHighPointIndicator = True -barSeries.ShowLowPointIndicator = True -barSeries.ShowFirstPointIndicator = True -barSeries.ShowLastPointIndicator = True -barSeries.ShowNegativePointIndicators = True -Me.radSparkline1.ShowAxis = True -Me.radSparkline1.AxisDrawMode = AxisDrawMode.AboveSeries -Me.radSparkline1.Series = barSeries + + -```` - -{{endregion}} You can see the result in the following image. diff --git a/controls/sparkline/printing-support.md b/controls/sparkline/printing-support.md index d56fd0fd2..f2e989bd7 100644 --- a/controls/sparkline/printing-support.md +++ b/controls/sparkline/printing-support.md @@ -14,21 +14,8 @@ __RadSparkline__ supports printing out of the box. You can use the __Print__ or #### Example 1: Use the PrintPreview Method. -{{source=..\SamplesCS\Sparkline\SparklineCode.cs region=Print}} -{{source=..\SamplesVB\Sparkline\SparklineCode.vb region=Print}} -````C# -private void radButton2_Click(object sender, EventArgs e) -{ - radSparkline1.PrintPreview(); -} + + -```` -````VB.NET -Private Sub RadButton2_Click(ByVal sender As Object, ByVal e As EventArgs) - radSparkline1.PrintPreview() -End Sub -```` - -{{endregion}} \ No newline at end of file diff --git a/controls/sparkline/series/sparkareaseries.md b/controls/sparkline/series/sparkareaseries.md index 3948f7b66..799492109 100644 --- a/controls/sparkline/series/sparkareaseries.md +++ b/controls/sparkline/series/sparkareaseries.md @@ -14,46 +14,10 @@ As a derivative of Categorical series, SparkAreaSeries plot their data points us #### Create SparkAreaSeries -{{source=..\SamplesCS\Sparkline\SparklineCode.cs region=AreaSeries}} -{{source=..\SamplesVB\Sparkline\SparklineCode.vb region=AreaSeries}} -````C# -public void CreateAreaSeries() -{ - var areaSeries = new SparkAreaSeries(); - areaSeries.DataPoints.Add(new CategoricalSparkDataPoint(13)); - areaSeries.DataPoints.Add(new CategoricalSparkDataPoint(20)); - areaSeries.DataPoints.Add(new CategoricalSparkDataPoint(15)); - areaSeries.DataPoints.Add(new CategoricalSparkDataPoint(5)); - areaSeries.DataPoints.Add(new CategoricalSparkDataPoint(29)); - areaSeries.DataPoints.Add(new CategoricalSparkDataPoint(8)); - areaSeries.DataPoints.Add(new CategoricalSparkDataPoint(22)); - areaSeries.ShowHighPointIndicator = true; - areaSeries.ShowLowPointIndicator = true; - areaSeries.HighPointShape = new StarShape(5, 3); - this.radSparkline1.Series = areaSeries; -} + + -```` -````VB.NET -Public Sub CreateAreaSeries() - Dim areaSeries = New SparkAreaSeries() - areaSeries.DataPoints.Add(New CategoricalSparkDataPoint(13)) - areaSeries.DataPoints.Add(New CategoricalSparkDataPoint(20)) - areaSeries.DataPoints.Add(New CategoricalSparkDataPoint(15)) - areaSeries.DataPoints.Add(New CategoricalSparkDataPoint(5)) - areaSeries.DataPoints.Add(New CategoricalSparkDataPoint(29)) - areaSeries.DataPoints.Add(New CategoricalSparkDataPoint(8)) - areaSeries.DataPoints.Add(New CategoricalSparkDataPoint(22)) - areaSeries.ShowHighPointIndicator = True - areaSeries.ShowLowPointIndicator = True - areaSeries.HighPointShape = New StarShape(5, 3) - Me.radSparkline1.Series = areaSeries -End Sub -```` - - -{{endregion}} >caption Figure 1: SparkAreaSeries diff --git a/controls/sparkline/series/sparkbarseries.md b/controls/sparkline/series/sparkbarseries.md index fac4b5953..9fa9858e1 100644 --- a/controls/sparkline/series/sparkbarseries.md +++ b/controls/sparkline/series/sparkbarseries.md @@ -14,44 +14,10 @@ __SparkBarSeries__ are used to visualize data points as bar blocks where the hei #### Create SparkBarSeries -{{source=..\SamplesCS\Sparkline\SparklineCode.cs region=BarSeries}} -{{source=..\SamplesVB\Sparkline\SparklineCode.vb region=BarSeries}} -````C# -public void CreateBarSeries() -{ - var barSeries = new SparkBarSeries(); - barSeries.DataPoints.Add(new CategoricalSparkDataPoint(13)); - barSeries.DataPoints.Add(new CategoricalSparkDataPoint(20)); - barSeries.DataPoints.Add(new CategoricalSparkDataPoint(15)); - barSeries.DataPoints.Add(new CategoricalSparkDataPoint(5)); - barSeries.DataPoints.Add(new CategoricalSparkDataPoint(29)); - barSeries.DataPoints.Add(new CategoricalSparkDataPoint(8)); - barSeries.DataPoints.Add(new CategoricalSparkDataPoint(22)); - barSeries.ShowHighPointIndicator = true; - barSeries.ShowLowPointIndicator = true; - this.radSparkline1.Series = barSeries; -} + + -```` -````VB.NET -Public Sub CreateBarSeries() - Dim barSeries = New SparkBarSeries() - barSeries.DataPoints.Add(New CategoricalSparkDataPoint(13)) - barSeries.DataPoints.Add(New CategoricalSparkDataPoint(20)) - barSeries.DataPoints.Add(New CategoricalSparkDataPoint(15)) - barSeries.DataPoints.Add(New CategoricalSparkDataPoint(5)) - barSeries.DataPoints.Add(New CategoricalSparkDataPoint(29)) - barSeries.DataPoints.Add(New CategoricalSparkDataPoint(8)) - barSeries.DataPoints.Add(New CategoricalSparkDataPoint(22)) - barSeries.ShowHighPointIndicator = True - barSeries.ShowLowPointIndicator = True - Me.radSparkline1.Series = barSeries -End Sub -```` - - -{{endregion}} >caption Figure 1: SparkBarSeries diff --git a/controls/sparkline/series/sparklineseries.md b/controls/sparkline/series/sparklineseries.md index 4ae6a3ccb..03cb67152 100644 --- a/controls/sparkline/series/sparklineseries.md +++ b/controls/sparkline/series/sparklineseries.md @@ -14,46 +14,10 @@ __SparkLineSeries__ plot their CategoricalSparkDataPoint on Cartesian Area. The #### Create SparkLineSeries -{{source=..\SamplesCS\Sparkline\SparklineCode.cs region=LineSeries}} -{{source=..\SamplesVB\Sparkline\SparklineCode.vb region=LineSeries}} -````C# -public void CreateLineSeries() -{ - var lineSeries = new SparkLineSeries(); - lineSeries.DataPoints.Add(new CategoricalSparkDataPoint(13)); - lineSeries.DataPoints.Add(new CategoricalSparkDataPoint(20)); - lineSeries.DataPoints.Add(new CategoricalSparkDataPoint(15)); - lineSeries.DataPoints.Add(new CategoricalSparkDataPoint(5)); - lineSeries.DataPoints.Add(new CategoricalSparkDataPoint(29)); - lineSeries.DataPoints.Add(new CategoricalSparkDataPoint(8)); - lineSeries.DataPoints.Add(new CategoricalSparkDataPoint(22)); - lineSeries.ShowHighPointIndicator = true; - lineSeries.ShowLowPointIndicator = true; - lineSeries.HighPointShape = new StarShape(5, 3); - this.radSparkline1.Series = lineSeries; -} + + -```` -````VB.NET -Public Sub CreateLineSeries() - Dim lineSeries = New SparkLineSeries() - lineSeries.DataPoints.Add(New CategoricalSparkDataPoint(13)) - lineSeries.DataPoints.Add(New CategoricalSparkDataPoint(20)) - lineSeries.DataPoints.Add(New CategoricalSparkDataPoint(15)) - lineSeries.DataPoints.Add(New CategoricalSparkDataPoint(5)) - lineSeries.DataPoints.Add(New CategoricalSparkDataPoint(29)) - lineSeries.DataPoints.Add(New CategoricalSparkDataPoint(8)) - lineSeries.DataPoints.Add(New CategoricalSparkDataPoint(22)) - lineSeries.ShowHighPointIndicator = True - lineSeries.ShowLowPointIndicator = True - lineSeries.HighPointShape = New StarShape(5, 3) - Me.radSparkline1.Series = lineSeries -End Sub -```` - - -{{endregion}} >caption Figure 1: SparkLineSeries diff --git a/controls/sparkline/series/sparkscatterseries.md b/controls/sparkline/series/sparkscatterseries.md index 8400e652a..173632f93 100644 --- a/controls/sparkline/series/sparkscatterseries.md +++ b/controls/sparkline/series/sparkscatterseries.md @@ -14,44 +14,10 @@ Unlike Categorical series, ScatterSeries plots its data upon two numerical axes. #### Create SparkScatterSeries -{{source=..\SamplesCS\Sparkline\SparklineCode.cs region=ScatterSeries}} -{{source=..\SamplesVB\Sparkline\SparklineCode.vb region=ScatterSeries}} -````C# -public void CreateScatterSeries() -{ - var scatterSeries = new SparkScatterSeries(); - scatterSeries.DataPoints.Add(new ScatterSparkDataPoint(13,1)); - scatterSeries.DataPoints.Add(new ScatterSparkDataPoint(20,2)); - scatterSeries.DataPoints.Add(new ScatterSparkDataPoint(15,3)); - scatterSeries.DataPoints.Add(new ScatterSparkDataPoint(5,4)); - scatterSeries.DataPoints.Add(new ScatterSparkDataPoint(29,5)); - scatterSeries.DataPoints.Add(new ScatterSparkDataPoint(8,6)); - scatterSeries.DataPoints.Add(new ScatterSparkDataPoint(22,71)); - scatterSeries.ShowHighPointIndicator = true; - scatterSeries.ShowLowPointIndicator = true; - this.radSparkline1.Series = scatterSeries; -} + + -```` -````VB.NET -Public Sub CreateScatterSeries() - Dim scatterSeries = New SparkScatterSeries() - scatterSeries.DataPoints.Add(New ScatterSparkDataPoint(13, 1)) - scatterSeries.DataPoints.Add(New ScatterSparkDataPoint(20, 2)) - scatterSeries.DataPoints.Add(New ScatterSparkDataPoint(15, 3)) - scatterSeries.DataPoints.Add(New ScatterSparkDataPoint(5, 4)) - scatterSeries.DataPoints.Add(New ScatterSparkDataPoint(29, 5)) - scatterSeries.DataPoints.Add(New ScatterSparkDataPoint(8, 6)) - scatterSeries.DataPoints.Add(New ScatterSparkDataPoint(22, 71)) - scatterSeries.ShowHighPointIndicator = True - scatterSeries.ShowLowPointIndicator = True - Me.radSparkline1.Series = scatterSeries -End Sub -```` - - -{{endregion}} >caption Figure 1: SparkScatterSeries diff --git a/controls/sparkline/series/sparkwinlossseries.md b/controls/sparkline/series/sparkwinlossseries.md index 31b71c4d0..21b2fcabd 100644 --- a/controls/sparkline/series/sparkwinlossseries.md +++ b/controls/sparkline/series/sparkwinlossseries.md @@ -14,44 +14,10 @@ Win Loss Chart provides a quick way of seeing overall situation of a series of d #### Create SparkBarSeries -{{source=..\SamplesCS\Sparkline\SparklineCode.cs region=WinLossSeries}} -{{source=..\SamplesVB\Sparkline\SparklineCode.vb region=WinLossSeries}} -````C# -public void CreateWinLossSeries() -{ - var winLossSeries = new SparkWinLossSeries(); - winLossSeries.DataPoints.Add(new CategoricalSparkDataPoint(13)); - winLossSeries.DataPoints.Add(new CategoricalSparkDataPoint(-20)); - winLossSeries.DataPoints.Add(new CategoricalSparkDataPoint(15)); - winLossSeries.DataPoints.Add(new CategoricalSparkDataPoint(5)); - winLossSeries.DataPoints.Add(new CategoricalSparkDataPoint(29)); - winLossSeries.DataPoints.Add(new CategoricalSparkDataPoint(-8)); - winLossSeries.DataPoints.Add(new CategoricalSparkDataPoint(-22)); - winLossSeries.ShowHighPointIndicator = true; - winLossSeries.ShowLowPointIndicator = true; - this.radSparkline1.Series = winLossSeries; -} - -```` -````VB.NET -Public Sub CreateWinLossSeries() - Dim winLossSeries = New SparkWinLossSeries() - winLossSeries.DataPoints.Add(New CategoricalSparkDataPoint(13)) - winLossSeries.DataPoints.Add(New CategoricalSparkDataPoint(-20)) - winLossSeries.DataPoints.Add(New CategoricalSparkDataPoint(15)) - winLossSeries.DataPoints.Add(New CategoricalSparkDataPoint(5)) - winLossSeries.DataPoints.Add(New CategoricalSparkDataPoint(29)) - winLossSeries.DataPoints.Add(New CategoricalSparkDataPoint(-8)) - winLossSeries.DataPoints.Add(New CategoricalSparkDataPoint(-22)) - winLossSeries.ShowHighPointIndicator = True - winLossSeries.ShowLowPointIndicator = True - Me.radSparkline1.Series = winLossSeries -End Sub - -```` - - -{{endregion}} + + + + >caption Figure 1: SparkBarSeries diff --git a/controls/sparkline/tooltips.md b/controls/sparkline/tooltips.md index 81dc0721f..69b1108ae 100644 --- a/controls/sparkline/tooltips.md +++ b/controls/sparkline/tooltips.md @@ -14,22 +14,10 @@ The tooltips are supported out of the box and you just need to enable them. #### Enable tooltips -{{source=..\SamplesCS\Sparkline\SparklineCode.cs region=EnableTooltips}} -{{source=..\SamplesVB\Sparkline\SparklineCode.vb region=EnableTooltips}} + + -````C# -radSparkline1.ShowToolTip = true; -```` -````VB.NET -radSparkline1.ShowToolTip = True - - -```` - - - -{{endregion}} The default tooltips will displayed when hovering over a particular data point. @@ -42,65 +30,17 @@ You can use the __DataPointTooltipTextNeeded__ event to set custom tooltip text. #### Subscribing to DataPointTooltipTextNeeded -{{source=..\SamplesCS\Sparkline\SparklineCode.cs region=TooltipController}} -{{source=..\SamplesVB\Sparkline\SparklineCode.vb region=TooltipController}} -````C# -var toolTipControler = new SparkTooltipController(); -toolTipControler.DataPointTooltipTextNeeded += ToolTipControler_DataPointTooltipTextNeeded; -radSparkline1.Controllers.Add(toolTipControler); - - -```` -````VB.NET -Dim toolTipControler = New SparkTooltipController() -AddHandler toolTipControler.DataPointTooltipTextNeeded, AddressOf ToolTipControler_DataPointTooltipTextNeeded -radSparkline1.Controllers.Add(toolTipControler) - - -```` - + + -{{endregion}} The following example shows how you can set the text in the event handler. #### Customizing the Tooltip Text -{{source=..\SamplesCS\Sparkline\SparklineCode.cs region=TooltipTextEvent}} -{{source=..\SamplesVB\Sparkline\SparklineCode.vb region=TooltipTextEvent}} -````C# -private void ToolTipControler_DataPointTooltipTextNeeded(object sender, Telerik.WinControls.UI.Sparkline.SparkDataPointTooltipTextNeededEventArgs e) -{ - var point = e.DataPoint as CategoricalSparkDataPoint; - if (point.Value > 10) - { - e.Text = "Value Critical"; - } - else - { - e.Text = "Normal Vlaue"; - } -} - -```` -````VB.NET -Private Sub ToolTipControler_DataPointTooltipTextNeeded(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.Sparkline.SparkDataPointTooltipTextNeededEventArgs) - Dim point = TryCast(e.DataPoint, CategoricalSparkDataPoint) - If point.Value > 10 Then - e.Text = "Value Critical" - Else - e.Text = "Normal Vlaue" - End If -End Sub - - -```` - - - - -{{endregion}} + + diff --git a/controls/spellchecker/dictionaries.md b/controls/spellchecker/dictionaries.md index c4f5f754d..08ac18079 100644 --- a/controls/spellchecker/dictionaries.md +++ b/controls/spellchecker/dictionaries.md @@ -28,87 +28,31 @@ previous_url: spellchecker-dictionaries #### Creating a custom WordDictionary -{{source=..\SamplesCS\SpellChecker\GermanDictionary.cs region=germanDictionary}} -{{source=..\SamplesVB\SpellChecker\GermanDictionary.vb region=germanDictionary}} - -````C# -public class GermanDictionary : WordDictionary -{ - protected override void EnsureDictionaryLoadedOverride() - { - using (MemoryStream ms = new MemoryStream(SamplesCS.Properties.Resources.de_DE)) - { - this.Load(ms); - } - } -} - -```` -````VB.NET -Public Class GermanDictionary - Inherits WordDictionary - Protected Overrides Sub EnsureDictionaryLoadedOverride() - Using ms As MemoryStream = New MemoryStream(My.Resources.de_DE) - Me.Load(ms) - End Using - End Sub -End Class - -```` - -{{endregion}} + + -4\. Next, we should add the custom dictionary to our **RadSpellChecker**. Please note, that dictionaries are added per control types basis using the __GetControlSpellChecker__ method. This way, using just one **RadSpellChecker** instance you can add different dictionaries of one and the same language in the context of different controls that need to be spell checked. For example, here we are going to add a dictionary that will be used only for **RadTextBox** instances. In addition, we need to define a **CultureInfo** that will be stored together with the dictionary in the list of dictionaries. This culture will serve as a primary key for the respective dictionary in the dictionaries collection. -{{source=..\SamplesCS\SpellChecker\Dictionaries.cs region=defineCulture}} -{{source=..\SamplesVB\SpellChecker\Dictionaries.vb region=defineCulture}} -````C# -private static readonly CultureInfo GermanCulture = CultureInfo.GetCultureInfo("de-DE"); +4\. Next, we should add the custom dictionary to our **RadSpellChecker**. Please note, that dictionaries are added per control types basis using the __GetControlSpellChecker__ method. This way, using just one **RadSpellChecker** instance you can add different dictionaries of one and the same language in the context of different controls that need to be spell checked. For example, here we are going to add a dictionary that will be used only for **RadTextBox** instances. In addition, we need to define a **CultureInfo** that will be stored together with the dictionary in the list of dictionaries. This culture will serve as a primary key for the respective dictionary in the dictionaries collection. -```` -````VB.NET -Friend Shared GermanCulture As CultureInfo = CultureInfo.GetCultureInfo("de-DE") + + -```` -{{endregion}} #### Adding a dictionary -{{source=..\SamplesCS\SpellChecker\Dictionaries.cs region=addingDictionary}} -{{source=..\SamplesVB\SpellChecker\Dictionaries.vb region=addingDictionary}} - -````C# -IControlSpellChecker textBoxControlSpellChecker = this.radSpellChecker1.GetControlSpellChecker(typeof(RadTextBox)); -DocumentSpellChecker documentSpellChecker = textBoxControlSpellChecker.SpellChecker as DocumentSpellChecker; -documentSpellChecker.AddDictionary(new GermanDictionary(), GermanCulture); + + -```` -````VB.NET -Dim textBoxControlSpellChecker As IControlSpellChecker = Me.radSpellChecker1.GetControlSpellChecker(GetType(RadTextBox)) -Dim documentSpellChecker As DocumentSpellChecker = TryCast(textBoxControlSpellChecker.SpellChecker, DocumentSpellChecker) -documentSpellChecker.AddDictionary(New GermanDictionary(), GermanCulture) -```` - -{{endregion}} 5\. Now, we have to set the __SpellCheckingCulture__ property that will determine which of the available dictionaries will be used (in case dictionaries of different languages are added). -{{source=..\SamplesCS\SpellChecker\Dictionaries.cs region=settingCulture}} -{{source=..\SamplesVB\SpellChecker\Dictionaries.vb region=settingCulture}} - -````C# -documentSpellChecker.SpellCheckingCulture = GermanCulture; - -```` -````VB.NET -documentSpellChecker.SpellCheckingCulture = GermanCulture + + -```` -{{endregion}} If this property is not set, **RadSpellChecker** will try check if there is a dictionary whose culture is the **CurrentUICulture** of the application. If such a dictionary is found, **RadSpellChecker** will use that dictionary. diff --git a/controls/spellchecker/getting-started.md b/controls/spellchecker/getting-started.md index 5978f5a82..8a9f86393 100644 --- a/controls/spellchecker/getting-started.md +++ b/controls/spellchecker/getting-started.md @@ -52,43 +52,19 @@ The following tutorial demonstrates how you can make **RadSpellChecker** check a #### Initialize RadTextBox with some text -{{source=..\SamplesCS\SpellChecker\SpChGettingStarted.cs region=settingText}} -{{source=..\SamplesVB\SpellChecker\SpChGettingStarted.vb region=settingText}} + + -````C# -this.radTextBox1.Text = "The quik broun foxx jumpd ovur lasy dog"; - -```` -````VB.NET -Me.RadTextBox1.Text = "The quik broun foxx jumpd ovur lasy dog" - -```` - -{{endregion}} 5\. Subscribe to the **Click** event of **RadButton**. In the event handler call the **Check** method of **RadSpellChecker** and pass the **RadTextBox** instance as a parameter: #### Spellcheck the RadTextBox -{{source=..\SamplesCS\SpellChecker\SpChGettingStarted.cs region=callingCheck}} -{{source=..\SamplesVB\SpellChecker\SpChGettingStarted.vb region=callingCheck}} - -````C# -private void radButton1_Click(object sender, EventArgs e) -{ - this.radSpellChecker1.Check(this.radTextBox1); -} - -```` -````VB.NET -Private Sub RadButton1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles RadButton1.Click - Me.RadSpellChecker1.Check(Me.RadTextBox1) -End Sub + + -```` -{{endregion}} Now when you press the button, **RadSpellChecker** form will appear with the appropriate suggestions for the mistaken words: diff --git a/controls/spellchecker/localization.md b/controls/spellchecker/localization.md index ce8327425..ca3696da5 100644 --- a/controls/spellchecker/localization.md +++ b/controls/spellchecker/localization.md @@ -21,107 +21,18 @@ To localize **RadSpellChecker** to display control text and messages in a specif Below is a sample implementation of an English localization provider: -{{source=..\SamplesCS\SpellChecker\SpellCheckerLocalization.cs region=myEnglishLocalizationProvider}} -{{source=..\SamplesVB\SpellChecker\SpellCheckerLocalization.vb region=myEnglishLocalizationProvider}} + + -````C# - -class MyEnglishSpellCheckerLocalizationProvider : RadSpellCheckerLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case RadSpellCheckerStringId.Title: - return "Spell Checking"; - case RadSpellCheckerStringId.OK: - return "OK"; - case RadSpellCheckerStringId.Cancel: - return "Cancel"; - case RadSpellCheckerStringId.Close: - return "Close"; - case RadSpellCheckerStringId.ChangeAll: - return "Change All"; - case RadSpellCheckerStringId.Change: - return "Change"; - case RadSpellCheckerStringId.Complete: - return "The spelling check is complete."; - case RadSpellCheckerStringId.AddToDictionary: - return "Add to Dictionary"; - case RadSpellCheckerStringId.Ingore: - return "Ignore"; - case RadSpellCheckerStringId.IngoreAll: - return "Ignore All"; - case RadSpellCheckerStringId.Suggestions: - return "Suggestions:"; - case RadSpellCheckerStringId.ChangeTo: - return "Change To:"; - case RadSpellCheckerStringId.NotInDictionary: - return "Not in Dicitionary:"; - } - - return null; - } -} -```` -````VB.NET -Class MyEnglishSpellCheckerLocalizationProvider - Inherits RadSpellCheckerLocalizationProvider - Public Overrides Function GetLocalizedString(id As String) As String - Select Case id - Case RadSpellCheckerStringId.Title - Return "Spell Checking" - Case RadSpellCheckerStringId.OK - Return "OK" - Case RadSpellCheckerStringId.Cancel - Return "Cancel" - Case RadSpellCheckerStringId.Close - Return "Close" - Case RadSpellCheckerStringId.ChangeAll - Return "Change All" - Case RadSpellCheckerStringId.Change - Return "Change" - Case RadSpellCheckerStringId.Complete - Return "The spelling check is complete." - Case RadSpellCheckerStringId.AddToDictionary - Return "Add to Dictionary" - Case RadSpellCheckerStringId.Ingore - Return "Ignore" - Case RadSpellCheckerStringId.IngoreAll - Return "Ignore All" - Case RadSpellCheckerStringId.Suggestions - Return "Suggestions:" - Case RadSpellCheckerStringId.ChangeTo - Return "Change To:" - Case RadSpellCheckerStringId.NotInDictionary - Return "Not in Dicitionary:" - End Select - Return Nothing - End Function -End Class - -```` - -{{endregion}} To apply the custom localization provider, instantiate and assign it to the current localization provider: #### Assigning the Current Localization Provider -{{source=..\SamplesCS\SpellChecker\SpellCheckerLocalization.cs region=localizeSpellChecker}} -{{source=..\SamplesVB\SpellChecker\SpellCheckerLocalization.vb region=localizeSpellChecker}} - -````C# - -RadSpellCheckerLocalizationProvider.CurrentProvider = new MyEnglishSpellCheckerLocalizationProvider(); - -```` -````VB.NET -RadSpellCheckerLocalizationProvider.CurrentProvider = New MyEnglishSpellCheckerLocalizationProvider() + + -```` -{{endregion}} The code provided above illustrates the approach to be used to localize the __RadSpellChecker__ and is not intended as a full translation. diff --git a/controls/spellchecker/spell-check-as-you-type.md b/controls/spellchecker/spell-check-as-you-type.md index 80e73a19b..674e766bf 100644 --- a/controls/spellchecker/spell-check-as-you-type.md +++ b/controls/spellchecker/spell-check-as-you-type.md @@ -21,23 +21,10 @@ As the user types in one of the supported controls a red underline indicates the In order to enable this functionality you should set the __AutoSpellCheckControl__ property of **RadSpellChecker** to an instance of the supported controls: -{{source=..\SamplesCS\SpellChecker\SpellCheckAsYouType.cs region=AutoSpellCheckControl}} -{{source=..\SamplesVB\SpellChecker\SpellCheckAsYouType.vb region=AutoSpellCheckControl}} + + -````C# -this.radSpellChecker1.AutoSpellCheckControl = this.textBox1; -this.radSpellChecker2.AutoSpellCheckControl = this.radTextBox1; -this.radSpellChecker3.AutoSpellCheckControl = this.radTextBoxControl1; -```` -````VB.NET -Me.RadSpellChecker1.AutoSpellCheckControl = Me.TextBox1 -Me.RadSpellChecker2.AutoSpellCheckControl = Me.RadTextBox1 -Me.RadSpellChecker3.AutoSpellCheckControl = Me.RadTextBoxControl1 - -```` - -{{endregion}} This property can also be set at design time: diff --git a/controls/spellchecker/spellchecking-modes.md b/controls/spellchecker/spellchecking-modes.md index 7fe5631f5..c2c620c49 100644 --- a/controls/spellchecker/spellchecking-modes.md +++ b/controls/spellchecker/spellchecking-modes.md @@ -24,19 +24,10 @@ To do this kind of check, you should set the __SpellCheckMode__ property to *Wor #### Setting SpellCheckMode.WordByWord -{{source=..\SamplesCS\SpellChecker\SpChGettingStarted.cs region=wordByWord}} -{{source=..\SamplesVB\SpellChecker\SpChGettingStarted.vb region=wordByWord}} + + -````C# -this.radSpellChecker1.SpellCheckMode = Telerik.WinControls.UI.SpellCheckMode.WordByWord; -```` -````VB.NET -Me.RadSpellChecker1.SpellCheckMode = Telerik.WinControls.UI.SpellCheckMode.WordByWord - -```` - -{{endregion}} When using this mode, **RadSpellChecker** will check every word in a separate window, which looks like this: @@ -56,19 +47,10 @@ To do this kind of check, you should set the __SpellCheckMode__ property to *All #### Setting SpellCheckMode.AllAtOnce -{{source=..\SamplesCS\SpellChecker\SpChGettingStarted.cs region=allAtOnce}} -{{source=..\SamplesVB\SpellChecker\SpChGettingStarted.vb region=allAtOnce}} - -````C# -this.radSpellChecker1.SpellCheckMode = Telerik.WinControls.UI.SpellCheckMode.AllAtOnce; - -```` -````VB.NET -Me.RadSpellChecker1.SpellCheckMode = Telerik.WinControls.UI.SpellCheckMode.AllAtOnce + + -```` -{{endregion}} When using SpellCheckMode.*AllAtOnce*, **RadSpellChecker** loads the entire content of the control being spell checked in a window looking like this: diff --git a/controls/spellchecker/spellchecking-radgridview.md b/controls/spellchecker/spellchecking-radgridview.md index 7c81ea023..7e2886515 100644 --- a/controls/spellchecker/spellchecking-radgridview.md +++ b/controls/spellchecker/spellchecking-radgridview.md @@ -21,62 +21,21 @@ Supposing that we have a **RadGridView** filled with data and a **RadSpellChecke #### Spell check RadGridView's editor -{{source=..\SamplesCS\SpellChecker\SpChWithRadGridView.cs region=validating}} -{{source=..\SamplesVB\SpellChecker\SpChWithRadGridView.vb region=validating}} - -````C# -string correctedValue = String.Empty; -void radGridView1_CellValidating(object sender, Telerik.WinControls.UI.CellValidatingEventArgs e) -{ - RadTextBoxEditor editor = e.ActiveEditor as RadTextBoxEditor; - if (editor != null) - { - RadTextBoxEditorElement element = editor.EditorElement as RadTextBoxEditorElement; - this.radSpellChecker1.Check(element.TextBoxItem.HostedControl); - correctedValue = e.ActiveEditor.Value.ToString(); - } -} - -```` -````VB.NET -Dim correctedValue As String = String.Empty -Private Sub RadGridView1_CellValidating(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.CellValidatingEventArgs) Handles RadGridView1.CellValidating - Dim editor As RadTextBoxEditor = TryCast(e.ActiveEditor, RadTextBoxEditor) - If editor IsNot Nothing Then - Dim element As RadTextBoxEditorElement = TryCast(editor.EditorElement, RadTextBoxEditorElement) - Me.RadSpellChecker1.Check(element.TextBoxItem.HostedControl) - correctedValue = e.ActiveEditor.Value.ToString() - End If -End Sub - -```` - -{{endregion}} - + + + + + Please note that the editor sets the corrected value to the opened editor, but not directly to the underlying data cell. We save this editor value in a variable named '*correctedValue*' 2\. Now we should subscribe to the **CellEndEdit** event which is fired after the editor is closed. In this event we should pass the saved corrected value to the data cell: #### Save the corrected value -{{source=..\SamplesCS\SpellChecker\SpChWithRadGridView.cs region=cellEndEdit}} -{{source=..\SamplesVB\SpellChecker\SpChWithRadGridView.vb region=cellEndEdit}} - -````C# -void radGridView1_CellEndEdit(object sender, GridViewCellEventArgs e) -{ - this.radGridView1.CurrentCell.Value = correctedValue; -} - -```` -````VB.NET -Private Sub RadGridView1_CellEndEdit(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewCellEventArgs) Handles RadGridView1.CellEndEdit - Me.RadGridView1.CurrentCell.Value = correctedValue -End Sub + + -```` -{{endregion}} The following figures provide the end-user experience with **RadSpellChecker** and **RadGridView**: diff --git a/controls/splashscreens/flyout/getting-started.md b/controls/splashscreens/flyout/getting-started.md index 5d64e2773..bf15ad698 100644 --- a/controls/splashscreens/flyout/getting-started.md +++ b/controls/splashscreens/flyout/getting-started.md @@ -17,8 +17,8 @@ The Flyout screen can be activated through the __RadFlyoutManager.Show()__ metho ## Show Flyout -{{source=..\SamplesCS\SplashScreens\Flyout\FlyoutSettings.cs region=GettingStarted_Show}} -{{source=..\SamplesVB\SplashScreens\Flyout\FlyoutSettings.vb region=GettingStarted_Show}} + + ````C# @@ -33,12 +33,10 @@ RadFlyoutManager.Show(Me.radGridView1, GetType(UserControl1)) ```` -{{endregion}} - ## Close Flyout -{{source=..\SamplesCS\SplashScreens\Flyout\FlyoutSettings.cs region=GettingStarted_Close}} -{{source=..\SamplesVB\SplashScreens\Flyout\FlyoutSettings.vb region=GettingStarted_Close}} + + ````C# @@ -53,11 +51,6 @@ RadFlyoutManager.Close() ```` -{{endregion}} - - - - ## Telerik UI for WinForms Learning Resources * [Telerik UI for WinForms flyout Component](https://www.telerik.com/products/winforms/flyout.aspx) * [Getting Started with Telerik UI for WinForms Components](https://docs.telerik.com/devtools/winforms/getting-started/first-steps) diff --git a/controls/splashscreens/overlay/customize-appearance.md b/controls/splashscreens/overlay/customize-appearance.md index 78c6297c4..c1b9f6a09 100644 --- a/controls/splashscreens/overlay/customize-appearance.md +++ b/controls/splashscreens/overlay/customize-appearance.md @@ -19,8 +19,8 @@ This tutorial will walk you through how you can customize the __Overlay Screen__ ## Show Overlay -{{source=..\SamplesCS\SplashScreens\Overlay\OverlaySettings.cs region=Customize_Appearance}} -{{source=..\SamplesVB\SplashScreens\Overlay\OverlaySettings.vb region=Customize_Appearance}} + + ````C# @@ -62,10 +62,6 @@ End Sub ```` -{{endregion}} - - - # See Also * [Overview]({%slug overlay-overview%}) diff --git a/controls/splashscreens/overlay/getting-started.md b/controls/splashscreens/overlay/getting-started.md index 62455904b..896aa15d9 100644 --- a/controls/splashscreens/overlay/getting-started.md +++ b/controls/splashscreens/overlay/getting-started.md @@ -17,8 +17,8 @@ The overlay form can be activated throught the __RadOverlayManager.Show()__ meth ## Show Overlay -{{source=..\SamplesCS\SplashScreens\Overlay\OverlaySettings.cs region=GettingStarted_Show}} -{{source=..\SamplesVB\SplashScreens\Overlay\OverlaySettings.vb region=GettingStarted_Show}} + + ````C# @@ -33,12 +33,10 @@ RadOverlayManager.Show(this.radGridView1) ```` -{{endregion}} - ## Close Overlay -{{source=..\SamplesCS\SplashScreens\Overlay\OverlaySettings.cs region=GettingStarted_Close}} -{{source=..\SamplesVB\SplashScreens\Overlay\OverlaySettings.vb region=GettingStarted_Close}} + + ````C# @@ -53,8 +51,6 @@ RadOverlayManager.Close() ```` -{{endregion}} - # See Also * [Overview]({%slug overlay-overview%}) diff --git a/controls/splashscreens/overlay/how-to/custom-overlay-screen.md b/controls/splashscreens/overlay/how-to/custom-overlay-screen.md index 49a561237..0f6654487 100644 --- a/controls/splashscreens/overlay/how-to/custom-overlay-screen.md +++ b/controls/splashscreens/overlay/how-to/custom-overlay-screen.md @@ -19,8 +19,8 @@ This tutorial will walk you through how you can create a custom __Overlay Screen ## Custom RadOverlayForm -{{source=..\SamplesCS\SplashScreens\Overlay\OverlaySettings.cs region=CustomOverlayForm}} -{{source=..\SamplesVB\SplashScreens\Overlay\OverlaySettings.vb region=CustomOverlayForm}} + + ````C# @@ -98,14 +98,12 @@ End Class ```` -{{endregion}} - 2\. Next step is to apply our custom form by returning it in the __CreateFrom__ of the __OverlayScreen__ class. ## Custom OverlayScreen -{{source=..\SamplesCS\SplashScreens\Overlay\OverlaySettings.cs region=CustomOverlayScreen}} -{{source=..\SamplesVB\SplashScreens\Overlay\OverlaySettings.vb region=CustomOverlayScreen}} + + ````C# @@ -133,14 +131,12 @@ End Class ```` -{{endregion}} - 3\. Our final step is to replace the default overlay screen with our custom one by setting the RadOverlayManager.OverlayInstance static property. ## Override OverlayInstance -{{source=..\SamplesCS\SplashScreens\Overlay\OverlaySettings.cs region=OverlayInstance}} -{{source=..\SamplesVB\SplashScreens\Overlay\OverlaySettings.vb region=OverlayInstance}} + + ````C# @@ -160,8 +156,6 @@ End Sub ```` -{{endregion}} - # See Also * [Overview]({%slug overlay-overview%}) diff --git a/controls/splashscreens/splashscreen/custom-splash.md b/controls/splashscreens/splashscreen/custom-splash.md index 2cc0c6ef1..ea982c223 100644 --- a/controls/splashscreens/splashscreen/custom-splash.md +++ b/controls/splashscreens/splashscreen/custom-splash.md @@ -289,8 +289,8 @@ Friend WithEvents timer1 As System.Windows.Forms.Timer 3\. Start the timer to update the remaining time in the UserControl: -{{source=..\SamplesCS\SplashScreens\SplashScreen\RestartRequiredUserControl.cs region=CustomSplash}} -{{source=..\SamplesVB\SplashScreens\SplashScreen\RestartRequiredUserControl.vb region=CustomSplash}} + + ````C# @@ -336,13 +336,10 @@ End Class ```` -{{endregion}} - - 4\. Show the splash with the custom control from your main form: -{{source=..\SamplesCS\SplashScreens\SplashScreen\SplashScreenSettings.cs region=ShowCustomSplash}} -{{source=..\SamplesVB\SplashScreens\SplashScreen\SplashScreenSettings.vb region=ShowCustomSplash}} + + ````C# @@ -355,9 +352,6 @@ RadSplashScreenManager.Show(GetType(RestartRequiredUserControl)) ```` -{{endregion}} - - # See Also * [Structure]({%slug splashscreen-structure%}) diff --git a/controls/splashscreens/splashscreen/getting-started.md b/controls/splashscreens/splashscreen/getting-started.md index 17be225e4..d994fded8 100644 --- a/controls/splashscreens/splashscreen/getting-started.md +++ b/controls/splashscreens/splashscreen/getting-started.md @@ -24,8 +24,8 @@ By default, the RadSplashScreenManager shows the default RadSplashScreenControl: ![WinForms RadSplashScreen Getting Started](images/splashscreen-getting-started001.gif) -{{source=..\SamplesCS\SplashScreens\SplashScreen\SplashScreenSettings.cs region=ShowDefaultSplash}} -{{source=..\SamplesVB\SplashScreens\SplashScreen\SplashScreenSettings.vb region=ShowDefaultSplash}} + + ````C# @@ -121,8 +121,6 @@ End Sub ```` -{{endregion}} - ## RadSplashScreenSettings The **RadSplashScreenSettings** allows specifying certain settings when showing the default **RadSplashScreenControl**. The available options are: diff --git a/controls/splitcontainer/building-a-layout-of-radsplitcontainers-programmatically.md b/controls/splitcontainer/building-a-layout-of-radsplitcontainers-programmatically.md index 461d3a425..69d92918b 100644 --- a/controls/splitcontainer/building-a-layout-of-radsplitcontainers-programmatically.md +++ b/controls/splitcontainer/building-a-layout-of-radsplitcontainers-programmatically.md @@ -15,86 +15,10 @@ You can programmatically build a layout of panels using **RadSplitContainer**. #### Building layout -{{source=..\SamplesCS\SplitContainer\BuildingLayout.cs region=basicLayout}} -{{source=..\SamplesVB\SplitContainer\BuildingLayout.vb region=basicLayout}} + + -````C# -RadSplitContainer container = new RadSplitContainer(); -container.Dock = DockStyle.Fill; -//left panel, sized absolutely -RadSplitContainer leftContainer = new RadSplitContainer(); -leftContainer.Orientation = Orientation.Horizontal; -leftContainer.SizeInfo.SizeMode = Telerik.WinControls.UI.Docking.SplitPanelSizeMode.Absolute; -leftContainer.SizeInfo.AbsoluteSize = new Size(150, 150); -container.SplitPanels.Add(leftContainer); -//middle panel, auto-sized -SplitPanel middlePanel = new SplitPanel(); -middlePanel.SplitPanelElement.Fill.BackColor = Color.Pink; -container.SplitPanels.Add(middlePanel); -//left panel, sized absolutely -RadSplitContainer rightContainer = new RadSplitContainer(); -rightContainer.Orientation = Orientation.Horizontal; -rightContainer.SizeInfo.SizeMode = Telerik.WinControls.UI.Docking.SplitPanelSizeMode.Absolute; -rightContainer.SizeInfo.AbsoluteSize = new Size(150, 150); -container.SplitPanels.Add(rightContainer); -//add panels 4 & 5 -SplitPanel leftTopPanel = new SplitPanel(); -leftContainer.SplitPanelElement.Fill.BackColor = Color.Yellow; -leftTopPanel.SizeInfo.SizeMode = Telerik.WinControls.UI.Docking.SplitPanelSizeMode.Absolute; -leftTopPanel.SizeInfo.AbsoluteSize = new Size(150, 150); -leftContainer.SplitPanels.Add(leftTopPanel); -SplitPanel leftBottomPanel = new SplitPanel(); -leftBottomPanel.SplitPanelElement.Fill.BackColor = Color.Green; -leftContainer.SplitPanels.Add(leftBottomPanel); -//add panels 6 & 7 -SplitPanel rightTopPanel = new SplitPanel(); -rightTopPanel.SplitPanelElement.Fill.BackColor = Color.Red; -rightTopPanel.SizeInfo.SizeMode = Telerik.WinControls.UI.Docking.SplitPanelSizeMode.Absolute; -rightTopPanel.SizeInfo.AbsoluteSize = new Size(150, 150); -rightContainer.SplitPanels.Add(rightTopPanel); -SplitPanel rightBottomPanel = new SplitPanel(); -rightBottomPanel.SplitPanelElement.Fill.BackColor = Color.Lime; -rightContainer.SplitPanels.Add(rightBottomPanel); -this.Controls.Add(container); -```` -````VB.NET -Dim container As RadSplitContainer = New RadSplitContainer() -container.Dock = DockStyle.Fill -'left panel, sized absolutely -Dim leftContainer As RadSplitContainer = New RadSplitContainer() -leftContainer.Orientation = Orientation.Horizontal -leftContainer.SizeInfo.SizeMode = Telerik.WinControls.UI.Docking.SplitPanelSizeMode.Absolute -leftContainer.SizeInfo.AbsoluteSize = New Size(150, 150) -container.SplitPanels.Add(leftContainer) -'middle panel, auto-sized -Dim middlePanel As SplitPanel = New SplitPanel() -container.SplitPanels.Add(middlePanel) -'left panel, sized absolutely -Dim rightContainer As RadSplitContainer = New RadSplitContainer() -rightContainer.Orientation = Orientation.Horizontal -rightContainer.SizeInfo.SizeMode = Telerik.WinControls.UI.Docking.SplitPanelSizeMode.Absolute -rightContainer.SizeInfo.AbsoluteSize = New Size(150, 150) -container.SplitPanels.Add(rightContainer) -'add panels 4 & 5 -Dim leftTopPanel As SplitPanel = New SplitPanel() -leftTopPanel.SizeInfo.SizeMode = Telerik.WinControls.UI.Docking.SplitPanelSizeMode.Absolute -leftTopPanel.SizeInfo.AbsoluteSize = New Size(150, 150) -leftContainer.SplitPanels.Add(leftTopPanel) -Dim leftBottomPanel As SplitPanel = New SplitPanel() -leftContainer.SplitPanels.Add(leftBottomPanel) -'add panels 6 & 7 -Dim rightTopPanel As SplitPanel = New SplitPanel() -rightTopPanel.SizeInfo.SizeMode = Telerik.WinControls.UI.Docking.SplitPanelSizeMode.Absolute -rightTopPanel.SizeInfo.AbsoluteSize = New Size(150, 150) -rightContainer.SplitPanels.Add(rightTopPanel) -Dim rightBottomPanel As SplitPanel = New SplitPanel() -rightContainer.SplitPanels.Add(rightBottomPanel) -Me.Controls.Add(container) - -```` - -{{endregion}} The result is shown on the screenshot below. Note that the *TelerikMetro* theme is initially applied: diff --git a/controls/splitcontainer/building-advanced-layouts.md b/controls/splitcontainer/building-advanced-layouts.md index f7f1e69c9..36475808f 100644 --- a/controls/splitcontainer/building-advanced-layouts.md +++ b/controls/splitcontainer/building-advanced-layouts.md @@ -17,74 +17,10 @@ This tutorial demonstrates how to create a 5*5 grid of **SplitPanel** instances, In order to achieve the layout on the top screen, refer to the code snippet below: -{{source=..\SamplesCS\SplitContainer\BuildingLayout.cs region=advancedLayout}} -{{source=..\SamplesVB\SplitContainer\BuildingLayout.vb region=advancedLayout}} - -````C# -private void CreateGrid(RadSplitContainer container, int cols, int rows, Orientation orientation, bool centerFill) -{ - container.Orientation = orientation; - for (int i = 0; i < rows; i++) - { - RadSplitContainer newContainer = new RadSplitContainer(); - newContainer.Orientation = Orientation.Vertical; - newContainer.SizeInfo.AbsoluteSize = new Size(100, 100); - for (int j = 0; j < cols; j++) - { - SplitPanel panel = CreateSplitPanel(); - panel.SizeInfo.AbsoluteSize = new Size(100, 100); - newContainer.SplitPanels.Add(panel); - } - container.SplitPanels.Add(newContainer); - } - if (centerFill) - { - (container.SplitPanels[rows / 2] as RadSplitContainer).SplitPanels[cols / 2].SizeInfo.SizeMode = Telerik.WinControls.UI.Docking.SplitPanelSizeMode.Fill; - } -} -// color helper method -Random random = new Random(); -private SplitPanel CreateSplitPanel() -{ - SplitPanel panel = new SplitPanel(); - Color back = Color.FromArgb(this.random.Next(155, 255), this.random.Next(155, 255), this.random.Next(155, 255)); - panel.SplitPanelElement.Fill.BackColor = back; - panel.SplitPanelElement.Fill.GradientStyle = GradientStyles.Solid; - return panel; -} - -```` -````VB.NET -Private Sub CreateGrid(ByVal container As RadSplitContainer, ByVal cols As Integer, ByVal rows As Integer, ByVal orientation As Orientation, ByVal centerFill As Boolean) - container.Orientation = orientation - For i As Integer = 0 To rows - 1 - Dim newContainer As New RadSplitContainer() - newContainer.Orientation = orientation.Vertical - newContainer.SizeInfo.AbsoluteSize = New Size(100, 100) - For j As Integer = 0 To cols - 1 - Dim panel As SplitPanel = CreateSplitPanel() - panel.SizeInfo.AbsoluteSize = New Size(100, 100) - newContainer.SplitPanels.Add(panel) - Next j - container.SplitPanels.Add(newContainer) - Next i - If centerFill Then - TryCast(container.SplitPanels(rows \ 2), RadSplitContainer).SplitPanels(cols \ 2).SizeInfo.SizeMode = Telerik.WinControls.UI.Docking.SplitPanelSizeMode.Fill - End If -End Sub -' color helper method -Private random As New Random() -Private Function CreateSplitPanel() As SplitPanel - Dim panel As New SplitPanel() - Dim back As Color = Color.FromArgb(Me.random.Next(155, 255), Me.random.Next(155, 255), Me.random.Next(155, 255)) - panel.SplitPanelElement.Fill.BackColor = back - panel.SplitPanelElement.Fill.GradientStyle = GradientStyles.Solid - Return panel -End Function - -```` - -{{endregion}} + + + + What we are doing here is to create a number (specified by the "**rows**" parameter) of split containers and for each container to add the desired number(defined by the "**cols**" parameter) split panels. When we have a descendant split panel with **SizeMode** set to *Fill*, then all other descendants are sized absolutely to allow the *Fill* panel occupy entire remaining size. The layout engine is smart enough to traverse the entire layout tree, thus allowing the fill panel to reside at any branch. @@ -98,28 +34,10 @@ Each **SplitPanelSizeInfo** instance has **MinimumSize** and **MaximumSize** mem #### Restricting panels -{{source=..\SamplesCS\SplitContainer\BuildingLayout.cs region=panelRestrictions}} -{{source=..\SamplesVB\SplitContainer\BuildingLayout.vb region=panelRestrictions}} - -````C# -private void ApplyPanelRestrictions(SplitPanel panel, Size minSize, Size maxSize) -{ - SplitPanelSizeInfo sizeInfo = panel.SizeInfo; - sizeInfo.MinimumSize = minSize; - sizeInfo.MaximumSize = maxSize; -} - -```` -````VB.NET -Private Sub ApplyPanelRestrictions(ByVal panel As SplitPanel, ByVal minSize As Size, ByVal maxSize As Size) - Dim sizeInfo As SplitPanelSizeInfo = panel.SizeInfo - sizeInfo.MinimumSize = minSize - sizeInfo.MaximumSize = maxSize -End Sub + + -```` -{{endregion}} The panel in the center is with applied size restrictions. diff --git a/controls/splitcontainer/customizing-appearance/accessing-and-customizing-elements.md b/controls/splitcontainer/customizing-appearance/accessing-and-customizing-elements.md index 8dae6aa2e..6ca6566a5 100644 --- a/controls/splitcontainer/customizing-appearance/accessing-and-customizing-elements.md +++ b/controls/splitcontainer/customizing-appearance/accessing-and-customizing-elements.md @@ -31,25 +31,10 @@ You can customize the nested elements at run time as well: #### Customize elements -{{source=..\SamplesCS\SplitContainer\BuildingLayout.cs region=CustomizeElements}} -{{source=..\SamplesVB\SplitContainer\BuildingLayout.vb region=CustomizeElements}} + + -````C# -this.radSplitContainer1.SplitPanels[0].BackColor = Color.Red; -this.radSplitContainer1.Splitters[0].BackgroundFill.BackColor = Color.Yellow; -this.radSplitContainer1.Splitters[0].Border.ForeColor = Color.Lime; -this.radSplitContainer1.Splitters[0].Border.BoxStyle = BorderBoxStyle.SingleBorder; -```` -````VB.NET -Me.radSplitContainer1.SplitPanels(0).BackColor = Color.Red -Me.radSplitContainer1.Splitters(0).BackgroundFill.BackColor = Color.Yellow -Me.radSplitContainer1.Splitters(0).Border.ForeColor = Color.Lime -Me.radSplitContainer1.Splitters(0).Border.BoxStyle = BorderBoxStyle.SingleBorder - -```` - -{{endregion}} # See Also diff --git a/controls/splitcontainer/splitter-buttons.md b/controls/splitcontainer/splitter-buttons.md index 02e07de93..b5535ee3d 100644 --- a/controls/splitcontainer/splitter-buttons.md +++ b/controls/splitcontainer/splitter-buttons.md @@ -19,22 +19,10 @@ In order to use the splitter buttons the following properties need to be set to #### Show Splitter Buttons -{{source=..\SamplesCS\SplitContainer\SplitterButtons.cs region=ShowSplitterButtons}} -{{source=..\SamplesVB\SplitContainer\SplitterButtons.vb region=ShowSplitterButtons}} -````C# -this.radSplitContainer1.EnableCollapsing = true; -this.radSplitContainer1.UseSplitterButtons = true; + + -```` -````VB.NET -Me.RadSplitContainer1.EnableCollapsing = True -Me.RadSplitContainer1.UseSplitterButtons = True -```` - - - -{{endregion}} >note Since **R3 2020 SP1** RadSplitContaiter comes with left and right arrow buttons on every SplitterElement for easier navigation. Thus, the users are able to collapse the SplitPanels to desired location. @@ -46,52 +34,26 @@ The control also exposes a convenient API for accessing the splitter elements. E #### Collapse Splitter -{{source=..\SamplesCS\SplitContainer\SplitterButtons.cs region=CollapsеSplitter}} -{{source=..\SamplesVB\SplitContainer\SplitterButtons.vb region=CollapsеSplitter}} -````C# -this.radSplitContainer1.MoveSplitter(this.radSplitContainer1.Splitters[0], RadDirection.Left); - -```` -````VB.NET -Me.RadSplitContainer1.MoveSplitter(Me.RadSplitContainer1.Splitters(0), RadDirection.Left) + + -```` -{{endregion}} #### Expand Splitter -{{source=..\SamplesCS\SplitContainer\SplitterButtons.cs region=ExpandSplitter}} -{{source=..\SamplesVB\SplitContainer\SplitterButtons.vb region=ExpandSplitter}} -````C# -this.radSplitContainer1.RestoreSplitterPosition(this.radSplitContainer1.Splitters[0]); + + -```` -````VB.NET -Me.RadSplitContainer1.RestoreSplitterPosition(Me.RadSplitContainer1.Splitters(0)) -```` - -{{endregion}} >note Since **R3 2020 SP1** RadSplitContainer offers **DefaultCollapseDirection** property that indicates the default collapse direction when performing a double click on SplitterElement to collapse a SplitPanel. For horizontal splitters you can set **RadDirection.Up** or **RadDirection.Down**. For vertical splitters you can set **RadDirection.Left** or **RadDirection.Right**. Here is an example how you can change the collapse direction to right when you have vertical splitters which direction by default is left: -{{source=..\SamplesCS\SplitContainer\SplitterButtons.cs region=DefaultColapseDirection}} -{{source=..\SamplesVB\SplitContainer\SplitterButtons.vb region=DefaultColapseDirection}} -````C# -this.radSplitContainer1.Splitters[0].DefaultCollapseDirection = RadDirection.Right; - -```` -````VB.NET -Me.RadSplitContainer1.Splitters(0).DefaultCollapseDirection = RadDirection.Right - -```` - + + -{{endregion}} >caption Figure 3: Change default split direction when double click on SplitterElement diff --git a/controls/spreadsheet/events.md b/controls/spreadsheet/events.md index bf28c39ab..73ef59b36 100644 --- a/controls/spreadsheet/events.md +++ b/controls/spreadsheet/events.md @@ -36,36 +36,10 @@ The code from **Example 1** shows how to disable the messages appearing when the #### Example 1: Disable messages related to protection using the MessageShowing event -{{source=..\SamplesCS\Spreadsheet\Events.cs region=radspreadsheet-events_1}} -{{source=..\SamplesVB\Spreadsheet\Events.vb region=radspreadsheet-events_1}} -````C# -public void AttachToMessageShowingEvent() -{ - this.radSpreadsheet.SpreadsheetElement.MessageShowing += radSpreadsheet_MessageShowing; -} -private void radSpreadsheet_MessageShowing(object sender, MessageShowingEventArgs e) -{ - if (e.NotificationType == Telerik.WinForms.Controls.Spreadsheet.Dialogs.MessageBoxNotificationType.ProtectedWorksheetError) - { - e.IsHandled = true; - } -} - -```` -````VB.NET -Public Sub AttachToMessageShowingEvent() - AddHandler Me.radSpreadsheet.SpreadsheetElement.MessageShowing, AddressOf radSpreadsheet_MessageShowing -End Sub -Private Sub radSpreadsheet_MessageShowing(ByVal sender As Object, ByVal e As MessageShowingEventArgs) - If e.NotificationType = Telerik.WinForms.Controls.Spreadsheet.Dialogs.MessageBoxNotificationType.ProtectedWorksheetError Then - e.IsHandled = True - End If -End Sub - -```` - - -{{endregion}} + + + + * **WorkbookCommandError**: Notifies that an error occurred while executing a command in RadSpreadsheet. The arguments are of type **CommandErrorEventArgs** and you can use the **Exception** property to check what exactly the error is. @@ -77,29 +51,9 @@ End Sub #### Example 2: Cancel a command through WorkbookCommandExecuting -{{source=..\SamplesCS\Spreadsheet\Events.cs region=radspreadsheet-events_2}} -{{source=..\SamplesVB\Spreadsheet\Events.vb region=radspreadsheet-events_2}} -````C# -private void radSpreadsheet_WorkbookCommandExecuting(object sender, Telerik.Windows.Documents.Spreadsheet.Commands.CommandExecutingEventArgs e) -{ - if (e.CommandName == "AddShapeCommand") - { - e.Cancel(); - } -} - -```` -````VB.NET -Private Sub radSpreadsheet_WorkbookCommandExecuting(ByVal sender As Object, ByVal e As Telerik.Windows.Documents.Spreadsheet.Commands.CommandExecutingEventArgs) - If e.CommandName = "AddShapeCommand" Then - e.Cancel() - End If -End Sub + + -```` - - -{{endregion}} * **WorkbookCommandExecuted**: Occurs when workbook command is executed. @@ -112,27 +66,9 @@ End Sub #### Example 3: Specify FileName, Title, Filter properties before saving a file in SaveFileDialog -{{source=..\SamplesCS\Spreadsheet\Events.cs region=radspreadsheet-events_4}} -{{source=..\SamplesVB\Spreadsheet\Events.vb region=radspreadsheet-events_4}} -````C# -private void RadSpreadsheet_BeforeSaveFile(object sender, Telerik.WinForms.Controls.Spreadsheet.Worksheets.SaveFileDialogEventArgs e) -{ - e.Dialog.FileName = "TelerikSpreadsheet.xlsx"; // Default file name - e.Dialog.Title = "Open Spreadsheet File"; // Title of the dialog - e.Dialog.Filter = "Spreadsheet files (*.xlsx)|*.xlsx|All files (*.*)|*.*"; // Filter for the file types -} - -```` -````VB.NET -Private Sub RadSpreadsheet_BeforeSaveFile(ByVal sender As Object, ByVal e As Telerik.WinForms.Controls.Spreadsheet.Worksheets.SaveFileDialogEventArgs) - e.Dialog.FileName = "TelerikSpreadsheet.xlsx" ' Default file name - e.Dialog.Title = "Open Spreadsheet File" ' Title of the dialog - e.Dialog.Filter = "Spreadsheet files (*.xlsx)|*.xlsx|All files (*.*)|*.*" ' Filter the file types -End Sub + + -```` - -{{endregion}} ## Workbook Events @@ -189,52 +125,9 @@ End Sub #### Example 4: Using the HyperlinkClicked event to implement confirmation for the clicked links in the document -{{source=..\SamplesCS\Spreadsheet\Events.cs region=HyperlinkClickedEvent}} -{{source=..\SamplesVB\Spreadsheet\Events.vb region=HyperlinkClickedEvent}} -````C# -private void ActiveWorksheetEditor_HyperlinkClicked(object sender, SpreadsheetHyperlinkClickedEventArgs e) -{ - if (e.URL.EndsWith("exe")) - { - e.Handled = true; - //Get CellIndex on the cell clicked to open the hyperlink - CellIndex cellIndex = e.CellIndex; - - MessageBoxResult Result = System.Windows.MessageBox.Show("You are about to open an executable file. Do you want to proceed?", "Possible unsafe link", MessageBoxButton.YesNo, MessageBoxImage.Question); - if (Result == MessageBoxResult.Yes) - { - Process.Start(new ProcessStartInfo() - { - FileName = e.URL, - UseShellExecute = true - }); - } - } -} - -```` -````VB.NET - -Private Sub ActiveWorksheetEditor_HyperlinkClicked(sender As Object, e As SpreadsheetHyperlinkClickedEventArgs) - If e.URL.EndsWith("exe") Then - e.Handled = True - - 'Get CellIndex on the cell clicked to open the hyperlink - Dim cellIndex As CellIndex = e.CellIndex - - Dim Result As MessageBoxResult = System.Windows.MessageBox.Show("You are about to open an executable file. Do you want to proceed?", "Possible unsafe link", MessageBoxButton.YesNo, MessageBoxImage.Question) - If Result = MessageBoxResult.Yes Then - Process.Start(New ProcessStartInfo() With { - .FileName = e.URL, - .UseShellExecute = True - }) - End If - End If -End Sub - -```` - -{{endregion}} + + + >The events related to selection in RadSpreadsheet are described in the [Working with UI Selection]({%slug radspreadsheet-ui-working-with-selection%}) topic. @@ -245,36 +138,10 @@ End Sub #### Example 5: Using the CellPropertyChangedEvent -{{source=..\SamplesCS\Spreadsheet\Events.cs region=radspreadsheet-events_3}} -{{source=..\SamplesVB\Spreadsheet\Events.vb region=radspreadsheet-events_3}} -````C# -public void AttachToCellPropertyChangedEvent() -{ - this.radSpreadsheet.SpreadsheetElement.ActiveWorksheet.Cells.CellPropertyChanged += Cells_CellPropertyChanged; -} -private void Cells_CellPropertyChanged(object sender, CellPropertyChangedEventArgs e) -{ - if (e.Property == CellPropertyDefinitions.FillProperty) - { - RadMessageBox.Show("The fill of a cell was changed!"); - } -} - -```` -````VB.NET -Public Sub AttachToCellPropertyChangedEvent() - AddHandler Me.radSpreadsheet.SpreadsheetElement.ActiveWorksheet.Cells.CellPropertyChanged, AddressOf Cells_CellPropertyChanged -End Sub -Private Sub Cells_CellPropertyChanged(ByVal sender As Object, ByVal e As CellPropertyChangedEventArgs) - If e.Property Is CellPropertyDefinitions.FillProperty Then - RadMessageBox.Show("The fill of a cell was changed!") - End If -End Sub - -```` - - -{{endregion}} + + + + * **CellRangeInsertedOrRemoved**: Occurs when a cell range is inserted or removed. Through the arguments, you can obtain information about the affected ranges, as well as whether the range is removed or not. diff --git a/controls/spreadsheet/features/context-menu.md b/controls/spreadsheet/features/context-menu.md index a60093547..bf9be3f1e 100644 --- a/controls/spreadsheet/features/context-menu.md +++ b/controls/spreadsheet/features/context-menu.md @@ -23,43 +23,10 @@ By default the WorksheetEditor of RadSpreadsheet have a context menu. The contro You can access and modify the default context menu in the ContextMenuShowing event. The following example demonstrates how you can remove the "Copy" item from the context menu. -{{source=..\SamplesCS\Spreadsheet\ContextMenuCode.cs region=context_menu_1}} -{{source=..\SamplesVB\Spreadsheet\ContextMenuCode.vb region=context_menu_1}} - -````C# -public ContextMenuCode() -{ - InitializeComponent(); - radSpreadsheet1.SpreadsheetElement.ContextMenuShowing += SpreadsheetElement_ContextMenuShowing; -} -private void SpreadsheetElement_ContextMenuShowing(object sender, SpreadsheetContextMenuOpeningEventArgs e) -{ - foreach (var item in e.Menu.Items) - { - if (item.Text == "Copy") - { - item.Visibility = ElementVisibility.Collapsed; - } - } -} - -```` -````VB.NET -Public Sub New() - InitializeComponent() - AddHandler radSpreadsheet1.SpreadsheetElement.ContextMenuShowing, AddressOf SpreadsheetElement_ContextMenuShowing -End Sub -Private Sub SpreadsheetElement_ContextMenuShowing(ByVal sender As Object, ByVal e As SpreadsheetContextMenuOpeningEventArgs) - For Each item In e.Menu.Items - If item.Text = "Copy" Then - item.Visibility = ElementVisibility.Collapsed - End If - Next item -End Sub - -```` - -{{endregion}} + + + + >note Please have in mind that most of the menu items have a binding to the respective command. Hence, their visibility depends on the command itself. Hence, if you want to hide a menu item, it is not enough simply to set the RadMenuItem.**Visibility** property to **Collapsed**. It is necessary to call the RadMenuItem.**UnbindProperty(RadElement.VisibilityProperty)** method as well. diff --git a/controls/spreadsheet/features/data-validation.md b/controls/spreadsheet/features/data-validation.md index 0c26c6668..eb2f5d5e1 100644 --- a/controls/spreadsheet/features/data-validation.md +++ b/controls/spreadsheet/features/data-validation.md @@ -42,27 +42,8 @@ Example 1 shows the use of the two methods that toggle this functionality - **Ci #### Example 1: Turn on and off Invalid Data Circles. -{{source=..\SamplesCS\Spreadsheet\FreezePanes.cs region=DataValidation}} -{{source=..\SamplesVB\Spreadsheet\FreezePanes.vb region=DataValidation}} - -````C# - -if (showCircles) -{ - this.radSpreadsheet1.SpreadsheetElement.ActiveWorksheetEditor.CircleInvalidData(); -} -else -{ - this.radSpreadsheet1.SpreadsheetElement.ActiveWorksheetEditor.ClearInvalidDataCircles(); -} - -```` -````VB.NET -If showCircles Then - Me.radSpreadsheet1.SpreadsheetElement.ActiveWorksheetEditor.CircleInvalidData() -Else - Me.radSpreadsheet1.SpreadsheetElement.ActiveWorksheetEditor.ClearInvalidDataCircles() -End If - -```` -{{endregion}} + + + + + diff --git a/controls/spreadsheet/features/freeze-panes.md b/controls/spreadsheet/features/freeze-panes.md index b5ece55fe..56853ed35 100644 --- a/controls/spreadsheet/features/freeze-panes.md +++ b/controls/spreadsheet/features/freeze-panes.md @@ -28,21 +28,10 @@ The following code will produce freeze panes like the example below: #### Freeze Panes -{{source=..\SamplesCS\Spreadsheet\FreezePanes.cs region=FreezePanes}} -{{source=..\SamplesVB\Spreadsheet\FreezePanes.vb region=FreezePanes}} + + -````C# - -Telerik.WinForms.Controls.Spreadsheet.Worksheets.RadWorksheetEditor worksheetEditor = this.radSpreadsheet1.SpreadsheetElement.ActiveWorksheetEditor; -worksheetEditor.FreezePanes(new Telerik.Windows.Documents.Spreadsheet.Model.CellIndex(4, 1)); -```` -````VB.NET -Dim worksheetEditor As Telerik.WinForms.Controls.Spreadsheet.Worksheets.RadWorksheetEditor = Me.radSpreadsheet1.SpreadsheetElement.ActiveWorksheetEditor -worksheetEditor.FreezePanes(New Telerik.Windows.Documents.Spreadsheet.Model.CellIndex(4, 1)) - -```` -{{endregion}} >note Note that the cell you want to freeze have to be visible at the moment you freeze. @@ -68,19 +57,10 @@ To unfreeze panes simply you need to use the **UnfreezePanes**() method of the * #### Unfreeze Panes -{{source=..\SamplesCS\Spreadsheet\FreezePanes.cs region=UnfreezePanes}} -{{source=..\SamplesVB\Spreadsheet\FreezePanes.vb region=UnfreezePanes}} - -````C# - -this.radSpreadsheet1.SpreadsheetElement.ActiveWorksheetEditor.UnfreezePanes(); + + -```` -````VB.NET -Me.radSpreadsheet1.SpreadsheetElement.ActiveWorksheetEditor.UnfreezePanes() -```` -{{endregion}} Alternatively, you can freeze/unfreeze panes from the **RadSpreadsheetRibbonBar** as well: diff --git a/controls/spreadsheet/features/printing.md b/controls/spreadsheet/features/printing.md index cac33f5d2..46097eb18 100644 --- a/controls/spreadsheet/features/printing.md +++ b/controls/spreadsheet/features/printing.md @@ -39,29 +39,10 @@ Depending on whether you want to show a print preview before printing you may us #### Print Methods -{{source=..\SamplesCS\Spreadsheet\SpreadsheetPrinting.cs region=PrintMethod}} -{{source=..\SamplesVB\Spreadsheet\SpreadsheetPrinting.vb region=PrintMethod}} -````C# -// Prints silently to the default printer without showing the print dialog. -var settings = new PrintWhatSettings(ExportWhat.ActiveSheet, false); -radSpreadsheet1.SpreadsheetElement.Print(settings); -// Prints showing the print dialog. -radSpreadsheet1.SpreadsheetElement.PrintPreview(); + + -```` -````VB.NET -'Prints silently to the default printer without showing the print dialog. -Dim settings = New PrintWhatSettings(ExportWhat.ActiveSheet, False) -radSpreadsheet1.SpreadsheetElement.Print(settings) -'Prints showing the print dialog. -radSpreadsheet1.SpreadsheetElement.PrintPreview() -```` - - - - -{{endregion}} The bellow image shows the options available in the PrintPreview dialog. diff --git a/controls/spreadsheet/features/ui-working-with-selection.md b/controls/spreadsheet/features/ui-working-with-selection.md index 88f7b3e8e..e3bbe7d5b 100644 --- a/controls/spreadsheet/features/ui-working-with-selection.md +++ b/controls/spreadsheet/features/ui-working-with-selection.md @@ -94,22 +94,11 @@ The __Selection__ class also exposes an __ActiveCell__ property that designates #### Change the ActiveCellMode -{{source=..\SamplesCS\Spreadsheet\SelectionCode.cs region=Selection_1}} -{{source=..\SamplesVB\Spreadsheet\SelectionCode.vb region=Selection_1}} -````C# -Selection selection = this.radSpreadsheet.SpreadsheetElement.ActiveWorksheetEditor.Selection; -selection.ActiveCellMode = ActiveCellMode.Edit; - -```` -````VB.NET -Dim selection = Me.radSpreadsheet.SpreadsheetElement.ActiveWorksheetEditor.Selection -selection.ActiveCellMode = ActiveCellMode.Edit - -```` - - -{{endregion}} - + + + + + ## Changing the UI Selection The UI cell selection can be a single cell or a rectangular region of cells. If you hold down the Ctrl key, you can select multiple rectangular regions of cells. Note that these cell ranges do not have to be adjacent. In fact, they can be dispersed across the worksheet and can even intersect. The next several examples aim to illustrate how to create one and multiple-region selection through the API of the RadSpreadsheet. @@ -124,22 +113,11 @@ One of the Select overloads gets a CellIndex parameter that points to the cell t #### Selecting a Cell -{{source=..\SamplesCS\Spreadsheet\SelectionCode.cs region=Selection_2}} -{{source=..\SamplesVB\Spreadsheet\SelectionCode.vb region=Selection_2}} -````C# -Selection selection_2 = this.radSpreadsheet.SpreadsheetElement.ActiveWorksheetEditor.Selection; -selection_2.Select(new CellIndex(0, 0), false); + + -```` -````VB.NET -Dim selection_2 = Me.radSpreadsheet.SpreadsheetElement.ActiveWorksheetEditor.Selection -selection_2.Select(New CellIndex(0, 0), False) -```` - -{{endregion}} - ![WinForms RadSpreadsheet Select First Cell](images/RadSpreadsheet_UI_Selection_03.png) The Selection class also offers a Select() method that takes a CellRange as an argument. The overload selects (or adds to the current selection) the designated region and makes the top left cell to be the Active one. The next sample snippet shows how to select the C3:D4 cell region: @@ -148,21 +126,10 @@ The Selection class also offers a Select() method that takes a CellRange as an a #### Select using CellRange -{{source=..\SamplesCS\Spreadsheet\SelectionCode.cs region=Selection_3}} -{{source=..\SamplesVB\Spreadsheet\SelectionCode.vb region=Selection_3}} -````C# -Selection selection_3 = this.radSpreadsheet.SpreadsheetElement.ActiveWorksheetEditor.Selection; -selection_3.Select(new CellRange(0, 0, 2, 2)); + + -```` -````VB.NET -Dim selection_3 = Me.radSpreadsheet.SpreadsheetElement.ActiveWorksheetEditor.Selection -selection_3.Select(New CellRange(0, 0, 2, 2)) -```` - - -{{endregion}} Another overload of the __Select__ method takes as input two __CellIndex__ instances that indicate the start and the end cell indexes of the selected region. Note that unlike the Select(CellRange) method, this overload makes the cell with the start CellIndex the active one. The following snippet illustrates how use the method to select the region B7 to E3. Note that the active cell is B7, not B3. @@ -172,21 +139,10 @@ Here is a sample code on how you can achieve the result from the above image thr #### Select Region -{{source=..\SamplesCS\Spreadsheet\SelectionCode.cs region=Selection_1}} -{{source=..\SamplesVB\Spreadsheet\SelectionCode.vb region=Selection_1}} -````C# -Selection selection = this.radSpreadsheet.SpreadsheetElement.ActiveWorksheetEditor.Selection; -selection.ActiveCellMode = ActiveCellMode.Edit; - -```` -````VB.NET -Dim selection = Me.radSpreadsheet.SpreadsheetElement.ActiveWorksheetEditor.Selection -selection.ActiveCellMode = ActiveCellMode.Edit + + -```` - -{{endregion}} A similar logic applies to the Select() methods which take shapes as their parameters. @@ -196,46 +152,20 @@ The following result can be achieved with the sample code below: #### Select Image -{{source=..\SamplesCS\Spreadsheet\SelectionCode.cs region=Selection_5}} -{{source=..\SamplesVB\Spreadsheet\SelectionCode.vb region=Selection_5}} -````C# -Selection selection_5 = this.radSpreadsheet.SpreadsheetElement.ActiveWorksheetEditor.Selection; -var image = this.radSpreadsheet.SpreadsheetElement.ActiveWorksheet.Images.First() as FloatingShapeBase; -selection_5.Select(image); - -```` -````VB.NET -Dim selection_5 = Me.radSpreadsheet.SpreadsheetElement.ActiveWorksheetEditor.Selection -Dim image = TryCast(Me.radSpreadsheet.SpreadsheetElement.ActiveWorksheet.Images.First(), FloatingShapeBase) -selection_5.Select(image) + + -```` - -{{endregion}} If you would like to select the second image while deselecting the first one, this can be achieved with the following code: #### Select Next Image -{{source=..\SamplesCS\Spreadsheet\SelectionCode.cs region=Selection_6}} -{{source=..\SamplesVB\Spreadsheet\SelectionCode.vb region=Selection_6}} -````C# -Selection selection_6 = this.radSpreadsheet.SpreadsheetElement.ActiveWorksheetEditor.Selection; -var image2 = this.radSpreadsheet.SpreadsheetElement.ActiveWorksheet.Images.ElementAt(1) as FloatingShapeBase; -selection_6.Select(image2, true); + + -```` -````VB.NET -Dim selection_6 = Me.radSpreadsheet.SpreadsheetElement.ActiveWorksheetEditor.Selection -Dim image2 = TryCast(Me.radSpreadsheet.SpreadsheetElement.ActiveWorksheet.Images.ElementAt(1), FloatingShapeBase) -selection_6.Select(image2, True) -```` - - -{{endregion}} The result will be the following: @@ -254,26 +184,10 @@ The following code snippet demonstrates how to use the __SelectAll__ method and #### Selecting all or the used Cells -{{source=..\SamplesCS\Spreadsheet\SelectionCode.cs region=Selection_7}} -{{source=..\SamplesVB\Spreadsheet\SelectionCode.vb region=Selection_7}} -````C# -Selection selection_7 = this.radSpreadsheet.SpreadsheetElement.ActiveWorksheetEditor.Selection; -selection_7.SelectAll(); -CellRange usedRange = this.radSpreadsheet.SpreadsheetElement.ActiveWorksheet.UsedCellRange; -selection_7.Select(usedRange); - -```` -````VB.NET -Dim selection_7 = Me.radSpreadsheet.SpreadsheetElement.ActiveWorksheetEditor.Selection -selection_7.SelectAll() -Dim usedRange As CellRange = Me.radSpreadsheet.SpreadsheetElement.ActiveWorksheet.UsedCellRange -selection_7.Select(usedRange) + + -```` - -{{endregion}} - ## Selection Events @@ -303,30 +217,10 @@ In some scenarios when you make a complex selection and want an event to be fire The following example shows how to make a complex selection from three parts, which will fire SelectionChanged event only once, instead of three times, thanks to the use of BeginUpdate() and EndUpdate() methods. -{{source=..\SamplesCS\Spreadsheet\SelectionCode.cs region=Selection_8}} -{{source=..\SamplesVB\Spreadsheet\SelectionCode.vb region=Selection_8}} -````C# -Selection selection = this.radSpreadsheet.SpreadsheetElement.ActiveWorksheetEditor.Selection; -selection.BeginUpdate(); -selection.Select(new CellRange(4, 3, 8, 5)); -selection.Select(new CellRange(5, 2, 3, 3), clearSelection: false); -selection.Select(new CellIndex(2, 1), clearSelection: false); -selection.EndUpdate(); - -```` -````VB.NET -Dim selection = Me.radSpreadsheet.SpreadsheetElement.ActiveWorksheetEditor.Selection -selection.BeginUpdate() -selection.Select(New CellRange(4, 3, 8, 5)) -selection.Select(New CellRange(5, 2, 3, 3), clearSelection:=False) -selection.Select(New CellIndex(2, 1), clearSelection:=False) -selection.EndUpdate() + + -```` - -{{endregion}} - ## Saving and Restoring the UI Selection @@ -336,30 +230,10 @@ With the RadSpreadsheet API you have the ability to save the current selection i The following example makes a single CellRange selection and saves it in a __SelectionState__ instance. After adding some new cells to the selection the old selection is restored through the __RestoreSelectionState__ method. -{{source=..\SamplesCS\Spreadsheet\SelectionCode.cs region=Selection_9}} -{{source=..\SamplesVB\Spreadsheet\SelectionCode.vb region=Selection_9}} -````C# -Selection selection = this.radSpreadsheet.SpreadsheetElement.ActiveWorksheetEditor.Selection; -selection.Select(new CellRange(4, 3, 8, 5)); -SelectionState selectionState = selection.CreateSelectionState(); -selection.Select(new CellRange(5, 2, 3, 3), clearSelection: false); -selection.Select(new CellIndex(2, 1), clearSelection: false); -selection.RestoreSelectionState(selectionState); + + -```` -````VB.NET -Dim selection = Me.radSpreadsheet.SpreadsheetElement.ActiveWorksheetEditor.Selection -selection.Select(New CellRange(4, 3, 8, 5)) -Dim selectionState As SelectionState = selection.CreateSelectionState() -selection.Select(New CellRange(5, 2, 3, 3), clearSelection:=False) -selection.Select(New CellIndex(2, 1), clearSelection:=False) -selection.RestoreSelectionState(selectionState) -```` - - -{{endregion}} - ## Filling the Selection with Data @@ -402,44 +276,18 @@ The current region concept is represented by a **CellRange** object that contain #### Get current region -{{source=..\SamplesCS\Spreadsheet\SelectionCode.cs region=selection_14}} -{{source=..\SamplesVB\Spreadsheet\SelectionCode.vb region=selection_14}} -````C# -Selection selection = this.radSpreadsheet.ActiveWorksheetEditor.Selection; -CellRange currentRegion = selection.CurrentRegion; + + -```` -````VB.NET -Dim selection As Selection = Me.radSpreadsheet.ActiveWorksheetEditor.Selection -Dim currentRegion As CellRange = selection.CurrentRegion -```` - -{{endregion}} To select the current region, call the SelectCurrentRegion method of the CellPosition instance. #### Select current region programmatically -{{source=..\SamplesCS\Spreadsheet\SelectionCode.cs region=selection_15}} -{{source=..\SamplesVB\Spreadsheet\SelectionCode.vb region=selection_15}} -````C# -Selection selection = this.radSpreadsheet.ActiveWorksheetEditor.Selection; -CellPosition activePosition = selection.ActiveRange.ActivePosition; -bool result = activePosition.SelectCurrentRegion(); -//or -selection.Select(selection.CurrentRegion); - -```` -````VB.NET -Dim selection As Selection = Me.radSpreadsheet.ActiveWorksheetEditor.Selection -Dim activePosition As CellPosition = selection.ActiveRange.ActivePosition -Dim result As Boolean = activePosition.SelectCurrentRegion() -'or -selection.Select(selection.CurrentRegion) - -```` - -{{endregion}} + + + + The current region can also be selected using the following keyboard combination: `Ctrl+Shift+Asterisk sign(8*)` diff --git a/controls/spreadsheet/getting-started/getting-started.md b/controls/spreadsheet/getting-started/getting-started.md index 2f4a79170..2a599f0f4 100644 --- a/controls/spreadsheet/getting-started/getting-started.md +++ b/controls/spreadsheet/getting-started/getting-started.md @@ -70,30 +70,10 @@ In some cases you may need to load the document in the code behind, not by using #### Load document with code. -{{source=..\SamplesCS\Spreadsheet\GettingStartedCode.cs region=LoadFile}} -{{source=..\SamplesVB\Spreadsheet\GettingStartedCode.vb region=LoadFile}} + + -````C# -string fileName = @"C:\Test.xlsx"; -var formatProvider = new XlsxFormatProvider(); -using (Stream input = new FileStream(fileName, FileMode.Open)) -{ - radSpreadsheet1.Workbook = formatProvider.Import(input); -} -```` -````VB.NET -Dim fileName As String = "C:\Test.xlsx" -Dim formatProvider = New XlsxFormatProvider() -Using input As Stream = New FileStream(fileName, FileMode.Open) - radSpreadsheet1.Workbook = formatProvider.Import(input) -End Using - -```` - - - -{{endregion}} >note Detailed information about the format providers is available [here](https://docs.telerik.com/devtools/document-processing/libraries/radspreadprocessing/formats-and-conversion/general-information). diff --git a/controls/spreadsheet/how-to/customize-row-column-headers.md b/controls/spreadsheet/how-to/customize-row-column-headers.md index 80cf9cd73..a333bcdf3 100644 --- a/controls/spreadsheet/how-to/customize-row-column-headers.md +++ b/controls/spreadsheet/how-to/customize-row-column-headers.md @@ -29,38 +29,8 @@ __Example 1__ shows a simple implementation for the converter class used for cre #### Example 1: Create a custom name converter -{{source=..\SamplesCS\Spreadsheet\NameConverter.cs region=name_canverter_0}} -{{source=..\SamplesVB\Spreadsheet\NameConverter.vb region=name_canverter_0}} -````C# -public class CustomNameConverter : HeaderNameRenderingConverterBase -{ - protected override string ConvertColumnIndexToNameOverride(HeaderNameRenderingConverterContext context, int columnIndex) - { - if (columnIndex == 0) - { - return "First Name"; - } - return base.ConvertColumnIndexToNameOverride(context, columnIndex); - } -} - -```` -````VB.NET -Public Class CustomNameConverter - Inherits HeaderNameRenderingConverterBase - Protected Overrides Function ConvertColumnIndexToNameOverride(ByVal context As HeaderNameRenderingConverterContext, ByVal columnIndex As Integer) As String - If columnIndex = 0 Then - Return "First Name" - End If - Return MyBase.ConvertColumnIndexToNameOverride(context, columnIndex) - End Function -End Class - -```` - - -{{endregion}} - + + @@ -69,20 +39,9 @@ After implementing your custom name converter you need to instantiate it and ass >caption Example 2: Instantiate and assign a custom converter -{{source=..\SamplesCS\Spreadsheet\NameConverter.cs region=name_canverter_1}} -{{source=..\SamplesVB\Spreadsheet\NameConverter.vb region=name_canverter_1}} -````C# -this.radSpreadsheet.SpreadsheetElement.Workbook.Worksheets[0].HeaderNameRenderingConverter = new CustomNameConverter(); - -```` -````VB.NET -Me.radSpreadsheet.SpreadsheetElement.Workbook.Worksheets(0).HeaderNameRenderingConverter = New CustomNameConverter() + + -```` - - -{{endregion}} - That's it. The column heading is changed. diff --git a/controls/spreadsheet/how-to/customize-selection.md b/controls/spreadsheet/how-to/customize-selection.md index d85b579f7..b7465450f 100644 --- a/controls/spreadsheet/how-to/customize-selection.md +++ b/controls/spreadsheet/how-to/customize-selection.md @@ -30,8 +30,8 @@ __SpreadsheetElement__ exposes several properties that enable you to control the #### Example 2: Customizing selection -{{source=..\SamplesCS\Spreadsheet\SelectionCode.cs region=Selection_10}} -{{source=..\SamplesVB\Spreadsheet\SelectionCode.vb region=Selection_10}} + + ````C# Brush strokeBrush = Brushes.Green; @@ -49,9 +49,6 @@ radSpreadsheet.SpreadsheetElement.SelectionStroke = strokeBrush radSpreadsheet.SpreadsheetElement.SelectionStrokeThickness = 2 ```` -{{endregion}} - - ## See Also * [Customize Row and Column Headers]({%slug radspreadsheet-howto-customize-row-column-headers%}) diff --git a/controls/spreadsheet/how-to/hide-row-column-headers-and-gridlines.md b/controls/spreadsheet/how-to/hide-row-column-headers-and-gridlines.md index 4abc90e71..1c81413ab 100644 --- a/controls/spreadsheet/how-to/hide-row-column-headers-and-gridlines.md +++ b/controls/spreadsheet/how-to/hide-row-column-headers-and-gridlines.md @@ -1,60 +1,42 @@ ---- -title: Hide Row and Column Headers and Gridlines -page_title: Hide Row and Column Headers and Gridlines - WinForms Spreadsheet Control -description: Row and Column headings, as well as worksheet gridlines, are handy when creating or editing a document in WinForms Spreadsheet. Learn how to hide them to make the spreadsheet more clean and presentable. -slug: radspreadsheet-howto-hide-row-column-headers-and-gridlines -tags: hide,row,and,column,headers,and,gridlines -published: True -position: 3 ---- - -# Hide Row and Column Headers and Gridlines - -Row and Column headings, as well as worksheet gridlines, are handy when creating or editing a document in __RadSpreadsheet__. However, at times you would want to hide them in order to make the spreadsheet more clean and presentable. This article will teach you about the options provided by RadSpreadsheet that allow you to achieve this. - -## Show or Hide Row and Column Headings - -The __RadWorksheetEditor__ exposes a Boolean property __ShowRowColumnHeadings__. Its default value is true and this makes the row and column headings visible. Setting the property to false as demonstrated in __Example 1__ hides them. - -#### Example 1: Hide Row and Column Headers - - -{{source=..\SamplesCS\Spreadsheet\SelectionCode.cs region=Selection_12}} -{{source=..\SamplesVB\Spreadsheet\SelectionCode.vb region=Selection_12}} -````C# -this.radSpreadsheet.SpreadsheetElement.ActiveWorksheetEditor.ShowRowColumnHeadings = false; - -```` -````VB.NET -Me.radSpreadsheet.SpreadsheetElement.ActiveWorksheetEditor.ShowRowColumnHeadings = False - -```` - - -{{endregion}} - -## Show or Hide Gridlines - -If you want to show or hide the gridlines of __RadSpreadsheet__ just set the __ShowGridlines__ Boolean property of __RadWorksheetEditor__ to true for showing the gridlines or false for hiding them. __Example 2__ shows how you can disable the gridlines. - - -#### Example 2: Hide Gridlines - - -{{source=..\SamplesCS\Spreadsheet\SelectionCode.cs region=Selection_13}} -{{source=..\SamplesVB\Spreadsheet\SelectionCode.vb region=Selection_13}} -````C# -this.radSpreadsheet.SpreadsheetElement.ActiveWorksheetEditor.ShowGridlines = false; - -```` -````VB.NET -Me.radSpreadsheet.SpreadsheetElement.ActiveWorksheetEditor.ShowGridlines = False - -```` - - -{{endregion}} - -## See Also - - * [Customize Row and Column Headers]({%slug radspreadsheet-howto-customize-row-column-headers%}) +--- +title: Hide Row and Column Headers and Gridlines +page_title: Hide Row and Column Headers and Gridlines - WinForms Spreadsheet Control +description: Row and Column headings, as well as worksheet gridlines, are handy when creating or editing a document in WinForms Spreadsheet. Learn how to hide them to make the spreadsheet more clean and presentable. +slug: radspreadsheet-howto-hide-row-column-headers-and-gridlines +tags: hide,row,and,column,headers,and,gridlines +published: True +position: 3 +--- + +# Hide Row and Column Headers and Gridlines + +Row and Column headings, as well as worksheet gridlines, are handy when creating or editing a document in __RadSpreadsheet__. However, at times you would want to hide them in order to make the spreadsheet more clean and presentable. This article will teach you about the options provided by RadSpreadsheet that allow you to achieve this. + +## Show or Hide Row and Column Headings + +The __RadWorksheetEditor__ exposes a Boolean property __ShowRowColumnHeadings__. Its default value is true and this makes the row and column headings visible. Setting the property to false as demonstrated in __Example 1__ hides them. + +#### Example 1: Hide Row and Column Headers + + + + + + + +## Show or Hide Gridlines + +If you want to show or hide the gridlines of __RadSpreadsheet__ just set the __ShowGridlines__ Boolean property of __RadWorksheetEditor__ to true for showing the gridlines or false for hiding them. __Example 2__ shows how you can disable the gridlines. + + +#### Example 2: Hide Gridlines + + + + + + + +## See Also + + * [Customize Row and Column Headers]({%slug radspreadsheet-howto-customize-row-column-headers%}) diff --git a/controls/spreadsheet/how-to/restricting-number-of-visible-rows-and-columns.md b/controls/spreadsheet/how-to/restricting-number-of-visible-rows-and-columns.md index f8c28e5f6..e9a84597c 100644 --- a/controls/spreadsheet/how-to/restricting-number-of-visible-rows-and-columns.md +++ b/controls/spreadsheet/how-to/restricting-number-of-visible-rows-and-columns.md @@ -16,19 +16,10 @@ By default the document of __RadSpreadsheet__ presents to the user 1048576 rows __RadSpreadsheetElement__ exposes a __VisibleSize__ property of type __SizeI__ that determines the count of the visible rows and columns. The __SizeI__ structure is similar to Size except that internally it uses integer instead of double values. That said, if you would like to set the visible columns and rows to 50 and 100 respectively, you need to create a __SizeI__ with __Width__ set to 50 and __Height__ set to 100 and assign the instance to the __VisiableSize__ property. Here is a sample snippet that illustrates how to achieve this: -{{source=..\SamplesCS\Spreadsheet\SelectionCode.cs region=Selection_11}} -{{source=..\SamplesVB\Spreadsheet\SelectionCode.vb region=Selection_11}} -````C# -radSpreadsheet.SpreadsheetElement.VisibleSize = new SizeI(5, 10); + + -```` -````VB.NET -radSpreadsheet.SpreadsheetElement.VisibleSize = New SizeI(5, 10) -```` - - -{{endregion}} As a result, __RadSpreadsheet__ displays to the user only 5 columns and 10 rows: diff --git a/controls/spreadsheet/import-export.md b/controls/spreadsheet/import-export.md index e29e52914..53d58c6a8 100644 --- a/controls/spreadsheet/import-export.md +++ b/controls/spreadsheet/import-export.md @@ -38,52 +38,16 @@ To open or save a document with RadSpreadsheet, you can use the **Import()** and #### Example 1: Import XLSX document -{{source=..\SamplesCS\Spreadsheet\Events.cs region=FormatProviderImport}} -{{source=..\SamplesVB\Spreadsheet\Events.vb region=FormatProviderImport}} + + -````C# -XlsxFormatProvider formatProvider = new XlsxFormatProvider(); -using (Stream input = new FileStream(fileName, FileMode.Open)) -{ - this.radSpreadsheet.Workbook = formatProvider.Import(input,null); -} -```` -````VB.NET -Dim formatProvider As New XlsxFormatProvider() -Using input As Stream = New FileStream(fileName, FileMode.Open) - Me.radSpreadsheet.Workbook = formatProvider.Import(input) -End Using - -```` - - -{{endregion}} #### Example 2: Export XLSX document -{{source=..\SamplesCS\Spreadsheet\Events.cs region=FormatProviderExport}} -{{source=..\SamplesVB\Spreadsheet\Events.vb region=FormatProviderExport}} - -````C# -XlsxFormatProvider formatProvider = new XlsxFormatProvider(); -using (Stream output = new FileStream(fileName, FileMode.Create)) -{ - // formatProvider.Export(this.radSpreadsheet.Workbook, output); //This method is obsolete since Q4 2024. - formatProvider.Export(this.radSpreadsheet.Workbook, output, TimeSpan.FromSeconds(10)); -} - -```` -````VB.NET -Dim formatProvider As New XlsxFormatProvider() -Using output As Stream = New FileStream(fileName, FileMode.Create) - ' formatProvider.Export(Me.radSpreadsheet.Workbook, output) This method is obsolete since Q4 2024. - formatProvider.Export(Me.radSpreadsheet.Workbook, output, TimeSpan.FromSeconds(10)) -End Using - -```` - -{{endregion}} + + + >More information about the usage of the format providers is available in the [Formats and Conversion](https://docs.telerik.com/devtools/document-processing/libraries/radspreadprocessing/formats-and-conversion/general-information) section of the documentation for the model of **RadSpreadsheet** - [**RadSpreadProcessing**](https://docs.telerik.com/devtools/document-processing/libraries/radspreadprocessing/overview). diff --git a/controls/spreadsheet/localization.md b/controls/spreadsheet/localization.md index a27a557a6..fc69dab4f 100644 --- a/controls/spreadsheet/localization.md +++ b/controls/spreadsheet/localization.md @@ -1,105 +1,41 @@ ---- -title: Localization -page_title: Localization - WinForms Spreadsheet Control -description: To change the default English localization provider in WinForms Spreadsheet, use the CurrentProvider static property of the SpreadsheetLocalizationProvider class. -slug: radspreadsheet-localization -tags: localization -published: True -position: 7 ---- - -# Localization - -To change the default English localization provider you should use the __CurrentProvider__ static property of the __SpreadsheetLocalizationProvider__ class. For example, you can load the string from a XML file like this: - -{{source=..\SamplesCS\Spreadsheet\Localization.cs region=LoadFromFile}} -{{source=..\SamplesVB\Spreadsheet\Localization.vb region=LoadFromFile}} -````C# -public void FileProvider() -{ - SpreadsheetLocalizationProvider.CurrentProvider = SpreadsheetLocalizationProvider.FromFile(@"C:\SpreadSheedStringsFile"); -} - -```` -````VB.NET -Public Sub FileProvider() - SpreadsheetLocalizationProvider.CurrentProvider = SpreadsheetLocalizationProvider.FromFile("C:\SpreadSheedStringsFile") -End Sub - -```` - - -{{endregion}} - - ->important You can download a XML file that contains all the currently used strings from here: [Strings file](https://github.com/telerik/winforms-sdk/blob/master/Localization%20Providers/SpreadsheetStrings.xml) -> - ->note __SpreadsheetLocalizationProvider__ contains all strings related to the __RadSpreadsheetRibbonBar__ as well. -> - -Another approach is to create a custom localization provider class which inherits __SpreadsheetLocalizationProvider__. In it you should just override the __GetLocalizedString__ method and return the localized string depending on current id. - -{{source=..\SamplesCS\Spreadsheet\Localization.cs region=CustomProvider}} -{{source=..\SamplesVB\Spreadsheet\Localization.vb region=CustomProvider}} -````C# -public class MySpreadsheetLocalizationProvider : SpreadsheetLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - //---------------------- - case "Spreadsheet_Workbook": - return "Spreadsheet Workbook"; - //---------------------- - } - return base.GetLocalizedString(id); - } -} - -```` -````VB.NET -Public Class MySpreadsheetLocalizationProvider - Inherits SpreadsheetLocalizationProvider - Public Overrides Function GetLocalizedString(ByVal id As String) As String - Select Case id - '---------------------- - Case "Spreadsheet_Workbook" - Return "Spreadsheet Workbook" - '---------------------- - End Select - Return MyBase.GetLocalizedString(id) - End Function -End Class - -```` - - -{{endregion}} - -The following code snippet shows how you can use the new class: - -{{source=..\SamplesCS\Spreadsheet\Localization.cs region=ChangeProvider}} -{{source=..\SamplesVB\Spreadsheet\Localization.vb region=ChangeProvider}} -````C# -public Localization() -{ - SpreadsheetLocalizationProvider.CurrentProvider = new MySpreadsheetLocalizationProvider(); - InitializeComponent(); -} - -```` -````VB.NET -Public Sub New() - SpreadsheetLocalizationProvider.CurrentProvider = New MySpreadsheetLocalizationProvider() - InitializeComponent() -End Sub - -```` - - -{{endregion}} - ->note It is necessary to set the SpreadsheetLocalizationProvider. __CurrentProvider__ property before initializing the components. -> \ No newline at end of file +--- +title: Localization +page_title: Localization - WinForms Spreadsheet Control +description: To change the default English localization provider in WinForms Spreadsheet, use the CurrentProvider static property of the SpreadsheetLocalizationProvider class. +slug: radspreadsheet-localization +tags: localization +published: True +position: 7 +--- + +# Localization + +To change the default English localization provider you should use the __CurrentProvider__ static property of the __SpreadsheetLocalizationProvider__ class. For example, you can load the string from a XML file like this: + + + + + + +>important You can download a XML file that contains all the currently used strings from here: [Strings file](https://github.com/telerik/winforms-sdk/blob/master/Localization%20Providers/SpreadsheetStrings.xml) +> + +>note __SpreadsheetLocalizationProvider__ contains all strings related to the __RadSpreadsheetRibbonBar__ as well. +> + +Another approach is to create a custom localization provider class which inherits __SpreadsheetLocalizationProvider__. In it you should just override the __GetLocalizedString__ method and return the localized string depending on current id. + + + + + + +The following code snippet shows how you can use the new class: + + + + + + +>note It is necessary to set the SpreadsheetLocalizationProvider. __CurrentProvider__ property before initializing the components. +> diff --git a/controls/syntax-editor/commands.md b/controls/syntax-editor/commands.md index c6f055ad6..39e98d654 100644 --- a/controls/syntax-editor/commands.md +++ b/controls/syntax-editor/commands.md @@ -38,18 +38,8 @@ The following example demonstrates how you can use commands to navigate and dele #### Example 1: Using commands in code-behind -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorGettingStarted.cs region=Commands}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorGettingStarted.vb region=Commands}} + + -````C# -this.radSyntaxEditor1.Commands.NavigateNextMatchCommand.Execute("Telerik"); -this.radSyntaxEditor1.Commands.DeleteCommand.Execute(null); -```` -````VB.NET -Me.radSyntaxEditor1.Commands.NavigateNextMatchCommand.Execute("Telerik") -Me.radSyntaxEditor1.Commands.DeleteCommand.Execute(Nothing) -```` - -{{endregion}} diff --git a/controls/syntax-editor/features/caret.md b/controls/syntax-editor/features/caret.md index f74ee208c..7dac5fb46 100644 --- a/controls/syntax-editor/features/caret.md +++ b/controls/syntax-editor/features/caret.md @@ -21,19 +21,10 @@ The caret of **RadSyntaxEditor** is a vertical 'blinking' line that represents t #### Setting the caret's display mode -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorGettingStarted.cs region=SetCaretDisplayMode}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorGettingStarted.vb region=SetCaretDisplayMode}} + + -````C# -this.radSyntaxEditor1.CaretDisplayMode = CaretDisplayMode.QuarterBlock; -```` -````VB.NET -Me.RadSyntaxEditor1.CaretDisplayMode = CaretDisplayMode.QuarterBlock - -```` - -{{endregion}} ## Hide the Caret @@ -41,21 +32,10 @@ If you want to hide the caret, you can do so by setting the **IsCaretVisible** p #### Setting the caret's display mode -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorGettingStarted.cs region=HideCaret}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorGettingStarted.vb region=HideCaret}} - -````C# -this.radSyntaxEditor1.IsCaretVisible = false; -this.radSyntaxEditor1.SyntaxEditorElement.IsReadOnly = true; - -```` -````VB.NET -Me.RadSyntaxEditor1.IsCaretVisible = False -Me.RadSyntaxEditor1.SyntaxEditorElement.IsReadOnly = True + + -```` -{{endregion}} ## Caret Color @@ -63,19 +43,10 @@ Through the **CaretColor** property, you can change the caret's color to a color #### Setting the caret's color -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorGettingStarted.cs region=CaretColor}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorGettingStarted.vb region=CaretColor}} + + -````C# -this.radSyntaxEditor1.CaretColor = Color.Red; -```` -````VB.NET -Me.RadSyntaxEditor1.CaretColor = Color.Red - -```` - -{{endregion}} #### Figure 2: RadSyntaxEditor caret with red color ![WinForms RadSyntaxEditor with Red Caret](images/caret005.png) @@ -84,19 +55,10 @@ Me.RadSyntaxEditor1.CaretColor = Color.Red **CaretPosition** property provides information about the position of the caret and gives opportunity to manage it. For example, by default the caret is displayed at the beggining of the document. You can change its position so that it shows at the end of the document by using the **MoveToEndOfDocument** method: -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorGettingStarted.cs region=CaretPosition}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorGettingStarted.vb region=CaretPosition}} - -````C# -this.radSyntaxEditor1.SyntaxEditorElement.CaretPosition.MoveToEndOfDocument(); - -```` -````VB.NET -Me.RadSyntaxEditor1.SyntaxEditorElement.CaretPosition.MoveToEndOfDocument() + + -```` -{{endregion}} Another useful methods are listed below: diff --git a/controls/syntax-editor/features/fonts.md b/controls/syntax-editor/features/fonts.md index e64f9d01a..9d75a25ad 100644 --- a/controls/syntax-editor/features/fonts.md +++ b/controls/syntax-editor/features/fonts.md @@ -14,21 +14,10 @@ position: 7 #### Example 1: Setting font properties -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorLayers.cs region= Font}} -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorLayers.vb region= Font}} + + -````C# -this.radSyntaxEditor1.SyntaxEditorElement.EditorFontSize = 18f; -this.radSyntaxEditor1.SyntaxEditorElement.EditorFontFamily = new Telerik.WinControls.SyntaxEditor.UI.FontFamily("TimesNewRoman"); - - -```` -````VB.NET -Me.RadSyntaxEditor1.SyntaxEditorElement.EditorFontSize = 18.0F -Me.RadSyntaxEditor1.SyntaxEditorElement.EditorFontFamily = New Telerik.WinControls.SyntaxEditor.UI.FontFamily("TimesNewRoman") - -```` These properties, however, will be applied to the line numbers, editor presenter and intelliprompt parts of the control. @@ -40,21 +29,8 @@ When the used font is **Consolas**, **Courier New** or **Lucida Console**, you c #### Example 2: Enabling monospaced font optimization -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorLayers.cs region= Optimization}} -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorLayers.vb region= Optimization}} - -````C# - -this.radSyntaxEditor1.SyntaxEditorElement.UseMonospacedFontOptimization = true; - -```` -````VB.NET -Me.RadSyntaxEditor1.SyntaxEditorElement.UseMonospacedFontOptimization = True - -```` - - + + - diff --git a/controls/syntax-editor/features/intelliprompts.md b/controls/syntax-editor/features/intelliprompts.md index d08a9296a..ee0f2430b 100644 --- a/controls/syntax-editor/features/intelliprompts.md +++ b/controls/syntax-editor/features/intelliprompts.md @@ -18,35 +18,10 @@ You can show a collection of items when the user inputs a given string through t #### Example 1: Populate and display the completion list window -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorGettingStarted.cs region=IntelliPrompts}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorGettingStarted.vb region=IntelliPrompts}} + + -````C# -CompletionInfoCollection completionList = new CompletionInfoCollection() -{ - new CompletionInfo("Collapsed", "Indicates that the element is collapsed.", Image.FromFile(@"../../SyntaxEditor/Entity-Enum.png")), - new CompletionInfo("Hidden", "Indicates that the element is hidden.",Image.FromFile(@"../../SyntaxEditor/Entity-Enum.png")), - new CompletionInfo("Visible", "Indicates that the element is visible." ,Image.FromFile(@"../../SyntaxEditor/Entity-Enum.png")), -}; - -this.radSyntaxEditor1.SyntaxEditorElement.IntelliPrompts.CompletionListWindow.Presenter.CompletionListItems = completionList; - -```` -````VB.NET - -Dim CompletionList As CompletionInfoCollection = New CompletionInfoCollection() From -{ - New CompletionInfo("Collapsed", "Indicates that the element is collapsed.", Image.FromFile("../../SyntaxEditor/Entity-Enum.png")), - New CompletionInfo("Hidden", "Indicates that the element is hidden.", Image.FromFile("../../SyntaxEditor/Entity-Enum.png")), - New CompletionInfo("Visible", "Indicates that the element is visible.", Image.FromFile("../../SyntaxEditor/Entity-Enum.png")) -} - -Me.RadSyntaxEditor1.SyntaxEditorElement.IntelliPrompts.CompletionListWindow.Presenter.CompletionListItems = CompletionList - -```` - -{{endregion}} #### Figure 1: Code completion ![WinForms RadSyntaxEditor's Code completion](images/intelliprompts001.png) @@ -59,34 +34,10 @@ Through the **OverloadListWindow** you can show a collection of overloads when t #### Example 2: Populate and display the completion list window -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorGettingStarted.cs region=}} - -````C# - -OverloadInfoCollection overloadList = new OverloadInfoCollection -{ - new OverloadInfo("Span? RadSyntaxEditor.Find(string searchText, int startIndex)", "Finds the specified search text.
searchText: The search text."), - new OverloadInfo("signature2signature2signature2signature2signature2", "description2"), -}; - -this.radSyntaxEditor1.SyntaxEditorElement.IntelliPrompts.OverloadListWindow.Presenter.OverloadListItems = overloadList; -this.radSyntaxEditor1.SyntaxEditorElement.IntelliPrompts.OverloadListWindow.Show(); - -```` -````VB.NET - -Dim OverloadList As OverloadInfoCollection = New OverloadInfoCollection From -{ - New OverloadInfo("Span? RadSyntaxEditor.Find(string searchText, int startIndex)", "Finds the specified search text.
searchText: The search text."), - New OverloadInfo("signature2signature2signature2signature2signature2", "description2") -} - -Me.RadSyntaxEditor1.SyntaxEditorElement.IntelliPrompts.OverloadListWindow.Presenter.OverloadListItems = OverloadLis -Me.RadSyntaxEditor1.SyntaxEditorElement.IntelliPrompts.OverloadListWindow.Show() + + -```` -{{endregion}} #### Figure 2: Code completion ![WinForms RadSyntaxEditor Show Code completion](images/intelliprompts002.png) diff --git a/controls/syntax-editor/features/keyboard-support.md b/controls/syntax-editor/features/keyboard-support.md index 16bbfd300..2501b684b 100644 --- a/controls/syntax-editor/features/keyboard-support.md +++ b/controls/syntax-editor/features/keyboard-support.md @@ -49,29 +49,8 @@ The keyboard combinations supported by the **RadSyntaxEditor** are listed in the If you need to handle a key combination which is not listed above, you can do so by handling the **PreviewSyntaxEditorKeyDown** event. -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorLayers.cs region=Keyboard}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorLayers.vb region=Keyboard}} + + -````C# -private void radSyntaxEditor1_PreviewSyntaxEditorKeyDown(object sender, PreviewSyntaxEditorKeyEventArgs e) -{ - if (e.Key == Keys.S && Keyboard.Modifiers == Keys.Control) - { - e.OriginalArgs.Handled = true; - } -} -```` -````VB.NET -Private Sub RadSyntaxEditor_PreviewSyntaxEditorKeyDown(sender As Object, e As PreviewSyntaxEditorKeyEventArgs) - If e.Key = Keys.S AndAlso Telerik.WinControls.SyntaxEditor.UI.Keyboard.Modifiers = Keys.Control Then - e.OriginalArgs.Handled = True - End If -End Sub - -```` - -{{endregion}} - - diff --git a/controls/syntax-editor/features/layers.md b/controls/syntax-editor/features/layers.md index 29b90cd96..a81e4775d 100644 --- a/controls/syntax-editor/features/layers.md +++ b/controls/syntax-editor/features/layers.md @@ -28,191 +28,35 @@ We will now create a custom layer which will be responsible for highlighting any #### Creating a custom layer -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorLayers.cs region=CustomLayer}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorLayers.vb region=CustomLayer}} - -````C# - -public class CommentsUILayer : LineBasedUILayer -{ - public override string Name - { - get - { - return "UnderlineOnMouseOver"; - } - } - - public CommentsUILayer() - { - } - - protected override FrameworkElement GetLinePartUIElement(Telerik.WinForms.SyntaxEditor.Core.Tagging.ClassificationTag tag, - Telerik.WinForms.SyntaxEditor.Core.Text.Span span, UIUpdateContext updateContext) - { - if (tag.ClassificationType != Telerik.WinForms.SyntaxEditor.Core.Tagging.ClassificationTypes.Comment) - { - return null; - } - - Rect rect = updateContext.Editor.GetLinePartBoundingRectangle(span); - Telerik.WinControls.SyntaxEditor.UI.Rectangle rectangle = this.GetElementFromPool(); - rectangle.ShouldHandleMouseInput = true; - rectangle.Width = rect.Width; - rectangle.Height = rect.Height; - rectangle.Fill = new SolidBrush(System.Drawing.Color.FromArgb(100, System.Drawing.Color.LightGray)); - - return rectangle; - } - - protected override void ResetPooledElementProperties(object element) - { - Telerik.WinControls.SyntaxEditor.UI.Rectangle rectangle = (Telerik.WinControls.SyntaxEditor.UI.Rectangle)element; - rectangle.ClearValue(Telerik.WinControls.SyntaxEditor.UI.Rectangle.FillProperty); - } -} - - -```` -````VB.NET - -Public Class CommentsUILayer - Inherits LineBasedUILayer(Of Telerik.WinForms.SyntaxEditor.Core.Tagging.ClassificationTag) - - Public Overrides ReadOnly Property Name As String - Get - Return "UnderlineOnMouseOver" - End Get - End Property - - Public Sub New() - End Sub - - Protected Overrides Function GetLinePartUIElement(ByVal tag As Telerik.WinForms.SyntaxEditor.Core.Tagging.ClassificationTag, _ - ByVal span As Telerik.WinForms.SyntaxEditor.Core.Text.Span, ByVal updateContext As UIUpdateContext) _ - As Telerik.WinControls.SyntaxEditor.UI.FrameworkElement - If Not tag.ClassificationType.Equals(Telerik.WinForms.SyntaxEditor.Core.Tagging.ClassificationTypes.Comment) Then - Return Nothing - End If - - Dim rect As Telerik.WinControls.SyntaxEditor.UI.Rect = updateContext.Editor.GetLinePartBoundingRectangle(span) - Dim rectangle As Telerik.WinControls.SyntaxEditor.UI.Rectangle = Me.GetElementFromPool(Of Telerik.WinControls.SyntaxEditor.UI.Rectangle)() - rectangle.ShouldHandleMouseInput = True - rectangle.Width = rect.Width - rectangle.Height = rect.Height - rectangle.Fill = New SolidBrush(System.Drawing.Color.FromArgb(100, System.Drawing.Color.LightGray)) - Return rectangle - End Function - - Protected Overrides Sub ResetPooledElementProperties(ByVal element As Object) - Dim rectangle As Telerik.WinControls.SyntaxEditor.UI.Rectangle = CType(element, Telerik.WinControls.SyntaxEditor.UI.Rectangle) - rectangle.ClearValue(Telerik.WinControls.SyntaxEditor.UI.Rectangle.FillProperty) - End Sub -End Class - -```` - -{{endregion}} + + + For our custom layer to be recognized by the **RadSyntaxEditor** we need to add it to the **UILayerStack**. We can do so by creating a custom **UILayersBuilder** and overriding its **BuildUILayers** method. #### Using the custom layer in a custom layers builder -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorLayers.cs region=Builder}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorLayers.vb region=Builder}} - -````C# - -public class CustomUILayersBuilder : Telerik.WinForms.Controls.SyntaxEditor.UI.Layers.UILayersBuilder -{ - private CommentsUILayer customLayer; - public override void BuildUILayers(UILayerStack uiLayers) - { - base.BuildUILayers(uiLayers); - - customLayer = new CommentsUILayer(); - uiLayers.AddLast(customLayer); - } - - public void ClearCustomLayer() - { - foreach (Telerik.WinControls.SyntaxEditor.UI.Rectangle item in this.customLayer.Container.Children.OfType()) - { - item.Fill = System.Drawing.Brushes.Transparent; - } - } -} - -```` -````VB.NET -Public Class CustomUILayersBuilder - Inherits Telerik.WinForms.Controls.SyntaxEditor.UI.Layers.UILayersBuilder - - Private customLayer As CommentsUILayer - - Public Overrides Sub BuildUILayers(ByVal uiLayers As Telerik.WinForms.Controls.SyntaxEditor.UI.Layers.UILayerStack) - MyBase.BuildUILayers(uiLayers) - customLayer = New CommentsUILayer() - uiLayers.AddLast(customLayer) - End Sub - - Public Sub ClearCustomLayer() - For Each item As Telerik.WinControls.SyntaxEditor.UI.Rectangle In Me.customLayer.Container.Children.OfType(Of Telerik.WinControls.SyntaxEditor.UI.Rectangle)() - item.Fill = System.Drawing.Brushes.Transparent - Next - End Sub -End Class + + -```` - -{{endregion}} Finally, we need to set the **UILayersBuilder** to an instance of the custom layers builder class. #### Using the custom layers builder -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorLayers.cs region=Apply}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorLayers.vb region=Apply}} - -````C# - -this.radSyntaxEditor1.SyntaxEditorElement.UILayersBuilder = new CustomUILayersBuilder(); + + -```` -````VB.NET -Me.RadSyntaxEditor1.SyntaxEditorElement.UILayersBuilder = New CustomUILayersBuilder() -```` - -{{endregion}} Consider that we have the following taggers applied to **RadSyntaxEditor**: -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorLayers.cs region=AddTaggers}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorLayers.vb region=AddTaggers}} - -````C# - CSharpTagger currentLanguageTagger = new Telerik.WinForms.Controls.SyntaxEditor.Tagging.Taggers.CSharpTagger(this.radSyntaxEditor1.SyntaxEditorElement); - this.radSyntaxEditor1.TaggersRegistry.RegisterTagger(currentLanguageTagger); - - CSharpFoldingTagger foldingTagger = new Telerik.WinForms.Controls.SyntaxEditor.Taggers.CSharpFoldingTagger(this.radSyntaxEditor1.SyntaxEditorElement); - foldingTagger.FoldingRegionDefinitions.Add(new FoldingRegionDefinition("#if", "#endif")); - -```` -````VB.NET - -Dim currentLanguageTagger As CSharpTagger = New Telerik.WinForms.Controls.SyntaxEditor.Taggers.CSharpTagger(Me.RadSyntaxEditor1.SyntaxEditorElement) -Me.RadSyntaxEditor1.TaggersRegistry.RegisterTagger(currentLanguageTagger) -Dim foldingTagger As CSharpFoldingTagger = New Telerik.WinForms.Controls.SyntaxEditor.Taggers.CSharpFoldingTagger(Me.RadSyntaxEditor1.SyntaxEditorElement) -foldingTagger.FoldingRegionDefinitions.Add(New FoldingRegionDefinition("#if", "#endif")) -RadSyntaxEditor1.TaggersRegistry.RegisterTagger(foldingTagger) - + + -```` -{{endregion}} Once you run the application, the comments are expected to be colored as it is illustrated below: diff --git a/controls/syntax-editor/features/margins.md b/controls/syntax-editor/features/margins.md index 57ceda98c..7fdc25ea9 100644 --- a/controls/syntax-editor/features/margins.md +++ b/controls/syntax-editor/features/margins.md @@ -18,60 +18,10 @@ The following example demonstrates how you can add some custom elements around t #### Defining Simple Margins -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorMargins.cs region=SimpleMargins}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorMargins.vb region=SimpleMargins}} - -````C# -this.radSyntaxEditor1.SyntaxEditorElement.Margins.Left.Add(new Telerik.WinControls.SyntaxEditor.UI.Rectangle() { Fill = Brushes.LightYellow, Width = 20 }); -this.radSyntaxEditor1.SyntaxEditorElement.Margins.Right.Add(new Telerik.WinControls.SyntaxEditor.UI.Rectangle() { Fill = Brushes.LightGreen, Width = 20 }); -this.radSyntaxEditor1.SyntaxEditorElement.Margins.Top.Add(new Telerik.WinControls.SyntaxEditor.UI.Rectangle() { Fill = Brushes.LightPink, Height = 20 }); -this.radSyntaxEditor1.SyntaxEditorElement.Margins.Bottom.Add(new Telerik.WinControls.SyntaxEditor.UI.Rectangle() { Fill = Brushes.LightSkyBlue, Height = 20 }); - -this.radSyntaxEditor1.SyntaxEditorElement.Margins.ScrollableLeft.Add(new Telerik.WinControls.SyntaxEditor.UI.Rectangle() { Fill = Brushes.LightBlue, Width = 20 }); -this.radSyntaxEditor1.SyntaxEditorElement.Margins.ScrollableRight.Add(new Telerik.WinControls.SyntaxEditor.UI.Rectangle() { Fill = Brushes.LightSeaGreen, Width = 20 }); -this.radSyntaxEditor1.SyntaxEditorElement.Margins.ScrollableTop.Add(new Telerik.WinControls.SyntaxEditor.UI.Rectangle() { Fill = Brushes.LightCoral, Height = 20 }); -this.radSyntaxEditor1.SyntaxEditorElement.Margins.ScrollableBottom.Add(new Telerik.WinControls.SyntaxEditor.UI.Rectangle() { Fill = Brushes.LightGray, Height = 20 }); - -```` -````VB.NET -Private Sub SetupSimpleMargins() - Me.RadSyntaxEditor1.SyntaxEditorElement.Margins.Left.Add(New Telerik.WinControls.SyntaxEditor.UI.Rectangle() With { - .Fill = Brushes.LightYellow, - .Width = 20 - }) - Me.RadSyntaxEditor1.SyntaxEditorElement.Margins.Right.Add(New Telerik.WinControls.SyntaxEditor.UI.Rectangle() With { - .Fill = Brushes.LightGreen, - .Width = 20 - }) - Me.RadSyntaxEditor1.SyntaxEditorElement.Margins.Top.Add(New Telerik.WinControls.SyntaxEditor.UI.Rectangle() With { - .Fill = Brushes.LightPink, - .Height = 20 - }) - Me.RadSyntaxEditor1.SyntaxEditorElement.Margins.Bottom.Add(New Telerik.WinControls.SyntaxEditor.UI.Rectangle() With { - .Fill = Brushes.LightSkyBlue, - .Height = 20 - }) - Me.RadSyntaxEditor1.SyntaxEditorElement.Margins.ScrollableLeft.Add(New Telerik.WinControls.SyntaxEditor.UI.Rectangle() With { - .Fill = Brushes.LightBlue, - .Width = 20 - }) - Me.RadSyntaxEditor1.SyntaxEditorElement.Margins.ScrollableRight.Add(New Telerik.WinControls.SyntaxEditor.UI.Rectangle() With { - .Fill = Brushes.LightSeaGreen, - .Width = 20 - }) - Me.RadSyntaxEditor1.SyntaxEditorElement.Margins.ScrollableTop.Add(New Telerik.WinControls.SyntaxEditor.UI.Rectangle() With { - .Fill = Brushes.LightCoral, - .Height = 20 - }) - Me.RadSyntaxEditor1.SyntaxEditorElement.Margins.ScrollableBottom.Add(New Telerik.WinControls.SyntaxEditor.UI.Rectangle() With { - .Fill = Brushes.LightGray, - .Height = 20 - }) -End Sub - -```` - -{{endregion}} + + + + >caption Figure 1: Defining Simple Margins @@ -91,94 +41,10 @@ This example demonstrates how to create a margin which holds a collection of bre #### Defining Breakpoints Margins -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorMargins.cs region=BreakpointsMargin}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorMargins.vb region=BreakpointsMargin}} - -````C# -private void SetupBreakPoints() -{ - BreakpointsMargin breakpointsMargin = new BreakpointsMargin(this.radSyntaxEditor1.SyntaxEditorElement); - this.radSyntaxEditor1.SyntaxEditorElement.Margins.ScrollableLeft.Insert(0, breakpointsMargin); -} - -/// -/// A margin holding a collection of breakpoints to highlight lines of the RadSyntaxEditor control. -/// -public class BreakpointsMargin : IndicatorsMargin -{ - /// - /// Initializes a new instance of the class. - /// - /// The RadSyntaxEditor instance. - public BreakpointsMargin(RadSyntaxEditorElement syntaxEditor) - : base(syntaxEditor) - { - this.IndicatorBrush = new SolidBrush(System.Drawing.Color.FromArgb(255, 210, 47, 47)); - } - - /// - /// Called when an indicator needs to be updated. This can happen when the indicator is - /// first created, when it is brought inside or outside of the viewport or when - /// the EditorFontSize property of the RadSyntaxEditor or the IndicatorBrush property - /// of the margin change. - /// - /// The Path to update. - /// The line number the indicator is placed on. - protected override void UpdateIndicator(Ellipse ellipse, int lineNumber) - { - if (ellipse.Width != this.Editor.EditorFontSize) - { - ellipse.Width = this.Editor.EditorFontSize; - } - - if (ellipse.Height != this.Editor.EditorFontSize) - { - ellipse.Height = this.Editor.EditorFontSize; - } - - if (ellipse.Background != this.IndicatorBrush) - { - ellipse.Background = this.IndicatorBrush; - } - } -} - - -```` -````VB.NET -Private Sub SetupBreakPoints() - Dim breakpointsMargin As BreakpointsMargin = New BreakpointsMargin(Me.RadSyntaxEditor1.SyntaxEditorElement) - Me.RadSyntaxEditor1.SyntaxEditorElement.Margins.ScrollableLeft.Insert(0, breakpointsMargin) -End Sub - -Public Class BreakpointsMargin - Inherits IndicatorsMargin(Of Ellipse) - - Public Sub New(ByVal syntaxEditor As RadSyntaxEditorElement) - MyBase.New(syntaxEditor) - Me.IndicatorBrush = New SolidBrush(System.Drawing.Color.FromArgb(255, 210, 47, 47)) - End Sub - - Protected Overrides Sub UpdateIndicator(ByVal ellipse As Ellipse, ByVal lineNumber As Integer) - If ellipse.Width <> Me.Editor.EditorFontSize Then - ellipse.Width = Me.Editor.EditorFontSize - End If - - If ellipse.Height <> Me.Editor.EditorFontSize Then - ellipse.Height = Me.Editor.EditorFontSize - End If - - If ellipse.Background Is Nothing Then - ellipse.Background = Me.IndicatorBrush - ElseIf Not ellipse.Background.Equals(Me.IndicatorBrush) Then - ellipse.Background = Me.IndicatorBrush - End If - End Sub -End Class - -```` - -{{endregion}} + + + + >caption Figure 2: Defining Breakpoint Margins @@ -192,108 +58,10 @@ This example demonstrates how to create a margin which holds a collection of boo #### Defining Bookmarks Margins -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorMargins.cs region=BookmarksMargin}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorMargins.vb region=BookmarksMargin}} - -````C# -private void SetupBookmarkMargins() -{ - BookmarksMargin bookmarksMargin = new BookmarksMargin(this.radSyntaxEditor1.SyntaxEditorElement); - this.radSyntaxEditor1.SyntaxEditorElement.Margins.ScrollableLeft.Insert(0, bookmarksMargin); -} -public class BookmarksMargin : GlyphsMargin -{ - private const string BookmarksGlyph = "\uF02E"; - - public BookmarksMargin(RadSyntaxEditorElement syntaxEditor) - : base(syntaxEditor) - { - this.CustomFont = "Font Awesome 5 Free Solid"; - } - - protected override void UpdateIndicator(TextBlock element, int lineNumber) - { - base.UpdateIndicator(element, lineNumber); - - element.Margin = new System.Windows.Forms.Padding(2, 0, 0, 0); - } - - public override string GetGlyph() - { - return BookmarksGlyph; - } -} - -public abstract class GlyphsMargin : IndicatorsMargin -{ - public GlyphsMargin(RadSyntaxEditorElement syntaxEditor) - : base(syntaxEditor) - { - } - - protected override void UpdateIndicator(TextBlock element, int lineNumber) - { - element.Width = this.Width; - element.Height = this.Width; - - element.FontFamily = new FontFamily(this.CustomFont); - element.Foreground = this.IndicatorBrush; - element.Text = this.GetGlyph(); - element.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; - } - - public abstract string GetGlyph(); -} - -```` -````VB.NET -Private Sub SetupBookmarkMargins() - Dim bookmarksMargin As BookmarksMargin = New BookmarksMargin(Me.RadSyntaxEditor1.SyntaxEditorElement) - Me.RadSyntaxEditor1.SyntaxEditorElement.Margins.ScrollableLeft.Insert(0, bookmarksMargin) -End Sub - -Public Class BookmarksMargin - Inherits GlyphsMargin - - Private Const BookmarksGlyph As String = "" - - Public Sub New(ByVal syntaxEditor As RadSyntaxEditorElement) - MyBase.New(syntaxEditor) - Me.CustomFont = "Font Awesome 5 Free Solid" - End Sub - - Protected Overrides Sub UpdateIndicator(ByVal element As TextBlock, ByVal lineNumber As Integer) - MyBase.UpdateIndicator(element, lineNumber) - element.Margin = New System.Windows.Forms.Padding(2, 0, 0, 0) - End Sub - - Public Overrides Function GetGlyph() As String - Return BookmarksGlyph - End Function -End Class - -Public MustInherit Class GlyphsMargin - Inherits IndicatorsMargin(Of TextBlock) - - Public Sub New(ByVal syntaxEditor As RadSyntaxEditorElement) - MyBase.New(syntaxEditor) - End Sub - - Protected Overrides Sub UpdateIndicator(ByVal element As TextBlock, ByVal lineNumber As Integer) - element.Width = Me.Width - element.Height = Me.Width - element.FontFamily = New FontFamily(Me.CustomFont) - element.Foreground = Me.IndicatorBrush - element.Text = Me.GetGlyph() - element.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality - End Sub - - Public MustOverride Function GetGlyph() As String -End Class - -```` - -{{endregion}} + + + + >caption Figure 3: Defining Bookmarks Margins @@ -305,60 +73,10 @@ Using the **GlyphsMargin** implementation in the previous example, we can constr #### Defining Stars Margins -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorMargins.cs region=StarsMargins}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorMargins.vb region=StarsMargins}} - -````C# -private void SetupStarsMargins() -{ - StarsMargin starsMargin = new StarsMargin(this.radSyntaxEditor1.SyntaxEditorElement); - this.radSyntaxEditor1.SyntaxEditorElement.Margins.ScrollableLeft.Insert(0, starsMargin); -} - -public class StarsMargin : GlyphsMargin -{ - private const string StarGlyph = "\uF005"; - - public StarsMargin(RadSyntaxEditorElement syntaxEditor) - : base(syntaxEditor) - { - this.Background = new System.Drawing.SolidBrush(System.Drawing.Color.LightGray); + + - this.CustomFont = "Font Awesome 5 Free Regular"; - } - public override string GetGlyph() - { - return StarGlyph; - } -} - -```` -````VB.NET -Private Sub SetupStarsMargins() - Dim starsMargin As StarsMargin = New StarsMargin(Me.RadSyntaxEditor1.SyntaxEditorElement) - Me.RadSyntaxEditor1.SyntaxEditorElement.Margins.ScrollableLeft.Insert(0, starsMargin) -End Sub - -Public Class StarsMargin - Inherits GlyphsMargin - - Private Const StarGlyph As String = "" - - Public Sub New(ByVal syntaxEditor As RadSyntaxEditorElement) - MyBase.New(syntaxEditor) - Me.Background = New System.Drawing.SolidBrush(System.Drawing.Color.LightGray) - Me.CustomFont = "Font Awesome 5 Free Regular" - End Sub - - Public Overrides Function GetGlyph() As String - Return StarGlyph - End Function -End Class - -```` - -{{endregion}} >caption Figure 4: Defining Stars Margins @@ -370,191 +88,10 @@ It is possible to create an indicator with a vector image which is scaled proper #### Defining SvgsMargins -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorMargins.cs region=SvgMargins}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorMargins.vb region=SvgMargins}} - -````C# -private void SetupSvgMargins() -{ - SvgsMargin svgsMargin = new SvgsMargin(this.radSyntaxEditor1.SyntaxEditorElement) - { - SvgImage = RadSvgImage.Deserialize(File.ReadAllText(@"..\..\Resources\insert merge field-01.svg")) - }; - this.radSyntaxEditor1.SyntaxEditorElement.Margins.ScrollableRight.Insert(0, svgsMargin); -} - -/// -/// A margin holding a collection of breakpoints to highlight lines of the RadSyntaxEditor control. -/// -public class SvgsMargin : IndicatorsMargin -{ - /// - /// Initializes a new instance of the class. - /// - /// The RadSyntaxEditor instance. - public SvgsMargin(RadSyntaxEditorElement syntaxEditor) - : base(syntaxEditor) - { - } - - public RadSvgImage SvgImage { get; set; } - - protected override void UpdateIndicator(RadSvgFrameworkElement svgElement, int lineNumber) - { - svgElement.SvgImage = this.SvgImage; - if (svgElement.Width != this.Editor.EditorFontSize) - { - svgElement.Width = this.Editor.EditorFontSize; - } - - if (svgElement.Height != this.Editor.EditorFontSize) - { - svgElement.Height = this.Editor.EditorFontSize; - } - } -} - -public class RadSvgFrameworkElement : FrameworkElement, IImageElement -{ - private ImagePrimitiveImpl imagePrimitiveImpl; - - private RadSvgImage svgImage; - - protected override void InitializeFields() - { - base.InitializeFields(); - - this.imagePrimitiveImpl = new ImagePrimitiveImpl(this); - } - - public RadSvgImage SvgImage - { - get - { - return this.svgImage; - } - set - { - this.svgImage = value; - } - } - - public System.Drawing.Image Image { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } - public int ImageIndex { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } - public string ImageKey { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } - - protected override void PaintElement(IGraphics graphics, float angle, System.Drawing.SizeF scale) - { - base.PaintElement(graphics, angle, scale); - - this.PaintImage(graphics, this.SvgImage); - } - - private void PaintImage(IGraphics graphics, RadSvgImage image) - { - image.Width = this.Bounds.Width; - image.Height = this.Bounds.Height; - - this.imagePrimitiveImpl.PaintImage(graphics, image, this.Bounds, - ImageLayout.Center, ContentAlignment.MiddleCenter, 1f, false); - } -} - -```` -````VB.NET -Private Sub SetupSvgMargins() - Dim svgsMargin As SvgsMargin = New SvgsMargin(Me.RadSyntaxEditor1.SyntaxEditorElement) With { - .SvgImage = RadSvgImage.Deserialize(File.ReadAllText("..\..\Resources\insert merge field-01.svg")) - } - Me.RadSyntaxEditor1.SyntaxEditorElement.Margins.ScrollableRight.Insert(0, svgsMargin) -End Sub - -Public Class SvgsMargin - Inherits IndicatorsMargin(Of RadSvgFrameworkElement) - - Public Sub New(ByVal syntaxEditor As RadSyntaxEditorElement) - MyBase.New(syntaxEditor) - End Sub - - Public Property SvgImage As RadSvgImage - - Protected Overrides Sub UpdateIndicator(ByVal svgElement As RadSvgFrameworkElement, ByVal lineNumber As Integer) - svgElement.SvgImage = Me.SvgImage - - If svgElement.Width <> Me.Editor.EditorFontSize Then - svgElement.Width = Me.Editor.EditorFontSize - End If - - If svgElement.Height <> Me.Editor.EditorFontSize Then - svgElement.Height = Me.Editor.EditorFontSize - End If - End Sub -End Class - -Public Class RadSvgFrameworkElement - Inherits FrameworkElement - Implements IImageElement - - Private imagePrimitiveImpl As ImagePrimitiveImpl - Private _svgImage As RadSvgImage - - Protected Overrides Sub InitializeFields() - MyBase.InitializeFields() - Me.imagePrimitiveImpl = New ImagePrimitiveImpl(Me) - End Sub - - Public Property SvgImage As RadSvgImage - Get - Return Me._svgImage - End Get - Set(ByVal value As RadSvgImage) - Me._svgImage = value - End Set - End Property - - Public Property Image As System.Drawing.Image Implements IImageElement.Image - Get - Throw New NotImplementedException() - End Get - Set(value As System.Drawing.Image) - Throw New NotImplementedException() - End Set - End Property - - Public Property ImageIndex As Integer Implements IImageElement.ImageIndex - Get - Throw New NotImplementedException() - End Get - Set(value As Integer) - Throw New NotImplementedException() - End Set - End Property - - Public Property ImageKey As String Implements IImageElement.ImageKey - Get - Throw New NotImplementedException() - End Get - Set(value As String) - Throw New NotImplementedException() - End Set - End Property - - Protected Overrides Sub PaintElement(ByVal graphics As IGraphics, ByVal angle As Single, ByVal scale As System.Drawing.SizeF) - MyBase.PaintElement(graphics, angle, scale) - Me.PaintImage(graphics, Me.SvgImage) - End Sub - - Private Sub PaintImage(ByVal graphics As IGraphics, ByVal image As RadSvgImage) - image.Width = Me.Bounds.Width - image.Height = Me.Bounds.Height - Me.imagePrimitiveImpl.PaintImage(graphics, image, Me.Bounds, ImageLayout.Center, ContentAlignment.MiddleCenter, 1.0F, False) - End Sub - -End Class - -```` - -{{endregion}} + + + + >caption Figure 5: Defining SVG Margins diff --git a/controls/syntax-editor/features/palettes.md b/controls/syntax-editor/features/palettes.md index e1eaf6062..b2ed00d2d 100644 --- a/controls/syntax-editor/features/palettes.md +++ b/controls/syntax-editor/features/palettes.md @@ -259,30 +259,10 @@ Here is a list of all the colors in the palettes and their default values for ea It is possible to change the palette according to which theme you prefer to use in your application. Here is an example: -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorGettingStarted.cs region=ChangeTheme}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorGettingStarted.vb region=ChangeTheme}} + + -````C# - if (TelerikHelper.IsDarkTheme(themeName)) - { - this.radSyntaxEditor1.Palette = SyntaxPalettes.NeutralDark; - } - else - { - this.radSyntaxEditor1.Palette = SyntaxPalettes.Light; - } -```` -````VB.NET -If TelerikHelper.IsDarkTheme(themeName) Then - Me.RadSyntaxEditor1.Palette = SyntaxPalettes.NeutralDark -Else - Me.RadSyntaxEditor1.Palette = SyntaxPalettes.Light -End If - -```` - -{{endregion}} ## Custom Palettes @@ -294,23 +274,10 @@ If you want to customize the colors shown in your **RadSyntaxEditor** control, y Here is an example how to modify specific elements og the **NeutralDark** palette: -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorGettingStarted.cs region=ModifyPalette}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorGettingStarted.vb region=ModifyPalette}} - -````C# -SyntaxPalettes.NeutralDark.XmlTagColor = Color.YellowGreen; -SyntaxPalettes.NeutralDark.XmlElementColor = Color.Blue; -this.radSyntaxEditor1.Palette = SyntaxPalettes.NeutralDark; + + -```` -````VB.NET -SyntaxPalettes.NeutralDark.XmlTagColor = Color.YellowGreen -SyntaxPalettes.NeutralDark.XmlElementColor = Color.Blue -Me.RadSyntaxEditor1.Palette = SyntaxPalettes.NeutralDark -```` - -{{endregion}} #### Difference between NeutralDark palette and modified NeutralDark pallete @@ -318,43 +285,10 @@ Me.RadSyntaxEditor1.Palette = SyntaxPalettes.NeutralDark ### Creating custom SyntaxEditorPalette in code behind -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorGettingStarted.cs region=CreateCustomPallete}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorGettingStarted.vb region=CreateCustomPallete}} - -````C# - SyntaxEditorPalette customPalette = new SyntaxEditorPalette(); - customPalette.KeywordColor = ColorTranslator.FromHtml("#3232eb"); - customPalette.PreprocessorKeywordColor = ColorTranslator.FromHtml("#848484"); - customPalette.CommentColor = ColorTranslator.FromHtml("#006633"); - customPalette.IdentifierColor = ColorTranslator.FromHtml("#000000"); - customPalette.OperatorColor = ColorTranslator.FromHtml("#323232"); - customPalette.XmlAttributeColor = ColorTranslator.FromHtml("#cc2828"); - customPalette.XmlElementColor = ColorTranslator.FromHtml("#ff28e9"); - customPalette.XmlCommentColor = ColorTranslator.FromHtml("#007b00"); - customPalette.XmlContentColor = ColorTranslator.FromHtml("#491cff"); - customPalette.XmlStringColor = ColorTranslator.FromHtml("#491cff"); - customPalette.XmlTagColor = ColorTranslator.FromHtml("#3aff4e"); - this.radSyntaxEditor1.Palette = customPalette; - -```` -````VB.NET -Dim customPalette As SyntaxEditorPalette = New SyntaxEditorPalette() -customPalette.KeywordColor = ColorTranslator.FromHtml("#3232eb") -customPalette.PreprocessorKeywordColor = ColorTranslator.FromHtml("#848484") -customPalette.CommentColor = ColorTranslator.FromHtml("#006633") -customPalette.IdentifierColor = ColorTranslator.FromHtml("#000000") -customPalette.OperatorColor = ColorTranslator.FromHtml("#323232") -customPalette.XmlAttributeColor = ColorTranslator.FromHtml("#cc2828") -customPalette.XmlElementColor = ColorTranslator.FromHtml("#ff28e9") -customPalette.XmlCommentColor = ColorTranslator.FromHtml("#007b00") -customPalette.XmlContentColor = ColorTranslator.FromHtml("#491cff") -customPalette.XmlStringColor = ColorTranslator.FromHtml("#491cff") -customPalette.XmlTagColor = ColorTranslator.FromHtml("#3aff4e") -Me.RadSyntaxEditor1.Palette = customPalette + + -```` -{{endregion}} #### Figure 2: RadSyntaxEditor with a custom palette ![WinForms RadSyntaxEditor with a custom palette](images/palettes003.png) diff --git a/controls/syntax-editor/features/selection-drag-drop.md b/controls/syntax-editor/features/selection-drag-drop.md index 22fbc87f0..7a77c452c 100644 --- a/controls/syntax-editor/features/selection-drag-drop.md +++ b/controls/syntax-editor/features/selection-drag-drop.md @@ -27,87 +27,10 @@ position: 10 #### Handling drag and drop events -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorSelectionDragDrop.cs region=SelectionDragDrop}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorSelectionDragDrop.vb region=SelectionDragDrop}} + + -````C# - private void WireEvents() - { - this.radSyntaxEditor1.SyntaxEditorElement.Selection.PreviewDragStart += Selection_PreviewDragStart; - this.radSyntaxEditor1.SyntaxEditorElement.Selection.PreviewDragOver += Selection_PreviewDragOver; - this.radSyntaxEditor1.SyntaxEditorElement.Selection.PreviewDragDrop += Selection_PreviewDragDrop; - } - - private void Selection_PreviewDragStart(object sender, Telerik.WinForms.Controls.SyntaxEditor.UI.PreviewDragStartEventArgs e) - { - //disable dragging the even lines - - e.CanStart &= (e.StartPostion.LineNumber + 1) % 2 != 0; - } - - - private void Selection_PreviewDragOver(object sender, Telerik.WinForms.Controls.SyntaxEditor.UI.PreviewDragOverEventArgs e) - { - //disable dropping over a text that contains "Telerik" - - CaretPosition start = new CaretPosition(e.DropPosition); - CaretPosition end = new CaretPosition(start); - start.MoveToPreviousWord(); - end.MoveToNextWord(); - string targetText = this.radSyntaxEditor1.SyntaxEditorElement.GetText(start, end); - if (targetText.Contains("Telerik")) - { - e.CanDrop = false; - } - else - { - e.CanDrop = true; - } - } - - private void Selection_PreviewDragDrop(object sender, Telerik.WinForms.Controls.SyntaxEditor.UI.PreviewDragDropEventArgs e) - { - //handle the drop operation - e.Handled = true; - } - - -```` -````VB.NET - - Private Sub WireEvents() - AddHandler Me.radSyntaxEditor1.SyntaxEditorElement.Selection.PreviewDragStart, AddressOf Selection_PreviewDragStart - AddHandler Me.radSyntaxEditor1.SyntaxEditorElement.Selection.PreviewDragOver, AddressOf Selection_PreviewDragOver - AddHandler Me.radSyntaxEditor1.SyntaxEditorElement.Selection.PreviewDragDrop, AddressOf Selection_PreviewDragDrop - End Sub - - Private Sub Selection_PreviewDragStart(ByVal sender As Object, ByVal e As Telerik.WinForms.Controls.SyntaxEditor.UI.PreviewDragStartEventArgs) - e.CanStart = e.CanStart And (e.StartPostion.LineNumber + 1) Mod 2 <> 0 - End Sub - - Private Sub Selection_PreviewDragOver(ByVal sender As Object, ByVal e As Telerik.WinForms.Controls.SyntaxEditor.UI.PreviewDragOverEventArgs) - Dim start As CaretPosition = New CaretPosition(e.DropPosition) - Dim [end] As CaretPosition = New CaretPosition(start) - start.MoveToPreviousWord() - [end].MoveToNextWord() - Dim targetText As String = Me.radSyntaxEditor1.SyntaxEditorElement.GetText(start, [end]) - - If targetText.Contains("Telerik") Then - e.CanDrop = False - Else - e.CanDrop = True - End If - End Sub - - Private Sub Selection_PreviewDragDrop(ByVal sender As Object, ByVal e As Telerik.WinForms.Controls.SyntaxEditor.UI.PreviewDragDropEventArgs) - e.Handled = True - End Sub - - -```` - -{{endregion}} >caption Disable dropping over "Telerik" diff --git a/controls/syntax-editor/features/selection.md b/controls/syntax-editor/features/selection.md index dbd390530..508e08a18 100644 --- a/controls/syntax-editor/features/selection.md +++ b/controls/syntax-editor/features/selection.md @@ -23,19 +23,10 @@ The user is able to select the content inside **RadSyntaxEditor** in the same wa The UI selection is enabled by default. To enable or disable it use the **IsSelectionEnabled** property #### Enable/Disable selection -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorGettingStarted.cs region=EnableSelection}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorGettingStarted.vb region=EnableSelection}} + + -````C# -this.radSyntaxEditor1.IsSelectionEnabled = true; -```` -````VB.NET -Me.RadSyntaxEditor1.IsSelectionEnabled = True - -```` - -{{endregion}} ## Keyboard Combinations @@ -61,21 +52,10 @@ You can modify the appearance of the selection in the control through the **Sele #### Customize the appearance of the selection -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorGettingStarted.cs region=SelectionColor}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorGettingStarted.vb region=SelectionColor}} - -````C# - this.radSyntaxEditor1.SyntaxEditorElement.SelectionFill = new SolidBrush(Color.FromArgb(95, Color.Red)); - this.radSyntaxEditor1.SyntaxEditorElement.SelectionStroke = new SolidBrush(Color.DarkRed); + + -```` -````VB.NET -Me.RadSyntaxEditor1.SyntaxEditorElement.SelectionFill = New SolidBrush(Color.FromArgb(95, Color.Red)) -Me.RadSyntaxEditor1.SyntaxEditorElement.SelectionStroke = New SolidBrush(Color.DarkRed) -```` - -{{endregion}} #### Figure 2: RadSyntaxEditor with custom selection color @@ -85,19 +65,10 @@ Me.RadSyntaxEditor1.SyntaxEditorElement.SelectionStroke = New SolidBrush(Color.D Through the control's **Selection** property, you can programmatically manipulate the selection and get additional details for the selected span(s). The following example demonstrates how you can get the entire selection as a string through the **GetSelectedText** method. -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorGettingStarted.cs region=ProgrammaticSelection}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorGettingStarted.vb region=ProgrammaticSelection}} - -````C# -string selectedText = this.radSyntaxEditor1.SyntaxEditorElement.Selection.GetSelectedText(); - -```` -````VB.NET -Dim selectedText As String = Me.RadSyntaxEditor1.SyntaxEditorElement.Selection.GetSelectedText() + + -```` -{{endregion}} # See Also diff --git a/controls/syntax-editor/features/taggers/custom-language.md b/controls/syntax-editor/features/taggers/custom-language.md index bf45a0466..dee13d29c 100644 --- a/controls/syntax-editor/features/taggers/custom-language.md +++ b/controls/syntax-editor/features/taggers/custom-language.md @@ -16,183 +16,21 @@ Let's define the following class which will be responsible for classifying the w #### The custom tagger -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorTaggers.cs region=PythonTagger}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorTaggers.vb region=PythonTagger}} + + -````C# - public class PythonTagger : WordTaggerBase - { - private static readonly string[] Keywords = new string[] - { - "False", "None", "True", "and", "as", "assert","break", "class", - "continue", "def", "del", "elif", "else", "except", "for", "from", - "global", "if", "import", "in", "is", "lambda", "nonlocal", "not", - "or", "pass", "raise", "finally", "return", "try", "while", "with", "yield" - }; - private static readonly string[] Comments = new string[] - { - "#" - }; - - private static readonly string[] Operators = new string[] - { - "+", "-", "*", "/" - }; - - public static readonly ClassificationType FruitsClassificationType = new ClassificationType("Fruits"); - - private static readonly string[] Fruits = new string[] - { - "apple", "banana", "cherry" - }; - - private static readonly Dictionary WordsToClassificationType = new Dictionary(); - - static PythonTagger() - { - WordsToClassificationType = new Dictionary(); - - foreach (var keyword in Keywords) - { - WordsToClassificationType.Add(keyword, ClassificationTypes.Keyword); - } - - foreach (var preprocessor in Operators) - { - WordsToClassificationType.Add(preprocessor, ClassificationTypes.Operator); - } - - foreach (var comment in Comments) - { - WordsToClassificationType.Add(comment, ClassificationTypes.Comment); - } - - foreach (var comment in Fruits) - { - WordsToClassificationType.Add(comment, FruitsClassificationType); - } - } - - public PythonTagger(RadSyntaxEditorElement editor) - : base(editor) - { - } - - protected override Dictionary GetWordsToClassificationTypes() - { - return PythonTagger.WordsToClassificationType; - } - - protected override bool TryGetClassificationType(string word, out ClassificationType classificationType) - { - int number; - - if (int.TryParse(word, out number)) - { - classificationType = ClassificationTypes.NumberLiteral; - return true; - } - - return base.TryGetClassificationType(word, out classificationType); - } - } - - -```` -````VB.NET - Public Class PythonTagger - Inherits WordTaggerBase - - Private Shared ReadOnly Keywords As String() = New String() {"False", "None", "True", "and", "as", "assert", "break", "class", "continue", "def", "del", "elif", "else", "except", "for", "from", "global", "if", "import", "in", "is", "lambda", "nonlocal", "not", "or", "pass", "raise", "finally", "return", "try", "while", "with", "yield"} - Private Shared ReadOnly Comments As String() = New String() {"#"} - Private Shared ReadOnly Operators As String() = New String() {"+", "-", "*", "/"} - Public Shared ReadOnly FruitsClassificationType As ClassificationType = New ClassificationType("Fruits") - Private Shared ReadOnly Fruits As String() = New String() {"apple", "banana", "cherry"} - Private Shared ReadOnly WordsToClassificationType As Dictionary(Of String, ClassificationType) = New Dictionary(Of String, ClassificationType)() - - Shared Sub New() - WordsToClassificationType = New Dictionary(Of String, ClassificationType)() - - For Each keyword In Keywords - WordsToClassificationType.Add(keyword, ClassificationTypes.Keyword) - Next - - For Each preprocessor In Operators - WordsToClassificationType.Add(preprocessor, ClassificationTypes.[Operator]) - Next - - For Each comment In Comments - WordsToClassificationType.Add(comment, ClassificationTypes.Comment) - Next - - For Each comment In Fruits - WordsToClassificationType.Add(comment, FruitsClassificationType) - Next - End Sub - - Public Sub New(ByVal editor As RadSyntaxEditorElement) - MyBase.New(editor) - End Sub - - Protected Overrides Function GetWordsToClassificationTypes() As Dictionary(Of String, ClassificationType) - Return PythonTagger.WordsToClassificationType - End Function - Protected Overrides Function TryGetClassificationType(word As String, ByRef classificationType As ClassificationType) As Boolean - Dim number As Integer - - If Integer.TryParse(word, number) Then - classificationType = ClassificationTypes.NumberLiteral - Return True - End If - - Return MyBase.TryGetClassificationType(word, classificationType) - End Function - - End Class - - -```` - -{{endregion}} The code above defines custom arrays of words which are then assigned a **Keyword**, **Comment**, **Operator** or the custom **Fruits** classification type. In addition, in the **TryGetClassificationType** method override we assign the **NumberLiteral** classification type to any word that can be parsed to an integer. We can then register the custom tagger in **RadSyntaxEditor**'s **TaggersRegistry** just as we would with any other tagger. We also add custom **TextFormatDefinitions** with specific foregrounds for the **NumberLiteral**, **Operator** and the custom **FruitsClassificationType** which we created earlier. #### Registering the custom tagger -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorTaggers.cs region=RegisterTagger}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorTaggers.vb region=RegisterTagger}} - -````C# -PythonTagger pythonTagger = new PythonTagger(this.radSyntaxEditor1.SyntaxEditorElement); -if (!this.radSyntaxEditor1.TaggersRegistry.IsTaggerRegistered(pythonTagger)) -{ - this.radSyntaxEditor1.TaggersRegistry.RegisterTagger(pythonTagger); -} - -this.radSyntaxEditor1.TextFormatDefinitions.AddLast(ClassificationTypes.NumberLiteral, new TextFormatDefinition(new SolidBrush(Color.Red))); -this.radSyntaxEditor1.TextFormatDefinitions.AddLast(ClassificationTypes.Operator, new TextFormatDefinition(new SolidBrush(Color.YellowGreen))); -this.radSyntaxEditor1.TextFormatDefinitions.AddLast(PythonTagger.FruitsClassificationType, new TextFormatDefinition(new SolidBrush(Color.LightCoral))); - - -```` -````VB.NET -Dim pythonTagger As PythonTagger = New PythonTagger(Me.RadSyntaxEditor1.SyntaxEditorElement) - -If Not Me.RadSyntaxEditor1.TaggersRegistry.IsTaggerRegistered(pythonTagger) Then - Me.RadSyntaxEditor1.TaggersRegistry.RegisterTagger(pythonTagger) -End If - -Me.RadSyntaxEditor1.TextFormatDefinitions.AddLast(ClassificationTypes.NumberLiteral, New TextFormatDefinition(New SolidBrush(Color.Red))) -Me.RadSyntaxEditor1.TextFormatDefinitions.AddLast(ClassificationTypes.[Operator], New TextFormatDefinition(New SolidBrush(Color.YellowGreen))) -Me.RadSyntaxEditor1.TextFormatDefinitions.AddLast(pythonTagger.FruitsClassificationType, New TextFormatDefinition(New SolidBrush(Color.LightCoral))) + + -```` -{{endregion}} - Upon loading some Python code in the editor you will observe a result similar to the one illustrated in Figure 1. >caption Figure 1: The custom Python tagger diff --git a/controls/syntax-editor/features/taggers/custom-taggers.md b/controls/syntax-editor/features/taggers/custom-taggers.md index 2503c6816..fd2afceb5 100644 --- a/controls/syntax-editor/features/taggers/custom-taggers.md +++ b/controls/syntax-editor/features/taggers/custom-taggers.md @@ -16,118 +16,19 @@ To demonstrate this we will create the following class which shows a tool-tip on #### Registering taggers -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorTaggers.cs region=DefineCustomTagger}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorTaggers.vb region=DefineCustomTagger}} - -````C# - public class SimpleToolTipTagger : TaggerBase - { - private string searchWord; - - public SimpleToolTipTagger(ITextDocumentEditor editor) - : base(editor) - { - } - - public override IEnumerable> GetTags(NormalizedSnapshotSpanCollection spans) - { - if (string.IsNullOrEmpty(this.searchWord)) - { - yield break; - } - - TextSnapshot snapshot = this.Document.CurrentSnapshot; - foreach (TextSnapshotSpan snapshotSpan in spans) - { - string lineString = snapshotSpan.GetText(); - int index = lineString.IndexOf(this.searchWord); - while (index != -1) - { - TextSnapshotSpan tempSnapshotSpan = new TextSnapshotSpan(snapshot, - new Span(snapshotSpan.Start + index, searchWord.Length)); - - yield return new TagSpan(tempSnapshotSpan, new ToolTipTag("Sample tooltip " + searchWord)); - - index = lineString.IndexOf(this.searchWord, index + this.searchWord.Length); - } - } - } - - public void UpdateSearchWord(string newSearchWord) - { - this.searchWord = newSearchWord; - this.CallOnTagsChanged(this.Document.CurrentSnapshot.Span); - } - } - -```` -````VB.NET - - Public Class SimpleToolTipTagger - Inherits TaggerBase(Of ToolTipTag) - - Private searchWord As String - - Public Sub New(ByVal editor As ITextDocumentEditor) - MyBase.New(editor) - End Sub - - Public Overrides Iterator Function GetTags(ByVal spans As NormalizedSnapshotSpanCollection) As IEnumerable(Of TagSpan(Of ToolTipTag)) - If String.IsNullOrEmpty(Me.searchWord) Then - Return - End If - - Dim snapshot As TextSnapshot = Me.Document.CurrentSnapshot - - For Each snapshotSpan As TextSnapshotSpan In spans - Dim lineString As String = snapshotSpan.GetText() - Dim index As Integer = lineString.IndexOf(Me.searchWord) - - While index <> -1 - Dim tempSnapshotSpan As TextSnapshotSpan = New TextSnapshotSpan(snapshot, New Span(snapshotSpan.Start + index, searchWord.Length)) - Yield New TagSpan(Of ToolTipTag)(tempSnapshotSpan, New ToolTipTag("Sample tooltip " & searchWord)) - index = lineString.IndexOf(Me.searchWord, index + Me.searchWord.Length) - End While - Next - End Function - - Public Sub UpdateSearchWord(ByVal newSearchWord As String) - Me.searchWord = newSearchWord - Me.CallOnTagsChanged(Me.Document.CurrentSnapshot.Span) - End Sub - End Class - -```` - -{{endregion}} + + + + To use the tagger you need to register it in the **TaggersRegistry** as you would do with any other tagger. You can then call the **UpdateSearchWord** method to apply the tagger to any spans containing a specific word. #### Using the custom tagger -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorTaggers.cs region=RegisterTooltipTagger}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorTaggers.vb region=RegisterTooltipTagger}} - -````C# -SimpleToolTipTagger simpleToolTipTagger = new SimpleToolTipTagger(this.radSyntaxEditor1.SyntaxEditorElement); -if (!this.radSyntaxEditor1.TaggersRegistry.IsTaggerRegistered(simpleToolTipTagger)) -{ - this.radSyntaxEditor1.TaggersRegistry.RegisterTagger(simpleToolTipTagger); -} -simpleToolTipTagger.UpdateSearchWord("Telerik"); - - -```` -````VB.NET -Dim simpleToolTipTagger As SimpleToolTipTagger = New SimpleToolTipTagger(Me.RadSyntaxEditor1.SyntaxEditorElement) -If Not Me.RadSyntaxEditor1.TaggersRegistry.IsTaggerRegistered(simpleToolTipTagger) Then - Me.RadSyntaxEditor1.TaggersRegistry.RegisterTagger(simpleToolTipTagger) -End If -simpleToolTipTagger.UpdateSearchWord("Telerik") - -```` - -{{endregion}} + + + + >caption The custom tool-tip tagger diff --git a/controls/syntax-editor/features/taggers/folding-taggers.md b/controls/syntax-editor/features/taggers/folding-taggers.md index f82dbceb9..7b9640fab 100644 --- a/controls/syntax-editor/features/taggers/folding-taggers.md +++ b/controls/syntax-editor/features/taggers/folding-taggers.md @@ -30,132 +30,19 @@ The folding taggers are used when you want to create collapsible (foldable) sect #### Adding FoldingRegionDefinitions -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorTaggers.cs region=RegionDefinition}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorTaggers.vb region=RegionDefinition}} + + -````C# - public CustomFoldingTagger(Telerik.WinForms.SyntaxEditor.Core.Editor.ITextDocumentEditor editor) - : base(editor) -{ - this.FoldingRegionDefinitions.Add(new FoldingRegionDefinition("FUNCTION", "END")); - this.FoldingRegionDefinitions.Add(new FoldingRegionDefinition("If", "End If")); -} - -```` -````VB.NET - -Public Sub New(ByVal editor As Telerik.WinForms.SyntaxEditor.Core.Editor.ITextDocumentEditor) - MyBase.New(editor) - Me.FoldingRegionDefinitions.Add(New FoldingRegionDefinition("FUNCTION", "END")) - Me.FoldingRegionDefinitions.Add(New FoldingRegionDefinition("If", "End If")) -End Sub - -```` - -{{endregion}} In addition, you may also want to override the **BuildStartRegionBlockPattern** and **BuildEndRegionBlockPattern** and return a custom regular expression to match the start and end. #### Default implementation of the BuildStartRegionBlockPattern and BuildEndRegionBlockPattern methods of the VisualBasicFoldingTagger -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorTaggers.cs region=DefaultStartEndTagger}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorTaggers.vb region=DefaultStartEndTagger}} - -````C# -protected override string BuildStartRegionBlockPattern(Dictionary startToEndMap) -{ - List finalList = new List(); - - foreach (string key in startToEndMap.Keys) - { - string endWord = startToEndMap[key]; - if (key == "If") - { - finalList.Add("\\b(? startToEndMap) -{ - List finalList = new List(); - - foreach (string value in startToEndMap.Values) - { - if (value == "End If") - { - finalList.Add("\\b(? + + + Here's a full list of the overridable methods which you can use in order to create your own custom folding taggers. You can check their default implementations in the various out of the box folding taggers to get a general understanding of how to use them by [downloading the source code]({%slug winforms/installation-deployment-and-distribution/download-product-files%}) of the UI for WinForms suite. * **string BuildStartRegionBlockPattern(Dictionary startToEndMap)**: Prepares patters for matching start of collapsible folding section. Default implementation is to join all start strings of provided collapsible sections. diff --git a/controls/syntax-editor/features/taggers/overview.md b/controls/syntax-editor/features/taggers/overview.md index bb4a70226..a66ea96b7 100644 --- a/controls/syntax-editor/features/taggers/overview.md +++ b/controls/syntax-editor/features/taggers/overview.md @@ -47,29 +47,10 @@ To be able to use these taggers in the **RadSyntaxEditor** control, you first ne #### Registering taggers -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorLayers.cs region=AddTaggers}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorLayers.vb region=AddTaggers}} + + -````C# - CSharpTagger currentLanguageTagger = new Telerik.WinForms.Controls.SyntaxEditor.Tagging.Taggers.CSharpTagger(this.radSyntaxEditor1.SyntaxEditorElement); - this.radSyntaxEditor1.TaggersRegistry.RegisterTagger(currentLanguageTagger); - CSharpFoldingTagger foldingTagger = new Telerik.WinForms.Controls.SyntaxEditor.Taggers.CSharpFoldingTagger(this.radSyntaxEditor1.SyntaxEditorElement); - foldingTagger.FoldingRegionDefinitions.Add(new FoldingRegionDefinition("#if", "#endif")); - -```` -````VB.NET - -Dim currentLanguageTagger As CSharpTagger = New Telerik.WinForms.Controls.SyntaxEditor.Taggers.CSharpTagger(Me.RadSyntaxEditor1.SyntaxEditorElement) -Me.RadSyntaxEditor1.TaggersRegistry.RegisterTagger(currentLanguageTagger) -Dim foldingTagger As CSharpFoldingTagger = New Telerik.WinForms.Controls.SyntaxEditor.Taggers.CSharpFoldingTagger(Me.RadSyntaxEditor1.SyntaxEditorElement) -foldingTagger.FoldingRegionDefinitions.Add(New FoldingRegionDefinition("#if", "#endif")) -RadSyntaxEditor1.TaggersRegistry.RegisterTagger(foldingTagger) - - -```` - -{{endregion}} >note As of R2 2021 **RadSyntaxEditor** offers **ShouldTaggersProcessEntireLines** property that indicates whether the entire line should be processed by the taggers. diff --git a/controls/syntax-editor/features/word-wrap.md b/controls/syntax-editor/features/word-wrap.md index ac3f64195..f767d66c6 100644 --- a/controls/syntax-editor/features/word-wrap.md +++ b/controls/syntax-editor/features/word-wrap.md @@ -16,23 +16,10 @@ The functionality can be enabled by setting the `IsWordWrapEnabled` property to #### Example 1: Setting IsWordWrapEnabled property -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorGettingStarted.cs region=WordWrap}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorGettingStarted.vb region=WordWrap}} + + -````C# -this.radSyntaxEditor1.IsWordWrapEnabled = true; - - -```` -````VB.NET - -Me.RadSyntaxEditor1.IsWordWrapEnabled = True - - -```` - -{{endregion}} >caption Figure 1: RadSyntaxEditor with Word Wrapping diff --git a/controls/syntax-editor/features/zooming.md b/controls/syntax-editor/features/zooming.md index 96e57d39a..43714bc34 100644 --- a/controls/syntax-editor/features/zooming.md +++ b/controls/syntax-editor/features/zooming.md @@ -20,19 +20,10 @@ The zooming functionality is enabled by default. To enable or disable it at run #### Enable/Disable zooming -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorGettingStarted.cs region=DisableZooming}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorGettingStarted.vb region=DisableZooming}} + + -````C# -this.radSyntaxEditor1.AllowScaling = false; -```` -````VB.NET -Me.RadSyntaxEditor1.AllowScaling = False - -```` - -{{endregion}} ## ScaleFactor @@ -40,19 +31,10 @@ The zoom factor can also be controlled by setting the control's **ScaleFactor** #### Setting the ScaleFactor -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorGettingStarted.cs region=ScaleFactor}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorGettingStarted.vb region=ScaleFactor}} - -````C# -this.radSyntaxEditor1.ScaleFactor = 1.5; - -```` -````VB.NET -Me.RadSyntaxEditor1.ScaleFactor = 1.5 + + -```` -{{endregion}} #### Figure 2: Setting the ScaleFactor @@ -64,36 +46,17 @@ You can also zoom the **RadSyntaxEditor** control programmatically by using the #### Zoom in and Zoom out -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorGettingStarted.cs region=ProgrammaticZooming}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorGettingStarted.vb region=ProgrammaticZooming}} + + -````C# -this.radSyntaxEditor1.ZoomIn(); // The zoom increase factor is 1.1 -this.radSyntaxEditor1.ZoomOut(); // The zoom decrease factor is 0.91 -```` -````VB.NET -Me.RadSyntaxEditor1.ZoomIn() 'The zoom increase factor Is 1.1 -Me.RadSyntaxEditor1.ZoomOut() 'The zoom decrease factor Is 0.91 - -```` - -{{endregion}} The **ZoomTo** method accepts a single argument - the zoom level to scroll to. This argument is directly set as the control's **ScaleFactor** and can thus accept values from 0.25 to 4, inclusive. #### Zoom to a particular zoom level -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorGettingStarted.cs region=ZoomTo}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorGettingStarted.vb region=ZoomTo}} - -````C# -this.radSyntaxEditor1.ZoomTo(2); + + -```` -````VB.NET -Me.RadSyntaxEditor1.ZoomTo(2); -```` -{{endregion}} diff --git a/controls/syntax-editor/getting-started.md b/controls/syntax-editor/getting-started.md index e2d44d989..8a3616401 100644 --- a/controls/syntax-editor/getting-started.md +++ b/controls/syntax-editor/getting-started.md @@ -57,33 +57,10 @@ Dim radSyntaxEditor1 As RadSyntaxEditor = New RadSyntaxEditor() To load a file in the **RadSyntaxEditor** you need to use its **Document** property. -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorGettingStarted.cs region=GettingStartedLoadDocument}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorGettingStarted.vb region=GettingStartedLoadDocument}} + + -````C# - -public RadForm1() - { - InitializeComponent(); - - using (StreamReader reader = new StreamReader("../../CS_File.txt")) - { - this.radSyntaxEditor1.Document = new TextDocument(reader); - } - } - -```` -````VB.NET -Public Sub New() - InitializeComponent() - - Using Reader As StreamReader = New StreamReader("../../CS_File.txt") - Me.RadSyntaxEditor1.Document = New TextDocument(Reader) - End Using -End Sub - -```` #### Figure 2: RadSyntaxEditor with a loaded C# file @@ -93,20 +70,10 @@ End Sub Once you have loaded the code, you need to register an appropriate tagger to enable syntax highlighting for the particular language. -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorGettingStarted.cs region=CSharpTagger}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorGettingStarted.vb region=CSharpTagger}} - -````C# + + -CSharpTagger cSharptagger = new CSharpTagger(this.radSyntaxEditor1.SyntaxEditorElement); -this.radSyntaxEditor1.TaggersRegistry.RegisterTagger(cSharptagger); -```` -````VB.NET -Dim CSharptagger As CSharpTagger = New CSharpTagger(Me.radSyntaxEditor1.SyntaxEditorElement) -Me.RadSyntaxEditor1.TaggersRegistry.RegisterTagger(CSharptagger) - -```` #### Figure 3: RadSyntaxEditor with C# code highlighting diff --git a/controls/syntax-editor/localization.md b/controls/syntax-editor/localization.md index 55a008079..dbd3cf700 100644 --- a/controls/syntax-editor/localization.md +++ b/controls/syntax-editor/localization.md @@ -20,40 +20,19 @@ To localize **RadSyntaxEditor** to display control text and messages in a specif #### Localizing RadSyntaxEditor Strings -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorLocalizing.cs region=Provider}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorLocalizing.vb region=Provider}} + + -````C# - - - -```` -````VB.NET - - - -```` - -{{endregion}} To apply the custom localization provider, instantiate and assign it to the current localization provider: #### Assigning the Current Localization Provider -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorLocalizing.cs region=Apply}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorLocalizing.vb region=Apply}} - -````C# - RadSyntaxEditorLocalizationProvider.CurrentProvider = new EnglishRadSyntaxEditorLocalizationProvider(); - -```` -````VB.NET -RadSyntaxEditorLocalizationProvider.CurrentProvider = New EnglishRadSyntaxEditorLocalizationProvider() + + -```` -{{endregion}} The code provided above illustrates the approach to be used to localize the **RadSyntaxEditor** and is not intended as a full translation. diff --git a/controls/syntax-editor/properties-methods-events.md b/controls/syntax-editor/properties-methods-events.md index 40268a633..e3dd9903f 100644 --- a/controls/syntax-editor/properties-methods-events.md +++ b/controls/syntax-editor/properties-methods-events.md @@ -76,38 +76,9 @@ position: 3 #### Selecting the word under the mouse on a single click -{{source=..\SamplesCS\SyntaxEditor\SyntaxEditorGettingStarted.cs region=MouseDownDetection}} -{{source=..\SamplesVB\SyntaxEditor\SyntaxEditorGettingStarted.vb region=MouseDownDetection}} - -````C# -private void RadSyntaxEditor1_MouseDown(object sender, MouseEventArgs e) -{ - CaretPosition clickPosition = this.radSyntaxEditor1.GetPositionFromControlPoint(e.Location); - - CaretPosition start = new CaretPosition(clickPosition); - start.MoveToCurrentWordStart(); - - CaretPosition end = new CaretPosition(clickPosition); - end.MoveToCurrentWordEnd(); - - this.radSyntaxEditor1.SyntaxEditorElement.CaretPosition.MoveToPosition(end); - this.radSyntaxEditor1.SyntaxEditorElement.Selection.Select(start, end); -} - -```` -````VB.NET - - Private Sub RadSyntaxEditor1_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) - Dim clickPosition As CaretPosition = Me.RadSyntaxEditor1.GetPositionFromControlPoint(e.Location) - Dim start As CaretPosition = New CaretPosition(clickPosition) - start.MoveToCurrentWordStart() - Dim [end] As CaretPosition = New CaretPosition(clickPosition) - [end].MoveToCurrentWordEnd() - Me.RadSyntaxEditor1.SyntaxEditorElement.CaretPosition.MoveToPosition([end]) - Me.RadSyntaxEditor1.SyntaxEditorElement.Selection.[Select](start, [end]) - End Sub - -```` + + + ## RadSyntaxEditor's Events diff --git a/controls/task-board/task-board-adding-task-cards.md b/controls/task-board/task-board-adding-task-cards.md index 9eba215ba..2896a5249 100644 --- a/controls/task-board/task-board-adding-task-cards.md +++ b/controls/task-board/task-board-adding-task-cards.md @@ -22,59 +22,10 @@ However, if the button is enabled, the default **RadTaskCardElement** that is ge #### Create a Predefined RadTaskCardElement -{{source=..\SamplesCS\TaskBoard\TaskBoardGettingStarted.cs region=PredefinedCard}} -{{source=..\SamplesVB\TaskBoard\TaskBoardGettingStarted.vb region=PredefinedCard}} + + -````C# -private void RadTaskBoardColumnElement_TaskCardAdding(RadTaskBoardColumnElement.TaskCardAddingEventArgs args) -{ - RadTaskCardElement defaultTaskCard = new RadTaskCardElement(); - defaultTaskCard.TitleText = "ListView improvements"; - defaultTaskCard.DescriptionText = "Research phase"; - defaultTaskCard.AccentSettings.Color = Color.Red; - - UserInfo user1 = new UserInfo(); - user1.FirstName = "Anne"; - user1.LastName = "Dodsworth"; - user1.Avatar = Properties.Resources.anne; - defaultTaskCard.Users.Add(user1); - - //assign a user defined in RadTaskBoard - //defaultTaskCard.Users.Add(this.radTaskBoard1.Users[1]); - - TagInfo tagWF = new TagInfo(); - tagWF.Text = "win-forms"; - defaultTaskCard.Tags.Add(tagWF); - args.TaskCard = defaultTaskCard; -} - -```` -````VB.NET - -Private Sub RadTaskBoardColumnElement_TaskCardAdding(args As RadTaskBoardColumnElement.TaskCardAddingEventArgs) - Dim defaultTaskCard As RadTaskCardElement = New RadTaskCardElement() - defaultTaskCard.TitleText = "ListView improvements" - defaultTaskCard.DescriptionText = "Research phase" - defaultTaskCard.AccentSettings.Color = Color.Red - Dim user1 As UserInfo = New UserInfo() - user1.FirstName = "Anne" - user1.LastName = "Dodsworth" - user1.Avatar = My.Resources.anne - defaultTaskCard.Users.Add(user1) - - 'assign a user defined in RadTaskBoard - 'defaultTaskCard.Users.Add(this.radTaskBoard1.Users(1)) - - Dim tagWF As TagInfo = New TagInfo() - tagWF.Text = "win-forms" - defaultTaskCard.Tags.Add(tagWF) - args.TaskCard = defaultTaskCard -End Sub - -```` - -{{endregion}} ![WinForms RadTaskBoard Adding Task Cards](images/task-board-adding-task-cards002.png) diff --git a/controls/task-board/task-board-adding-user-and-tasks.md b/controls/task-board/task-board-adding-user-and-tasks.md index 8dee49065..36267ff21 100644 --- a/controls/task-board/task-board-adding-user-and-tasks.md +++ b/controls/task-board/task-board-adding-user-and-tasks.md @@ -22,39 +22,10 @@ Once, there are users in the RadTaskBoard.**Users** collection at design time, t #### Adding Users at Run time -{{source=..\SamplesCS\TaskBoard\TaskBoardGettingStarted.cs region=AddUser}} -{{source=..\SamplesVB\TaskBoard\TaskBoardGettingStarted.vb region=AddUser}} - -````C# -UserInfo user1 = new UserInfo(); -user1.FirstName = "Anne"; -user1.LastName = "Dodsworth"; -user1.Avatar = Properties.Resources.anne; - -UserInfo user2 = new UserInfo(); -user2.FirstName = "Andrew"; -user2.LastName = "Fuller"; -user2.Avatar = Properties.Resources.andrew1; - -this.radTaskBoard1.Users.Add(user1); -this.radTaskBoard1.Users.Add(user2); - -```` -````VB.NET -Dim user1 As UserInfo = New UserInfo() -user1.FirstName = "Anne" -user1.LastName = "Dodsworth" -user1.Avatar = My.Resources.anne -Dim user2 As UserInfo = New UserInfo() -user2.FirstName = "Andrew" -user2.LastName = "Fuller" -user2.Avatar = My.Resources.andrew1 -Me.radTaskBoard1.Users.Add(user1) -Me.radTaskBoard1.Users.Add(user2) - -```` - -{{endregion}} + + + + ## Adding Tags @@ -70,41 +41,11 @@ Once, there are tags in the RadTaskBoard.**Tags** collection at design time, the #### Adding Tags at Run time -{{source=..\SamplesCS\TaskBoard\TaskBoardGettingStarted.cs region=AddTag}} -{{source=..\SamplesVB\TaskBoard\TaskBoardGettingStarted.vb region=AddTag}} - -````C# -TagInfo tagWF = new TagInfo(); -tagWF.ForeColor = Color.Red; -tagWF.BackColor = Color.Black; -tagWF.Text = "win-forms"; - -TagInfo tagWPF = new TagInfo(); -tagWPF.Text = "wpf"; -tagWPF.ForeColor = Color.Aqua; -tagWF.BackColor = Color.Blue; + + -this.radTaskBoard1.Tags.Add(tagWF); -this.radTaskBoard1.Tags.Add(tagWPF); -```` -````VB.NET -Dim tagWF As TagInfo = New TagInfo() -tagWF.ForeColor = Color.Red -tagWF.BackColor = Color.Black -tagWF.Text = "win-forms" -Dim tagWPF As TagInfo = New TagInfo() -tagWPF.Text = "wpf" -tagWPF.ForeColor = Color.Aqua -tagWF.BackColor = Color.Blue -Me.radTaskBoard1.Tags.Add(tagWF) -Me.radTaskBoard1.Tags.Add(tagWPF) - -```` - -{{endregion}} - >note When you add a **TagInfo** to a card, the TagInfo is added to the main collection in **RadTaskBoard**, so it can be reused. # See Also diff --git a/controls/task-board/task-board-getting-started.md b/controls/task-board/task-board-getting-started.md index f11fdbaae..5484b90ec 100644 --- a/controls/task-board/task-board-getting-started.md +++ b/controls/task-board/task-board-getting-started.md @@ -35,97 +35,10 @@ The Telerik UI for WinForms assemblies can be install by using one of the availa To get started, just drag a **RadTaskBoad** from the toolbox and drop it onto the form. Then, define the columns you need in the control and the task cards contained in each column: -{{source=..\SamplesCS\TaskBoard\TaskBoardGettingStarted.cs region=GettingStarted}} -{{source=..\SamplesVB\TaskBoard\TaskBoardGettingStarted.vb region=GettingStarted}} - -````C# - -UserInfo user1 = new UserInfo(); -user1.FirstName = "Anne"; -user1.LastName = "Dodsworth"; -user1.Avatar = Properties.Resources.anne; -UserInfo user2 = new UserInfo(); -user2.FirstName = "Andrew"; -user2.LastName = "Fuller"; -user2.Avatar = Properties.Resources.andrew1; - -RadTaskCardElement card = new RadTaskCardElement(); - -RadTaskBoardColumnElement c1 = new RadTaskBoardColumnElement(); -c1.Title = "Backlog"; -c1.Subtitle = "Internal Issues"; - -RadTaskBoardColumnElement c2 = new RadTaskBoardColumnElement(); -c2.Title = "In Development"; -c2.Subtitle = "Prioritized Issues"; -c2.IsCollapsed = true; -this.radTaskBoard1.Columns.Add(c1); -this.radTaskBoard1.Columns.Add(c2); - -card.TitleText = "ListView improvements"; -card.DescriptionText = "Research phase"; -card.AccentSettings.Color = Color.Red; - -card.Users.Add(user1); -card.Users.Add(user2); - -TagInfo tagWF = new TagInfo(); -tagWF.Text = "win-forms"; -TagInfo tagWPF = new TagInfo(); -tagWPF.Text = "wpf"; -card.Tags.Add(tagWF); -card.Tags.Add(tagWPF); - -card.SubTasks.Add(new SubTask(card)); -card.SubTasks.Add(new SubTask(card)); -card.SubTasks.Add(new SubTask(card)); -SubTask x = new SubTask(card); -x.Completed = true; -card.SubTasks.Add(x); -c1.TaskCardCollection.Add(card); - -```` -````VB.NET -Dim user1 As UserInfo = New UserInfo() -user1.FirstName = "Anne" -user1.LastName = "Dodsworth" -user1.Avatar = My.Resources.anne -Dim user2 As UserInfo = New UserInfo() -user2.FirstName = "Andrew" -user2.LastName = "Fuller" -user2.Avatar = My.Resources.andrew1 -Dim card As RadTaskCardElement = New RadTaskCardElement() -Dim c1 As RadTaskBoardColumnElement = New RadTaskBoardColumnElement() -c1.Title = "Backlog" -c1.Subtitle = "Internal Issues" -Dim c2 As RadTaskBoardColumnElement = New RadTaskBoardColumnElement() -c2.Title = "In Development" -c2.Subtitle = "Prioritized Issues" -c2.IsCollapsed = True -Me.radTaskBoard1.Columns.Add(c1) -Me.radTaskBoard1.Columns.Add(c2) -card.TitleText = "ListView improvements" -card.DescriptionText = "Research phase" -card.AccentSettings.Color = Color.Red -card.Users.Add(user1) -card.Users.Add(user2) -Dim tagWF As TagInfo = New TagInfo() -tagWF.Text = "win-forms" -Dim tagWPF As TagInfo = New TagInfo() -tagWPF.Text = "wpf" -card.Tags.Add(tagWF) -card.Tags.Add(tagWPF) -card.SubTasks.Add(New SubTask(card)) -card.SubTasks.Add(New SubTask(card)) -card.SubTasks.Add(New SubTask(card)) -Dim x As SubTask = New SubTask(card) -x.Completed = True -card.SubTasks.Add(x) -c1.TaskCardCollection.Add(card) - -```` - -{{endregion}} + + + + ![WinForms RadTaskBoard Getting Started](images/task-board-getting-started001.png) diff --git a/controls/task-board/task-board-sorting-tasks.md b/controls/task-board/task-board-sorting-tasks.md index 3084bc769..65e6dc23d 100644 --- a/controls/task-board/task-board-sorting-tasks.md +++ b/controls/task-board/task-board-sorting-tasks.md @@ -32,66 +32,17 @@ If the **SortColumns** method is called, the column's title is considered and th However, after applying the custom comparer, "Done" column is always first: -{{source=..\SamplesCS\TaskBoard\TaskBoardGettingStarted.cs region=ApplyCustomColumnComparer}} -{{source=..\SamplesVB\TaskBoard\TaskBoardGettingStarted.vb region=ApplyCustomColumnComparer}} + + -````C# -this.radTaskBoard1.TaskBoardElement.ColumnComparer = new MyCustomComparer(); -this.radTaskBoard1.SortColumns(); -```` -````VB.NET -Me.radTaskBoard1.TaskBoardElement.ColumnComparer = New MyCustomComparer() -Me.radTaskBoard1.SortColumns() -```` +Here is the specific implementation ensuring that the first column: -{{endregion}} + + -Here is the specific implementation ensuring that the first column: -{{source=..\SamplesCS\TaskBoard\TaskBoardGettingStarted.cs region=SortingColumns}} -{{source=..\SamplesVB\TaskBoard\TaskBoardGettingStarted.vb region=SortingColumns}} - -````C# -private class MyCustomComparer : ColumnComparer -{ - - public override int Compare(RadTaskBoardColumnElement x, RadTaskBoardColumnElement y) - { - // The column with Done text is First. - if (x.Title == "Done") - { - return -1; - } - else if (y.Title == "Done") - { - return 1; - } - return base.Compare(x, y); - } -} - -```` -````VB.NET -Private Class MyCustomComparer - Inherits ColumnComparer - - Public Overrides Function Compare(ByVal x As RadTaskBoardColumnElement, ByVal y As RadTaskBoardColumnElement) As Integer - If x.Title = "Done" Then - Return -1 - ElseIf y.Title = "Done" Then - Return 1 - End If - - Return MyBase.Compare(x, y) - End Function -End Class - - -```` - -{{endregion}} >caption Custom Columns Sort Order @@ -102,51 +53,17 @@ End Class The **SortTasks** method sorts the tasks of all columns. The default Comparer used by all columns is RadTaskBoardElement.**TaskCardComparer** and it will sort the tasks by their TitleText. If you need custom sort for all columns you can create an ancestor of the TaskCardComparer class and set it to the TaskBoardElement.TaskCardComparer. To create custom tasks sorting per column you can use the RadTaskBoardColumnElement.TaskCardComparer property which is defined per column. If the RadTaskBoardColumnElement.TaskCardComparer is not explicitly set it will refer to the TaskBoardElement.TaskCardComparer. -{{source=..\SamplesCS\TaskBoard\TaskBoardGettingStarted.cs region=ApplyCustomTaskComparer}} -{{source=..\SamplesVB\TaskBoard\TaskBoardGettingStarted.vb region=ApplyCustomTaskComparer}} + + -````C# -this.radTaskBoard1.TaskBoardElement.TaskCardComparer = new CustomTaskCardComparer(); -this.radTaskBoard1.SortTasks(); -```` -````VB.NET - Me.radTaskBoard1.TaskBoardElement.TaskCardComparer = New CustomTaskCardComparer() - Me.radTaskBoard1.SortTasks() -```` +Here is the specific implementation ensuring the reversed alphabetical order for the tasks: -{{endregion}} + + -Here is the specific implementation ensuring the reversed alphabetical order for the tasks: -{{source=..\SamplesCS\TaskBoard\TaskBoardGettingStarted.cs region=SortingTasks}} -{{source=..\SamplesVB\TaskBoard\TaskBoardGettingStarted.vb region=SortingTasks}} - -````C# -public class CustomTaskCardComparer : TaskCardComparer -{ - public override int Compare(RadTaskCardElement x, RadTaskCardElement y) - { - int defaultResult = base.Compare(x, y); - return defaultResult * (-1); - } -} - -```` -````VB.NET -Public Class CustomTaskCardComparer - Inherits TaskCardComparer - - Public Overrides Function Compare(ByVal x As RadTaskCardElement, ByVal y As RadTaskCardElement) As Integer - Dim defaultResult As Integer = MyBase.Compare(x, y) - Return defaultResult * (-1) - End Function -End Class - -```` - -{{endregion}} >caption Sorted Tasks in Reversed Alphabetical Order diff --git a/controls/task-board/task-board-tooltips.md b/controls/task-board/task-board-tooltips.md index 07be58eb5..22c1411af 100644 --- a/controls/task-board/task-board-tooltips.md +++ b/controls/task-board/task-board-tooltips.md @@ -33,61 +33,10 @@ The code snippet below demonstrates how you can use RadTaskBoard.**ToolTipTextNe #### Changing the Tooltips for the Card Tags and Card Users -{{source=..\SamplesCS\TaskBoard\TaskBoardGettingStarted.cs region=Tooltips}} -{{source=..\SamplesVB\TaskBoard\TaskBoardGettingStarted.vb region=Tooltips}} - -````C# - -private void RadTaskBoard1_ToolTipTextNeeded(object sender, ToolTipTextNeededEventArgs e) -{ - RadTaskCardTagElement tagElement = sender as RadTaskCardTagElement; - RadTaskCardUserElement userElement = sender as RadTaskCardUserElement; - LightVisualElement lve = sender as LightVisualElement; - if (tagElement!=null ) - { - if (tagElement.Text=="win-forms") - { - e.ToolTipText = "Windows Forms"; - } - else if (tagElement.Text=="wpf") - { - e.ToolTipText = "Windows Presentation Foundation"; - } - } - else if (userElement!=null) - { - e.ToolTipText = userElement.UserInfo.Initials + " " + userElement.UserInfo.LastName; - } - else if (lve!=null && lve.Class== "TaskCardDescription") - { - e.ToolTipText = "Custom description"; - } -} - -```` -````VB.NET -Private Sub RadTaskBoard1_ToolTipTextNeeded(ByVal sender As Object, ByVal e As ToolTipTextNeededEventArgs) - Dim tagElement As RadTaskCardTagElement = TryCast(sender, RadTaskCardTagElement) - Dim userElement As RadTaskCardUserElement = TryCast(sender, RadTaskCardUserElement) - Dim lve As LightVisualElement = TryCast(sender, LightVisualElement) - - If tagElement IsNot Nothing Then - - If tagElement.Text = "win-forms" Then - e.ToolTipText = "Windows Forms" - ElseIf tagElement.Text = "wpf" Then - e.ToolTipText = "Windows Presentation Foundation" - End If - ElseIf userElement IsNot Nothing Then - e.ToolTipText = userElement.UserInfo.Initials & " " + userElement.UserInfo.LastName - ElseIf lve IsNot Nothing AndAlso lve.[Class] = "TaskCardDescription" Then - e.ToolTipText = "Custom description" - End If -End Sub - -```` - -{{endregion}} + + + + >caption Custom tooltip for the Tag element diff --git a/controls/task-dialog/task-dialog-element-types.md b/controls/task-dialog/task-dialog-element-types.md index 7577cd20f..18a198573 100644 --- a/controls/task-dialog/task-dialog-element-types.md +++ b/controls/task-dialog/task-dialog-element-types.md @@ -45,44 +45,10 @@ The **State** property is of type **RadTaskDialogProgressBarState** which offers #### Adding a RadTaskDialogProgressBar -{{source=..\SamplesCS\TaskDialog\TaskDialogGettingStarted.cs region=ProgressElement}} -{{source=..\SamplesVB\TaskDialog\TaskDialogGettingStarted.vb region=ProgressElement}} - -````C# - RadTaskDialogPage page = new RadTaskDialogPage(); - page.Caption = "Window Title"; - page.Heading = "Main instruction"; - page.Text = "Main text here..."; - page.Icon = RadTaskDialogIcon.ShieldErrorRedBar; - page.Icon.SvgImage = RadTaskDialogIcon.GetSvgImage(RadTaskDialogIconImage.FlatShieldSuccess, new Size(32, 32)); - - RadTaskDialogProgressBar taskProgressBar = new RadTaskDialogProgressBar(); - taskProgressBar.Value = 30; - taskProgressBar.State = RadTaskDialogProgressBarState.Error; - page.ProgressBar = taskProgressBar; - page.ProgressBar.Text = "Content"; - - RadTaskDialog.ShowDialog(page); - -```` -````VB.NET - - Dim page As RadTaskDialogPage = New RadTaskDialogPage() - page.Caption = "Window Title" - page.Heading = "Main instruction" - page.Text = "Main text here..." - page.Icon = RadTaskDialogIcon.ShieldErrorRedBar - page.Icon.SvgImage = RadTaskDialogIcon.GetSvgImage(RadTaskDialogIconImage.FlatShieldSuccess, New Size(32, 32)) - Dim taskProgressBar As RadTaskDialogProgressBar = New RadTaskDialogProgressBar() - taskProgressBar.Value = 30 - taskProgressBar.State = RadTaskDialogProgressBarState.[Error] - page.ProgressBar = taskProgressBar - page.ProgressBar.Text = "Content" - RadTaskDialog.ShowDialog(page) - -```` - -{{endregion}} + + + + ## RadTaskDialogVerificationCheckBox @@ -92,43 +58,10 @@ The **State** property is of type **RadTaskDialogProgressBarState** which offers #### Adding a RadTaskDialogVerificationCheckBox -{{source=..\SamplesCS\TaskDialog\TaskDialogGettingStarted.cs region=VerificationCheckBox}} -{{source=..\SamplesVB\TaskDialog\TaskDialogGettingStarted.vb region=VerificationCheckBox}} - -````C# - RadTaskDialogPage page = new RadTaskDialogPage(); - page.Caption = "Window Title"; - page.Heading = "Main instruction"; - page.Text = "Main text here..."; - page.Icon = RadTaskDialogIcon.ShieldErrorRedBar; - page.Icon.SvgImage = RadTaskDialogIcon.GetSvgImage(RadTaskDialogIconImage.FlatShieldSuccess, new Size(32, 32)); - - RadTaskDialogVerificationCheckBox verificationCheck = new RadTaskDialogVerificationCheckBox(); - verificationCheck.Text = "Verification"; - verificationCheck.CheckStateChanged += new EventHandler(delegate(object sender, EventArgs e) { RadMessageBox.Show(verificationCheck.CheckState.ToString()); }); - page.Verification = verificationCheck; - RadTaskDialog.ShowDialog(page); - -```` -````VB.NET - - Dim page As RadTaskDialogPage = New RadTaskDialogPage() - page.Caption = "Window Title" - page.Heading = "Main instruction" - page.Text = "Main text here..." - page.Icon = RadTaskDialogIcon.ShieldErrorRedBar - page.Icon.SvgImage = RadTaskDialogIcon.GetSvgImage(RadTaskDialogIconImage.FlatShieldSuccess, New Size(32, 32)) - Dim verificationCheck As RadTaskDialogVerificationCheckBox = New RadTaskDialogVerificationCheckBox() - verificationCheck.Text = "Verification" - AddHandler verificationCheck.CheckStateChanged, New EventHandler(Function(sender As Object, e As EventArgs) - RadMessageBox.Show(verificationCheck.CheckState.ToString()) - End Function) - page.Verification = verificationCheck - RadTaskDialog.ShowDialog(page) - -```` - -{{endregion}} + + + + ## RadTaskDialogCommandLinkButton @@ -138,41 +71,10 @@ The **State** property is of type **RadTaskDialogProgressBarState** which offers #### Adding a RadTaskDialogCommandLinkButton -{{source=..\SamplesCS\TaskDialog\TaskDialogGettingStarted.cs region=LinkButton}} -{{source=..\SamplesVB\TaskDialog\TaskDialogGettingStarted.vb region=LinkButton}} - -````C# - RadTaskDialogPage page = new RadTaskDialogPage(); - page.Caption = "Window Title"; - page.Heading = "Main instruction"; - page.Text = "Main text here..."; - page.Icon = RadTaskDialogIcon.ShieldWarningYellowBar; - page.Icon.SvgImage = RadTaskDialogIcon.GetSvgImage(RadTaskDialogIconImage.FlatShieldWarning, new Size(32, 32)); - - RadTaskDialogCommandLinkButton linkButton = new RadTaskDialogCommandLinkButton(); - linkButton.Text = "Link Button"; - linkButton.DescriptionText = "This is a link button"; - page.ContentArea.Buttons.Add(linkButton); - RadTaskDialog.ShowDialog(page); - -```` -````VB.NET - Dim page As RadTaskDialogPage = New RadTaskDialogPage() - page.Caption = "Window Title" - page.Heading = "Main instruction" - page.Text = "Main text here..." - page.Icon = RadTaskDialogIcon.ShieldWarningYellowBar - page.Icon.SvgImage = RadTaskDialogIcon.GetSvgImage(RadTaskDialogIconImage.FlatShieldWarning, New Size(32, 32)) - Dim linkButton As RadTaskDialogCommandLinkButton = New RadTaskDialogCommandLinkButton() - linkButton.Text = "Link Button" - linkButton.DescriptionText = "This is a link button" - page.ContentArea.Buttons.Add(linkButton) - RadTaskDialog.ShowDialog(page) - - -```` - -{{endregion}} + + + + ## RadTaskDialogRadioButton @@ -182,47 +84,10 @@ Adding multiple **RadTaskDialogRadioButtons** allows users to choose from differ #### Adding a RadTaskDialogRadioButton -{{source=..\SamplesCS\TaskDialog\TaskDialogGettingStarted.cs region=RadioChoices}} -{{source=..\SamplesVB\TaskDialog\TaskDialogGettingStarted.vb region=RadioChoices}} - -````C# - RadTaskDialogPage page = new RadTaskDialogPage(); - page.Caption = "Window Title"; - page.Heading = "Main instruction"; - page.Text = "Main text here..."; - page.Icon = RadTaskDialogIcon.ShieldWarningYellowBar; - page.Icon.SvgImage = RadTaskDialogIcon.GetSvgImage(RadTaskDialogIconImage.FlatShieldWarning, new Size(32, 32)); - - page.RadioButtons = new RadItemOwnerGenericCollection() - { - new RadRadioButtonElement() { Text = "Radio 1" }, - new RadRadioButtonElement() { Text = "Radio 2" } - }; - - RadTaskDialog.ShowDialog(page); - -```` -````VB.NET - Dim page As RadTaskDialogPage = New RadTaskDialogPage() - page.Caption = "Window Title" - page.Heading = "Main instruction" - page.Text = "Main text here..." - page.Icon = RadTaskDialogIcon.ShieldWarningYellowBar - page.Icon.SvgImage = RadTaskDialogIcon.GetSvgImage(RadTaskDialogIconImage.FlatShieldWarning, New Size(32, 32)) - page.RadioButtons = New RadItemOwnerGenericCollection(Of RadTaskDialogRadioButton)() From { - New RadRadioButtonElement() With { - .Text = "Radio 1" - }, - New RadRadioButtonElement() With { - .Text = "Radio 2" - } - } - RadTaskDialog.ShowDialog(page) - - -```` - -{{endregion}} + + + + ## RadTaskDialogButton @@ -232,56 +97,10 @@ Adding multiple **RadTaskDialogRadioButtons** allows users to choose from differ #### Adding a RadTaskDialogButton -{{source=..\SamplesCS\TaskDialog\TaskDialogGettingStarted.cs region=DialogButtons}} -{{source=..\SamplesVB\TaskDialog\TaskDialogGettingStarted.vb region=DialogButtons}} - -````C# - RadTaskDialogPage page = new RadTaskDialogPage(); - page.Caption = "Window Title"; - page.Heading = "Main instruction"; - page.Text = "Main text here..."; - page.Icon = RadTaskDialogIcon.ShieldSuccessGreenBar ; - page.Icon.SvgImage = RadTaskDialogIcon.GetSvgImage(RadTaskDialogIconImage.GradientShieldSuccess , new Size(32, 32)); - - RadTaskDialogButton button1 = new RadTaskDialogButton(); - button1.Text = "Custom Button1"; - button1.Click += new EventHandler(delegate(object sender, EventArgs e) { RadMessageBox.Show("Clicked Button1!"); }); - page.DefaultButton = button1; - page.CommandAreaButtons.Add(button1); - RadTaskDialogButton button2 = new RadTaskDialogButton(); - button2.Text = "Custom Button2"; - button2.Click += new EventHandler(delegate(object sender, EventArgs e) { RadMessageBox.Show("Clicked Button2!"); }); - page.CommandAreaButtons.Add(button2); - - RadTaskDialog.ShowDialog(page); - -```` -````VB.NET - - Dim page As RadTaskDialogPage = New RadTaskDialogPage() - page.Caption = "Window Title" - page.Heading = "Main instruction" - page.Text = "Main text here..." - page.Icon = RadTaskDialogIcon.ShieldSuccessGreenBar - page.Icon.SvgImage = RadTaskDialogIcon.GetSvgImage(RadTaskDialogIconImage.GradientShieldSuccess, New Size(32, 32)) - Dim button1 As RadTaskDialogButton = New RadTaskDialogButton() - button1.Text = "Custom Button1" - AddHandler button1.Click, New EventHandler(Function(sender As Object, e As EventArgs) - RadMessageBox.Show("Clicked Button1!") - End Function) - page.DefaultButton = button1 - page.CommandAreaButtons.Add(button1) - Dim button2 As RadTaskDialogButton = New RadTaskDialogButton() - button2.Text = "Custom Button2" - AddHandler button2.Click, New EventHandler(Function(sender As Object, e As EventArgs) - RadMessageBox.Show("Clicked Button2!") - End Function) - page.CommandAreaButtons.Add(button2) - RadTaskDialog.ShowDialog(page) - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/task-dialog/task-dialog-getting-started.md b/controls/task-dialog/task-dialog-getting-started.md index 79d861ba6..979ea446b 100644 --- a/controls/task-dialog/task-dialog-getting-started.md +++ b/controls/task-dialog/task-dialog-getting-started.md @@ -40,117 +40,10 @@ This article will walk you through the creation of a sample task dialog that con ![WinForms RadTaskDialog Getting Started](images/task-dialog-overview001.gif) -{{source=..\SamplesCS\TaskDialog\TaskDialogGettingStarted.cs region=Example1}} -{{source=..\SamplesVB\TaskDialog\TaskDialogGettingStarted.vb region=Example1}} - -````C# - -RadTaskDialogPage page = new RadTaskDialogPage(); -page.Caption = "Window Title"; -page.Heading = "Main instruction"; -page.Text = "Main text here..."; -page.Icon = RadTaskDialogIcon.ShieldSuccessGreenBar; -page.Icon.SvgImage = RadTaskDialogIcon.GetSvgImage(RadTaskDialogIconImage.FlatShieldSuccess, new Size(32, 32)); - -RadTaskDialogButton button1 = new RadTaskDialogButton(); -button1.Text = "Custom Button1"; -button1.Click += new EventHandler(delegate(object sender, EventArgs e) { RadMessageBox.Show("Clicked Button1!"); }); -page.DefaultButton = button1; -page.CommandAreaButtons.Add(button1); -RadTaskDialogButton button2 = new RadTaskDialogButton(); -button2.Text = "Custom Button2"; -button2.Click += new EventHandler(delegate(object sender, EventArgs e) { RadMessageBox.Show("Clicked Button2!"); }); -page.CommandAreaButtons.Add(button2); - -RadTaskDialogCommandLinkButton linkButton = new RadTaskDialogCommandLinkButton(); -linkButton.Text = "Link Button"; -linkButton.DescriptionText = "This is a link button"; -page.ContentArea.Buttons.Add(linkButton); - -RadTaskDialogProgressBar taskProgressBar = new RadTaskDialogProgressBar(); -taskProgressBar.Value = 30; -page.ProgressBar = taskProgressBar; -page.ProgressBar.Text = "Content"; - -page.RadioButtons = new RadItemOwnerGenericCollection() -{ - new RadRadioButtonElement() { Text = "Radio 1" }, - new RadRadioButtonElement() { Text = "Radio 2" } -}; - -RadTaskDialogVerificationCheckBox verificationCheck = new RadTaskDialogVerificationCheckBox(); -verificationCheck.Text = "Verification"; -verificationCheck.CheckStateChanged += new EventHandler(delegate(object sender, EventArgs e) - { RadMessageBox.Show(verificationCheck.CheckState.ToString()); }); -page.Verification = verificationCheck; - -page.Expander.Text = "Collapsible information here..."; -page.Expander.Expanded = true; -page.Expander.ExpandedButtonText = "Collapse Info"; -page.Expander.CollapsedButtonText = "More Info"; -page.Expander.Position = RadTaskDialogExpanderPosition.AfterFootnote; - -page.Footnote.Text = "Telerik Hyperlink "; - -RadTaskDialog.ShowDialog(page); - - -```` -````VB.NET - -Dim page As RadTaskDialogPage = New RadTaskDialogPage() -page.Caption = "Window Title" -page.Heading = "Main instruction" -page.Text = "Main text here..." -page.Icon = RadTaskDialogIcon.ShieldSuccessGreenBar -page.Icon.SvgImage = RadTaskDialogIcon.GetSvgImage(RadTaskDialogIconImage.FlatShieldSuccess, New Size(32, 32)) -Dim button1 As RadTaskDialogButton = New RadTaskDialogButton() -button1.Text = "Custom Button1" -AddHandler button1.Click, AddressOf New EventHandler(Function(sender As Object, e As EventArgs) - RadMessageBox.Show("Clicked Button1!") - End Function) -page.DefaultButton = button1 -page.CommandAreaButtons.Add(button1) -Dim button2 As RadTaskDialogButton = New RadTaskDialogButton() -button2.Text = "Custom Button2" -AddHandler button2.Click, AddressOf New EventHandler(Function(sender As Object, e As EventArgs) - RadMessageBox.Show("Clicked Button2!") - End Function) -page.CommandAreaButtons.Add(button2) -Dim linkButton As RadTaskDialogCommandLinkButton = New RadTaskDialogCommandLinkButton() -linkButton.Text = "Link Button" -linkButton.DescriptionText = "This is a link button" -page.ContentArea.Buttons.Add(linkButton) -Dim taskProgressBar As RadTaskDialogProgressBar = New RadTaskDialogProgressBar() -taskProgressBar.Value = 30 -page.ProgressBar = taskProgressBar -page.ProgressBar.Text = "Content" -page.RadioButtons = New RadItemOwnerGenericCollection(Of RadTaskDialogRadioButton)() From { - New RadRadioButtonElement() With { - .Text = "Radio 1" - }, - New RadRadioButtonElement() With { - .Text = "Radio 2" - } -} -Dim verificationCheck As RadTaskDialogVerificationCheckBox = New RadTaskDialogVerificationCheckBox() -verificationCheck.Text = "Verification" -AddHandler verificationCheck.CheckStateChanged, AddressOf New EventHandler(Function(sender As Object, e As EventArgs) - RadMessageBox.Show(verificationCheck.CheckState.ToString()) - End Function) -page.Verification = verificationCheck -page.Expander.Text = "Collapsible information here..." -page.Expander.Expanded = True -page.Expander.ExpandedButtonText = "Collapse Info" -page.Expander.CollapsedButtonText = "More Info" -page.Expander.Position = RadTaskDialogExpanderPosition.AfterFootnote -page.Footnote.Text = "Telerik Hyperlink " -RadTaskDialog.ShowDialog(page) - - -```` - -{{endregion}} + + + + ## Multiple Pages @@ -159,32 +52,10 @@ RadTaskDialog.ShowDialog(page) >important Please make sure that the **AllowCloseDialog** property is set to *false* for the **RadTaskDialogCommandLinkButton**. Otherwise, the task dialog is expected to be closed when the user clicks the button. -{{source=..\SamplesCS\TaskDialog\TaskDialogGettingStarted.cs region=MultiplePages}} -{{source=..\SamplesVB\TaskDialog\TaskDialogGettingStarted.vb region=MultiplePages}} - -````C# -linkButton.AllowCloseDialog = false; -linkButton.Click += new EventHandler(delegate(object sender, EventArgs e) -{ - RadTaskDialogPage nextPage = new RadTaskDialogPage(); - //construct the next page's content here - page.Navigate(nextPage); -}); - -```` -````VB.NET - -linkButton.AllowCloseDialog = False -AddHandler linkButton.Click, New EventHandler(Function(sender As Object, e As EventArgs) - Dim nextPage As RadTaskDialogPage = New RadTaskDialogPage() - 'construct the next page's content here - page.Navigate(nextPage) - End Function) - + + -```` -{{endregion}} ## See Also diff --git a/controls/task-dialog/task-dialog-icons.md b/controls/task-dialog/task-dialog-icons.md index 42e4ceb53..15614d50b 100644 --- a/controls/task-dialog/task-dialog-icons.md +++ b/controls/task-dialog/task-dialog-icons.md @@ -14,30 +14,10 @@ position: 4 #### Specifying the dialog icon -{{source=..\SamplesCS\TaskDialog\TaskDialogGettingStarted.cs region=DialogIcon}} -{{source=..\SamplesVB\TaskDialog\TaskDialogGettingStarted.vb region=DialogIcon}} + + -````C# - RadTaskDialogPage page = new RadTaskDialogPage(); - page.Caption = "Window Title"; - page.Heading = "Main instruction"; - page.Text = "Main text here..."; - page.Icon = RadTaskDialogIcon.Information; - RadTaskDialog.Show(page); -```` -````VB.NET - - Dim page As RadTaskDialogPage = New RadTaskDialogPage() - page.Caption = "Window Title" - page.Heading = "Main instruction" - page.Text = "Main text here..." - page.Icon = RadTaskDialogIcon.Information - RadTaskDialog.Show(page) - -```` - -{{endregion}} You can find listed below the available built-in icons: @@ -89,29 +69,10 @@ If none of the built-in icons fits your needs, it is possible to construct your ![WinForms RadTaskDialog Custom Icon](images/task-dialog-icons011.png) -{{source=..\SamplesCS\TaskDialog\TaskDialogGettingStarted.cs region=CustomIcon}} -{{source=..\SamplesVB\TaskDialog\TaskDialogGettingStarted.vb region=CustomIcon}} - -````C# - RadTaskDialogPage page = new RadTaskDialogPage(); - page.Caption = "Window Title"; - page.Heading = "Main instruction"; - page.Text = "Main text here..."; - page.Icon = new RadTaskDialogIcon(new Bitmap(Properties.Resources.TV_car,new Size(64,64))); - RadTaskDialog.Show(page); - -```` -````VB.NET - Dim page As RadTaskDialogPage = New RadTaskDialogPage() - page.Caption = "Window Title" - page.Heading = "Main instruction" - page.Text = "Main text here..." - page.Icon = New RadTaskDialogIcon(New Bitmap(My.Resources.TV_car1, New Size(64, 64))) - RadTaskDialog.Show(page) - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/taskbar-button/features/jumplist.md b/controls/taskbar-button/features/jumplist.md index 63e2cffc7..f00c8caf5 100644 --- a/controls/taskbar-button/features/jumplist.md +++ b/controls/taskbar-button/features/jumplist.md @@ -18,76 +18,10 @@ A jump list is a system-provided menu that appears when the user right-clicks a The following code snippet demonstrates how to define a jump list for a Form inside the Windows Forms application we have: -{{source=..\SamplesCS\TaskbarButton\TaskbarButtonGettingStarted.cs region=JumpList}} -{{source=..\SamplesVB\TaskbarButton\TaskbarButtonGettingStarted.vb region=JumpList}} + + -````C# -RadJumpList list = new RadJumpList("Mail Application", this.Handle); - -JumpLink task = new JumpLink("https://www.telerik.com/", "Telerik and Kendo UI components"); -task.ShowCommand = Telerik.WinControls.Taskbar.Core.WindowShowCommand.Show; -task.IconReference = new IconReference(@"R:\UX\Progress Rebranding\Product Icons\WinForms.ico", 0); -list.Tasks.Add(task); - -JumpListCategory userActionsCategory = new JumpListCategory("Actions"); - -JumpLink userActionLink = new JumpLink(System.Reflection.Assembly.GetEntryAssembly().Location, "Clear History"); -userActionLink.Arguments = "-1"; - -userActionsCategory.JumpItems.Add(userActionLink); -list.Categories.Add(userActionsCategory); - -string notepadPath = Path.Combine(Environment.SystemDirectory, "notepad.exe"); -JumpLink jlNotepad = new JumpLink(notepadPath, "Notepad"); -jlNotepad.IconReference = new IconReference(@"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", 0); - -string calcPath = Path.Combine(Environment.SystemDirectory, "calc.exe"); -JumpLink jlCalculator = new JumpLink(calcPath, "Calculator"); -jlCalculator.IconReference = new IconReference(calcPath, 0); - -string mspaintPath = Path.Combine(Environment.SystemDirectory, "mspaint.exe"); -JumpLink jlPaint = new JumpLink(mspaintPath, "Paint"); -jlPaint.IconReference = new IconReference(mspaintPath, 0); - -list.Tasks.Add(jlNotepad); -list.Tasks.Add(jlPaint); -list.Tasks.Add(new JumpSeparator()); -list.Tasks.Add(jlCalculator); - -// To update the JumpList and the taskbar we need to call Refresh method. -list.Refresh(); - -```` -````VB.NET -Dim list As RadJumpList = New RadJumpList("Mail Application", Me.Handle) -Dim task As JumpLink = New JumpLink("https://www.telerik.com/", "Telerik and Kendo UI components") -task.ShowCommand = Telerik.WinControls.Taskbar.Core.WindowShowCommand.Show -task.IconReference = New IconReference("R:\UX\Progress Rebranding\Product Icons\WinForms.ico", 0) -list.Tasks.Add(task) -Dim userActionsCategory As JumpListCategory = New JumpListCategory("Actions") -Dim userActionLink As JumpLink = New JumpLink(System.Reflection.Assembly.GetEntryAssembly().Location, "Clear History") -userActionLink.Arguments = "-1" -userActionsCategory.JumpItems.Add(userActionLink) -list.Categories.Add(userActionsCategory) -Dim notepadPath As String = Path.Combine(Environment.SystemDirectory, "notepad.exe") -Dim jlNotepad As JumpLink = New JumpLink(notepadPath, "Notepad") -jlNotepad.IconReference = New IconReference("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", 0) -Dim calcPath As String = Path.Combine(Environment.SystemDirectory, "calc.exe") -Dim jlCalculator As JumpLink = New JumpLink(calcPath, "Calculator") -jlCalculator.IconReference = New IconReference(calcPath, 0) -Dim mspaintPath As String = Path.Combine(Environment.SystemDirectory, "mspaint.exe") -Dim jlPaint As JumpLink = New JumpLink(mspaintPath, "Paint") -jlPaint.IconReference = New IconReference(mspaintPath, 0) -list.Tasks.Add(jlNotepad) -list.Tasks.Add(jlPaint) -list.Tasks.Add(New JumpSeparator()) -list.Tasks.Add(jlCalculator) -list.Refresh() - -```` - -{{endregion}} ![WinForms TaskbarButton Define Jump List](images/taskbar-button-features-jumplist002.png) diff --git a/controls/taskbar-button/features/progress.md b/controls/taskbar-button/features/progress.md index 637f91abe..caa081fba 100644 --- a/controls/taskbar-button/features/progress.md +++ b/controls/taskbar-button/features/progress.md @@ -15,42 +15,10 @@ The RadTaskbarButton component provides you with the possibility to display the In the following example, we are going to simulate the progress of a running task in the taskbar. On each second, the __ProgressPercentage__ property is increased by 10 percent. -{{source=..\SamplesCS\TaskbarButton\TaskbarButtonGettingStarted.cs region=Progress_Indication}} -{{source=..\SamplesVB\TaskbarButton\TaskbarButtonGettingStarted.vb region=Progress_Indication}} + + -````C# -Timer timer = new Timer(); -void ShowTaskProgress() -{ - timer.Interval = 1000; - timer.Tick += Timer_Tick; - timer.Start(); -} - -private void Timer_Tick(object sender, System.EventArgs e) -{ - this.radTaskbarButton1.ProgressPercentage += 10; -} - -```` -````VB.NET -Private timer As Timer = New Timer() - -Private Sub ShowTaskProgress() - timer.Interval = 1000 - timer.Tick += AddressOf Timer_Tick - timer.Start() -End Sub - -Private Sub Timer_Tick(ByVal sender As Object, ByVal e As System.EventArgs) - Me.radTaskbarButton1.ProgressPercentage += 10 -End Sub - - -```` - -{{endregion}} ### Progress State diff --git a/controls/taskbar-button/features/thumbnail-buttons.md b/controls/taskbar-button/features/thumbnail-buttons.md index e4f1e6fcf..c81bd67b5 100644 --- a/controls/taskbar-button/features/thumbnail-buttons.md +++ b/controls/taskbar-button/features/thumbnail-buttons.md @@ -35,57 +35,17 @@ RadTaskbarButton can display buttons in its thumbnail part. Adding buttons to yo #### Adding Thumbnail Buttons -{{source=..\SamplesCS\TaskbarButton\TaskbarButtonGettingStarted.cs region=ThumbnailButtons}} -{{source=..\SamplesVB\TaskbarButton\TaskbarButtonGettingStarted.vb region=ThumbnailButtons}} + + -````C# -Telerik.WinControls.Taskbar.RadThumbnailButton radThumbnailButton1 = new Telerik.WinControls.Taskbar.RadThumbnailButton(); -Telerik.WinControls.Taskbar.RadThumbnailButton radThumbnailButton2 = new Telerik.WinControls.Taskbar.RadThumbnailButton(); -this.radTaskbarButton1.ThumbnailButtons.Add(radThumbnailButton1); -this.radTaskbarButton1.ThumbnailButtons.Add(radThumbnailButton2); -```` -````VB.NET - -Dim radThumbnailButton1 As Telerik.WinControls.Taskbar.RadThumbnailButton = New Telerik.WinControls.Taskbar.RadThumbnailButton() -Dim radThumbnailButton2 As Telerik.WinControls.Taskbar.RadThumbnailButton = New Telerik.WinControls.Taskbar.RadThumbnailButton() -Me.RadTaskbarButton1.ThumbnailButtons.Add(radThumbnailButton1) -Me.RadTaskbarButton1.ThumbnailButtons.Add(radThumbnailButton2 - -```` - -{{endregion}} - - To add image content to the buttons, you can populate the __ThumbnailButtonsImageList__ collection of the __RadTaskbarButton__ with the required images. Then, you can set the ImageIndex property of each button to the index of image inside the collection. -{{source=..\SamplesCS\TaskbarButton\TaskbarButtonGettingStarted.cs region=Thumbnail_Image}} -{{source=..\SamplesVB\TaskbarButton\TaskbarButtonGettingStarted.vb region=Thumbnail_Image}} - -````C# - -var images = new ImageList(); -images.Images.Add(new Bitmap("../../ProgressIcon.ico")); -images.Images.Add(new Bitmap("../../WinFormsIcon.ico")); -this.radTaskbarButton1.ThumbnailButtonsImageList = images; -this.radTaskbarButton1.ThumbnailButtons[0].ImageIndex = 0; -this.radTaskbarButton1.ThumbnailButtons[1].ImageIndex = 1; - + + -```` -````VB.NET -Dim images = New ImageList() -images.Images.Add(New Bitmap("../../ProgressIcon.ico")) -images.Images.Add(New Bitmap("../../WinFormsIcon.ico")) -Me.RadTaskbarButton1.ThumbnailButtonsImageList = images -Me.RadTaskbarButton1.ThumbnailButtons(0).ImageIndex = 0 -Me.RadTaskbarButton1.ThumbnailButtons(1).ImageIndex = 1 - -```` - -{{endregion}} >caution Note that once thumbnail buttons are added to the TnumbnailButtons collection and submitted to the application, they no longer can be modified. Only can be hidden by setting the Hidden property. @@ -113,24 +73,10 @@ To distinguish which button is clicked by the user and execute any application l There could be requirement to add non interactive icon in the buttons section inside the thumbnail preview. To simulate this effect you can use the NonBackground and NonInteractive properties. The first one will remove the border rectangle and mouse hover effects and the second one will disable the button press event. -{{source=..\SamplesCS\TaskbarButton\TaskbarButtonGettingStarted.cs region=Non_Interactive_State}} -{{source=..\SamplesVB\TaskbarButton\TaskbarButtonGettingStarted.vb region=Non_Interactive_State}} - -````C# - -this.radTaskbarButton1.ThumbnailButtons[0].NoBackground = true; -this.radTaskbarButton1.ThumbnailButtons[0].NonInteractive = true; - - -```` -````VB.NET - -Me.RadTaskbarButton1.ThumbnailButtons(0).NoBackground = True -Me.RadTaskbarButton1.ThumbnailButtons(0).NonInteractive = True + + -```` -{{endregion}} >caption Figure 3: NonInteractive Button diff --git a/controls/taskbar-button/features/tooltips.md b/controls/taskbar-button/features/tooltips.md index 15c717bff..19d1a5b5d 100644 --- a/controls/taskbar-button/features/tooltips.md +++ b/controls/taskbar-button/features/tooltips.md @@ -19,41 +19,18 @@ RadTaskbarButton exposes Microsoft API to set tooltip text on its thumbnail prev To set a ToolTip on the thumbnail preview part of the control, you can use the __ThumbnailTooltip__ property of __RadTaskbarButton__. -{{source=..\SamplesCS\TaskbarButton\TaskbarButtonGettingStarted.cs region=ThumbnailTooltip}} -{{source=..\SamplesVB\TaskbarButton\TaskbarButtonGettingStarted.vb region=ThumbnailTooltip}} + + -````C# -this.radTaskbarButton1.ThumbnailTooltip = "My RadTaskbar Button ToolTip"; -```` -````VB.NET - -Me.RadTaskbarButton1.ThumbnailTooltip = "My RadTaskbar Button ToolTip" - -```` - -{{endregion}} - - To set ToolTip to the thumbnail buttons, you can directly use their **ToolTip** property. -{{source=..\SamplesCS\TaskbarButton\TaskbarButtonGettingStarted.cs region=ThumbnailButtonTooltip}} -{{source=..\SamplesVB\TaskbarButton\TaskbarButtonGettingStarted.vb region=ThumbnailButtonTooltip}} + + -````C# -this.radTaskbarButton1.ThumbnailButtons[1].ToolTip = "Telerik WinForms"; -```` -````VB.NET - -Me.RadTaskbarButton1.ThumbnailButtons[1].ToolTip = "Telerik WinForms" - -```` - -{{endregion}} - ## See Also * [Getting Started]({%slug taskbar-button-getting-started%}) diff --git a/controls/taskbar-button/taskbar-manager.md b/controls/taskbar-button/taskbar-manager.md index 88182e130..b2d7429ae 100644 --- a/controls/taskbar-button/taskbar-manager.md +++ b/controls/taskbar-button/taskbar-manager.md @@ -12,44 +12,10 @@ position: 5 **RadTaskbarManager** allows you to manage the functionality offered by our RadTaskbarButton at run time, e.g. start/stop flashing or updating the tool tip for the thumbnail. It offers convenient public static API for that purpose. Additional information is available in the [Properties, Methods and Events]({%slug taskbar-button-properties-methods-events%}) article. -{{source=..\SamplesCS\TaskbarButton\TaskbarButtonGettingStarted.cs region=Manager}} -{{source=..\SamplesVB\TaskbarButton\TaskbarButtonGettingStarted.vb region=Manager}} + + -````C# -private void radButton1_Click(object sender, EventArgs e) -{ - RadTaskbarManager.Flash(this.Handle); -} - -private void radButton2_Click(object sender, EventArgs e) -{ - RadTaskbarManager.StopFlash(this.Handle); -} - -private void radButton3_Click(object sender, EventArgs e) -{ - RadTaskbarManager.SetThumbnailTooltip(this.Handle, DateTime.Now.ToLongTimeString()); -} - -```` -````VB.NET - -Private Sub radButton1_Click(ByVal sender As Object, ByVal e As EventArgs) - RadTaskbarManager.Flash(Me.Handle) -End Sub - -Private Sub radButton2_Click(ByVal sender As Object, ByVal e As EventArgs) - RadTaskbarManager.StopFlash(Me.Handle) -End Sub - -Private Sub radButton3_Click(ByVal sender As Object, ByVal e As EventArgs) - RadTaskbarManager.SetThumbnailTooltip(Me.Handle, DateTime.Now.ToLongTimeString()) -End Sub - -```` - -{{endregion}} ![WinForms TaskbarButton Manager](images/taskbar-manager001.gif) diff --git a/controls/toast-notification/adding-toast-notifications-programmatically.md b/controls/toast-notification/adding-toast-notifications-programmatically.md index eb0668a86..33e0058b1 100644 --- a/controls/toast-notification/adding-toast-notifications-programmatically.md +++ b/controls/toast-notification/adding-toast-notifications-programmatically.md @@ -17,110 +17,9 @@ It is possible to build a **RadToastNotification** at run time, passing the [Rad #### Adding RadToastNotification at RunTime -{{source=..\SamplesCS\ToastNotification\ProgrammaticallyAddedToasts.cs region=ProgrammaticallyAddedNotifications}} -{{source=..\SamplesVB\ToastNotification\ProgrammaticallyAddedToasts.vb region=ProgrammaticallyAddedNotifications}} + + -````C# - - RadToastNotificationManager radToastNotificationManager = new RadToastNotificationManager(); - - public ProgrammaticallyAddedToasts() - { - InitializeComponent(); - - RadButton button = new RadButton(); - this.Controls.Add(button); - button.Click += button_Click; - - RadToastNotificationManager.RadToastOnActivated += RadToastNotificationManager_RadToastOnActivated; - - RadToastNotification defaultWeatherNotification = new RadToastNotification(RadToastTemplateType.ToastWeather, "Weather in Sofia"); - this.radToastNotificationManager.ToastNotifications.Add(defaultWeatherNotification); - - string xmlContent = @" - - - Login Information: - - - - - - - - - "; - RadToastNotification customLoginNotification = new RadToastNotification(RadToastTemplateType.ToastGeneric, "Login", xmlContent); - this.radToastNotificationManager.ToastNotifications.Add(customLoginNotification); - } - - private void RadToastNotificationManager_RadToastOnActivated(RadToastOnActivatedEventArgs e) - { - foreach (KeyValuePair pair in e.UserInput) - { - Console.WriteLine(pair.Key + " " + pair.Value); - } - } - - private void button_Click(object sender, EventArgs e) - { - this.radToastNotificationManager.ShowNotification(1); - } - - protected override void OnClosed(EventArgs e) - { - base.OnClosed(e); - this.radToastNotificationManager.Unregister(); - } - -```` -````VB.NET - - Friend WithEvents radToastNotificationManager As RadToastNotificationManager = New RadToastNotificationManager() - - Private Sub RadToastNotificationManager_RadToastOnActivated(ByVal e As RadToastOnActivatedEventArgs) Handles radToastNotificationManager.RadToastOnActivated - For Each pair As KeyValuePair(Of String, Object) In e.UserInput - Console.WriteLine(pair.Key & " " + pair.Value) - Next - End Sub - - Public Sub New() - InitializeComponent() - Dim button As RadButton = New RadButton() - Me.Controls.Add(button) - AddHandler button.Click, AddressOf button_Click - - Dim defaultWeatherNotification As RadToastNotification = New RadToastNotification(RadToastTemplateType.ToastWeather, "Weather in Sofia") - Me.radToastNotificationManager.ToastNotifications.Add(defaultWeatherNotification) - Dim xmlContent As String = "" & _ - "" & _ - "" & _ - "Login Information:" & _ - "" & _ - "" & _ - "" & _ - "" & _ - "" & _ - "" & _ - " " & _ - " " & _ - "" - Dim customLoginNotification As RadToastNotification = New RadToastNotification(RadToastTemplateType.ToastGeneric, "Login", xmlContent) - Me.radToastNotificationManager.ToastNotifications.Add(customLoginNotification) - End Sub - - Private Sub button_Click(ByVal sender As Object, ByVal e As EventArgs) - Me.radToastNotificationManager.ShowNotification(1) - End Sub - - Protected Overrides Sub OnClosed(ByVal e As EventArgs) - MyBase.OnClosed(e) - Me.radToastNotificationManager.Unregister() - End Sub - -```` - -{{endregion}} >important [Obsolete as of R3 2021 SP 1] **RadToastActivated** event is **not** fired on the main UI thread. Hence, you should be cautious when interacting with the controls on the form. Note that all UI controls are not thread safe controls in the whole Windows Forms platform (not just Telerik controls, but all controls out there). You should use [Invoke](https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.control.invoke?redirectedfrom=MSDN&view=net-5.0#System_Windows_Forms_Control_Invoke_System_Delegate_) to update the controls in cross threading scenario. diff --git a/controls/toast-notification/getting-started.md b/controls/toast-notification/getting-started.md index 457bec202..7a62f1bdd 100644 --- a/controls/toast-notification/getting-started.md +++ b/controls/toast-notification/getting-started.md @@ -68,50 +68,10 @@ Register RadToastNotificationManager and Show a Notification #### Show a Notification -{{source=..\SamplesCS\ToastNotification\ToastNotificationGettingStarted.cs region=RegisterGettingStarted}} -{{source=..\SamplesVB\ToastNotification\ToastNotificationGettingStarted.vb region=RegisterGettingStarted}} + + -````C# -public ToastNotificationGettingsStarted() -{ - InitializeComponent(); - - this.radButton1.Click+=radButton1_Click; -} - -private void radButton1_Click(object sender, EventArgs e) -{ - this.radToastNotificationManager1.ShowNotification(3); -} - -protected override void OnClosed(EventArgs e) -{ - base.OnClosed(e); - this.radToastNotificationManager1.Unregister(); -} - - -```` -````VB.NET -Public Sub New() - InitializeComponent() - - AddHandler Me.RadButton1.Click, AddressOf radButton1_Click -End Sub - -Private Sub radButton1_Click(ByVal sender As Object, ByVal e As EventArgs) - Me.radToastNotificationManager1.ShowNotification(3) -End Sub - -Protected Overrides Sub OnClosed(ByVal e As EventArgs) - MyBase.OnClosed(e) - Me.radToastNotificationManager1.Unregister() -End Sub - -```` - -{{endregion}} >important The screenshot below is captured under OS Windows 10. The toast notification templates may differ according to the operating system (and OS style theme) that shows them. diff --git a/controls/toast-notification/handling-users-input.md b/controls/toast-notification/handling-users-input.md index cef2501cd..b27c2d009 100644 --- a/controls/toast-notification/handling-users-input.md +++ b/controls/toast-notification/handling-users-input.md @@ -20,66 +20,10 @@ CTAControlName: ToastNotification We will extend the example for building log-in toast notification in the [Adding Toast Notifications Programmatically ]({%slug toast-notification-adding-toast-notifications-programmatically%}) article and check the user name and password. -{{source=..\SamplesCS\ToastNotification\ToastNotificationGettingStarted.cs region=Activated}} -{{source=..\SamplesVB\ToastNotification\ToastNotificationGettingStarted.vb region=Activated}} + + -````C# - -protected override void OnLoad(EventArgs e) -{ - base.OnLoad(e); - - RadToastNotificationManager.RadToastActivated+=RadToastNotificationManager_RadToastActivated; -} - -private void RadToastNotificationManager_RadToastActivated(RadToastActivatedEventArgs e) -{ - Dictionary userInput = e.UserInput; - string userName = userInput["UserNameInput"]; - string password = userInput["PasswordInput"]; - if (userName == string.Empty) - { - RadMessageBox.Show("UserName is empty!"); - } - - if (password == string.Empty) - { - RadMessageBox.Show("Password is empty!"); - } - - this.Invoke((MethodInvoker)delegate { this.Text = "UserName: " + userName + "Password: " + password; }); - -} - -```` -````VB.NET - -Protected Overrides Sub OnLoad(ByVal e As EventArgs) - MyBase.OnLoad(e) - AddHandler RadToastNotificationManager.RadToastActivated, AddressOf RadToastNotificationManager_RadToastActivated -End Sub - -Private Sub RadToastNotificationManager_RadToastActivated(ByVal e As RadToastActivatedEventArgs) - Dim userInput As Dictionary(Of String, String) = e.UserInput - Dim userName As String = userInput("UserNameInput") - Dim password As String = userInput("PasswordInput") - - If userName = String.Empty Then - RadMessageBox.Show("UserName is empty!") - End If - - If password = String.Empty Then - RadMessageBox.Show("Password is empty!") - End If - - Me.Invoke(CType(Function() - Me.Text = "UserName: " & userName & "Password: " & password - End Function, Windows.Forms.MethodInvoker)) -End Sub - -```` -{{endregion}} Toast notifications remains in the Windows Action Center until removed and the user can interact with them, even if the application is already closed. Thus, they provide the ability to respond after the application has been closed. The following code snippet demonstrates a sample approach how to detect when a toast has been clicked in this case: diff --git a/controls/track-and-status-controls/progressbar/customizing-appearance/accessing-and-customizing-elements.md b/controls/track-and-status-controls/progressbar/customizing-appearance/accessing-and-customizing-elements.md index 0c486bc40..30c119e19 100644 --- a/controls/track-and-status-controls/progressbar/customizing-appearance/accessing-and-customizing-elements.md +++ b/controls/track-and-status-controls/progressbar/customizing-appearance/accessing-and-customizing-elements.md @@ -27,27 +27,10 @@ You can customize the nested elements at run time as well: #### Customize elements -{{source=..\SamplesCS\TrackAndStatus\ProgressBar\ProgressGettingStarted.cs region=CustomizeElements}} -{{source=..\SamplesVB\TrackAndStatus\ProgressBar\ProgressGettingStarted.vb region=CustomizeElements}} - -````C# -this.radProgressBar1.ForeColor = Color.Red; -this.radProgressBar1.ProgressBarElement.IndicatorElement1.BackColor = Color.Lime; -this.radProgressBar1.ProgressBarElement.IndicatorElement1.DrawBorder = true; -this.radProgressBar1.ProgressBarElement.IndicatorElement1.BorderColor = Color.Fuchsia; -this.radProgressBar1.ProgressBarElement.IndicatorElement1.BorderGradientStyle = Telerik.WinControls.GradientStyles.Solid; - -```` -````VB.NET -Me.RadProgressBar1.ForeColor = Color.Red -Me.RadProgressBar1.ProgressBarElement.IndicatorElement1.BackColor = Color.Lime -Me.RadProgressBar1.ProgressBarElement.IndicatorElement1.DrawBorder = True -Me.RadProgressBar1.ProgressBarElement.IndicatorElement1.BorderColor = Color.Fuchsia -Me.RadProgressBar1.ProgressBarElement.IndicatorElement1.BorderGradientStyle = Telerik.WinControls.GradientStyles.Solid - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/track-and-status-controls/progressbar/getting-started.md b/controls/track-and-status-controls/progressbar/getting-started.md index 23526f963..6d6274f98 100644 --- a/controls/track-and-status-controls/progressbar/getting-started.md +++ b/controls/track-and-status-controls/progressbar/getting-started.md @@ -48,37 +48,10 @@ In this tutorial, you will use a **RadProgressBar** to show the progress of a lo #### Handling the Timer Tick event -{{source=..\SamplesCS\TrackAndStatus\ProgressBar\ProgressGettingStarted.cs region=tick}} -{{source=..\SamplesVB\TrackAndStatus\ProgressBar\ProgressGettingStarted.vb region=tick}} - -````C# -int ticks = 0; -private void timer1_Tick(object sender, EventArgs e) -{ - ticks++; - radProgressBar1.Value1 = ticks; - if (ticks == 100) - { - timer1.Enabled = false; - ticks = 0; - } -} - -```` -````VB.NET -Private ticks As Integer = 0 -Private Sub timer1_Tick(ByVal sender As Object, ByVal e As EventArgs) - ticks += 1 - RadProgressBar1.Value1 = ticks - If ticks = 100 Then - Timer1.Enabled = False - ticks = 0 - End If -End Sub - -```` - -{{endregion}} + + + + 6\. In the design view of the form, select the __RadButton__ control. @@ -90,24 +63,10 @@ End Sub 10\. Replace the automatically-generated event handler with this code: -{{source=..\SamplesCS\TrackAndStatus\ProgressBar\ProgressGettingStarted.cs region=click}} -{{source=..\SamplesVB\TrackAndStatus\ProgressBar\ProgressGettingStarted.vb region=click}} - -````C# -void radButton1_Click(object sender, EventArgs e) -{ - timer1.Enabled = true; -} - -```` -````VB.NET -Private Sub radButton1_Click(ByVal sender As Object, ByVal e As EventArgs) - Timer1.Enabled = True -End Sub + + -```` -{{endregion}} 11\. In the design view of the form select the __RadProgressBar__ control. diff --git a/controls/track-and-status-controls/rating/customization.md b/controls/track-and-status-controls/rating/customization.md index 83416956e..576a090d3 100644 --- a/controls/track-and-status-controls/rating/customization.md +++ b/controls/track-and-status-controls/rating/customization.md @@ -15,39 +15,10 @@ previous_url: track-and-status-controls-rating-customization __RadRating__ introduces an easy way to customize the item’s **BackColor** when hovering, selecting, selected a value: -{{source=..\SamplesCS\TrackAndStatus\Rating\RatingGettingStarted.cs region=Background}} -{{source=..\SamplesVB\TrackAndStatus\Rating\RatingGettingStarted.vb region=Background}} - -````C# - -foreach (RatingStarVisualElement item in this.radRating1.Items) -{ - item.Fill.BackColor = Color.LightBlue; - item.HoverElement.Fill.BackColor = Color.DeepSkyBlue; - item.ValueElement.Fill.BackColor = Color.DodgerBlue; - item.SelectedValueElement.Fill.BackColor = Color.Blue; - item.Fill.GradientStyle = Telerik.WinControls.GradientStyles.Solid; - item.HoverElement.Fill.GradientStyle = Telerik.WinControls.GradientStyles.Solid; - item.ValueElement.Fill.GradientStyle = Telerik.WinControls.GradientStyles.Solid; - item.SelectedValueElement.Fill.GradientStyle = GradientStyles.Solid; -} - -```` -````VB.NET -For Each item As RatingStarVisualElement In Me.RadRating1.Items - item.Fill.BackColor = Color.LightBlue - item.HoverElement.Fill.BackColor = Color.DeepSkyBlue - item.ValueElement.Fill.BackColor = Color.DodgerBlue - item.SelectedValueElement.Fill.BackColor = Color.Blue - item.Fill.GradientStyle = Telerik.WinControls.GradientStyles.Solid - item.HoverElement.Fill.GradientStyle = Telerik.WinControls.GradientStyles.Solid - item.ValueElement.Fill.GradientStyle = Telerik.WinControls.GradientStyles.Solid - item.SelectedValueElement.Fill.GradientStyle = GradientStyles.Solid -Next - -```` - -{{endregion}} + + + + >caption Figure 1: Default look @@ -61,101 +32,14 @@ Next By default __RadRating__ supports three main element shapes: Stars, Diamonds and Hearts. If a different kind of shape is needed, __RadRating__ allows you to create and use your own custom visual elements. The following example demonstrates creating a circle visual element: -{{source=..\SamplesCS\TrackAndStatus\Rating\RatingGettingStarted.cs region=CustomShape}} -{{source=..\SamplesVB\TrackAndStatus\Rating\RatingGettingStarted.vb region=CustomShape}} - -````C# - -for (int i = 0; i < 5; i++) -{ - CustomShapeElement myShape = new CustomShapeElement(); - myShape.Fill.BackColor = Color.LightBlue; - myShape.HoverElement.Fill.BackColor = Color.DeepSkyBlue; - myShape.ValueElement.Fill.BackColor = Color.DodgerBlue; - myShape.SelectedValueElement.Fill.BackColor = Color.Blue; - - myShape.Fill.GradientStyle = Telerik.WinControls.GradientStyles.Solid; - myShape.HoverElement.Fill.GradientStyle = Telerik.WinControls.GradientStyles.Solid; - myShape.ValueElement.Fill.GradientStyle = Telerik.WinControls.GradientStyles.Solid; - myShape.SelectedValueElement.Fill.GradientStyle = GradientStyles.Solid; - this.radRating1.Items.Add(myShape); -} - -```` -````VB.NET -For i As Integer = 0 To 4 - Dim myShape As New CustomShapeElement() - myShape.Fill.BackColor = Color.LightBlue - myShape.HoverElement.Fill.BackColor = Color.DeepSkyBlue - myShape.ValueElement.Fill.BackColor = Color.DodgerBlue - myShape.SelectedValueElement.Fill.BackColor = Color.Blue - myShape.Fill.GradientStyle = Telerik.WinControls.GradientStyles.Solid - myShape.HoverElement.Fill.GradientStyle = Telerik.WinControls.GradientStyles.Solid - myShape.ValueElement.Fill.GradientStyle = Telerik.WinControls.GradientStyles.Solid - myShape.SelectedValueElement.Fill.GradientStyle = GradientStyles.Solid - Me.RadRating1.Items.Add(myShape) -Next - -```` - -{{endregion}} - -{{source=..\SamplesCS\TrackAndStatus\Rating\RatingGettingStarted.cs region=CustomShapeClasses}} -{{source=..\SamplesVB\TrackAndStatus\Rating\RatingGettingStarted.vb region=CustomShapeClasses}} - -````C# - -public class CustomShapeElement : RatingVisualElement -{ - protected override ElementShape GetShape() - { - return new CustomShape(); - } - - protected override Type ThemeEffectiveType - { - get - { - return typeof(RatingVisualElement); - } - } -} - -public class CustomShape : ElementShape -{ - public override GraphicsPath CreatePath(Rectangle bounds) - { - GraphicsPath path = new GraphicsPath(); - path.AddEllipse(bounds); - - return path; - } -} - -```` -````VB.NET -Public Class CustomShapeElement -Inherits RatingVisualElement - Protected Overrides Function GetShape() As ElementShape - Return New CustomShape() - End Function - Protected Overrides ReadOnly Property ThemeEffectiveType() As Type - Get - Return GetType(RatingVisualElement) - End Get - End Property -End Class -Public Class CustomShape -Inherits ElementShape - Public Overrides Function CreatePath(bounds As Rectangle) As GraphicsPath - Dim path As New GraphicsPath() - path.AddEllipse(bounds) - Return path - End Function -End Class - -```` - -{{endregion}} + + + + + + + + + ![WinForms RadRating rating-customization 003](images/rating-customization003.png) diff --git a/controls/track-and-status-controls/rating/getting-started.md b/controls/track-and-status-controls/rating/getting-started.md index cc5b0c12d..00efb4253 100644 --- a/controls/track-and-status-controls/rating/getting-started.md +++ b/controls/track-and-status-controls/rating/getting-started.md @@ -48,60 +48,10 @@ Below are the basic steps needed to get started with __RadRating__ control in Vi #### Handling the ValueChanged event -{{source=..\SamplesCS\TrackAndStatus\Rating\RatingGettingStarted.cs region=GettingStarted}} -{{source=..\SamplesVB\TrackAndStatus\Rating\RatingGettingStarted.vb region=GettingStarted}} - -````C# - -double averageRating = 0; -int numberOfChanges = 0; - -public RatingGettingStarted() -{ - InitializeComponent(); - - this.radRating1.Caption = "The best movie ever"; - this.radRating1.Description = "Your rating:"; - this.radRating1.SelectionMode = Telerik.WinControls.UI.RatingSelectionMode.HalfItem; - this.radRating1.ValueChanged += radRating1_ValueChanged; -} - -private void radRating1_ValueChanged(object sender, EventArgs e) -{ - Telerik.WinControls.UI.RadRating rating = sender as Telerik.WinControls.UI.RadRating; - if (rating != null) - { - averageRating += (double)rating.Value; - numberOfChanges++; - double result = averageRating / numberOfChanges; - rating.Description = string.Format("Your rating: {0:F2}/{1}", result, rating.Maximum); - } -} - -```` -````VB.NET -Private averageRating As Double = 0 -Private numberOfChanges As Integer = 0 -Public Sub New() - InitializeComponent() - Me.RadRating1.Caption = "The best movie ever" - Me.RadRating1.Description = "Your rating:" - Me.RadRating1.SelectionMode = Telerik.WinControls.UI.RatingSelectionMode.HalfItem - AddHandler Me.RadRating1.ValueChanged, AddressOf radRating1_ValueChanged -End Sub -Private Sub radRating1_ValueChanged(sender As Object, e As EventArgs) - Dim rating As Telerik.WinControls.UI.RadRating = TryCast(sender, Telerik.WinControls.UI.RadRating) - If rating IsNot Nothing Then - averageRating += CDbl(rating.Value) - numberOfChanges += 1 - Dim result As Double = averageRating / numberOfChanges - rating.Description = String.Format("Your rating: {0:F2}/{1}", result, rating.Maximum) - End If -End Sub - -```` - -{{endregion}} + + + + 5\. Press F5 to run the application. diff --git a/controls/track-and-status-controls/rating/properties-and-events.md b/controls/track-and-status-controls/rating/properties-and-events.md index d3b625f63..11c49aae5 100644 --- a/controls/track-and-status-controls/rating/properties-and-events.md +++ b/controls/track-and-status-controls/rating/properties-and-events.md @@ -54,19 +54,10 @@ You can find below how to set the aforementioned properties and how they affect * **ShowItemToolTips** - by default __RadRating__ shows tooltips when hovering the items. The user can disable this functionality by setting *ShowItemToolTips* property to False: -{{source=..\SamplesCS\TrackAndStatus\Rating\RatingGettingStarted.cs region=ShowItemToolTips}} -{{source=..\SamplesVB\TrackAndStatus\Rating\RatingGettingStarted.vb region=ShowItemToolTips}} + + -````C# -this.radRating1.ShowItemToolTips = false; -```` -````VB.NET -Me.RadRating1.ShowItemToolTips = False - -```` - -{{endregion}} |ShowItemToolTips=false|ShowItemToolTips=true| |----|----| @@ -75,20 +66,10 @@ Me.RadRating1.ShowItemToolTips = False * **RightToLeft** - __RadRating__ supports **RightToLeft** functionality. It is disabled by default, so you should enable it: -{{source=..\SamplesCS\TrackAndStatus\Rating\RatingGettingStarted.cs region=RightToLeft}} -{{source=..\SamplesVB\TrackAndStatus\Rating\RatingGettingStarted.vb region=RightToLeft}} - -````C# - -this.radRating1.RightToLeft = System.Windows.Forms.RightToLeft.Yes; + + -```` -````VB.NET -Me.RadRating1.RightToLeft = System.Windows.Forms.RightToLeft.Yes -```` - -{{endregion}} |RightToLeft=false|RightToLeft=true| |----|----| @@ -96,20 +77,10 @@ Me.RadRating1.RightToLeft = System.Windows.Forms.RightToLeft.Yes * *Direction* property can be used to control the hover direction. -{{source=..\SamplesCS\TrackAndStatus\Rating\RatingGettingStarted.cs region=Direction}} -{{source=..\SamplesVB\TrackAndStatus\Rating\RatingGettingStarted.vb region=Direction}} - -````C# - -this.radRating1.Direction = RatingDirection.Reversed; - -```` -````VB.NET -Me.RadRating1.Direction = RatingDirection.Reversed + + -```` -{{endregion}} |Direction=Standard|Direction=Reversed| |----|----| @@ -117,22 +88,10 @@ Me.RadRating1.Direction = RatingDirection.Reversed * **Orientation** - the default __RadRating__ orientation is *Horizontal*. It is allowed to change it to Vertical: -{{source=..\SamplesCS\TrackAndStatus\Rating\RatingGettingStarted.cs region=Orientation}} -{{source=..\SamplesVB\TrackAndStatus\Rating\RatingGettingStarted.vb region=Orientation}} + + -````C# - -this.radRating1.Orientation = Orientation.Vertical; -this.radRating1.AutoSize = true; -```` -````VB.NET -Me.RadRating1.Orientation = Orientation.Vertical -Me.RadRating1.AutoSize = True - -```` - -{{endregion}} |Orientation=Horizontal|Orientation=Vertical| |----|----| @@ -140,24 +99,9 @@ Me.RadRating1.AutoSize = True * **Caption, Subcaption and Description** – specify texts for the captions of __RadRating__: -{{source=..\SamplesCS\TrackAndStatus\Rating\RatingGettingStarted.cs region=Captions}} -{{source=..\SamplesVB\TrackAndStatus\Rating\RatingGettingStarted.vb region=Captions}} - -````C# - -this.radRating1.Caption = "Rate the movie"; -this.radRating1.Description = "Description"; -this.radRating1.Subcaption = "SubCaption"; - -```` -````VB.NET -Me.RadRating1.Caption = "Rate the movie" -Me.RadRating1.Description = "Description" -Me.RadRating1.Subcaption = "SubCaption" - -```` + + -{{endregion}} ![WinForms RadRating Description](images/rating-properties-and-events013.png) @@ -166,52 +110,24 @@ Me.RadRating1.Subcaption = "SubCaption" #### RatingSelectionMode.Precise -{{source=..\SamplesCS\TrackAndStatus\Rating\RatingGettingStarted.cs region=SelectionPrecise}} -{{source=..\SamplesVB\TrackAndStatus\Rating\RatingGettingStarted.vb region=SelectionPrecise}} + + -````C# - -this.radRating1.SelectionMode = Telerik.WinControls.UI.RatingSelectionMode.Precise; -```` -````VB.NET -Me.RadRating1.SelectionMode = Telerik.WinControls.UI.RatingSelectionMode.Precise - -```` - -{{endregion}} #### RatingSelectionMode.HalfItem -{{source=..\SamplesCS\TrackAndStatus\Rating\RatingGettingStarted.cs region=SelectionHalfItem}} -{{source=..\SamplesVB\TrackAndStatus\Rating\RatingGettingStarted.vb region=SelectionHalfItem}} - -````C# -this.radRating1.SelectionMode = Telerik.WinControls.UI.RatingSelectionMode.HalfItem; + + -```` -````VB.NET -Me.RadRating1.SelectionMode = Telerik.WinControls.UI.RatingSelectionMode.HalfItem -```` - -{{endregion}} #### RatingSelectionMode.FullItem -{{source=..\SamplesCS\TrackAndStatus\Rating\RatingGettingStarted.cs region=SelectionFullItem}} -{{source=..\SamplesVB\TrackAndStatus\Rating\RatingGettingStarted.vb region=SelectionFullItem}} - -````C# -this.radRating1.SelectionMode = Telerik.WinControls.UI.RatingSelectionMode.FullItem; + + -```` -````VB.NET -Me.RadRating1.SelectionMode = Telerik.WinControls.UI.RatingSelectionMode.FullItem -```` - -{{endregion}} |SelectionMode=FullItem|SelectionMode=HalfItem|SelectionMode=Precise| |----|----|----| @@ -221,40 +137,19 @@ Me.RadRating1.SelectionMode = Telerik.WinControls.UI.RatingSelectionMode.FullIte #### Specify minimum/maximum -{{source=..\SamplesCS\TrackAndStatus\Rating\RatingGettingStarted.cs region=Ranges}} -{{source=..\SamplesVB\TrackAndStatus\Rating\RatingGettingStarted.vb region=Ranges}} - -````C# - -this.radRating1.Minimum = 10; -this.radRating1.Maximum = 40; - -```` -````VB.NET -Me.RadRating1.Minimum = 10 -Me.RadRating1.Maximum = 40 + + -```` -{{endregion}} ![WinForms RadRating Minimum Maximum](images/rating-properties-and-events009.png)![WinForms RadRating rating-properties-and-events 010](images/rating-properties-and-events010.png) * **Value** - sets or gets the value of the __RadRating__: -{{source=..\SamplesCS\TrackAndStatus\Rating\RatingGettingStarted.cs region=Value}} -{{source=..\SamplesVB\TrackAndStatus\Rating\RatingGettingStarted.vb region=Value}} - -````C# -this.radRating1.Value = 43.4; - -```` -````VB.NET -Me.RadRating1.Value = 43.4 + + -```` -{{endregion}} # See Also diff --git a/controls/track-and-status-controls/scrollbar/customizing-appearance/accessing-and-customizing-elements.md b/controls/track-and-status-controls/scrollbar/customizing-appearance/accessing-and-customizing-elements.md index 96c9a1604..f71b6a0f3 100644 --- a/controls/track-and-status-controls/scrollbar/customizing-appearance/accessing-and-customizing-elements.md +++ b/controls/track-and-status-controls/scrollbar/customizing-appearance/accessing-and-customizing-elements.md @@ -30,25 +30,10 @@ You can customize the nested elements at run time as well: #### Customize elements -{{source=..\SamplesCS\TrackAndStatus\ScrollBar\ScrollGettingStarted.cs region=CustomizeElements}} -{{source=..\SamplesVB\TrackAndStatus\ScrollBar\ScrollGettingStarted.vb region=CustomizeElements}} + + -````C# -this.radHScrollBar1.ScrollBarElement.ThumbElement.ThumbFill.BackColor = Color.Lime; -this.radHScrollBar1.ScrollBarElement.ThumbElement.ThumbBorder.ForeColor = Color.Red; -this.radHScrollBar1.ScrollBarElement.ThumbElement.ThumbFill.GradientStyle = GradientStyles.Solid; -this.radHScrollBar1.ScrollBarElement.SecondButton.ArrowPrimitive.ForeColor = Color.Aqua; -```` -````VB.NET -Me.RadHScrollBar1.ScrollBarElement.ThumbElement.ThumbFill.BackColor = Color.Lime -Me.RadHScrollBar1.ScrollBarElement.ThumbElement.ThumbBorder.ForeColor = Color.Red -Me.RadHScrollBar1.ScrollBarElement.ThumbElement.ThumbFill.GradientStyle = GradientStyles.Solid -Me.RadHScrollBar1.ScrollBarElement.SecondButton.ArrowPrimitive.ForeColor = Color.Aqua - -```` - -{{endregion}} # See Also diff --git a/controls/track-and-status-controls/scrollbar/getting-started.md b/controls/track-and-status-controls/scrollbar/getting-started.md index dce21c3dc..0effc6dcd 100644 --- a/controls/track-and-status-controls/scrollbar/getting-started.md +++ b/controls/track-and-status-controls/scrollbar/getting-started.md @@ -52,32 +52,10 @@ Using Telerik scroll bars is a bit more intricate compared to using the standard #### Adding controls to the panel -{{source=..\SamplesCS\TrackAndStatus\ScrollBar\ScrollGettingStarted.cs region=buttons}} -{{source=..\SamplesVB\TrackAndStatus\ScrollBar\ScrollGettingStarted.vb region=buttons}} - -````C# -for (int i = 1; i < 15; i++) -{ - RadButton button = new RadButton(); - button.Location = new Point(30, i * 30 + 5 * i); - button.Size = new Size(70, 30); - button.Text = "RadButton" + i.ToString(); - this.radPanel2.Controls.Add(button); -} - -```` -````VB.NET -For i As Integer = 1 To 14 - Dim button As New RadButton() - button.Location = New Point(30, i * 30 + 5 * i) - button.Size = New Size(70, 30) - button.Text = "RadButton" & i.ToString() - Me.RadPanel2.Controls.Add(button) -Next i - -```` - -{{endregion}} + + + + >note You can add controls by drag and drop at design time as well. > @@ -88,42 +66,19 @@ Next i #### Handling the Scroll event -{{source=..\SamplesCS\TrackAndStatus\ScrollBar\ScrollGettingStarted.cs region=scroll}} -{{source=..\SamplesVB\TrackAndStatus\ScrollBar\ScrollGettingStarted.vb region=scroll}} - -````C# -void radVScrollBar1_Scroll(object sender, ScrollEventArgs e) -{ - this.radPanel2.Top = -this.radVScrollBar1.Value; -} + + -```` -````VB.NET -Private Sub radVScrollBar1_Scroll(ByVal sender As Object, ByVal e As ScrollEventArgs) - Me.RadPanel2.Top = -Me.RadVScrollBar1.Value -End Sub -```` - -{{endregion}} 6\. The last required step is to set the __Maximum__ property of the scroll bar to reflect the size of the __scrollable height__ which is the __total height__ of the scrollable content minus the __visible height__. For the example of this section in particular, that is the height of the second panel minus the height of the first panel. #### Specify RadVScrollBar's maximum -{{source=..\SamplesCS\TrackAndStatus\ScrollBar\ScrollGettingStarted.cs region=maximum}} -{{source=..\SamplesVB\TrackAndStatus\ScrollBar\ScrollGettingStarted.vb region=maximum}} - -````C# -this.radVScrollBar1.Maximum = this.radPanel2.Size.Height - this.radPanel1.Size.Height; - -```` -````VB.NET -Me.RadVScrollBar1.Maximum = Me.RadPanel2.Size.Height - Me.RadPanel1.Size.Height + + -```` -{{endregion}} ![WinForms RadScrollBar Scroll Controls](images/track-and-status-controls-scroll-bar-getting-started005.png) diff --git a/controls/track-and-status-controls/stepprogressbar/customizing-appearance/custom-indicator.md b/controls/track-and-status-controls/stepprogressbar/customizing-appearance/custom-indicator.md index c90bb5a28..a5d2ed9ae 100644 --- a/controls/track-and-status-controls/stepprogressbar/customizing-appearance/custom-indicator.md +++ b/controls/track-and-status-controls/stepprogressbar/customizing-appearance/custom-indicator.md @@ -17,81 +17,10 @@ This article demonstrates how you can apply custom shapes to the RadStepProgress The following code snippet demonstrates how to apply one of the predefined [ElementShapes]({%slug winforms/telerik-presentation-framework/shapes%}) that the Telerik Presentation Framework offers. -{{source=..\SamplesCS\TrackAndStatus\StepProgressBar\StepProgressBarGettingStarted.cs region=ShapeIndicators}} -{{source=..\SamplesVB\TrackAndStatus\StepProgressBar\StepProgressBarGettingStarted.vb region=ShapeIndicators}} - -````C# -private void CreateShapeProgressBar() -{ - var stepProgressBar = new RadStepProgressBar(); - stepProgressBar.Dock = DockStyle.Fill; - var item1 = new StepProgressItem() { FirstHeader = "Step 1", SecondHeader = "New", SecondDescription = "Unassigned" }; - var item2 = new StepProgressItem() { FirstHeader = "Step 2", SecondHeader = "InProgress", SecondDescription = "Dev" }; - var item3 = new StepProgressItem() { FirstHeader = "Step 3", SecondHeader = "ReadyForTest", SecondDescription = "Dev" }; - var item4 = new StepProgressItem() { FirstHeader = "Step 4", SecondHeader = "Testing", SecondDescription = "QA", Progress = 61, }; - var item5 = new StepProgressItem() { FirstHeader = "Step 5", SecondHeader = "Done", SecondDescription = "N/A" }; - item1.StepIndicator.Shape = new DonutShape(); - item1.StepIndicator.Text = ""; - item2.StepIndicator.Shape = new EllipseShape(); - item3.StepIndicator.Shape = new DiamondShape(); - item4.StepIndicator.Shape = new HeartShape(); - item5.StepIndicator.Shape = new StarShape(); - stepProgressBar.Steps.Add(item1); - stepProgressBar.Steps.Add(item2); - stepProgressBar.Steps.Add(item3); - stepProgressBar.Steps.Add(item4); - stepProgressBar.Steps.Add(item5); - this.Controls.Add(stepProgressBar); -} - -```` -````VB.NET -Private Sub CreateShapeProgressBar() - Dim stepProgressBar = New RadStepProgressBar() - stepProgressBar.Dock = DockStyle.Fill - Dim item1 = New StepProgressItem() With { - .FirstHeader = "Step 1", - .SecondHeader = "New", - .SecondDescription = "Unassigned" - } - Dim item2 = New StepProgressItem() With { - .FirstHeader = "Step 2", - .SecondHeader = "InProgress", - .SecondDescription = "Dev" - } - Dim item3 = New StepProgressItem() With { - .FirstHeader = "Step 3", - .SecondHeader = "ReadyForTest", - .SecondDescription = "Dev" - } - Dim item4 = New StepProgressItem() With { - .FirstHeader = "Step 4", - .SecondHeader = "Testing", - .SecondDescription = "QA", - .Progress = 61 - } - Dim item5 = New StepProgressItem() With { - .FirstHeader = "Step 5", - .SecondHeader = "Done", - .SecondDescription = "N/A" - } - item1.StepIndicator.Shape = New DonutShape() - item1.StepIndicator.Text = "" - item2.StepIndicator.Shape = New EllipseShape() - item3.StepIndicator.Shape = New DiamondShape() - item4.StepIndicator.Shape = New HeartShape() - item5.StepIndicator.Shape = New StarShape() - stepProgressBar.Steps.Add(item1) - stepProgressBar.Steps.Add(item2) - stepProgressBar.Steps.Add(item3) - stepProgressBar.Steps.Add(item4) - stepProgressBar.Steps.Add(item5) - Me.Controls.Add(stepProgressBar) -End Sub - -```` - -{{endregion}} + + + + ![WinForms RadStepProgressBar Predifined Shapes](images/stepprogressbar-appearance-customindicator001.png) @@ -101,110 +30,10 @@ In the following code snippet, we are changing the default look of all shapes wi > The custom shape in the following example is generated using the [ShapeEditor]({%slug winforms/tools/shapeeditor%}) designer. -{{source=..\SamplesCS\TrackAndStatus\StepProgressBar\StepProgressBarGettingStarted.cs region=CustomIndicator}} -{{source=..\SamplesVB\TrackAndStatus\StepProgressBar\StepProgressBarGettingStarted.vb region=CustomIndicator}} - -````C# -private void CreateCustomIndicator() -{ - var stepProgressBar = new RadStepProgressBar(); - stepProgressBar.Dock = DockStyle.Fill; - var item1 = new StepProgressItem() { FirstHeader = "Step 1", SecondHeader = "New", SecondDescription = "Unassigned" }; - var item2 = new StepProgressItem() { FirstHeader = "Step 2", SecondHeader = "InProgress", SecondDescription = "Dev" }; - var item3 = new StepProgressItem() { FirstHeader = "Step 3", SecondHeader = "ReadyForTest", SecondDescription = "Dev" }; - var item4 = new StepProgressItem() { FirstHeader = "Step 4", SecondHeader = "Testing", SecondDescription = "QA", Progress = 61, }; - var item5 = new StepProgressItem() { FirstHeader = "Step 5", SecondHeader = "Done", SecondDescription = "N/A" }; - stepProgressBar.Steps.Add(item1); - stepProgressBar.Steps.Add(item2); - stepProgressBar.Steps.Add(item3); - stepProgressBar.Steps.Add(item4); - stepProgressBar.Steps.Add(item5); - SetFirstLastCustomShape(stepProgressBar); - this.Controls.Add(stepProgressBar); -} - -private void SetFirstLastCustomShape(RadStepProgressBar radStepProgressBar) -{ - foreach (StepProgressItem item in radStepProgressBar.Steps) - { - string shapeAsString = "20,20,200,100:20,20,False,0,0,0,0,0:200,20,False,0,0,0,0,0:220,70,False,0,0,0,0,0:200,120,False,0,0,0,0,0:20,120,False,0,0,0,0,0:40,70,False,0,0,0,0,0:"; - if (item.IsFirst) - { - shapeAsString = "20,20,200,100:20,20,False,0,0,0,0,0:200,20,False,0,0,0,0,0:220,70,False,0,0,0,0,0:200,120,False,0,0,0,0,0:20,120,False,0,0,0,0,0:"; - } - else if (item.IsLast) - { - shapeAsString = "20,20,200,100:20,20,False,0,0,0,0,0:180,20,True,230,20,230,120,0:180,120,False,0,0,0,0,0:20,120,False,0,0,0,0,0:40,70,False,0,0,0,0,0:"; - } - item.StepIndicator.Shape = new CustomShape() { AsString = shapeAsString }; - radStepProgressBar.StepProgressBarElement.IndicatorSize = new Size(60, 30); - radStepProgressBar.StepProgressBarElement.StepSpacing = 22; - radStepProgressBar.StepProgressBarElement.HideConnections = true; - } -} - -```` -````VB.NET -Private Sub CreateHorizontalStepProgressBar() - Dim stepProgressBar = New RadStepProgressBar() - stepProgressBar.Dock = DockStyle.Fill - Dim item1 = New StepProgressItem() With { - .FirstHeader = "Step 1", - .SecondHeader = "New", - .SecondDescription = "Unassigned" - } - Dim item2 = New StepProgressItem() With { - .FirstHeader = "Step 2", - .SecondHeader = "InProgress", - .SecondDescription = "Dev" - } - Dim item3 = New StepProgressItem() With { - .FirstHeader = "Step 3", - .SecondHeader = "ReadyForTest", - .SecondDescription = "Dev" - } - Dim item4 = New StepProgressItem() With { - .FirstHeader = "Step 4", - .SecondHeader = "Testing", - .SecondDescription = "QA", - .Progress = 61 - } - Dim item5 = New StepProgressItem() With { - .FirstHeader = "Step 5", - .SecondHeader = "Done", - .SecondDescription = "N/A" - } - stepProgressBar.Steps.Add(item1) - stepProgressBar.Steps.Add(item2) - stepProgressBar.Steps.Add(item3) - stepProgressBar.Steps.Add(item4) - stepProgressBar.Steps.Add(item5) - SetFirstLastCustomShape(stepProgressBar) - Me.Controls.Add(stepProgressBar) -End Sub - -Private Sub SetFirstLastCustomShape(ByVal radStepProgressBar As RadStepProgressBar) - For Each item As StepProgressItem In radStepProgressBar.Steps - Dim shapeAsString As String = "20,20,200,100:20,20,False,0,0,0,0,0:200,20,False,0,0,0,0,0:220,70,False,0,0,0,0,0:200,120,False,0,0,0,0,0:20,120,False,0,0,0,0,0:40,70,False,0,0,0,0,0:" - - If item.IsFirst Then - shapeAsString = "20,20,200,100:20,20,False,0,0,0,0,0:200,20,False,0,0,0,0,0:220,70,False,0,0,0,0,0:200,120,False,0,0,0,0,0:20,120,False,0,0,0,0,0:" - ElseIf item.IsLast Then - shapeAsString = "20,20,200,100:20,20,False,0,0,0,0,0:180,20,True,230,20,230,120,0:180,120,False,0,0,0,0,0:20,120,False,0,0,0,0,0:40,70,False,0,0,0,0,0:" - End If - - item.StepIndicator.Shape = New CustomShape() With { - .AsString = shapeAsString - } - radStepProgressBar.StepProgressBarElement.IndicatorSize = New Size(60, 30) - radStepProgressBar.StepProgressBarElement.StepSpacing = 22 - radStepProgressBar.StepProgressBarElement.HideConnections = True - Next -End Sub - -```` - -{{endregion}} + + + + ![WinForms RadStepProgressBar Custom Shapes](images/stepprogressbar-appearance-customindicator002.png) diff --git a/controls/track-and-status-controls/stepprogressbar/features/layout-mode.md b/controls/track-and-status-controls/stepprogressbar/features/layout-mode.md index 966f70be2..8824ec49c 100644 --- a/controls/track-and-status-controls/stepprogressbar/features/layout-mode.md +++ b/controls/track-and-status-controls/stepprogressbar/features/layout-mode.md @@ -17,71 +17,10 @@ The RadStepProgressBar control is arranged horizontally by default which means t To change the orientation of the control, set the __Orientation__ property. The orientation can be __Horizontal__ or __Vertical__. By default the control is horizontally orientated. -{{source=..\SamplesCS\TrackAndStatus\StepProgressBar\StepProgressBarGettingStarted.cs region=VerticalStepProgressBar}} -{{source=..\SamplesVB\TrackAndStatus\StepProgressBar\StepProgressBarGettingStarted.vb region=VerticalStepProgressBar}} - -````C# -private void CreateVerticalStepProgressBar() -{ - var stepProgressBar = new RadStepProgressBar(); - stepProgressBar.Dock = DockStyle.Fill; - stepProgressBar.Orientation = Orientation.Vertical; - var item1 = new StepProgressItem() { FirstHeader = "Step 1", SecondHeader = "New", SecondDescription = "Unassigned" }; - var item2 = new StepProgressItem() { FirstHeader = "Step 2", SecondHeader = "InProgress", SecondDescription = "Dev" }; - var item3 = new StepProgressItem() { FirstHeader = "Step 3", SecondHeader = "ReadyForTest", SecondDescription = "Dev" }; - var item4 = new StepProgressItem() { FirstHeader = "Step 4", SecondHeader = "Testing", SecondDescription = "QA", Progress = 61, }; - var item5 = new StepProgressItem() { FirstHeader = "Step 5", SecondHeader = "Done", SecondDescription = "N/A" }; - stepProgressBar.Steps.Add(item1); - stepProgressBar.Steps.Add(item2); - stepProgressBar.Steps.Add(item3); - stepProgressBar.Steps.Add(item4); - stepProgressBar.Steps.Add(item5); - this.Controls.Add(stepProgressBar); -} - -```` -````VB.NET -Private Sub CreateVerticalStepProgressBar() - Dim stepProgressBar = New RadStepProgressBar() - stepProgressBar.Dock = DockStyle.Fill - stepProgressBar.Orientation = Orientation.Vertical - Dim item1 = New StepProgressItem() With { - .FirstHeader = "Step 1", - .SecondHeader = "New", - .SecondDescription = "Unassigned" - } - Dim item2 = New StepProgressItem() With { - .FirstHeader = "Step 2", - .SecondHeader = "InProgress", - .SecondDescription = "Dev" - } - Dim item3 = New StepProgressItem() With { - .FirstHeader = "Step 3", - .SecondHeader = "ReadyForTest", - .SecondDescription = "Dev" - } - Dim item4 = New StepProgressItem() With { - .FirstHeader = "Step 4", - .SecondHeader = "Testing", - .SecondDescription = "QA", - .Progress = 61 - } - Dim item5 = New StepProgressItem() With { - .FirstHeader = "Step 5", - .SecondHeader = "Done", - .SecondDescription = "N/A" - } - stepProgressBar.Steps.Add(item1) - stepProgressBar.Steps.Add(item2) - stepProgressBar.Steps.Add(item3) - stepProgressBar.Steps.Add(item4) - stepProgressBar.Steps.Add(item5) - Me.Controls.Add(stepProgressBar) -End Sub - -```` - -{{endregion}} + + + + ![WinForms RadStepProgressBar Orientation](images/stepprogressbar-features-layout001.png) @@ -89,143 +28,19 @@ End Sub To change the horizontal flow direction, set the __RightToLeft__ property. -{{source=..\SamplesCS\TrackAndStatus\StepProgressBar\StepProgressBarGettingStarted.cs region=HorizontalStepProgressBarRightToLeft}} -{{source=..\SamplesVB\TrackAndStatus\StepProgressBar\StepProgressBarGettingStarted.vb region=HorizontalStepProgressBarRightToLeft}} - -````C# -private void CreateHorizontalStepProgressBar_RightToLeft() -{ - var stepProgressBar = new RadStepProgressBar(); - stepProgressBar.Dock = DockStyle.Fill; - stepProgressBar.RightToLeft = RightToLeft.Yes; - var item1 = new StepProgressItem() { FirstHeader = "Step 1", SecondHeader = "New", SecondDescription = "Unassigned" }; - var item2 = new StepProgressItem() { FirstHeader = "Step 2", SecondHeader = "InProgress", SecondDescription = "Dev" }; - var item3 = new StepProgressItem() { FirstHeader = "Step 3", SecondHeader = "ReadyForTest", SecondDescription = "Dev" }; - var item4 = new StepProgressItem() { FirstHeader = "Step 4", SecondHeader = "Testing", SecondDescription = "QA", Progress = 61, }; - var item5 = new StepProgressItem() { FirstHeader = "Step 5", SecondHeader = "Done", SecondDescription = "N/A" }; - stepProgressBar.Steps.Add(item1); - stepProgressBar.Steps.Add(item2); - stepProgressBar.Steps.Add(item3); - stepProgressBar.Steps.Add(item4); - stepProgressBar.Steps.Add(item5); - this.Controls.Add(stepProgressBar); -} - -```` -````VB.NET -Private Sub CreateHorizontalStepProgressBar_RightToLeft() - Dim stepProgressBar = New RadStepProgressBar() - stepProgressBar.Dock = DockStyle.Fill - stepProgressBar.RightToLeft = RightToLeft.Yes - Dim item1 = New StepProgressItem() With { - .FirstHeader = "Step 1", - .SecondHeader = "New", - .SecondDescription = "Unassigned" - } - Dim item2 = New StepProgressItem() With { - .FirstHeader = "Step 2", - .SecondHeader = "InProgress", - .SecondDescription = "Dev" - } - Dim item3 = New StepProgressItem() With { - .FirstHeader = "Step 3", - .SecondHeader = "ReadyForTest", - .SecondDescription = "Dev" - } - Dim item4 = New StepProgressItem() With { - .FirstHeader = "Step 4", - .SecondHeader = "Testing", - .SecondDescription = "QA", - .Progress = 61 - } - Dim item5 = New StepProgressItem() With { - .FirstHeader = "Step 5", - .SecondHeader = "Done", - .SecondDescription = "N/A" - } - stepProgressBar.Steps.Add(item1) - stepProgressBar.Steps.Add(item2) - stepProgressBar.Steps.Add(item3) - stepProgressBar.Steps.Add(item4) - stepProgressBar.Steps.Add(item5) - Me.Controls.Add(stepProgressBar) - End Sub - -```` - -{{endregion}} + + + + ![WinForms RadStepProgressBar Horizontal Flow Direction](images/stepprogressbar-features-layout002.png) The same property is applicable in vertical orientation. -{{source=..\SamplesCS\TrackAndStatus\StepProgressBar\StepProgressBarGettingStarted.cs region=VerticalStepProgressBarRightToLeft}} -{{source=..\SamplesVB\TrackAndStatus\StepProgressBar\StepProgressBarGettingStarted.vb region=VerticalStepProgressBarRightToLeft}} - -````C# -private void CreateVerticalStepProgressBar_RightToLeft() -{ - var stepProgressBar = new RadStepProgressBar(); - stepProgressBar.Dock = DockStyle.Fill; - stepProgressBar.Orientation = Orientation.Vertical; - stepProgressBar.RightToLeft = RightToLeft.Yes; - var item1 = new StepProgressItem() { FirstHeader = "Step 1", SecondHeader = "New", SecondDescription = "Unassigned" }; - var item2 = new StepProgressItem() { FirstHeader = "Step 2", SecondHeader = "InProgress", SecondDescription = "Dev" }; - var item3 = new StepProgressItem() { FirstHeader = "Step 3", SecondHeader = "ReadyForTest", SecondDescription = "Dev" }; - var item4 = new StepProgressItem() { FirstHeader = "Step 4", SecondHeader = "Testing", SecondDescription = "QA", Progress = 61, }; - var item5 = new StepProgressItem() { FirstHeader = "Step 5", SecondHeader = "Done", SecondDescription = "N/A" }; - stepProgressBar.Steps.Add(item1); - stepProgressBar.Steps.Add(item2); - stepProgressBar.Steps.Add(item3); - stepProgressBar.Steps.Add(item4); - stepProgressBar.Steps.Add(item5); - this.Controls.Add(stepProgressBar); -} - -```` -````VB.NET -Private Sub CreateVerticalStepProgressBar_RightToLeft() - Dim stepProgressBar = New RadStepProgressBar() - stepProgressBar.Dock = DockStyle.Fill - stepProgressBar.Orientation = Orientation.Vertical - stepProgressBar.RightToLeft = RightToLeft.Yes - Dim item1 = New StepProgressItem() With { - .FirstHeader = "Step 1", - .SecondHeader = "New", - .SecondDescription = "Unassigned" - } - Dim item2 = New StepProgressItem() With { - .FirstHeader = "Step 2", - .SecondHeader = "InProgress", - .SecondDescription = "Dev" - } - Dim item3 = New StepProgressItem() With { - .FirstHeader = "Step 3", - .SecondHeader = "ReadyForTest", - .SecondDescription = "Dev" - } - Dim item4 = New StepProgressItem() With { - .FirstHeader = "Step 4", - .SecondHeader = "Testing", - .SecondDescription = "QA", - .Progress = 61 - } - Dim item5 = New StepProgressItem() With { - .FirstHeader = "Step 5", - .SecondHeader = "Done", - .SecondDescription = "N/A" - } - stepProgressBar.Steps.Add(item1) - stepProgressBar.Steps.Add(item2) - stepProgressBar.Steps.Add(item3) - stepProgressBar.Steps.Add(item4) - stepProgressBar.Steps.Add(item5) - Me.Controls.Add(stepProgressBar) -End Sub - -```` - -{{endregion}} + + + + ![WinForms RadStepProgressBar Vertical Flow Direction](images/stepprogressbar-features-layout003.png) diff --git a/controls/track-and-status-controls/stepprogressbar/features/progress-mode.md b/controls/track-and-status-controls/stepprogressbar/features/progress-mode.md index 70e19e42b..a0d815f2e 100644 --- a/controls/track-and-status-controls/stepprogressbar/features/progress-mode.md +++ b/controls/track-and-status-controls/stepprogressbar/features/progress-mode.md @@ -17,61 +17,10 @@ The __RadStepProgressBar__ control allows you to change how its steps are relate Setting the progress of a given step changes the progress of all items prior to the step to 100. The progress of the items after the given step changes to 0. The following example demonstrates how the Progress of the third step is set to 80. This automatically sets the progress of all prior steps to 100. This is the __default__ progress mode. -{{source=..\SamplesCS\TrackAndStatus\StepProgressBar\StepProgressBarGettingStarted.cs region=StepProgressMode_Linear}} -{{source=..\SamplesVB\TrackAndStatus\StepProgressBar\StepProgressBarGettingStarted.vb region=StepProgressMode_Linear}} - -````C# -private void StepProgressMode_Linear() -{ - var stepProgressBar = new RadStepProgressBar(); - var item1 = new StepProgressItem() { Progress = 0, FirstHeader = "Step 1", }; - var item2 = new StepProgressItem() { Progress = 0, FirstHeader = "Step 2" }; - var item3 = new StepProgressItem() { Progress = 80, FirstHeader = "Step 3" }; - var item4 = new StepProgressItem() { Progress = 0, FirstHeader = "Step 4" }; - var item5 = new StepProgressItem() { Progress = 0, FirstHeader = "Step 5" }; - stepProgressBar.Steps.Add(item1); - stepProgressBar.Steps.Add(item2); - stepProgressBar.Steps.Add(item3); - stepProgressBar.Steps.Add(item4); - stepProgressBar.Steps.Add(item5); - this.Controls.Add(stepProgressBar); -} - -```` -````VB.NET -Private Sub StepProgressMode_Linear() - Dim stepProgressBar = New RadStepProgressBar() - Dim item1 = New StepProgressItem() With { - .Progress = 0, - .FirstHeader = "Step 1" - } - Dim item2 = New StepProgressItem() With { - .Progress = 0, - .FirstHeader = "Step 2" - } - Dim item3 = New StepProgressItem() With { - .Progress = 80, - .FirstHeader = "Step 3" - } - Dim item4 = New StepProgressItem() With { - .Progress = 0, - .FirstHeader = "Step 4" - } - Dim item5 = New StepProgressItem() With { - .Progress = 0, - .FirstHeader = "Step 5" - } - stepProgressBar.Steps.Add(item1) - stepProgressBar.Steps.Add(item2) - stepProgressBar.Steps.Add(item3) - stepProgressBar.Steps.Add(item4) - stepProgressBar.Steps.Add(item5) - Me.Controls.Add(stepProgressBar) -End Sub - -```` - -{{endregion}} + + + + ![WinForms RadStepProgressBar Linear](images/stepprogressbar-features-progressmode001.png) @@ -81,63 +30,10 @@ Setting the progress of a step affects the other steps. Setting the progress of > In __Single and Independent__ mode, the progress is not indicated inside the connection. -{{source=..\SamplesCS\TrackAndStatus\StepProgressBar\StepProgressBarGettingStarted.cs region=StepProgressMode_Single}} -{{source=..\SamplesVB\TrackAndStatus\StepProgressBar\StepProgressBarGettingStarted.vb region=StepProgressMode_Single}} - -````C# -private void StepProgressMode_Single() -{ - var stepProgressBar = new RadStepProgressBar(); - stepProgressBar.ProgressMode = StepProgressMode.Single; - var item1 = new StepProgressItem() { Progress = 100, FirstHeader = "Step 1", }; - var item2 = new StepProgressItem() { Progress = 100, FirstHeader = "Step 2" }; - var item3 = new StepProgressItem() { Progress = 100, FirstHeader = "Step 3" }; - var item4 = new StepProgressItem() { Progress = 50, FirstHeader = "Step 4" }; - var item5 = new StepProgressItem() { Progress = 0, FirstHeader = "Step 5" }; - stepProgressBar.Steps.Add(item1); - stepProgressBar.Steps.Add(item2); - stepProgressBar.Steps.Add(item3); - stepProgressBar.Steps.Add(item4); - stepProgressBar.Steps.Add(item5); - this.Controls.Add(stepProgressBar); -} - -```` -````VB.NET -Private Sub StepProgressMode_Single() - Dim stepProgressBar = New RadStepProgressBar() - stepProgressBar.ProgressMode = StepProgressMode.Single - Dim item1 = New StepProgressItem() With { - .Progress = 100, - .FirstHeader = "Step 1" - } - Dim item2 = New StepProgressItem() With { - .Progress = 100, - .FirstHeader = "Step 2" - } - Dim item3 = New StepProgressItem() With { - .Progress = 100, - .FirstHeader = "Step 3" - } - Dim item4 = New StepProgressItem() With { - .Progress = 50, - .FirstHeader = "Step 4" - } - Dim item5 = New StepProgressItem() With { - .Progress = 0, - .FirstHeader = "Step 5" - } - stepProgressBar.Steps.Add(item1) - stepProgressBar.Steps.Add(item2) - stepProgressBar.Steps.Add(item3) - stepProgressBar.Steps.Add(item4) - stepProgressBar.Steps.Add(item5) - Me.Controls.Add(stepProgressBar) -End Sub - -```` - -{{endregion}} + + + + ![WinForms RadStepProgressBar Single](images/stepprogressbar-features-progressmode002.png) @@ -147,63 +43,10 @@ Setting the progress of a step does not affect the other steps. The progress of > In **Single** and **Independent** mode, the progress is not indicated inside the connection. -{{source=..\SamplesCS\TrackAndStatus\StepProgressBar\StepProgressBarGettingStarted.cs region=StepProgressMode_Independent}} -{{source=..\SamplesVB\TrackAndStatus\StepProgressBar\StepProgressBarGettingStarted.vb region=StepProgressMode_Independent}} - -````C# -private void StepProgressMode_Independent() -{ - var stepProgressBar = new RadStepProgressBar(); - stepProgressBar.ProgressMode = StepProgressMode.Independent; - var item1 = new StepProgressItem() { Progress = 100, FirstHeader = "Step 1", }; - var item2 = new StepProgressItem() { Progress = 100, FirstHeader = "Step 2" }; - var item3 = new StepProgressItem() { Progress = 0, FirstHeader = "Step 3" }; - var item4 = new StepProgressItem() { Progress = 50, FirstHeader = "Step 4" }; - var item5 = new StepProgressItem() { Progress = 0, FirstHeader = "Step 5" }; - stepProgressBar.Steps.Add(item1); - stepProgressBar.Steps.Add(item2); - stepProgressBar.Steps.Add(item3); - stepProgressBar.Steps.Add(item4); - stepProgressBar.Steps.Add(item5); - this.Controls.Add(stepProgressBar); -} - -```` -````VB.NET -Private Sub StepProgressMode_Independent() - Dim stepProgressBar = New RadStepProgressBar() - stepProgressBar.ProgressMode = StepProgressMode.Independent - Dim item1 = New StepProgressItem() With { - .Progress = 100, - .FirstHeader = "Step 1" - } - Dim item2 = New StepProgressItem() With { - .Progress = 100, - .FirstHeader = "Step 2" - } - Dim item3 = New StepProgressItem() With { - .Progress = 0, - .FirstHeader = "Step 3" - } - Dim item4 = New StepProgressItem() With { - .Progress = 50, - .FirstHeader = "Step 4" - } - Dim item5 = New StepProgressItem() With { - .Progress = 0, - .FirstHeader = "Step 5" - } - stepProgressBar.Steps.Add(item1) - stepProgressBar.Steps.Add(item2) - stepProgressBar.Steps.Add(item3) - stepProgressBar.Steps.Add(item4) - stepProgressBar.Steps.Add(item5) - Me.Controls.Add(stepProgressBar) -End Sub - -```` - -{{endregion}} + + + + ![WinForms RadStepProgressBar Independent](images/stepprogressbar-features-progressmode003.png) diff --git a/controls/track-and-status-controls/stepprogressbar/features/tooltip.md b/controls/track-and-status-controls/stepprogressbar/features/tooltip.md index 09a9e41f1..ad2ec706f 100644 --- a/controls/track-and-status-controls/stepprogressbar/features/tooltip.md +++ b/controls/track-and-status-controls/stepprogressbar/features/tooltip.md @@ -17,81 +17,10 @@ There are two ways to assign tooltips to step indicators in __RadStepProgressBar The code snippet below demonstrates how you can assign a tooltip to a step indicator. -{{source=..\SamplesCS\TrackAndStatus\StepProgressBar\StepProgressBarGettingStarted.cs region=StepIndicator_ToolTipText}} -{{source=..\SamplesVB\TrackAndStatus\StepProgressBar\StepProgressBarGettingStarted.vb region=StepIndicator_ToolTipText}} - -````C# -private void StepIndicator_ToolTipText() -{ - var stepProgressBar = new RadStepProgressBar(); - var item1 = new StepProgressItem() { Progress = 100, FirstHeader = "Step 1" }; - var item2 = new StepProgressItem() { Progress = 100, FirstHeader = "Step 2" }; - var item3 = new StepProgressItem() { Progress = 80, FirstHeader = "Step 3" }; - var item4 = new StepProgressItem() { Progress = 0, FirstHeader = "Step 4" }; - var item5 = new StepProgressItem() { Progress = 0, FirstHeader = "Step 5" }; - item1.StepIndicator.AutoToolTip = true; - item1.StepIndicator.ToolTipText = item1.FirstHeader; - item2.StepIndicator.AutoToolTip = true; - item2.StepIndicator.ToolTipText = item2.FirstHeader; - item3.StepIndicator.AutoToolTip = true; - item3.StepIndicator.ToolTipText = item3.FirstHeader; - item4.StepIndicator.AutoToolTip = true; - item4.StepIndicator.ToolTipText = item4.FirstHeader; - item5.StepIndicator.AutoToolTip = true; - item5.StepIndicator.ToolTipText = item5.FirstHeader; - stepProgressBar.Steps.Add(item1); - stepProgressBar.Steps.Add(item2); - stepProgressBar.Steps.Add(item3); - stepProgressBar.Steps.Add(item4); - stepProgressBar.Steps.Add(item5); - this.Controls.Add(stepProgressBar); -} - -```` -````VB.NET -Private Sub StepIndicator_ToolTipText() - Dim stepProgressBar = New RadStepProgressBar() - Dim item1 = New StepProgressItem() With { - .Progress = 100, - .FirstHeader = "Step 1" - } - Dim item2 = New StepProgressItem() With { - .Progress = 100, - .FirstHeader = "Step 2" - } - Dim item3 = New StepProgressItem() With { - .Progress = 80, - .FirstHeader = "Step 3" - } - Dim item4 = New StepProgressItem() With { - .Progress = 0, - .FirstHeader = "Step 4" - } - Dim item5 = New StepProgressItem() With { - .Progress = 0, - .FirstHeader = "Step 5" - } - item1.StepIndicator.AutoToolTip = True - item1.StepIndicator.ToolTipText = item1.FirstHeader - item2.StepIndicator.AutoToolTip = True - item2.StepIndicator.ToolTipText = item2.FirstHeader - item3.StepIndicator.AutoToolTip = True - item3.StepIndicator.ToolTipText = item3.FirstHeader - item4.StepIndicator.AutoToolTip = True - item4.StepIndicator.ToolTipText = item4.FirstHeader - item5.StepIndicator.AutoToolTip = True - item5.StepIndicator.ToolTipText = item5.FirstHeader - stepProgressBar.Steps.Add(item1) - stepProgressBar.Steps.Add(item2) - stepProgressBar.Steps.Add(item3) - stepProgressBar.Steps.Add(item4) - stepProgressBar.Steps.Add(item5) - Me.Controls.Add(stepProgressBar) -End Sub - -```` - -{{endregion}} + + + + ![WinForms RadStepProgressBar ToolTipText](images/stepprogressbar-features-tooltip001.png) @@ -99,80 +28,10 @@ End Sub The code snippet below demonstrates how you can use the ToolTipTextNeeded event handler to set the ToolTipText of step indicators. -{{source=..\SamplesCS\TrackAndStatus\StepProgressBar\StepProgressBarGettingStarted.cs region=ToolTipTextNeeded}} -{{source=..\SamplesVB\TrackAndStatus\StepProgressBar\StepProgressBarGettingStarted.vb region=ToolTipTextNeeded}} - -````C# -private void ToolTipTextNeeded() -{ - var stepProgressBar = new RadStepProgressBar(); - stepProgressBar.ToolTipTextNeeded += StepProgressBar_ToolTipTextNeeded; - var item1 = new StepProgressItem() { Progress = 100, FirstHeader = "Step 1", }; - var item2 = new StepProgressItem() { Progress = 100, FirstHeader = "Step 2" }; - var item3 = new StepProgressItem() { Progress = 80, FirstHeader = "Step 3" }; - var item4 = new StepProgressItem() { Progress = 0, FirstHeader = "Step 4" }; - var item5 = new StepProgressItem() { Progress = 0, FirstHeader = "Step 5" }; - stepProgressBar.Steps.Add(item1); - stepProgressBar.Steps.Add(item2); - stepProgressBar.Steps.Add(item3); - stepProgressBar.Steps.Add(item4); - stepProgressBar.Steps.Add(item5); - this.Controls.Add(stepProgressBar); -} -private void StepProgressBar_ToolTipTextNeeded(object sender, ToolTipTextNeededEventArgs e) -{ - var indicator = sender as StepItemIndicatorElement; - if (indicator != null) - { - e.ToolTipText = (indicator.Parent as StepProgressItem).FirstHeader; - } -} - - -```` -````VB.NET -Private Sub ToolTipTextNeeded() - Dim stepProgressBar = New RadStepProgressBar() - stepProgressBar.ToolTipTextNeeded += AddressOf StepProgressBar_ToolTipTextNeeded - Dim item1 = New StepProgressItem() With { - .Progress = 100, - .FirstHeader = "Step 1" - } - Dim item2 = New StepProgressItem() With { - .Progress = 100, - .FirstHeader = "Step 2" - } - Dim item3 = New StepProgressItem() With { - .Progress = 80, - .FirstHeader = "Step 3" - } - Dim item4 = New StepProgressItem() With { - .Progress = 0, - .FirstHeader = "Step 4" - } - Dim item5 = New StepProgressItem() With { - .Progress = 0, - .FirstHeader = "Step 5" - } - stepProgressBar.Steps.Add(item1) - stepProgressBar.Steps.Add(item2) - stepProgressBar.Steps.Add(item3) - stepProgressBar.Steps.Add(item4) - stepProgressBar.Steps.Add(item5) - Me.Controls.Add(stepProgressBar) -End Sub - -Private Sub StepProgressBar_ToolTipTextNeeded(ByVal sender As Object, ByVal e As ToolTipTextNeededEventArgs) - Dim indicator = TryCast(sender, StepItemIndicatorElement) - - If indicator IsNot Nothing Then - e.ToolTipText = (TryCast(indicator.Parent, StepProgressItem)).FirstHeader - End If -End Sub - -```` - -{{endregion}} + + + + ![WinForms RadStepProgressBar ToolTipTextNeeded](images/stepprogressbar-features-tooltip002.png) diff --git a/controls/track-and-status-controls/stepprogressbar/getting-started.md b/controls/track-and-status-controls/stepprogressbar/getting-started.md index 68c3efb4e..7263ea0ba 100644 --- a/controls/track-and-status-controls/stepprogressbar/getting-started.md +++ b/controls/track-and-status-controls/stepprogressbar/getting-started.md @@ -44,69 +44,10 @@ The following picture shows the final result produced by the code of this tutori To start using the __RadStepProgressBar__ control, you can just populate its __Items__ collection with __StepProgressItem__ objects. Each __StepProgressItem__ will produce a step visual element with track bar rendered between the steps. The following example shows how to add 5 steps along with text to each step added via several properties of the StepProgressItem elements. -{{source=..\SamplesCS\TrackAndStatus\StepProgressBar\StepProgressBarGettingStarted.cs region=ShowStepProgressBar}} -{{source=..\SamplesVB\TrackAndStatus\StepProgressBar\StepProgressBarGettingStarted.vb region=ShowStepProgressBar}} - -````C# -private void CreateStepProgressBar() -{ - var stepProgressBar = new RadStepProgressBar(); - stepProgressBar.Dock = DockStyle.Fill; - var item1 = new StepProgressItem() {FirstHeader="Step 1", SecondHeader = "New", SecondDescription = "Unassigned" }; - var item2 = new StepProgressItem() {FirstHeader="Step 2", SecondHeader = "InProgress", SecondDescription = "Dev" }; - var item3 = new StepProgressItem() {FirstHeader="Step 3", SecondHeader = "ReadyForTest", SecondDescription = "Dev" }; - var item4 = new StepProgressItem() {FirstHeader="Step 4", SecondHeader = "Testing", SecondDescription = "QA", Progress = 61, }; - var item5 = new StepProgressItem() {FirstHeader="Step 5", SecondHeader = "Done", SecondDescription = "N/A" }; - stepProgressBar.Steps.Add(item1); - stepProgressBar.Steps.Add(item2); - stepProgressBar.Steps.Add(item3); - stepProgressBar.Steps.Add(item4); - stepProgressBar.Steps.Add(item5); - this.Controls.Add(stepProgressBar); -} - -```` -````VB.NET -Private Sub CreateStepProgressBar() - Dim stepProgressBar = New RadStepProgressBar() - stepProgressBar.Dock = DockStyle.Fill - Dim item1 = New StepProgressItem() With { - .FirstHeader = "Step 1", - .SecondHeader = "New", - .SecondDescription = "Unassigned" - } - Dim item2 = New StepProgressItem() With { - .FirstHeader = "Step 2", - .SecondHeader = "InProgress", - .SecondDescription = "Dev" - } - Dim item3 = New StepProgressItem() With { - .FirstHeader = "Step 3", - .SecondHeader = "ReadyForTest", - .SecondDescription = "Dev" - } - Dim item4 = New StepProgressItem() With { - .FirstHeader = "Step 4", - .SecondHeader = "Testing", - .SecondDescription = "QA", - .Progress = 61 - } - Dim item5 = New StepProgressItem() With { - .FirstHeader = "Step 5", - .SecondHeader = "Done", - .SecondDescription = "N/A" - } - stepProgressBar.Steps.Add(item1) - stepProgressBar.Steps.Add(item2) - stepProgressBar.Steps.Add(item3) - stepProgressBar.Steps.Add(item4) - stepProgressBar.Steps.Add(item5) - Me.Controls.Add(stepProgressBar) -End Sub - -```` - -{{endregion}} + + + + When you run the project, you can observe that the first step is complete. While the second one is half completed. Each step has two headers and two descriptions thus allowing you to add detailed information about each step. diff --git a/controls/track-and-status-controls/trackbar/customizing-appearance/accessing-and-customizing-elements.md b/controls/track-and-status-controls/trackbar/customizing-appearance/accessing-and-customizing-elements.md index f1295354f..7b6d0cba2 100644 --- a/controls/track-and-status-controls/trackbar/customizing-appearance/accessing-and-customizing-elements.md +++ b/controls/track-and-status-controls/trackbar/customizing-appearance/accessing-and-customizing-elements.md @@ -31,31 +31,10 @@ You can customize the nested elements at run time as well: #### Customize elements -{{source=..\SamplesCS\TrackAndStatus\TrackBar\TrackBarPropertiesAndEvents.cs region=CustomizeElements}} -{{source=..\SamplesVB\TrackAndStatus\TrackBar\TrackBarPropertiesAndEvents.vb region=CustomizeElements}} - -````C# -this.radTrackBar1.ShowButtons = true; -this.radTrackBar1.TrackBarElement.LeftButton.ButtonFillElement.BackColor = Color.Lime; -this.radTrackBar1.TrackBarElement.BodyElement.ScaleContainerElement.TrackBarLineElement.BackColor = Color.Lime; -this.radTrackBar1.TrackBarElement.BodyElement.ScaleContainerElement.TrackBarLineElement.BorderColor = Color.Red; -this.radTrackBar1.TrackBarElement.BodyElement.ScaleContainerElement.TrackBarLineElement.DrawBorder = true; -this.radTrackBar1.TrackBarElement.BodyElement.ScaleContainerElement.TrackBarLineElement.BorderGradientStyle = GradientStyles.Solid; -this.radTrackBar1.TrackBarElement.BodyElement.ScaleContainerElement.TopScaleElement.TickContainerElement.TickColor = Color.Aqua; - -```` -````VB.NET -Me.RadTrackBar1.ShowButtons = True -Me.RadTrackBar1.TrackBarElement.LeftButton.ButtonFillElement.BackColor = Color.Lime -Me.RadTrackBar1.TrackBarElement.BodyElement.ScaleContainerElement.TrackBarLineElement.BackColor = Color.Lime -Me.RadTrackBar1.TrackBarElement.BodyElement.ScaleContainerElement.TrackBarLineElement.BorderColor = Color.Red -Me.RadTrackBar1.TrackBarElement.BodyElement.ScaleContainerElement.TrackBarLineElement.DrawBorder = True -Me.RadTrackBar1.TrackBarElement.BodyElement.ScaleContainerElement.TrackBarLineElement.BorderGradientStyle = GradientStyles.Solid -Me.RadTrackBar1.TrackBarElement.BodyElement.ScaleContainerElement.TopScaleElement.TickContainerElement.TickColor = Color.Aqua - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/track-and-status-controls/trackbar/customizing-appearance/customization.md b/controls/track-and-status-controls/trackbar/customizing-appearance/customization.md index 0291c6ac3..a4f945df5 100644 --- a/controls/track-and-status-controls/trackbar/customizing-appearance/customization.md +++ b/controls/track-and-status-controls/trackbar/customizing-appearance/customization.md @@ -17,102 +17,10 @@ previous_url: track-and-status-controls-trackbar-customization #### Dates selection example -{{source=..\SamplesCS\TrackAndStatus\TrackBar\TrackBarCustomization.cs region=calendarExample}} -{{source=..\SamplesVB\TrackAndStatus\TrackBar\TrackBarCustomization.vb region=calendarExample}} + + -````C# -public TrackBarCustomization() -{ - InitializeComponent(); - this.radTrackBar1.Maximum = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month); - this.radTrackBar1.Minimum = 1; - this.radTrackBar1.LargeTickFrequency = 1; - this.radTrackBar1.LabelStyle = Telerik.WinControls.UI.TrackBarLabelStyle.Both; - this.radTrackBar1.TrackBarMode = Telerik.WinControls.UI.TrackBarRangeMode.Range; - this.radTrackBar1.Ranges[0].End = 7; - this.radTrackBar1.Ranges.Add(new Telerik.WinControls.UI.TrackBarRange(18, 23)); - this.radTrackBar1.TickFormatting += new Telerik.WinControls.UI.TickFormattingEventHandler(radTrackBar1_TickFormatting); - this.radTrackBar1.LabelFormatting += new Telerik.WinControls.UI.LabelFormattingEventHandler(radTrackBar1_LabelFormatting); -} -void radTrackBar1_TickFormatting(object sender, TickFormattingEventArgs e) -{ - //since the ticks are zero-bazed, just add 1 to simulate days - int day = e.TickNumber + 1; - DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, day); - //color sat & sun - if (dt.DayOfWeek == DayOfWeek.Sunday || dt.DayOfWeek == DayOfWeek.Saturday) - { - e.TickElement.Line1.BackColor = Color.Orange; - e.TickElement.Line2.BackColor = Color.Yellow; - } - //offset the bottom ticket - if (e.TickElement.IsTopLeft) - { - e.TickElement.PositionOffset = new SizeF(0, 5); - } - //set the minimum size of the ticks - e.TickElement.MinSize = new Size(2, 5); -} -void radTrackBar1_LabelFormatting(object sender, LabelFormattingEventArgs e) -{ - DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, int.Parse(e.LabelElement.Text)); - //colorize the sat & sun - if (dt.DayOfWeek == DayOfWeek.Sunday || dt.DayOfWeek == DayOfWeek.Saturday) - { - e.LabelElement.ForeColor = Color.Red; - } - //make the top labels display the days - if (e.LabelElement.IsTopLeft) - { - e.LabelElement.Text = dt.ToString("ddd", new CultureInfo("en-US")); - } -} -```` -````VB.NET -Public Sub New() - InitializeComponent() - Me.RadTrackBar1.Maximum = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month) - Me.RadTrackBar1.Minimum = 1 - Me.RadTrackBar1.LargeTickFrequency = 1 - Me.RadTrackBar1.LabelStyle = Telerik.WinControls.UI.TrackBarLabelStyle.Both - Me.RadTrackBar1.TrackBarMode = Telerik.WinControls.UI.TrackBarRangeMode.Range - Me.RadTrackBar1.Ranges(0).[End] = 7 - Me.RadTrackBar1.Ranges.Add(New Telerik.WinControls.UI.TrackBarRange(18, 23)) - AddHandler Me.RadTrackBar1.TickFormatting, AddressOf radTrackBar1_TickFormatting - AddHandler Me.RadTrackBar1.LabelFormatting, AddressOf radTrackBar1_LabelFormatting -End Sub -Private Sub radTrackBar1_TickFormatting(sender As Object, e As TickFormattingEventArgs) - 'since the ticks are zero-bazed, just add 1 to simulate days - Dim day As Integer = e.TickNumber + 1 - Dim dt As New DateTime(DateTime.Now.Year, DateTime.Now.Month, day) - 'color sat & sun - If dt.DayOfWeek = DayOfWeek.Sunday OrElse dt.DayOfWeek = DayOfWeek.Saturday Then - e.TickElement.Line1.BackColor = Color.Orange - e.TickElement.Line2.BackColor = Color.Yellow - End If - 'offset the bottom ticket - If e.TickElement.IsTopLeft Then - e.TickElement.PositionOffset = New SizeF(0, 5) - End If - 'set the minimum size of the ticks - e.TickElement.MinSize = New Size(2, 5) -End Sub -Private Sub radTrackBar1_LabelFormatting(sender As Object, e As LabelFormattingEventArgs) - Dim dt As New DateTime(DateTime.Now.Year, DateTime.Now.Month, Integer.Parse(e.LabelElement.Text)) - 'colorize the sat & sun - If dt.DayOfWeek = DayOfWeek.Sunday OrElse dt.DayOfWeek = DayOfWeek.Saturday Then - e.LabelElement.ForeColor = Color.Red - End If - 'make the top labels display the days - If e.LabelElement.IsTopLeft Then - e.LabelElement.Text = dt.ToString("ddd", New CultureInfo("en-US")) - End If -End Sub - -```` - -{{endregion}} # See Also diff --git a/controls/track-and-status-controls/trackbar/getting-started.md b/controls/track-and-status-controls/trackbar/getting-started.md index 969b75457..4c1e5be6b 100644 --- a/controls/track-and-status-controls/trackbar/getting-started.md +++ b/controls/track-and-status-controls/trackbar/getting-started.md @@ -54,24 +54,10 @@ This tutorial demonstrates connecting a **RadTrackBar** to a **RadTextBox** cont 1. Replace the automatically-generated event handler with the following code: -{{source=..\SamplesCS\TrackAndStatus\TrackBar\TrackGettingStarted.cs region=valueChanged}} -{{source=..\SamplesVB\TrackAndStatus\TrackBar\TrackGettingStarted.vb region=valueChanged}} + + -````C# -void radTrackBar1_ValueChanged(object sender, EventArgs e) -{ - this.radTextBox1.Text = radTrackBar1.Value.ToString(); -} -```` -````VB.NET -Private Sub radTrackBar1_ValueChanged(ByVal sender As Object, ByVal e As EventArgs) - Me.radTextBox1.Text = radTrackBar1.Value.ToString() -End Sub - -```` - -{{endregion}} 8\. Press __F5__ to run the project. diff --git a/controls/track-and-status-controls/trackbar/modes.md b/controls/track-and-status-controls/trackbar/modes.md index 2534944cf..aa104e03f 100644 --- a/controls/track-and-status-controls/trackbar/modes.md +++ b/controls/track-and-status-controls/trackbar/modes.md @@ -25,113 +25,44 @@ In this mode **RadTrackBar** works like a standard **TrackBar**. It contains one In this mode **RadTrackBar** looks like **RadTrackBar** in *SingleThumb* mode, but it can contain more than one thumb. To show more than one thumb you should add the desired ranges (__TrackBarRange__) in the __Ranges__ collection of control. For example: -{{source=..\SamplesCS\TrackAndStatus\TrackBar\TrackBarPropertiesAndEvents.cs region=TrackBarModeStartFromTheBeginning}} -{{source=..\SamplesVB\TrackAndStatus\TrackBar\TrackBarPropertiesAndEvents.vb region=TrackBarModeStartFromTheBeginning}} + + -````C# -this.radTrackBar1.TrackBarMode = Telerik.WinControls.UI.TrackBarRangeMode.StartFromTheBeginning; -this.radTrackBar1.Ranges.Add(new TrackBarRange(0, 5, "MyRange1")); -this.radTrackBar1.Ranges.Add(new TrackBarRange(0, 15, "MyRange2")); - -```` -````VB.NET -Me.RadTrackBar1.TrackBarMode = Telerik.WinControls.UI.TrackBarRangeMode.StartFromTheBeginning -Me.RadTrackBar1.Ranges.Add(New TrackBarRange(0, 5, "MyRange1")) -Me.RadTrackBar1.Ranges.Add(New TrackBarRange(0, 15, "MyRange2")) - -```` - -{{endregion}} ![WinForms RadTrackBar StartFromTheBeginning](images/track-and-status-controls-trackbar-modes002.png) In order to access the values of the thumbs in this mode you should go through the __Ranges__ collection and check the values of each __TrackBarRange__. Please, note that even though __TrackBarRange__ has both __Start__ and __End__ properties, in this mode **RadTrackBar** uses only the __End__ property, so you should access it in order to take the value of some range. -{{source=..\SamplesCS\TrackAndStatus\TrackBar\TrackBarPropertiesAndEvents.cs region=accessValuesStartFromTheBeginningMode}} -{{source=..\SamplesVB\TrackAndStatus\TrackBar\TrackBarPropertiesAndEvents.vb region=accessValuesStartFromTheBeginningMode}} - -````C# -float fitstRangeValue = this.radTrackBar1.Ranges[0].End; -float secondRangeValue = this.radTrackBar1.Ranges[1].End; - -```` -````VB.NET -Dim fitstRangeValue As Single = Me.RadTrackBar1.Ranges(0).[End] -Dim secondRangeValue As Single = Me.RadTrackBar1.Ranges(1).[End] + + -```` -{{endregion}} To receive notification when the **Value** is changed in this mode, you should use the __RangeValueChanged__ event of the __RadTrackBar__: -{{source=..\SamplesCS\TrackAndStatus\TrackBar\TrackBarPropertiesAndEvents.cs region=Ranges_CollectionChangedEvent}} -{{source=..\SamplesVB\TrackAndStatus\TrackBar\TrackBarPropertiesAndEvents.vb region=Ranges_CollectionChangedEvent}} -````C# -private void RadTrackBar1_RangeValueChanged(object sender, RangeChangedEventArgs e) -{ - Console.WriteLine("Radge {0} Start {1}, End {2}", e.ChangedRange.Text, e.ChangedRange.Start, e.ChangedRange.End); -} + + -```` -````VB.NET -Private Sub RadTrackBar1_RangeValueChanged(ByVal sender As Object, ByVal e As RangeChangedEventArgs) - Console.WriteLine("Radge {0} Start {1}, End {2}", e.ChangedRange.Text, e.ChangedRange.Start, e.ChangedRange.End) -End Sub -```` - - -{{endregion}} ## Range This mode allows you to define one or more __Ranges__ with __Start__ and __End__ values. In this mode there the __Ranges__ cannot to overlap each other. To display a second range, you should add the desired __Range (TrackBarRange)__ in the __Ranges__ collection of the control. For example: -{{source=..\SamplesCS\TrackAndStatus\TrackBar\TrackBarPropertiesAndEvents.cs region=TrackBarModeRange}} -{{source=..\SamplesVB\TrackAndStatus\TrackBar\TrackBarPropertiesAndEvents.vb region=TrackBarModeRange}} - -````C# -this.radTrackBar1.TrackBarMode = Telerik.WinControls.UI.TrackBarRangeMode.Range; -this.radTrackBar1.Ranges[0].Start = 2; -this.radTrackBar1.Ranges[0].End = 5; -this.radTrackBar1.Ranges.Add(new TrackBarRange(10, 15)); - -```` -````VB.NET -Me.RadTrackBar1.TrackBarMode = Telerik.WinControls.UI.TrackBarRangeMode.Range -Me.RadTrackBar1.Ranges(0).Start = 2 -Me.RadTrackBar1.Ranges(0).[End] = 5 -Me.RadTrackBar1.Ranges.Add(New TrackBarRange(10, 15)) + + -```` -{{endregion}} ![WinForms RadTrackBar Range](images/track-and-status-controls-trackbar-modes003.png) To receive notification when the **Value** is changed in this mode, you should use the __RangeValueChanged__ event of the RadTrackBar: -{{source=..\SamplesCS\TrackAndStatus\TrackBar\TrackBarPropertiesAndEvents.cs region=Ranges_CollectionChangedEvent}} -{{source=..\SamplesVB\TrackAndStatus\TrackBar\TrackBarPropertiesAndEvents.vb region=Ranges_CollectionChangedEvent}} -````C# -private void RadTrackBar1_RangeValueChanged(object sender, RangeChangedEventArgs e) -{ - Console.WriteLine("Radge {0} Start {1}, End {2}", e.ChangedRange.Text, e.ChangedRange.Start, e.ChangedRange.End); -} - -```` -````VB.NET -Private Sub RadTrackBar1_RangeValueChanged(ByVal sender As Object, ByVal e As RangeChangedEventArgs) - Console.WriteLine("Radge {0} Start {1}, End {2}", e.ChangedRange.Text, e.ChangedRange.Start, e.ChangedRange.End) -End Sub - -```` + + - -{{endregion}} >important The __Ranges__ collection of **RadTrackBar** contains one default range that is used to display a default range for all modes. This collection should always contain at least one range, so if you execute the *Clear* method of the collection all ranges except the first one will be removed. > diff --git a/controls/track-and-status-controls/trackbar/properties-events.md b/controls/track-and-status-controls/trackbar/properties-events.md index 028cd0097..8259ee18a 100644 --- a/controls/track-and-status-controls/trackbar/properties-events.md +++ b/controls/track-and-status-controls/trackbar/properties-events.md @@ -44,47 +44,19 @@ position: 5 #### Formatting ticks -{{source=..\SamplesCS\TrackAndStatus\TrackBar\TrackBarPropertiesAndEvents.cs region=TickFormattingEvent}} -{{source=..\SamplesVB\TrackAndStatus\TrackBar\TrackBarPropertiesAndEvents.vb region=TickFormattingEvent}} + + -````C# -void radTrackBar1_TickFormatting(object sender, TickFormattingEventArgs e) -{ - e.TickElement.Line1.BackColor = Color.Red; -} -```` -````VB.NET -Private Sub radTrackBar1_TickFormatting(sender As Object, e As TickFormattingEventArgs) - e.TickElement.Line1.BackColor = Color.Red -End Sub - -```` - -{{endregion}} ![WinForms RadTrackBar Formatting ticks](images/track-and-status-controls-trackbar-programming-radtrackbar023.png) #### Formatting labels -{{source=..\SamplesCS\TrackAndStatus\TrackBar\TrackBarPropertiesAndEvents.cs region=LabelFormattingEvent}} -{{source=..\SamplesVB\TrackAndStatus\TrackBar\TrackBarPropertiesAndEvents.vb region=LabelFormattingEvent}} - -````C# -void radTrackBar1_LabelFormatting(object sender, LabelFormattingEventArgs e) -{ - e.LabelElement.ForeColor = Color.Red; -} - -```` -````VB.NET -Private Sub radTrackBar1_LabelFormatting(sender As Object, e As LabelFormattingEventArgs) - e.LabelElement.ForeColor = Color.Red -End Sub + + -```` -{{endregion}} ![WinForms RadTrackBar Formatting labels](images/track-and-status-controls-trackbar-programming-radtrackbar024.png) diff --git a/controls/track-and-status-controls/waitingbar/associated-control.md b/controls/track-and-status-controls/waitingbar/associated-control.md index dad0d5b9f..903e74d84 100644 --- a/controls/track-and-status-controls/waitingbar/associated-control.md +++ b/controls/track-and-status-controls/waitingbar/associated-control.md @@ -28,42 +28,8 @@ The following tutorial demonstrates how to indicate the data loading operation i #### Data loading -{{source=..\SamplesCS\TrackAndStatus\WaitingBar\WaitingBarAssociatedControl.cs region=BusyIndicator}} -{{source=..\SamplesVB\TrackAndStatus\WaitingBar\WaitingBarAssociatedControl.vb region=BusyIndicator}} + + -````C# -System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer(); -private void radButton1_Click(object sender, EventArgs e) -{ - timer.Interval = 3000; - timer.Tick += timer_Tick; - this.radWaitingBar1.AssociatedControl=this.radGridView1; - this.radWaitingBar1.StartWaiting(); - timer.Start(); -} -private void timer_Tick(object sender, EventArgs e) -{ - timer.Stop(); - this.radWaitingBar1.AssociatedControl=null; - this.radGridView1.DataSource = this.categoriesBindingSource; -} -```` -````VB.NET -Private timer As New System.Windows.Forms.Timer() -Private Sub RadButton1_Click(sender As Object, e As EventArgs) Handles RadButton1.Click - Timer.Interval = 3000 - AddHandler Timer.Tick, AddressOf timer_Tick - Me.RadWaitingBar1.AssociatedControl = Me.RadGridView1 - Me.RadWaitingBar1.StartWaiting() - Timer.Start() -End Sub -Private Sub timer_Tick(sender As Object, e As EventArgs) - timer.[Stop]() - Me.RadWaitingBar1.AssociatedControl = Nothing - Me.radGridView1.DataSource = Me.categoriesBindingSource -End Sub -```` - -{{endregion}} diff --git a/controls/track-and-status-controls/waitingbar/customizing-appearance/accessing-and-customizing-elements.md b/controls/track-and-status-controls/waitingbar/customizing-appearance/accessing-and-customizing-elements.md index 383e097f8..089306756 100644 --- a/controls/track-and-status-controls/waitingbar/customizing-appearance/accessing-and-customizing-elements.md +++ b/controls/track-and-status-controls/waitingbar/customizing-appearance/accessing-and-customizing-elements.md @@ -30,33 +30,10 @@ You can customize the nested elements at run time as well: #### Customize elements -{{source=..\SamplesCS\TrackAndStatus\WaitingBar\CustomizingRadWaitingBar.cs region=AccessingCustomizingElements}} -{{source=..\SamplesVB\TrackAndStatus\WaitingBar\CustomizingRadWaitingBar.vb region=AccessingCustomizingElements}} - -````C# -this.radWaitingBar1.WaitingIndicators[0].BackColor = Color.Aqua; -this.radWaitingBar1.WaitingIndicators[0].Text = "Aqua"; -this.radWaitingBar1.WaitingIndicators[1].BackColor = Color.Red; -this.radWaitingBar1.WaitingIndicators[1].Text = "Red"; -this.radWaitingBar1.WaitingBarElement.ContentElement.BorderColor = Color.Black; -this.radWaitingBar1.WaitingBarElement.ContentElement.BorderGradientStyle = Telerik.WinControls.GradientStyles.Solid; -this.radWaitingBar1.WaitingBarElement.ContentElement.DrawBorder = true; -this.radWaitingBar1.BackColor = Color.Yellow; - -```` -````VB.NET -Me.RadWaitingBar1.WaitingIndicators(0).BackColor = Color.Aqua -Me.RadWaitingBar1.WaitingIndicators(0).Text = "Aqua" -Me.RadWaitingBar1.WaitingIndicators(1).BackColor = Color.Red -Me.RadWaitingBar1.WaitingIndicators(1).Text = "Red" -Me.RadWaitingBar1.WaitingBarElement.ContentElement.BorderColor = Color.Black -Me.RadWaitingBar1.WaitingBarElement.ContentElement.BorderGradientStyle = Telerik.WinControls.GradientStyles.Solid -Me.RadWaitingBar1.WaitingBarElement.ContentElement.DrawBorder = True -Me.RadWaitingBar1.BackColor = Color.Yellow - -```` - -{{endregion}} + + + + ## Customizing RadWaitingBar @@ -70,25 +47,10 @@ The text of __RadWaitingBar__ is not displayed by default. To show the text, set #### Customize the text of RadWaitingBar -{{source=..\SamplesCS\TrackAndStatus\WaitingBar\CustomizingRadWaitingBar.cs region=text}} -{{source=..\SamplesVB\TrackAndStatus\WaitingBar\CustomizingRadWaitingBar.vb region=text}} - -````C# -this.radWaitingBar1.ShowText = true; -this.radWaitingBar1.Text = "Waiting..."; -this.radWaitingBar1.WaitingBarElement.TextElement.AngleTransform = 180; -this.radWaitingBar1.WaitingBarElement.TextElement.TextAlignment = ContentAlignment.MiddleLeft; + + -```` -````VB.NET -Me.RadWaitingBar1.ShowText = True -Me.RadWaitingBar1.Text = "Waiting..." -Me.RadWaitingBar1.WaitingBarElement.TextElement.AngleTransform = 180 -Me.RadWaitingBar1.WaitingBarElement.TextElement.TextAlignment = ContentAlignment.MiddleLeft -```` - -{{endregion}} ![WinForms RadWaitingBar Customize the text of RadWaitingBar](images/track-and-status-controls-waitingbar-customizing-radwaitingbar001.gif) @@ -98,35 +60,10 @@ To set the __RadWaitingBar__ in dash style, set the __WaitingStyle__ property to #### Customize RadWaitingBar’s Dash style -{{source=..\SamplesCS\TrackAndStatus\WaitingBar\CustomizingRadWaitingBar.cs region=dash}} -{{source=..\SamplesVB\TrackAndStatus\WaitingBar\CustomizingRadWaitingBar.vb region=dash}} - -````C# -this.radWaitingBar1.WaitingStyle = Telerik.WinControls.Enumerations.WaitingBarStyles.Dash; -WaitingBarSeparatorElement dash = this.radWaitingBar1.WaitingBarElement.SeparatorElement; -dash.NumberOfColors = 2; -dash.BackColor = Color.Orange; -dash.BackColor2 = Color.Yellow; -dash.SweepAngle = 45; -dash.StepWidth = 15; -dash.SeparatorWidth = 10; -dash.GradientPercentage = 0.25f; - -```` -````VB.NET -Me.RadWaitingBar1.WaitingStyle = Telerik.WinControls.Enumerations.WaitingBarStyles.Dash -Dim dash As WaitingBarSeparatorElement = Me.RadWaitingBar1.WaitingBarElement.SeparatorElement -dash.NumberOfColors = 2 -dash.BackColor = Color.Orange -dash.BackColor2 = Color.Yellow -dash.SweepAngle = 45 -dash.StepWidth = 15 -dash.SeparatorWidth = 10 -dash.GradientPercentage = 0.25F - -```` - -{{endregion}} + + + + ![WinForms RadWaitingBar Customize RadWaitingBar’s Dash style](images/track-and-status-controls-waitingbar-customizing-radwaitingbar002.gif) @@ -136,61 +73,10 @@ The waiting indicators also support dash style. To customize the appearance of t #### Waiting indicators' Dash style -{{source=..\SamplesCS\TrackAndStatus\WaitingBar\CustomizingRadWaitingBar.cs region=waitingIndicators}} -{{source=..\SamplesVB\TrackAndStatus\WaitingBar\CustomizingRadWaitingBar.vb region=waitingIndicators}} - -````C# -this.radWaitingBar1.WaitingBarElement.WaitingIndicators[0].BackColor = Color.LightGreen; -this.radWaitingBar1.WaitingBarElement.WaitingIndicators[0].NumberOfColors = 1; -this.radWaitingBar1.WaitingBarElement.WaitingIndicators[1].BackColor = Color.LightGreen; -this.radWaitingBar1.WaitingBarElement.WaitingIndicators[1].NumberOfColors = 1; -WaitingBarSeparatorElement separator = ((WaitingBarIndicatorElement)this.radWaitingBar1.WaitingBarElement.WaitingIndicators[0]).SeparatorElement; -WaitingBarSeparatorElement helpSeparator = ((WaitingBarIndicatorElement)this.radWaitingBar1.WaitingBarElement.WaitingIndicators[1]).SeparatorElement; -separator.Dash = true; -helpSeparator.Dash = true; -separator.NumberOfColors = 2; -separator.BackColor = Color.Orange; -separator.BackColor2 = Color.Yellow; -separator.SweepAngle = 45; -separator.StepWidth = 15; -separator.SeparatorWidth = 10; -separator.GradientPercentage = 0.25f; -helpSeparator.NumberOfColors = 2; -helpSeparator.BackColor = Color.Orange; -helpSeparator.BackColor2 = Color.Yellow; -helpSeparator.SweepAngle = 45; -helpSeparator.StepWidth = 15; -helpSeparator.SeparatorWidth = 10; -helpSeparator.GradientPercentage = 0.25f; - -```` -````VB.NET -Me.RadWaitingBar1.WaitingBarElement.WaitingIndicators(0).BackColor = Color.LightGreen -Me.RadWaitingBar1.WaitingBarElement.WaitingIndicators(0).NumberOfColors = 1 -Me.RadWaitingBar1.WaitingBarElement.WaitingIndicators(1).BackColor = Color.LightGreen -Me.RadWaitingBar1.WaitingBarElement.WaitingIndicators(1).NumberOfColors = 1 -Dim separator As WaitingBarSeparatorElement = DirectCast(Me.RadWaitingBar1.WaitingBarElement.WaitingIndicators(0), WaitingBarIndicatorElement).SeparatorElement -Dim helpSeparator As WaitingBarSeparatorElement = DirectCast(Me.RadWaitingBar1.WaitingBarElement.WaitingIndicators(1), WaitingBarIndicatorElement).SeparatorElement -separator.Dash = True -helpSeparator.Dash = True -separator.NumberOfColors = 2 -separator.BackColor = Color.Orange -separator.BackColor2 = Color.Yellow -separator.SweepAngle = 45 -separator.StepWidth = 15 -separator.SeparatorWidth = 10 -separator.GradientPercentage = 0.25F -helpSeparator.NumberOfColors = 2 -helpSeparator.BackColor = Color.Orange -helpSeparator.BackColor2 = Color.Yellow -helpSeparator.SweepAngle = 45 -helpSeparator.StepWidth = 15 -helpSeparator.SeparatorWidth = 10 -helpSeparator.GradientPercentage = 0.25F - -```` - -{{endregion}} + + + + ![WinForms RadWaitingBar Waiting indicators' Dash style](images/track-and-status-controls-waitingbar-customizing-radwaitingbar003.gif) @@ -200,27 +86,10 @@ Different shapes can be applied to both the __WaitingBarElement__ and the waitin #### Customize the shape of RadWatingBar -{{source=..\SamplesCS\TrackAndStatus\WaitingBar\CustomizingRadWaitingBar.cs region=shape}} -{{source=..\SamplesVB\TrackAndStatus\WaitingBar\CustomizingRadWaitingBar.vb region=shape}} - -````C# -Telerik.WinControls.EllipseShape shape = new Telerik.WinControls.EllipseShape(); -this.radWaitingBar1.WaitingBarElement.Shape = shape; -this.radWaitingBar1.WaitingBarElement.ContentElement.Shape = shape; -this.radWaitingBar1.WaitingBarElement.WaitingIndicators[0].Shape = shape; -this.radWaitingBar1.WaitingBarElement.WaitingIndicators[1].Shape = shape; - -```` -````VB.NET -Dim shape As New Telerik.WinControls.EllipseShape() -Me.RadWaitingBar1.WaitingBarElement.Shape = shape -Me.RadWaitingBar1.WaitingBarElement.ContentElement.Shape = shape -Me.RadWaitingBar1.WaitingBarElement.WaitingIndicators(0).Shape = shape -Me.RadWaitingBar1.WaitingBarElement.WaitingIndicators(1).Shape = shape + + -```` -{{endregion}} ![WinForms RadWaitingBar Customize the shape of RadWatingBar](images/track-and-status-controls-waitingbar-customizing-radwaitingbar004.gif) diff --git a/controls/track-and-status-controls/waitingbar/getting-started.md b/controls/track-and-status-controls/waitingbar/getting-started.md index 9ed842607..8f752f896 100644 --- a/controls/track-and-status-controls/waitingbar/getting-started.md +++ b/controls/track-and-status-controls/waitingbar/getting-started.md @@ -40,25 +40,9 @@ The Telerik UI for WinForms assemblies can be install by using one of the availa #### Adding a RadWaitingBar at runtime -{{source=..\SamplesCS\TrackAndStatus\WaitingBar\WaitingGettingStarted.cs region=AddWaitingBar}} -{{source=..\SamplesVB\TrackAndStatus\WaitingBar\WaitingGettingStarted.vb region=AddWaitingBar}} + + -````C# -RadWaitingBar radWaitingBar = new RadWaitingBar(); -radWaitingBar.WaitingStyle = Telerik.WinControls.Enumerations.WaitingBarStyles.Dash; -radWaitingBar.WaitingDirection = ProgressOrientation.Left; -this.Controls.Add(radWaitingBar); - -```` -````VB.NET -Dim radWaitingBar As New RadWaitingBar() -radWaitingBar.WaitingStyle = Telerik.WinControls.Enumerations.WaitingBarStyles.Dash -radWaitingBar.WaitingDirection = ProgressOrientation.Left -Me.Controls.Add(radWaitingBar) - -```` - -{{endregion}} The following tutorial illustrates how to start and stop the animation of __RadWaitingBar__: @@ -84,39 +68,10 @@ The following tutorial illustrates how to start and stop the animation of __RadW #### RadButton's Click event handler -{{source=..\SamplesCS\TrackAndStatus\WaitingBar\WaitingGettingStarted.cs region=click}} -{{source=..\SamplesVB\TrackAndStatus\WaitingBar\WaitingGettingStarted.vb region=click}} - -````C# -private void radButton1_Click(object sender, EventArgs e) -{ - if (radWaitingBar1.IsWaiting) - { - radWaitingBar1.StopWaiting(); - this.radButton1.Text = "Start"; - } - else - { - radWaitingBar1.StartWaiting(); - this.radButton1.Text = "Stop"; - } -} - -```` -````VB.NET -Private Sub radButton1_Click(ByVal sender As Object, ByVal e As EventArgs) - If RadWaitingBar1.IsWaiting Then - RadWaitingBar1.StopWaiting() - Me.RadButton1.Text = "Start" - Else - RadWaitingBar1.StartWaiting() - Me.RadButton1.Text = "Stop" - End If -End Sub - -```` - -{{endregion}} + + + + 10\. Press __F5__ to run the project. @@ -130,84 +85,10 @@ The following example demonstrates how to add __DotsLineWaitingBarIndicatorEleme ![WinForms RadWaitingBar Adding Indicator Elements programmatically](images/track-and-status-controls-waitingbar-getting-started002.gif) -{{source=..\SamplesCS\TrackAndStatus\WaitingBar\CustomizingRadWaitingBar.cs region=AddingIndicators}} -{{source=..\SamplesVB\TrackAndStatus\WaitingBar\CustomizingRadWaitingBar.vb region=AddingIndicators}} - -````C# -RadWaitingBar radWaitingBar1 = new RadWaitingBar(); -radWaitingBar1.Size = new System.Drawing.Size(200, 200); -radWaitingBar1.WaitingStyle = Telerik.WinControls.Enumerations.WaitingBarStyles.DotsSpinner; -radWaitingBar1.StartWaiting(); -int radius = 20; -int elementCount = 5; -for (int i = 0; i < 4; i++) -{ - radius += 10; - elementCount += 1; - DotsSpinnerWaitingBarIndicatorElement dsi = new DotsSpinnerWaitingBarIndicatorElement(); - radWaitingBar1.WaitingIndicators.Add(dsi); - dsi.Radius = radius; - dsi.ElementCount = elementCount; - dsi.RotationDirection = (RotationDirection)(i % 2); -} -DotsLineWaitingBarIndicatorElement dli = new DotsLineWaitingBarIndicatorElement(); -radWaitingBar1.WaitingIndicators.Add(dli); -dli.PositionOffset = new SizeF(0, 50); -DotsLineWaitingBarIndicatorElement dli1 = new DotsLineWaitingBarIndicatorElement(); -radWaitingBar1.WaitingIndicators.Add(dli1); -dli1.WaitingDirection = Telerik.WinControls.ProgressOrientation.Left; -dli1.PositionOffset = new SizeF(0, -50); -DotsLineWaitingBarIndicatorElement dli2 = new DotsLineWaitingBarIndicatorElement(); -radWaitingBar1.WaitingIndicators.Add(dli2); -dli2.WaitingDirection = Telerik.WinControls.ProgressOrientation.Bottom; -dli2.PositionOffset = new SizeF(50, 0); -DotsLineWaitingBarIndicatorElement dli4 = new DotsLineWaitingBarIndicatorElement(); -radWaitingBar1.WaitingIndicators.Add(dli4); -dli4.WaitingDirection = Telerik.WinControls.ProgressOrientation.Top; -dli4.PositionOffset = new SizeF(-50, 0); -radWaitingBar1.Location = new Point(10, 10); -this.Controls.Add(radWaitingBar1); -radWaitingBar1.StartWaiting(); - -```` -````VB.NET -Dim radWaitingBar1 As New RadWaitingBar() -radWaitingBar1.Size = New System.Drawing.Size(200, 200) -radWaitingBar1.WaitingStyle = Telerik.WinControls.Enumerations.WaitingBarStyles.DotsSpinner -radWaitingBar1.StartWaiting() -Dim radius As Integer = 20 -Dim elementCount As Integer = 5 -For i As Integer = 0 To 3 - radius += 10 - elementCount += 1 - Dim dsi As New DotsSpinnerWaitingBarIndicatorElement() - radWaitingBar1.WaitingIndicators.Add(dsi) - dsi.Radius = radius - dsi.ElementCount = elementCount - dsi.RotationDirection = DirectCast(i Mod 2, RotationDirection) -Next -Dim dli As New DotsLineWaitingBarIndicatorElement() -radWaitingBar1.WaitingIndicators.Add(dli) -dli.PositionOffset = New SizeF(0, 50) -Dim dli1 As New DotsLineWaitingBarIndicatorElement() -radWaitingBar1.WaitingIndicators.Add(dli1) -dli1.WaitingDirection = Telerik.WinControls.ProgressOrientation.Left -dli1.PositionOffset = New SizeF(0, -50) -Dim dli2 As New DotsLineWaitingBarIndicatorElement() -radWaitingBar1.WaitingIndicators.Add(dli2) -dli2.WaitingDirection = Telerik.WinControls.ProgressOrientation.Bottom -dli2.PositionOffset = New SizeF(50, 0) -Dim dli4 As New DotsLineWaitingBarIndicatorElement() -radWaitingBar1.WaitingIndicators.Add(dli4) -dli4.WaitingDirection = Telerik.WinControls.ProgressOrientation.Top -dli4.PositionOffset = New SizeF(-50, 0) -radWaitingBar1.Location = New Point(10, 10) -Me.Controls.Add(radWaitingBar1) -radWaitingBar1.StartWaiting() - -```` - -{{endregion}} + + + + ## See Also diff --git a/controls/track-and-status-controls/waitingbar/using-waitingbar-with-a-background-worker.md b/controls/track-and-status-controls/waitingbar/using-waitingbar-with-a-background-worker.md index bec01b718..7c9e741ad 100644 --- a/controls/track-and-status-controls/waitingbar/using-waitingbar-with-a-background-worker.md +++ b/controls/track-and-status-controls/waitingbar/using-waitingbar-with-a-background-worker.md @@ -25,68 +25,17 @@ The aim of the sample application is to calculate numbers of the Fibonacci seque 1\. When the form is loaded the BackgroundWorker instance should be initialized. Additionally, you should subscribe to two of its events: __DoWork__ and __RunWorkerCompleted__. -{{source=..\SamplesCS\TrackAndStatus\WaitingBar\BGWorkerForm.cs region=initialization}} -{{source=..\SamplesVB\TrackAndStatus\WaitingBar\BGWorkerForm.vb region=initialization}} - -````C# -private void Form1_Load(object sender, EventArgs e) -{ - myBackgroundWorker = new BackgroundWorker(); - myBackgroundWorker.WorkerReportsProgress = true; - myBackgroundWorker.WorkerSupportsCancellation = true; - myBackgroundWorker.DoWork += new DoWorkEventHandler(myBackgroundWorker1_DoWork); - myBackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(myBackgroundWorker1_RunWorkerCompleted); -} - -```` -````VB.NET -Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) - myBackgroundWorker = New BackgroundWorker() - myBackgroundWorker.WorkerReportsProgress = True - myBackgroundWorker.WorkerSupportsCancellation = True - AddHandler myBackgroundWorker.DoWork, AddressOf myBackgroundWorker1_DoWork - AddHandler myBackgroundWorker.RunWorkerCompleted, AddressOf myBackgroundWorker1_RunWorkerCompleted -End Sub - -```` - -{{endregion}} + + + + 2\. When the user clicks the *Start* __RadButton__, you should run the BackgroundWorker through the __RunWorkerAsync__ method and, also, start the __RadWaitingBar__ waiting process using the __StartWaiting__ method. -{{source=..\SamplesCS\TrackAndStatus\WaitingBar\BGWorkerForm.cs region=startingWorker}} -{{source=..\SamplesVB\TrackAndStatus\WaitingBar\BGWorkerForm.vb region=startingWorker}} - -````C# -private void radButton1_Click(object sender, EventArgs e) -{ - if (!myBackgroundWorker.IsBusy) - { - myBackgroundWorker.RunWorkerAsync(radSpinEditor1.Value); - this.radButton1.Enabled = false; - this.radButton2.Enabled = true; - this.radWaitingBar1.StartWaiting(); - begin = DateTime.Now; - this.radLabel1.Text = "Calculations in process..."; - } -} - -```` -````VB.NET -Private Sub radButton1_Click(ByVal sender As Object, ByVal e As EventArgs) - If Not myBackgroundWorker.IsBusy Then - myBackgroundWorker.RunWorkerAsync(radSpinEditor1.Value) - Me.radButton1.Enabled = False - Me.radButton2.Enabled = True - Me.radWaitingBar1.StartWaiting() - begin = Date.Now - Me.radLabel1.Text = "Calculations in process..." - End If -End Sub - -```` - -{{endregion}} + + + + >caption Fig.2 Calculation in progress @@ -94,110 +43,19 @@ End Sub 3\. In the __DoWork__ event handler you should execute the time-consuming operation, i.e. calculate the required Fibonacci number. -{{source=..\SamplesCS\TrackAndStatus\WaitingBar\BGWorkerForm.cs region=working}} -{{source=..\SamplesVB\TrackAndStatus\WaitingBar\BGWorkerForm.vb region=working}} - -````C# -void myBackgroundWorker1_DoWork(object sender, DoWorkEventArgs e) -{ - BackgroundWorker worker = sender as BackgroundWorker; - int n = Convert.ToInt32(e.Argument); - e.Result = PerformComplexComputations(n, worker, e); -} -private long PerformComplexComputations(int n, BackgroundWorker worker, DoWorkEventArgs e) -{ - long result = 0; - if (worker.CancellationPending) - { - e.Cancel = true; - } - else - { - if (n < 2) return 1; - result = PerformComplexComputations(n - 1, worker, e) + PerformComplexComputations(n - 2, worker, e); - } - return result; -} - -```` -````VB.NET -Private Sub myBackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) - Dim worker As BackgroundWorker = TryCast(sender, BackgroundWorker) - Dim n As Integer = Convert.ToInt32(e.Argument) - e.Result = PerformComplexComputations(n, worker, e) -End Sub -Private Function PerformComplexComputations(ByVal n As Integer, ByVal worker As BackgroundWorker, ByVal e As DoWorkEventArgs) As Long - Dim result As Long = 0 - If worker.CancellationPending Then - e.Cancel = True - Else - If n < 2 Then - Return 1 - End If - result = PerformComplexComputations(n - 1, worker, e) + PerformComplexComputations(n - 2, worker, e) - End If - Return result -End Function - -```` - -{{endregion}} + + + + >note If you want to interupt the long-lasting operation, you can click the **Cancel** button where the BackgroundWorker.**CancelAsync** method is called. 4\. When the long-running operation has completed, you should stop the __RadWaitingBar__ control waiting process through the __StopWaiting__ method. Additionally, you should display the result to the user. -{{source=..\SamplesCS\TrackAndStatus\WaitingBar\BGWorkerForm.cs region=workCompleted}} -{{source=..\SamplesVB\TrackAndStatus\WaitingBar\BGWorkerForm.vb region=workCompleted}} - -````C# -void myBackgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) -{ - this.radWaitingBar1.StopWaiting(); - this.radWaitingBar1.ResetWaiting(); - this.radButton1.Enabled = true; - this.radButton2.Enabled = false; - end = DateTime.Now; - if ((e.Cancelled == true)) - { - this.radLabel1.Text = "Calculations are canceled!"; - } - else if (!(e.Error == null)) - { - this.radLabel1.Text = ("Error: " + e.Error.Message); - } - else - { - this.radLabel1.Text = "The " + this.radSpinEditor1.Value.ToString() + "th member of the Fibonacci sequence is: " + e.Result.ToString(); - TimeSpan span = new TimeSpan(); - span = end - begin; - this.radLabel1.Text += "\nCalculating time: " + span.TotalSeconds + " seconds"; - } -} - -```` -````VB.NET -Private Sub myBackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) - Me.radWaitingBar1.StopWaiting() - Me.radWaitingBar1.ResetWaiting() - Me.radButton1.Enabled = True - Me.radButton2.Enabled = False - [end] = Date.Now - If (e.Cancelled = True) Then - Me.radLabel1.Text = "Calculations are canceled!" - ElseIf Not (e.Error Is Nothing) Then - Me.radLabel1.Text = ("Error: " & e.Error.Message) - Else - Me.radLabel1.Text = "The " & Me.radSpinEditor1.Value.ToString() & "th member of the Fibonacci sequence is: " & e.Result.ToString() - Dim span As New TimeSpan() - span = [end].Subtract(begin) - Me.radLabel1.Text += vbLf & "Calculating time: " & span.TotalSeconds & " seconds" - End If -End Sub - -```` - -{{endregion}} + + + + >caption Fig.3 Result diff --git a/controls/treemap/colorizers.md b/controls/treemap/colorizers.md index d9a668a40..59315a1a2 100644 --- a/controls/treemap/colorizers.md +++ b/controls/treemap/colorizers.md @@ -56,25 +56,10 @@ The available palettes for the PaletteColorizer are: #### Apply PaletteColorizer -{{source=..\SamplesCS\TreeMap\TreeMapGettingStarted.cs region=PaletteColorizer}} -{{source=..\SamplesVB\TreeMap\TreeMapGettingStarted.vb region=PaletteColorizer}} + + -````C# -PaletteColorizer paletteColorizer = new PaletteColorizer(); -paletteColorizer.Palette = TreeMapPalette.Arctic; -this.radTreeMap1.Colorizer = paletteColorizer; - -```` -````VB.NET - -Dim paletteColorizer As PaletteColorizer = New PaletteColorizer() -paletteColorizer.Palette = TreeMapPalette.Arctic -Me.radTreeMap1.Colorizer = paletteColorizer - -```` - -{{endregion}} >caption TreeMapPalette.Arctic @@ -88,32 +73,10 @@ This RangeColorizer contains a set of ranges defined by the **Stops** collection ![WinForms RadTreeMap RangeColorizer](images/treemap-colorizers002.png) -{{source=..\SamplesCS\TreeMap\TreeMapGettingStarted.cs region=RangeColorizer}} -{{source=..\SamplesVB\TreeMap\TreeMapGettingStarted.vb region=RangeColorizer}} - -````C# - -RangeColorizer rangeColorizer = new RangeColorizer(); -rangeColorizer.Palette = TreeMapPalette.Cold; -rangeColorizer.Stops.AddRange(new List() { 5, 10, 20, 25, 60 }); -this.radTreeMap1.Colorizer = rangeColorizer; - -```` -````VB.NET -Dim rangeColorizer As RangeColorizer = New RangeColorizer() -rangeColorizer.Palette = TreeMapPalette.Cold -rangeColorizer.Stops.AddRange(New List(Of Double)() From { - 5, - 10, - 20, - 25, - 60 -}) -Me.radTreeMap1.Colorizer = rangeColorizer - -```` - -{{endregion}} + + + + >Each Stop value can be absolute or relative (between 0 and 1) depending on the IsAbsolute property value. This may be useful for cases when half of the items need to be colored in one color, and the rest of them in another. Just add Stops 0, 0.5, 1 and thus two ranges will be defined: 0-0.5 and 0.5-1. Two palette colorw will be used in this case. @@ -123,27 +86,10 @@ A colorizer, which contains a set of gradient stops. It chooses the color to be ![WinForms RadTreeMap GradientColorizer](images/treemap-colorizers003.png) -{{source=..\SamplesCS\TreeMap\TreeMapGettingStarted.cs region=GradientColorizer}} -{{source=..\SamplesVB\TreeMap\TreeMapGettingStarted.vb region=GradientColorizer}} - -````C# + + -GradientColorizer gradientColorizer = new GradientColorizer(); -gradientColorizer.StartColor = Color.Red; -gradientColorizer.EndColor = Color.Yellow; -this.radTreeMap1.Colorizer = gradientColorizer; - -```` -````VB.NET - -Dim gradientColorizer As GradientColorizer = New GradientColorizer() -gradientColorizer.StartColor = System.Drawing.Color.Red -gradientColorizer.EndColor = System.Drawing.Color.Yellow -Me.radTreeMap1.Colorizer = gradientColorizer -```` - -{{endregion}} In case of grouping, the GradientColorizer offers: @@ -153,27 +99,10 @@ In case of grouping, the GradientColorizer offers: >note The **StartColor** and **EndColor** properties have default values coming from the first color defined in the two palettes respectively. -{{source=..\SamplesCS\TreeMap\TreeMapGettingStarted.cs region=GroupedGradient}} -{{source=..\SamplesVB\TreeMap\TreeMapGettingStarted.vb region=GroupedGradient}} - -````C# - -GradientColorizer groupGradientColorizer = new GradientColorizer(); -groupGradientColorizer.StartPalette = TreeMapPalette.Fluent; -groupGradientColorizer.EndPalette = TreeMapPalette.Forest; -this.radTreeMap1.Colorizer = groupGradientColorizer; - -```` -````VB.NET - -Dim groupGradientColorizer As GradientColorizer = New GradientColorizer() -groupGradientColorizer.StartPalette = TreeMapPalette.Fluent -groupGradientColorizer.EndPalette = TreeMapPalette.Forest -Me.radTreeMap1.Colorizer = groupGradientColorizer + + -```` -{{endregion}} ![WinForms RadTreeMap Start/End Palette](images/treemap-colorizers006.png) diff --git a/controls/treemap/customizing-appearance.md b/controls/treemap/customizing-appearance.md index 440530fb0..89dd017c9 100644 --- a/controls/treemap/customizing-appearance.md +++ b/controls/treemap/customizing-appearance.md @@ -38,69 +38,10 @@ It is fired right after a group is already painted. It is appropriate if you nee >note If the **GroupPainting** is **Handled**, the **GroupPainted** and **ItemPainting** events wouldn't be fired. -{{source=..\SamplesCS\TreeMap\TreeMapGettingStarted.cs region=GroupPainting}} -{{source=..\SamplesVB\TreeMap\TreeMapGettingStarted.vb region=GroupPainting}} - -````C# - -private void RadTreeMap1_GroupPainting(object sender, TreeMapGroupPaintingEventArgs e) -{ - if (e.Group.Text == "Asia") - { - e.Handled = true; - - e.Graphics.DrawString("Custom Header Text", itemsFont, Brushes.Red, e.HeaderRect); - Rectangle contentRectangle = new Rectangle(new Point(e.Bounds.X, e.HeaderRect.Bottom), - new Size(e.Bounds.Width, e.Bounds.Height - e.HeaderRect.Height)); - e.Graphics.FillRectangle(Brushes.Yellow, contentRectangle); - e.Graphics.DrawString("No data", itemsFont, Brushes.Red, - new Point(contentRectangle.X + contentRectangle.Width / 3, - contentRectangle.Y + contentRectangle.Height / 2)); - - } -} - -private void RadTreeMap1_GroupPainted(object sender, TreeMapGroupPaintedEventArgs e) -{ - if (e.Group.Text == "Europe") - { - Image img = new Bitmap(Properties.Resources.Paris, new Size(this.radTreeMap1.TreeMapElement.GroupHeaderHeight, - this.radTreeMap1.TreeMapElement.GroupHeaderHeight)); - Point imageLocation = new Point(e.Bounds.X + e.Bounds.Width / 2 - img.Width, e.Bounds.Y); - e.Graphics.DrawImage(img, imageLocation); - } -} - - -```` -````VB.NET - -Private Sub RadTreeMap1_GroupPainting(ByVal sender As Object, ByVal e As TreeMapGroupPaintingEventArgs) - If e.Group.Text = "Asia" Then - e.Handled = True - e.Graphics.DrawString("Custom Header Text", itemsFont, Brushes.Red, e.HeaderRect) - Dim contentRectangle As Rectangle = New Rectangle(New Point(e.Bounds.X, e.HeaderRect.Bottom), - New Size(e.Bounds.Width, e.Bounds.Height - e.HeaderRect.Height)) - e.Graphics.FillRectangle(Brushes.Yellow, contentRectangle) - e.Graphics.DrawString("No data", itemsFont, Brushes.Red, - New Point(contentRectangle.X + contentRectangle.Width / 3, - contentRectangle.Y + contentRectangle.Height / 2)) - End If -End Sub - -Private Sub RadTreeMap1_GroupPainted(ByVal sender As Object, ByVal e As TreeMapGroupPaintedEventArgs) - If e.Group.Text = "Europe" Then - Dim img As Image = New Bitmap(My.Resources.Paris, New Size(Me.radTreeMap1.TreeMapElement.GroupHeaderHeight, - Me.radTreeMap1.TreeMapElement.GroupHeaderHeight)) - Dim imageLocation As Point = New Point(e.Bounds.X + e.Bounds.Width / 2 - img.Width, e.Bounds.Y) - e.Graphics.DrawImage(img, imageLocation) - End If -End Sub - + + -```` -{{endregion}} ![WinForms RadTreeMap GroupPainted](images/customizing-appearance001.png) @@ -130,69 +71,10 @@ It is fired right after an item is already painted. It is appropriate if you nee ![WinForms RadTreeMap ItemPainted](images/customizing-appearance002.png) -{{source=..\SamplesCS\TreeMap\TreeMapGettingStarted.cs region=ItemPainting}} -{{source=..\SamplesVB\TreeMap\TreeMapGettingStarted.vb region=ItemPainting}} - -````C# - -Font itemsFont = new Font("Arial", 12f, FontStyle.Bold); -private void RadTreeMap1_ItemPainting(object sender, TreeMapItemPaintingEventArgs e) -{ - e.Font = itemsFont; - if (e.Item.Text == "Paris") - { - e.ForeColor = Color.White; - e.TextAlignment = ContentAlignment.TopCenter; - e.BorderColor = Color.Red; - } - else - { - e.ForeColor = Color.Black; - e.TextAlignment = ContentAlignment.TopLeft; - e.BorderColor = Color.Transparent; - } -} - -private void RadTreeMap1_ItemPainted(object sender, TreeMapItemPaintedEventArgs e) -{ - if (e.Item.Text == "Paris") - { - Image img = new Bitmap(Properties.Resources.Paris, new Size(100, 100)); - Point imageLocation = new Point(e.Bounds.X + e.Bounds.Width / 2 - img.Width / 2, e.Bounds.Y + 20); - e.Graphics.DrawImage(img, imageLocation); - } -} - -```` -````VB.NET - -Private itemsFont As Font = New Font("Arial", 12.0F, FontStyle.Bold) - -Private Sub RadTreeMap1_ItemPainting(ByVal sender As Object, ByVal e As TreeMapItemPaintingEventArgs) - e.Font = itemsFont - - If e.Item.Text = "Paris" Then - e.ForeColor = Color.White - e.TextAlignment = ContentAlignment.TopCenter - e.BorderColor = Color.Red - Else - e.ForeColor = Color.Black - e.TextAlignment = ContentAlignment.TopLeft - e.BorderColor = Color.Transparent - End If -End Sub - -Private Sub RadTreeMap1_ItemPainted(ByVal sender As Object, ByVal e As TreeMapItemPaintedEventArgs) - If e.Item.Text = "Paris" Then - Dim img As Image = New Bitmap(My.Resources.Paris, New Size(100, 100)) - Dim imageLocation As Point = New Point(e.Bounds.X + e.Bounds.Width / 2 - img.Width / 2, e.Bounds.Y + 20) - e.Graphics.DrawImage(img, imageLocation) - End If -End Sub - -```` - -{{endregion}} + + + + >note If the **ItemPainting** is **Handled**, the **ItemPainted** wouldn't be fired. diff --git a/controls/treemap/data-binding.md b/controls/treemap/data-binding.md index 225b04392..2a0d850f8 100644 --- a/controls/treemap/data-binding.md +++ b/controls/treemap/data-binding.md @@ -24,27 +24,11 @@ Data binding is a mechanism for automatic population of the RadTreeMap with item ## Run Time -{{source=..\SamplesCS\TreeMap\TreeMapGettingStarted.cs region=Bind}} -{{source=..\SamplesVB\TreeMap\TreeMapGettingStarted.vb region=Bind}} + + -````C# - -this.radTreeMap1.DisplayMember = "ProductName"; -this.radTreeMap1.ValueMember = "ProductID"; -this.radTreeMap1.DataSource = this.productsBindingSource; -```` -````VB.NET -Me.radTreeMap1.DisplayMember = "ProductName" -Me.radTreeMap1.ValueMember = "ProductID" -Me.radTreeMap1.DataSource = Me.productsBindingSource - -```` - -{{endregion}} - - ## Design Time It is possible to specify the **DataSource**, **DisplayMember**, **ValueMember** properties via the Smart Tag. The following tutorial demonstrates how to bind the tree map control to the Northwind.Products table: diff --git a/controls/treemap/features/grouping.md b/controls/treemap/features/grouping.md index 74c537415..d8d44fc3b 100644 --- a/controls/treemap/features/grouping.md +++ b/controls/treemap/features/grouping.md @@ -28,29 +28,11 @@ When using [bound mode]({%slug treemap-data-binding%}), once the **RadTreeMap** ![WinForms RadTreeMap grouped by CategoryID](images/winforms-treemap-grouping003.png) -{{source=..\SamplesCS\TreeMap\TreeMapGettingStarted.cs region=Grouping}} -{{source=..\SamplesVB\TreeMap\TreeMapGettingStarted.vb region=Grouping}} + + -````C# -this.radTreeMap1.DisplayMember = "ProductName"; -this.radTreeMap1.ValueMember = "ProductID"; -this.radTreeMap1.DataSource = this.productsBindingSource; -this.radTreeMap1.GroupDescriptors.Add("CategoryID", ListSortDirection.Descending); -```` -````VB.NET - -Me.radTreeMap1.DisplayMember = "ProductName" -Me.radTreeMap1.ValueMember = "ProductID" -Me.radTreeMap1.DataSource = Me.productsBindingSource -Me.radTreeMap1.GroupDescriptors.Add("CategoryID", ListSortDirection.Ascending) - -```` - -{{endregion}} - - # See Also * [Structure]({%slug treemap-structure%}) diff --git a/controls/treemap/features/legend.md b/controls/treemap/features/legend.md index ecf80ee9d..83978d4f0 100644 --- a/controls/treemap/features/legend.md +++ b/controls/treemap/features/legend.md @@ -16,74 +16,18 @@ RadTreeMap has built-in support for a legend – descriptions about the treemap ![WinForms RadTreeMap's legend](images/winforms-treemap-legend001.png) -{{source=..\SamplesCS\TreeMap\TreeMapGettingStarted.cs region=Legend}} -{{source=..\SamplesVB\TreeMap\TreeMapGettingStarted.vb region=Legend}} + + -````C# - -this.radTreeMap1.ShowLegend = true; -this.radTreeMap1.TreeMapElement.LegendPosition = RadPosition.Right; -this.radTreeMap1.TreeMapElement.LegendElement.LegendTitle = "Continents"; -this.radTreeMap1.TreeMapElement.LegendElement.PanelElement.Orientation = Orientation.Vertical; - -```` -````VB.NET - -Me.radTreeMap1.ShowLegend = True -Me.radTreeMap1.TreeMapElement.LegendPosition = RadPosition.Right -Me.radTreeMap1.TreeMapElement.LegendElement.LegendTitle = "Continents" -Me.radTreeMap1.TreeMapElement.LegendElement.PanelElement.Orientation = Orientation.Vertical -```` - -{{endregion}} - The TreeMapElement.LegendElement.**VisualItemCreating** event allows you to create custom legend elements or customize the default ones: #### Customize the default LegendItemElement -{{source=..\SamplesCS\TreeMap\TreeMapGettingStarted.cs region=FormattingLegendItems}} -{{source=..\SamplesVB\TreeMap\TreeMapGettingStarted.vb region=FormattingLegendItems}} + + -````C# - -Font f = new Font("Arial", 10f, FontStyle.Bold); -private void LegendElement_VisualItemCreating(object sender, - Telerik.WinControls.UI.TreeMap.LegendItemElementCreatingEventArgs e) -{ - Telerik.WinControls.UI.TreeMap.LegendItemElement legendElement = - new Telerik.WinControls.UI.TreeMap.LegendItemElement(e.GroupItem); - legendElement.Font = f; - legendElement.TitleElement.ForeColor = Color.Red; - legendElement.MarkerElement.DrawBorder = true; - legendElement.MarkerElement.BorderBoxStyle = BorderBoxStyle.SingleBorder; - legendElement.MarkerElement.BorderColor = Color.Red; - legendElement.MarkerElement.BorderWidth = 1; - e.ItemElement = legendElement; -} - -```` -````VB.NET - -Private f As Font = New Font("Arial", 10.0F, FontStyle.Bold) - -Private Sub LegendElement_VisualItemCreating(ByVal sender As Object, - ByVal e As Telerik.WinControls.UI.TreeMap.LegendItemElementCreatingEventArgs) - Dim legendElement As Telerik.WinControls.UI.TreeMap.LegendItemElement = - New Telerik.WinControls.UI.TreeMap.LegendItemElement(e.GroupItem) - legendElement.Font = f - legendElement.TitleElement.ForeColor = Color.Red - legendElement.MarkerElement.DrawBorder = True - legendElement.MarkerElement.BorderBoxStyle = BorderBoxStyle.SingleBorder - legendElement.MarkerElement.BorderColor = Color.Red - legendElement.MarkerElement.BorderWidth = 1 - e.ItemElement = legendElement -End Sub - -```` - -{{endregion}} ![WinForms RadTreeMap Customize the default LegendItemElement](images/winforms-treemap-legend002.png) diff --git a/controls/treemap/features/tooltips.md b/controls/treemap/features/tooltips.md index 86f81c8e3..bcb76980b 100644 --- a/controls/treemap/features/tooltips.md +++ b/controls/treemap/features/tooltips.md @@ -44,47 +44,10 @@ When the **ToolTipDisplayMode** property is set to **ScreenTip**, the **ScreenTi #### Customizing Screentips -{{source=..\SamplesCS\TreeMap\TreeMapGettingStarted.cs region=Screentips}} -{{source=..\SamplesVB\TreeMap\TreeMapGettingStarted.vb region=Screentips}} - -````C# - -private void RadTreeMap1_ScreenTipShowing(object sender, TreeMapScreenTipEventArgs e) -{ - if (e.Item.Text == "Paris") - { - e.ScreenTip.MainTextLabel.Image = Properties.Resources.Paris; - e.ScreenTip.MainTextLabel.TextImageRelation = TextImageRelation.TextAboveImage; - e.Text = "Current population: " + e.Item.AlgorithmValue; - e.FooterText = "2021"; - } - else - { - e.FooterText = string.Empty; - e.ScreenTip.MainTextLabel.Image = null; - - } -} - -```` -````VB.NET - -Private Sub RadTreeMap1_ScreenTipShowing(ByVal sender As Object, ByVal e As TreeMapScreenTipEventArgs) - If e.Item.Text = "Paris" Then - e.ScreenTip.MainTextLabel.Image = My.Resources.Paris - e.ScreenTip.MainTextLabel.TextImageRelation = TextImageRelation.TextAboveImage - e.Text = "Current population: " & e.Item.AlgorithmValue - e.FooterText = "2021" - Else - e.FooterText = String.Empty - e.ScreenTip.MainTextLabel.Image = Nothing - End If -End Sub - - -```` - -{{endregion}} + + + + ![WinForms RadTreeMap Customizing Screentips](images/winforms-treemap-tooltips002.png) @@ -106,30 +69,10 @@ The **TreeMapToolTipEventArgs** gives access to the following argumens: * **Item** - Gets the data item or group. -{{source=..\SamplesCS\TreeMap\TreeMapGettingStarted.cs region=Tooltips}} -{{source=..\SamplesVB\TreeMap\TreeMapGettingStarted.vb region=Tooltips}} - -````C# - -private void RadTreeMap1_ToolTipShowing(object sender, TreeMapToolTipEventArgs e) -{ - e.ToolTip.IsBalloon = true; - e.Text = "Current population: " + e.Item.AlgorithmValue; - e.Duration = 2000; -} - -```` -````VB.NET - -Private Sub RadTreeMap1_ToolTipShowing(ByVal sender As Object, ByVal e As TreeMapToolTipEventArgs) - e.ToolTip.IsBalloon = True - e.Text = "Current population: " & e.Item.AlgorithmValue - e.Duration = 2000 -End Sub - -```` - -{{endregion}} + + + + ![WinForms RadTreeMap TreeMapToolTipEventArgs](images/winforms-treemap-tooltips004.png) diff --git a/controls/treemap/getting-started.md b/controls/treemap/getting-started.md index efa8f175e..bde9e0567 100644 --- a/controls/treemap/getting-started.md +++ b/controls/treemap/getting-started.md @@ -39,61 +39,11 @@ This article shows how you can start using **RadTreeMap**. Just drag a RadTreeMa ![WinForms RadTreeMap Getting Started](images/treemap-getting-started001.png) -{{source=..\SamplesCS\TreeMap\TreeMapGettingStarted.cs region=Populate}} -{{source=..\SamplesVB\TreeMap\TreeMapGettingStarted.vb region=Populate}} + + -````C# - -DataTable dt = new DataTable(); -dt.Columns.Add("Country", typeof(string)); -dt.Columns.Add("Population", typeof(float)); -dt.Columns.Add("Continent", typeof(string)); -dt.Rows.Add("Italy", 59.55f, "Europe"); -dt.Rows.Add("France", 67.39f, "Europe"); -dt.Rows.Add("Germany", 83.24f, "Europe"); -dt.Rows.Add("Spain", 47.35f, "Europe"); -dt.Rows.Add("Bulgaria", 6.9f, "Europe"); - -dt.Rows.Add("Egypt", 102.3f, "Africa"); -dt.Rows.Add("Marocco", 36.9f, "Africa"); -dt.Rows.Add("Kenia", 53.77f, "Africa"); -dt.Rows.Add("Mali", 20.25f, "Africa"); - -this.radTreeMap1.DisplayMember = "Country"; -this.radTreeMap1.ValueMember = "Population"; -this.radTreeMap1.DataSource = dt; - -```` -````VB.NET - -Dim dt As DataTable = New DataTable() -dt.Columns.Add("Country", GetType(String)) -dt.Columns.Add("Population", GetType(Single)) -dt.Columns.Add("Continent", GetType(String)) - -dt.Rows.Add("Italy", 59.55F, "Europe") -dt.Rows.Add("France", 67.39F, "Europe") -dt.Rows.Add("Germany", 83.24F, "Europe") -dt.Rows.Add("Spain", 47.35F, "Europe") -dt.Rows.Add("Bulgaria", 6.9F, "Europe") - -dt.Rows.Add("Egypt", 102.3F, "Africa") -dt.Rows.Add("Marocco", 36.9F, "Africa") -dt.Rows.Add("Kenia", 53.77F, "Africa") -dt.Rows.Add("Mali", 20.25F, "Africa") - -Me.radTreeMap1.DisplayMember = "Country" -Me.radTreeMap1.ValueMember = "Population" -Me.radTreeMap1.DataSource = dt - - -```` - -{{endregion}} - - ## See Also * [Structure]({%slug treemap-structure%}) diff --git a/controls/treemap/layout-strategies.md b/controls/treemap/layout-strategies.md index 5f663caff..f3c074e27 100644 --- a/controls/treemap/layout-strategies.md +++ b/controls/treemap/layout-strategies.md @@ -22,22 +22,10 @@ It creates rectangles with best aspect ratio: ![WinForms RadTreeMap Squarified](images/treemap-layout-strategies001.png) -{{source=..\SamplesCS\TreeMap\TreeMapGettingStarted.cs region=Squarified}} -{{source=..\SamplesVB\TreeMap\TreeMapGettingStarted.vb region=Squarified}} + + -````C# - -SquarifiedAlgorithm squarifiedAlgorithm = new SquarifiedAlgorithm(); -this.radTreeMap1.Algorithm = squarifiedAlgorithm; -```` -````VB.NET -Dim squarifiedAlgorithm As SquarifiedAlgorithm = New SquarifiedAlgorithm() -Me.radTreeMap1.Algorithm = squarifiedAlgorithm - -```` - -{{endregion}} >note The default layout is Squarified. @@ -49,50 +37,17 @@ It creates rectangles with high aspect ratio and displays them sorted either hor For the **Slice and Dice** algorithm you can specify **Orientation** (*Horizontal*, *Vertical* or *Smart*) and **SortDirection** (*Ascending* or *Descending*): -{{source=..\SamplesCS\TreeMap\TreeMapGettingStarted.cs region=HorizontalSliceDice}} -{{source=..\SamplesVB\TreeMap\TreeMapGettingStarted.vb region=HorizontalSliceDice}} - -````C# - -SliceDiceAlgorithm sliceDiceAlgorithm = new SliceDiceAlgorithm(); -sliceDiceAlgorithm.Orientation = SliceDiceOrientation.Horizontal; -sliceDiceAlgorithm.SortDirection = ListSortDirection.Descending; -this.radTreeMap1.Algorithm = sliceDiceAlgorithm; - -```` -````VB.NET - -Dim sliceDiceAlgorithm As SliceDiceAlgorithm = New SliceDiceAlgorithm() -sliceDiceAlgorithm.Orientation = SliceDiceOrientation.Horizontal -sliceDiceAlgorithm.SortDirection = System.ComponentModel.ListSortDirection.Descending -Me.radTreeMap1.Algorithm = sliceDiceAlgorithm + + -```` - -{{endregion}} Setting the **Orientation** to *Smart* means that the algorithm will automatically choose the most appropriate orientation depending on your data and the available space. -{{source=..\SamplesCS\TreeMap\TreeMapGettingStarted.cs region=SmartSliceDice}} -{{source=..\SamplesVB\TreeMap\TreeMapGettingStarted.vb region=SmartSliceDice}} - -````C# - -SliceDiceAlgorithm sliceDiceAlgorithmSmart = new SliceDiceAlgorithm(); -sliceDiceAlgorithmSmart.Orientation = SliceDiceOrientation.Smart; -this.radTreeMap1.Algorithm = sliceDiceAlgorithmSmart; - -```` -````VB.NET - -Dim sliceDiceAlgorithmSmart As SliceDiceAlgorithm = New SliceDiceAlgorithm() -sliceDiceAlgorithmSmart.Orientation = SliceDiceOrientation.Smart -Me.radTreeMap1.Algorithm = sliceDiceAlgorithmSmart + + -```` -{{endregion}} #### Vertical Slice and Dice diff --git a/controls/treemap/unbound-mode.md b/controls/treemap/unbound-mode.md index 35ac738fc..a5aca3662 100644 --- a/controls/treemap/unbound-mode.md +++ b/controls/treemap/unbound-mode.md @@ -38,92 +38,10 @@ Then, you can click the *Edit Items* option and specify the **Group** for each a ### Populating with Data at Run Time -{{source=..\SamplesCS\TreeMap\TreeMapGettingStarted.cs region=UnboundMode}} -{{source=..\SamplesVB\TreeMap\TreeMapGettingStarted.vb region=UnboundMode}} - -````C# - -TreeMapDataItemGroup treeMapDataItemGroup1 = new TreeMapDataItemGroup(); -TreeMapDataItemGroup treeMapDataItemGroup2 = new TreeMapDataItemGroup(); -TreeMapDataItemGroup treeMapDataItemGroup3 = new TreeMapDataItemGroup(); -TreeMapDataItem treeMapDataItem1 = new TreeMapDataItem(); -TreeMapDataItem treeMapDataItem2 = new TreeMapDataItem(); -TreeMapDataItem treeMapDataItem3 = new TreeMapDataItem(); -TreeMapDataItem treeMapDataItem4 = new TreeMapDataItem(); -TreeMapDataItem treeMapDataItem5 = new TreeMapDataItem(); - -treeMapDataItemGroup1.LegendTitle = "Europe"; -treeMapDataItemGroup1.Text = "Europe"; -treeMapDataItemGroup2.LegendTitle = "Asia"; -treeMapDataItemGroup2.Text = "Asia"; -treeMapDataItemGroup3.LegendTitle = "Africa"; -treeMapDataItemGroup3.Text = "Africa"; -this.radTreeMap1.Groups.AddRange(new Telerik.WinControls.UI.TreeMap.TreeMapDataItemGroup[] { -treeMapDataItemGroup1, -treeMapDataItemGroup2, -treeMapDataItemGroup3}); -treeMapDataItem1.Group = treeMapDataItemGroup1; -treeMapDataItem1.Text = "Sofia"; -treeMapDataItem1.Value = 45; -treeMapDataItem2.Group = treeMapDataItemGroup1; -treeMapDataItem2.Text = "Paris"; -treeMapDataItem2.Value = 140; -treeMapDataItem3.Group = treeMapDataItemGroup1; -treeMapDataItem3.Text = "Rome"; -treeMapDataItem3.Value = 86; -treeMapDataItem4.Group = treeMapDataItemGroup2; -treeMapDataItem4.Text = "Bangkok"; -treeMapDataItem4.Value = 220; -treeMapDataItem5.Group = treeMapDataItemGroup3; -treeMapDataItem5.Text = "Cairo"; -treeMapDataItem5.Value = 180; -this.radTreeMap1.Items.AddRange(new Telerik.WinControls.UI.TreeMap.TreeMapDataItem[] { -treeMapDataItem1, -treeMapDataItem2, -treeMapDataItem3, -treeMapDataItem4, -treeMapDataItem5}); - -```` -````VB.NET - -Dim treeMapDataItemGroup1 As TreeMapDataItemGroup = New TreeMapDataItemGroup() -Dim treeMapDataItemGroup2 As TreeMapDataItemGroup = New TreeMapDataItemGroup() -Dim treeMapDataItemGroup3 As TreeMapDataItemGroup = New TreeMapDataItemGroup() -Dim treeMapDataItem1 As TreeMapDataItem = New TreeMapDataItem() -Dim treeMapDataItem2 As TreeMapDataItem = New TreeMapDataItem() -Dim treeMapDataItem3 As TreeMapDataItem = New TreeMapDataItem() -Dim treeMapDataItem4 As TreeMapDataItem = New TreeMapDataItem() -Dim treeMapDataItem5 As TreeMapDataItem = New TreeMapDataItem() -treeMapDataItemGroup1.LegendTitle = "Europe" -treeMapDataItemGroup1.Text = "Europe" -treeMapDataItemGroup2.LegendTitle = "Asia" -treeMapDataItemGroup2.Text = "Asia" -treeMapDataItemGroup3.LegendTitle = "Africa" -treeMapDataItemGroup3.Text = "Africa" -Me.radTreeMap1.Groups.AddRange(New Telerik.WinControls.UI.TreeMap.TreeMapDataItemGroup() {treeMapDataItemGroup1, - treeMapDataItemGroup2, treeMapDataItemGroup3}) -treeMapDataItem1.Group = treeMapDataItemGroup1 -treeMapDataItem1.Text = "Sofia" -treeMapDataItem1.Value = 45 -treeMapDataItem2.Group = treeMapDataItemGroup1 -treeMapDataItem2.Text = "Paris" -treeMapDataItem2.Value = 140 -treeMapDataItem3.Group = treeMapDataItemGroup1 -treeMapDataItem3.Text = "Rome" -treeMapDataItem3.Value = 86 -treeMapDataItem4.Group = treeMapDataItemGroup2 -treeMapDataItem4.Text = "Bangkok" -treeMapDataItem4.Value = 220 -treeMapDataItem5.Group = treeMapDataItemGroup3 -treeMapDataItem5.Text = "Cairo" -treeMapDataItem5.Value = 180 -Me.radTreeMap1.Items.AddRange(New Telerik.WinControls.UI.TreeMap.TreeMapDataItem() {treeMapDataItem1, - treeMapDataItem2, treeMapDataItem3, treeMapDataItem4, treeMapDataItem5}) - -```` - -{{endregion}} + + + + ![WinForms RadTreeMap Unbound Mode Result](images/treemap-unbound-mode004.png) diff --git a/controls/treeview/breadcrumb.md b/controls/treeview/breadcrumb.md index e9f1d9193..ac79755ef 100644 --- a/controls/treeview/breadcrumb.md +++ b/controls/treeview/breadcrumb.md @@ -19,19 +19,10 @@ previous_url: treeview-breadcrumb Use __DefaultTreeView__ property of __RadBreadCrumb__ to associate the bread crumb with an instance of __RadTreeView__.  -{{source=..\SamplesCS\TreeView\BreadCrumb.cs region=defaultTreeView}} -{{source=..\SamplesVB\TreeView\BreadCrumb.vb region=defaultTreeView}} + + -````C# -this.radBreadCrumb1.DefaultTreeView = radTreeView1; -```` -````VB.NET -Me.RadBreadCrumb1.DefaultTreeView = Me.RadTreeView1 - -```` - -{{endregion}} ## Selecting Nodes @@ -41,18 +32,10 @@ The **SelectTreeNodeOnClick** property determines whether the nodes in the tree ![WinForms RadTreeView Selecting Nodes](images/treeview-breadcrumb004.gif) -{{source=..\SamplesCS\TreeView\BreadCrumb.cs region=SelectingNodes}} -{{source=..\SamplesVB\TreeView\BreadCrumb.vb region=SelectingNodes}} -````C# -this.radBreadCrumb1.SelectTreeNodeOnClick = true; + + -```` -````VB.NET -Me.RadBreadCrumb1.SelectTreeNodeOnClick = True -```` - -{{endregion}} # See Also * [RadBreadCrumb]({%slug breadcrumb-overview%}) diff --git a/controls/treeview/context-menus/default-context-menu.md b/controls/treeview/context-menus/default-context-menu.md index 850e285e9..2acbfe8c0 100644 --- a/controls/treeview/context-menus/default-context-menu.md +++ b/controls/treeview/context-menus/default-context-menu.md @@ -31,19 +31,9 @@ RadTreeView displays a default context menu which appears when you right-click o The default context menu is not enabled by default and if you right-click a node, it will not appear on the screen. In order to enable it, you should set the __AllowDefaultContextMenu__ property to *true*: -{{source=..\SamplesCS\TreeView\ContextMenus\TreeViewMenus.cs region=defaultMenu}} -{{source=..\SamplesVB\TreeView\ContextMenus\TreeViewMenus.vb region=defaultMenu}} + + -````C# -this.radTreeView1.AllowDefaultContextMenu = true; - -```` -````VB.NET -Me.RadTreeView1.AllowDefaultContextMenu = True - -```` - -{{endregion}} ![WinForms RadTreeView Default Menu](images/treeview-context-menus-default-context-menu001.png) @@ -54,56 +44,28 @@ __Enabling the New item__ To enable the New item, you should set the __AllowAdd__ property to *true*: -{{source=..\SamplesCS\TreeView\ContextMenus\TreeViewMenus.cs region=allowAdd}} -{{source=..\SamplesVB\TreeView\ContextMenus\TreeViewMenus.vb region=allowAdd}} - -````C# -this.radTreeView1.AllowAdd = true; - -```` -````VB.NET -Me.RadTreeView1.AllowAdd = True + + -```` - -{{endregion}} ![WinForms RadTreeView AllowAdd](images/treeview-context-menus-default-context-menu002.png) __Enabling the Edit item__: To enable the Edit item, you should set the __AllowEdit__ property to *true*: -{{source=..\SamplesCS\TreeView\ContextMenus\TreeViewMenus.cs region=allowEdit}} -{{source=..\SamplesVB\TreeView\ContextMenus\TreeViewMenus.vb region=allowEdit}} - -````C# -this.radTreeView1.AllowEdit = true; - -```` -````VB.NET -Me.RadTreeView1.AllowEdit = True + + -```` -{{endregion}} ![WinForms RadTreeView AllowEdit](images/treeview-context-menus-default-context-menu005.png) __Enabling the Delete item__: To enable the Delete item, you should set the __AllowRemove__ property to *true*: -{{source=..\SamplesCS\TreeView\ContextMenus\TreeViewMenus.cs region=allowRemove}} -{{source=..\SamplesVB\TreeView\ContextMenus\TreeViewMenus.vb region=allowRemove}} - -````C# -this.radTreeView1.AllowRemove = true; - -```` -````VB.NET -Me.RadTreeView1.AllowRemove = True + + -```` -{{endregion}} ![WinForms RadTreeView AllowRemove](images/treeview-context-menus-default-context-menu004.png) diff --git a/controls/treeview/context-menus/modifying-the-default-context-menu.md b/controls/treeview/context-menus/modifying-the-default-context-menu.md index ae67cf1d8..3380ab8bb 100644 --- a/controls/treeview/context-menus/modifying-the-default-context-menu.md +++ b/controls/treeview/context-menus/modifying-the-default-context-menu.md @@ -69,55 +69,10 @@ Here is a table of the data that we are going to pass to RadTreeView: Following our requirements, we prepare the this implementation: -{{source=..\SamplesCS\TreeView\ContextMenus\TreeViewMenus.cs region=removingItems}} -{{source=..\SamplesVB\TreeView\ContextMenus\TreeViewMenus.vb region=removingItems}} - -````C# -void radTreeView1_ContextMenuOpening1(object sender, Telerik.WinControls.UI.TreeViewContextMenuOpeningEventArgs e) -{ - DataRowView rowView = (DataRowView)e.Node.DataBoundItem; - DataRow row = rowView.Row; - for (int i = e.Menu.Items.Count - 1; i >= 0; i--) - { - if (e.Menu.Items[i].Name == "Delete") - { - if ((bool)row.ItemArray[2] == true) - { - e.Menu.Items.Remove(e.Menu.Items[i]); - } - } - if (e.Menu.Items[i].Name == "New") - { - if (e.Node.Level == 0) - { - e.Menu.Items.Remove(e.Menu.Items[i]); - } - } - } -} - -```` -````VB.NET -Private Sub radTreeView1_ContextMenuOpening1(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.TreeViewContextMenuOpeningEventArgs) - Dim rowView As DataRowView = CType(e.Node.DataBoundItem, DataRowView) - Dim row As DataRow = rowView.Row - For i As Integer = e.Menu.Items.Count - 1 To 0 Step -1 - If e.Menu.Items(i).Name = "Delete" Then - If CBool(row.ItemArray(2)) = True Then - e.Menu.Items.Remove(e.Menu.Items(i)) - End If - End If - If e.Menu.Items(i).Name = "New" Then - If e.Node.Level = 0 Then - e.Menu.Items.Remove(e.Menu.Items(i)) - End If - End If - Next i -End Sub - -```` - -{{endregion}} + + + + And here is the result: diff --git a/controls/treeview/data-binding/binding-to-database-data.md b/controls/treeview/data-binding/binding-to-database-data.md index 06cd72dd7..db335d5e1 100644 --- a/controls/treeview/data-binding/binding-to-database-data.md +++ b/controls/treeview/data-binding/binding-to-database-data.md @@ -58,27 +58,9 @@ The purpose of this example is to demonstrate how to bind to database data. 1. In the form's __Load__ event handler add the code shown below. -{{source=..\SamplesCS\TreeView\DataBinding\BindingToDatabaseData.cs region=database}} -{{source=..\SamplesVB\TreeView\DataBinding\BindingToDatabaseData.vb region=database}} - -````C# -this.radTreeView1.DataSource = this.artistsBindingSource; -this.radTreeView1.DisplayMember = "ArtistName"; -this.radTreeView1.ValueMember = "ArtistID"; -this.radTreeView1.RelationBindings.Add(new RelationBinding(this.albumsBindingSource, "AlbumName", "ArtistID", "ArtistID", "AlbumID")); -this.radTreeView1.RelationBindings.Add(new RelationBinding(this.songsBindingSource, "SongName", "AlbumID", "AlbumID", "SongID")); - -```` -````VB.NET -Me.RadTreeView1.DataSource = Me.ArtistsBindingSource -Me.RadTreeView1.DisplayMember = "ArtistName" -Me.RadTreeView1.ValueMember = "ArtistID" -Me.RadTreeView1.RelationBindings.Add(New RelationBinding(Me.AlbumsBindingSource, "AlbumName", "ArtistID", "ArtistID", "AlbumID")) -Me.RadTreeView1.RelationBindings.Add(New RelationBinding(Me.SongsBindingSource, "SongName", "AlbumID", "AlbumID", "SongID")) - -```` - -{{endregion}} + + + # See Also diff --git a/controls/treeview/data-binding/binding-to-object-relational-data.md b/controls/treeview/data-binding/binding-to-object-relational-data.md index 246ebdb96..71c1b2dbc 100644 --- a/controls/treeview/data-binding/binding-to-object-relational-data.md +++ b/controls/treeview/data-binding/binding-to-object-relational-data.md @@ -24,43 +24,19 @@ The two steps that must be done are these: 1\. Set the DataSource of RadTreeView to a collection of your root objects (a collection of Customer object in this case): -{{source=..\SamplesCS\TreeView\DataBinding\BindingToRelatedData.cs region=customers}} -{{source=..\SamplesVB\TreeView\DataBinding\BindingToRelatedData.vb region=customers}} + + -````C# - -IEnumerable customers = context.GetTable().ToList(); -this.radTreeView1.DataSource = customers; -```` -````VB.NET -Dim customers As IEnumerable(Of Customer) = context.GetTable(Of Customer)().ToList() -Me.RadTreeView1.DataSource = customers - -```` - -{{endregion}} >note The above context object is created by binding the project to the NorthWind database using [LINQ to SQl](https://msdn.microsoft.com/en-us/library/bb386976(v=vs.110).aspx) 2\. Set the __DisplayMember__ corresponding to the DisplayMembers of the different types of objects and set the __ChildMember__ corresponding to the names of the properties that represent the collections of sub objects. -{{source=..\SamplesCS\TreeView\DataBinding\BindingToRelatedData.cs region=relationClasses}} -{{source=..\SamplesVB\TreeView\DataBinding\BindingToRelatedData.vb region=relationClasses}} - -````C# - -this.radTreeView1.DisplayMember = "ContactName\\ShipName\\UnitPrice"; -this.radTreeView1.ChildMember = "Customers\\Orders\\Order_Details"; - -```` -````VB.NET -Me.RadTreeView1.DisplayMember = "ContactName\ShipName\UnitPrice" -Me.RadTreeView1.ChildMember = "Customers\Orders\Order_Details" + + -```` -{{endregion}} As a result, we get the following hierarchy in RadTreeView: diff --git a/controls/treeview/data-binding/binding-to-self-referencing-data.md b/controls/treeview/data-binding/binding-to-self-referencing-data.md index a02fec7b8..be02328c9 100644 --- a/controls/treeview/data-binding/binding-to-self-referencing-data.md +++ b/controls/treeview/data-binding/binding-to-self-referencing-data.md @@ -21,149 +21,10 @@ In order to set the parent-child relation between the records of the data source The following example demonstrates how to bind RadTreeView to a self referencing DataTable. -{{source=..\SamplesCS\TreeView\DataBinding\BindingToSelfRefData.cs region=selfRef}} -{{source=..\SamplesVB\TreeView\DataBinding\BindingToSelfRefData.vb region=selfRef}} - -````C# - -public BindingToSelfRefData() -{ - InitializeComponent(); - - this.radTreeView1.DisplayMember = "name"; - this.radTreeView1.ParentMember = "pid"; - this.radTreeView1.ChildMember = "id"; - this.radTreeView1.DataSource = this.GetSampleData(); -} - -private DataTable GetSampleData() -{ - DataTable dt = new DataTable(); - - DataColumn dc = new DataColumn(); - dc.ColumnName = "id"; - dc.DataType = typeof(int); - dt.Columns.Add(dc); - - DataColumn dc1 = new DataColumn(); - dc1.ColumnName = "name"; - dc1.DataType = typeof(string); - dt.Columns.Add(dc1); - - DataColumn dc2 = new DataColumn(); - dc2.ColumnName = "pid"; - dc2.DataType = typeof(int); - dt.Columns.Add(dc2); - - DataRow dr = dt.NewRow(); - dr[0] = 0; - dr[1] = "My Computer"; - dr[2] = DBNull.Value; - dt.Rows.Add(dr); - - dr = dt.NewRow(); - dr[0] = 1; - dr[1] = @"C:\"; - dr[2] = 0; - dt.Rows.Add(dr); - - dr = dt.NewRow(); - dr[0] = 2; - dr[1] = @"D:\"; - dr[2] = 0; - dt.Rows.Add(dr); - - dr = dt.NewRow(); - dr[0] = 3; - dr[1] = "Program Files"; - dr[2] = 1; - dt.Rows.Add(dr); - - dr = dt.NewRow(); - dr[0] = 4; - dr[1] = "Microsoft"; - dr[2] = 3; - dt.Rows.Add(dr); - - dr = dt.NewRow(); - dr[0] = 5; - dr[1] = "Telerik"; - dr[2] = 3; - dt.Rows.Add(dr); - - dr = dt.NewRow(); - dr[0] = 6; - dr[1] = "WINDOWS"; - dr[2] = 1; - dt.Rows.Add(dr); - - return dt; -} - -```` -````VB.NET -Public Sub New() - InitializeComponent() - Me.RadTreeView1.DisplayMember = "name" - Me.RadTreeView1.ParentMember = "pid" - Me.RadTreeView1.ChildMember = "id" - Me.RadTreeView1.DataSource = Me.GetSampleData() -End Sub -Private Function GetSampleData() As DataTable - Dim dt As New DataTable() - Dim dc As New DataColumn() - dc.ColumnName = "id" - dc.DataType = GetType(Integer) - dt.Columns.Add(dc) - Dim dc1 As New DataColumn() - dc1.ColumnName = "name" - dc1.DataType = GetType(String) - dt.Columns.Add(dc1) - Dim dc2 As New DataColumn() - dc2.ColumnName = "pid" - dc2.DataType = GetType(Integer) - dt.Columns.Add(dc2) - Dim dr As DataRow = dt.NewRow() - dr(0) = 0 - dr(1) = "My Computer" - dr(2) = DBNull.Value - dt.Rows.Add(dr) - dr = dt.NewRow() - dr(0) = 1 - dr(1) = "C:\" - dr(2) = 0 - dt.Rows.Add(dr) - dr = dt.NewRow() - dr(0) = 2 - dr(1) = "D:\" - dr(2) = 0 - dt.Rows.Add(dr) - dr = dt.NewRow() - dr(0) = 3 - dr(1) = "Program Files" - dr(2) = 1 - dt.Rows.Add(dr) - dr = dt.NewRow() - dr(0) = 4 - dr(1) = "Microsoft" - dr(2) = 3 - dt.Rows.Add(dr) - dr = dt.NewRow() - dr(0) = 5 - dr(1) = "Telerik" - dr(2) = 3 - dt.Rows.Add(dr) - dr = dt.NewRow() - dr(0) = 6 - dr(1) = "WINDOWS" - dr(2) = 1 - dt.Rows.Add(dr) - Return dt -End Function - -```` - -{{endregion}} + + + + As a result we get the hierarchy of nodes shown below: diff --git a/controls/treeview/data-binding/binding-to-xml-data.md b/controls/treeview/data-binding/binding-to-xml-data.md index dcfdd25a6..1e06b8bbb 100644 --- a/controls/treeview/data-binding/binding-to-xml-data.md +++ b/controls/treeview/data-binding/binding-to-xml-data.md @@ -32,32 +32,8 @@ Assuming that "toc.xml" is in the TreeView\DataBinding directory which is relati ![WinForms RadTreeView Binding to XML Data](images/treeview-data-binding-binding-to-xml-data001.png) -{{source=..\SamplesCS\TreeView\DataBinding\BindingToXmlData.cs region=toc}} -{{source=..\SamplesVB\TreeView\DataBinding\BindingToXmlData.vb region=toc}} - -````C# -DataSet tocDataSet = new DataSet("Toc"); -tocDataSet.ReadXml("TreeView\\DataBinding\\toc.xml"); -this.radTreeView1.DataMember = "Node"; -this.radTreeView1.DisplayMember = "Title"; -this.radTreeView1.ChildMember = "id"; -this.radTreeView1.ParentMember = "parentId"; -this.radTreeView1.DataSource = tocDataSet; - -```` -````VB.NET -Dim tocDataSet As DataSet = New DataSet("Toc") -tocDataSet.ReadXml("TreeView\DataBinding\toc.xml") -Me.RadTreeView1.DataMember = "Node" -Me.RadTreeView1.DisplayMember = "Title" -Me.RadTreeView1.ChildMember = "id" -Me.RadTreeView1.ParentMember = "parentId" -Me.RadTreeView1.DataSource = tocDataSet - -```` - -{{endregion}} - + + diff --git a/controls/treeview/data-binding/databinding-checkboxes.md b/controls/treeview/data-binding/databinding-checkboxes.md index 62ec1508e..a9ba2dfa3 100644 --- a/controls/treeview/data-binding/databinding-checkboxes.md +++ b/controls/treeview/data-binding/databinding-checkboxes.md @@ -14,75 +14,10 @@ Since R3 2014 __RadTreeView__ supports binding the check-boxes of the nodes to a ![WinForms RadTreeView Binding check boxes](images/treeview-data-binding-data-binding-basics003.png) -{{source=..\SamplesCS\TreeView\DataBinding\BasicsHierarchyForm.cs region=CheckedMember}} -{{source=..\SamplesVB\TreeView\DataBinding\BasicsHierarchyForm.vb region=CheckedMember}} + + -````C# - -DataTable parentDt = new DataTable("Parent"); -parentDt.Columns.Add("MasterId", typeof(string)); -parentDt.Columns.Add("Title", typeof(string)); -parentDt.Columns.Add("IsActive", typeof(bool)); - -DataTable childDt = new DataTable("Child"); -childDt.Columns.Add("ChildId", typeof(string)); -childDt.Columns.Add("ParentId", typeof(string)); -childDt.Columns.Add("Name", typeof(string)); -childDt.Columns.Add("Status", typeof(bool)); - -string parentId = string.Empty; -string childId = string.Empty; -for (int i = 1; i <= 5; i++) -{ - parentId = Guid.NewGuid().ToString(); - parentDt.Rows.Add(parentId, "Node." + i, i % 2 == 0); - - for (int j = 1; j < 5; j++) - { - childId = Guid.NewGuid().ToString(); - childDt.Rows.Add(childId, parentId, "SubNode." + i + "." + j, j % 2 == 0); - } -} - -radTreeView1.DataSource = parentDt; -radTreeView1.RelationBindings.Add(new RelationBinding(childDt,null,"Name","MasterId","ParentId","ChildId","Status")); -radTreeView1.DisplayMember = "Title"; -radTreeView1.ValueMember = "Id"; -radTreeView1.CheckedMember = "IsActive"; -radTreeView1.CheckBoxes = true; -```` -````VB.NET - -Dim parentDt As New DataTable("Parent") -parentDt.Columns.Add("MasterId", GetType(String)) -parentDt.Columns.Add("Title", GetType(String)) -parentDt.Columns.Add("IsActive", GetType(Boolean)) -Dim childDt As New DataTable("Child") -childDt.Columns.Add("ChildId", GetType(String)) -childDt.Columns.Add("ParentId", GetType(String)) -childDt.Columns.Add("Name", GetType(String)) -childDt.Columns.Add("Status", GetType(Boolean)) -Dim parentId As String = String.Empty -Dim childId As String = String.Empty -For i As Integer = 1 To 5 - parentId = Guid.NewGuid().ToString() - parentDt.Rows.Add(parentId, "Node." & i, i Mod 2 = 0) - For j As Integer = 1 To 4 - childId = Guid.NewGuid().ToString() - childDt.Rows.Add(childId, parentId, "SubNode." & i & "." & j, j Mod 2 = 0) - Next -Next -radTreeView1.DataSource = parentDt -radTreeView1.RelationBindings.Add(New RelationBinding(childDt, Nothing, "Name", "MasterId", "ParentId", "ChildId", "Status")) -radTreeView1.DisplayMember = "Title" -radTreeView1.ValueMember = "Id" -radTreeView1.CheckedMember = "IsActive" -radTreeView1.CheckBoxes = True - -```` - -{{endregion}} ## Binding CheckBoxes with Object Relational Hierarchy @@ -91,208 +26,20 @@ Consider the following diagram which can be illustrated with the sample classes Note that the __IsActive__ and the __Status__ properties represent boolean data. -{{source=..\SamplesCS\TreeView\DataBinding\BindingToRelatedData.cs region=DataClasses}} -{{source=..\SamplesVB\TreeView\DataBinding\BindingToRelatedData.vb region=DataClasses}} - -````C# - -public class Parent -{ - public string ParentId { get; set; } - - public string Title { get; set; } - - public bool IsActive { get; set; } - - public List Children { get; set; } - - public Parent(string parentId, string title, bool isActive, List children) - { - this.ParentId = parentId; - this.Title = title; - this.IsActive = isActive; - this.Children = children; - } -} - -public class Child -{ - public string ChildId { get; set; } - - public string ParentId { get; set; } - - public string Name { get; set; } - - public bool Status { get; set; } - - public Child(string childId, string parentId, string name, bool status) - { - this.ChildId = childId; - this.ParentId = parentId; - this.Name = name; - this.Status = status; - } -} + + -```` -````VB.NET -Public Class Parent - Public Property ParentId() As String - Get - Return m_ParentId - End Get - Set(value As String) - m_ParentId = value - End Set - End Property - Private m_ParentId As String - Public Property Title() As String - Get - Return m_Title - End Get - Set(value As String) - m_Title = value - End Set - End Property - Private m_Title As String - Public Property IsActive() As Boolean - Get - Return m_IsActive - End Get - Set(value As Boolean) - m_IsActive = value - End Set - End Property - Private m_IsActive As Boolean - Public Property Children() As List(Of Child) - Get - Return m_Children - End Get - Set(value As List(Of Child)) - m_Children = value - End Set - End Property - Private m_Children As List(Of Child) - Public Sub New(parentId As String, title As String, isActive As Boolean, children As List(Of Child)) - Me.ParentId = parentId - Me.Title = title - Me.IsActive = isActive - Me.Children = children - End Sub -End Class -Public Class Child - Public Property ChildId() As String - Get - Return m_ChildId - End Get - Set(value As String) - m_ChildId = value - End Set - End Property - Private m_ChildId As String - Public Property ParentId() As String - Get - Return m_ParentId - End Get - Set(value As String) - m_ParentId = value - End Set - End Property - Private m_ParentId As String - Public Property Name() As String - Get - Return m_Name - End Get - Set(value As String) - m_Name = value - End Set - End Property - Private m_Name As String - Public Property Status() As Boolean - Get - Return m_Status - End Get - Set(value As Boolean) - m_Status = value - End Set - End Property - Private m_Status As Boolean - Public Sub New(childId As String, parentId As String, name As String, status As Boolean) - Me.ChildId = childId - Me.ParentId = parentId - Me.Name = name - Me.Status = status - End Sub -End Class -```` - -{{endregion}} The code snippet below illustrates how to bind the check-boxes coming from the described properties: ![WinForms RadTreeView Binding CheckBoxes with Object Relational Hierarchy](images/treeview-data-binding-binding-to-object-relational-data003.png) -{{source=..\SamplesCS\TreeView\DataBinding\BindingToRelatedData.cs region=CheckedMember}} -{{source=..\SamplesVB\TreeView\DataBinding\BindingToRelatedData.vb region=CheckedMember}} - -````C# - -List dataItems = new List(); -Parent currentParent; -Child currentChild; -List children; -string parentId = string.Empty; -string childId = string.Empty; -for (int i = 1; i <= 5; i++) -{ - parentId = Guid.NewGuid().ToString(); - - children = new List(); - for (int j = 1; j < 5; j++) - { - childId = Guid.NewGuid().ToString(); - currentChild = new Child(childId, parentId, "SubNode." + i + "." + j, j % 2 == 0); - children.Add(currentChild); - } - currentParent = new Parent(parentId, "Node." + i, i % 2 == 0,children); - dataItems.Add(currentParent); -} - -radTreeView1.DataSource = dataItems; -radTreeView1.DisplayMember = "Title\\Name"; -radTreeView1.ChildMember = "Parent\\Children"; -radTreeView1.CheckedMember = "IsActive\\Status"; -radTreeView1.CheckBoxes = true; + + -```` -````VB.NET -Dim dataItems As New List(Of Parent)() -Dim currentParent As Parent -Dim currentChild As Child -Dim children As List(Of Child) -Dim parentId As String = String.Empty -Dim childId As String = String.Empty -For i As Integer = 1 To 5 - parentId = Guid.NewGuid().ToString() - children = New List(Of Child)() - For j As Integer = 1 To 4 - childId = Guid.NewGuid().ToString() - currentChild = New Child(childId, parentId, "SubNode." & i & "." & j, j Mod 2 = 0) - children.Add(currentChild) - Next - currentParent = New Parent(parentId, "Node." & i, i Mod 2 = 0, children) - dataItems.Add(currentParent) -Next -radTreeView1.DataSource = dataItems -radTreeView1.DisplayMember = "Title\Name" -radTreeView1.ChildMember = "Parent\Children" -radTreeView1.CheckedMember = "IsActive\Status" -radTreeView1.CheckBoxes = True -```` -{{endregion}} # See Also * [Binding to Database Data]({%slug winforms/treeview/data-binding/binding-to-database-data%}) diff --git a/controls/treeview/data-binding/load-on-demand-with-crud-operations.md b/controls/treeview/data-binding/load-on-demand-with-crud-operations.md index a7419e129..33cdf15c8 100644 --- a/controls/treeview/data-binding/load-on-demand-with-crud-operations.md +++ b/controls/treeview/data-binding/load-on-demand-with-crud-operations.md @@ -19,570 +19,58 @@ In this example, we will use the following scenario: A hierarchy, which has __Te Below you can see the implementation of these types. Note that their child collections are __BindingLists__ and that every type implements __INotifyPropertyChanged__. We will use this approach so that every property change will bubble up to the top-most collection which we will monitor: -{{source=..\SamplesCS\TreeView\DataBinding\LoadOnDemandWithCrudOperations.cs region=Models}} -{{source=..\SamplesVB\TreeView\DataBinding\LoadOnDemandWithCrudOperations.vb region=Models}} - -````C# -public class Team : INotifyPropertyChanged -{ - private string teamName; - public string TeamName - { - get { return this.teamName; } - set - { - this.teamName = value; - this.OnPropertyChanged("TeamName"); - } - } - public BindingList TeamMembers { get; private set; } - public BindingList TeamTasks { get; private set; } - public Team(string teamName) - { - this.TeamName = teamName; - this.TeamMembers = new BindingList(); - this.TeamTasks = new BindingList(); - this.TeamMembers.ListChanged += TeamMembers_ListChanged; - this.TeamTasks.ListChanged += TeamTasks_ListChanged; - } - private void TeamTasks_ListChanged(object sender, ListChangedEventArgs e) - { - this.OnPropertyChanged("TeamTasks"); - } - private void TeamMembers_ListChanged(object sender, ListChangedEventArgs e) - { - this.OnPropertyChanged("TeamName"); - } - public event PropertyChangedEventHandler PropertyChanged; - protected virtual void OnPropertyChanged(string propName) - { - if (this.PropertyChanged != null) - { - this.PropertyChanged(this, new PropertyChangedEventArgs(propName)); - } - } -} -public class TeamMember : INotifyPropertyChanged -{ - private string memberName; - public string MemberName - { - get - { - return this.memberName; - } - set - { - this.memberName = value; - this.OnPropertyChanged("MemberName"); - } - } - public BindingList MemberTasks { get; private set; } - public TeamMember(string memberName) - { - this.MemberName = memberName; - this.MemberTasks = new BindingList(); - this.MemberTasks.ListChanged += MemberTasks_ListChanged; - } - void MemberTasks_ListChanged(object sender, ListChangedEventArgs e) - { - this.OnPropertyChanged("MemberTasks"); - } - public event PropertyChangedEventHandler PropertyChanged; - protected virtual void OnPropertyChanged(string propName) - { - if (this.PropertyChanged != null) - { - this.PropertyChanged(this, new PropertyChangedEventArgs(propName)); - } - } -} -public class Task : INotifyPropertyChanged -{ - private string taskName; - public string TaskName - { - get { return this.taskName; } - set - { - this.taskName = value; - this.OnPropertyChanged("TaskName"); - } - } - public Task(string taskName) - { - this.TaskName = taskName; - } - public event PropertyChangedEventHandler PropertyChanged; - protected virtual void OnPropertyChanged(string propName) - { - if (this.PropertyChanged != null) - { - this.PropertyChanged(this, new PropertyChangedEventArgs(propName)); - } - } -} - -```` -````VB.NET -Public Class Team - Implements INotifyPropertyChanged - Private m_teamName As String - Public Property TeamName() As String - Get - Return Me.m_teamName - End Get - Set(value As String) - Me.m_teamName = value - Me.OnPropertyChanged("TeamName") - End Set - End Property - Public Property TeamMembers() As BindingList(Of TeamMember) - Get - Return m_TeamMembers - End Get - Private Set(value As BindingList(Of TeamMember)) - m_TeamMembers = value - End Set - End Property - Private m_TeamMembers As BindingList(Of TeamMember) - Public Property TeamTasks() As BindingList(Of Task) - Get - Return m_TeamTasks - End Get - Private Set(value As BindingList(Of Task)) - m_TeamTasks = value - End Set - End Property - Private m_TeamTasks As BindingList(Of Task) - Public Sub New(teamName As String) - Me.TeamName = teamName - Me.TeamMembers = New BindingList(Of TeamMember)() - Me.TeamTasks = New BindingList(Of Task)() - AddHandler Me.TeamMembers.ListChanged, AddressOf TeamMembers_ListChanged - AddHandler Me.TeamTasks.ListChanged, AddressOf TeamTasks_ListChanged - End Sub - Private Sub TeamTasks_ListChanged(sender As Object, e As ListChangedEventArgs) - Me.OnPropertyChanged("TeamTasks") - End Sub - Private Sub TeamMembers_ListChanged(sender As Object, e As ListChangedEventArgs) - Me.OnPropertyChanged("TeamName") - End Sub - Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged - Protected Overridable Sub OnPropertyChanged(propName As String) - RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propName)) - End Sub -End Class -Public Class TeamMember - Implements INotifyPropertyChanged - Private m_memberName As String - Public Property MemberName() As String - Get - Return Me.m_memberName - End Get - Set(value As String) - Me.m_memberName = value - Me.OnPropertyChanged("MemberName") - End Set - End Property - Public Property MemberTasks() As BindingList(Of Task) - Get - Return m_MemberTasks - End Get - Private Set(value As BindingList(Of Task)) - m_MemberTasks = value - End Set - End Property - Private m_MemberTasks As BindingList(Of Task) - Public Sub New(memberName As String) - Me.MemberName = memberName - Me.MemberTasks = New BindingList(Of Task)() - AddHandler Me.MemberTasks.ListChanged, AddressOf MemberTasks_ListChanged - End Sub - Private Sub MemberTasks_ListChanged(sender As Object, e As ListChangedEventArgs) - Me.OnPropertyChanged("MemberTasks") - End Sub - Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged - Protected Overridable Sub OnPropertyChanged(propName As String) - RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propName)) - End Sub -End Class -Public Class Task - Implements INotifyPropertyChanged - Private m_taskName As String - Public Property TaskName() As String - Get - Return Me.m_taskName - End Get - Set(value As String) - Me.m_taskName = value - Me.OnPropertyChanged("TaskName") - End Set - End Property - Public Sub New(taskName As String) - Me.TaskName = taskName - End Sub - Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged - Protected Overridable Sub OnPropertyChanged(propName As String) - RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propName)) - End Sub -End Class - -```` - -{{endregion}} + + -Now, we need to initialize the __RadTreeView__, which will visualize our business objects: -{{source=..\SamplesCS\TreeView\DataBinding\LoadOnDemandWithCrudOperations.cs region=InitilaizeTreeView}} -{{source=..\SamplesVB\TreeView\DataBinding\LoadOnDemandWithCrudOperations.vb region=InitilaizeTreeView}} -````C# -this.radTreeView1.Dock = DockStyle.Fill; -this.radTreeView1.AllowRemove = true; -this.radTreeView1.AllowAdd = true; -this.radTreeView1.LazyMode = true; -this.radTreeView1.AllowDefaultContextMenu = true; +Now, we need to initialize the __RadTreeView__, which will visualize our business objects: -```` -````VB.NET -Me.RadTreeView1.Dock = DockStyle.Fill -Me.RadTreeView1.AllowRemove = True -Me.RadTreeView1.AllowAdd = True -Me.RadTreeView1.LazyMode = True -Me.RadTreeView1.AllowDefaultContextMenu = True + + -```` -{{endregion}} Since we will not bind our objects to __RadTreeView__, we will use the __Tag__ property to save the business object. The following method will be very helpful further in this article: -{{source=..\SamplesCS\TreeView\DataBinding\LoadOnDemandWithCrudOperations.cs region=CreateNode}} -{{source=..\SamplesVB\TreeView\DataBinding\LoadOnDemandWithCrudOperations.vb region=CreateNode}} + + -````C# -private RadTreeNode CreateNode(string text, object tag) -{ - RadTreeNode newNode = new RadTreeNode(text); - newNode.Tag = tag; - return newNode; -} -```` -````VB.NET -Private Function CreateNode(text As String, tag As Object) As RadTreeNode - Dim newNode As New RadTreeNode(text) - newNode.Tag = tag - Return newNode -End Function -```` +After we have this method and our tree view set up, we can actually create the hierarchy: -{{endregion}} + + -After we have this method and our tree view set up, we can actually create the hierarchy: -{{source=..\SamplesCS\TreeView\DataBinding\LoadOnDemandWithCrudOperations.cs region=InitializeHierarchy}} -{{source=..\SamplesVB\TreeView\DataBinding\LoadOnDemandWithCrudOperations.vb region=InitializeHierarchy}} - -````C# -private void InitializeHierarchy() -{ - //the Teams collection is a property of the Form - this.Teams = new BindingList(); - Team winFormsTeam = new Team("WinForms"); - this.Teams.Add(winFormsTeam); - TeamMember john = new TeamMember("John"); - winFormsTeam.TeamMembers.Add(john); - Task johnsTask = new Task("Refactor RadTreeView"); - john.MemberTasks.Add(johnsTask); - TeamMember alice = new TeamMember("Alice"); - winFormsTeam.TeamMembers.Add(alice); - Task aliceTask = new Task("Help John"); - alice.MemberTasks.Add(aliceTask); - Task winFormsUnassignedTask = new Task("Create an article regarding TreeView load on demand and CRUD operations"); - winFormsTeam.TeamTasks.Add(winFormsUnassignedTask); - Team wpfTeam = new Team("WPF"); - this.Teams.Add(wpfTeam); - TeamMember annie = new TeamMember("Annie"); - wpfTeam.TeamMembers.Add(annie); - Task annieTask = new Task("Research for control XXXXX"); - annie.MemberTasks.Add(annieTask); - Task unnasignedWpfTask = new Task("Help Annie"); - wpfTeam.TeamTasks.Add(unnasignedWpfTask); - Task secondUnnasignedWpfTask = new Task("Evaluate the research of Annie"); - wpfTeam.TeamTasks.Add(secondUnnasignedWpfTask); - TeamMember memberWithoutTasks = new TeamMember("Jack"); - wpfTeam.TeamMembers.Add(memberWithoutTasks); - foreach (Team team in this.Teams) - { - this.radTreeView1.Nodes.Add(this.CreateNode(team.TeamName, team)); - } -} - -```` -````VB.NET -Private Sub InitializeHierarchy() - 'the Teams collection is a property of the Form - Me.Teams = New BindingList(Of Team)() - Dim winFormsTeam As New Team("WinForms") - Me.Teams.Add(winFormsTeam) - Dim john As New TeamMember("John") - winFormsTeam.TeamMembers.Add(john) - Dim johnsTask As New Task("Refactor RadTreeView") - john.MemberTasks.Add(johnsTask) - Dim alice As New TeamMember("Alice") - winFormsTeam.TeamMembers.Add(alice) - Dim aliceTask As New Task("Help John") - alice.MemberTasks.Add(aliceTask) - Dim winFormsUnassignedTask As New Task("Create an article regarding TreeView load on demand and CRUD operations") - winFormsTeam.TeamTasks.Add(winFormsUnassignedTask) - Dim wpfTeam As New Team("WPF") - Me.Teams.Add(wpfTeam) - Dim annie As New TeamMember("Annie") - wpfTeam.TeamMembers.Add(annie) - Dim annieTask As New Task("Research for control XXXXX") - annie.MemberTasks.Add(annieTask) - Dim unnasignedWpfTask As New Task("Help Annie") - wpfTeam.TeamTasks.Add(unnasignedWpfTask) - Dim secondUnnasignedWpfTask As New Task("Evaluate the research of Annie") - wpfTeam.TeamTasks.Add(secondUnnasignedWpfTask) - Dim memberWithoutTasks As New TeamMember("Jack") - wpfTeam.TeamMembers.Add(memberWithoutTasks) - For Each team As Team In Me.Teams - Me.RadTreeView1.Nodes.Add(Me.CreateNode(team.TeamName, team)) - Next -End Sub - -```` - -{{endregion}} You see at the bottom that we are adding the __Teams__ to the __Nodes__ collection of the __RadTreeView__. They will be our base and when expanded we will load their children. As we speak about loading children, you need to subscribe to the __NodesNeeded__ event. In the event handler we will check for the __Tag__ of the parent node and of the current node. This will allow us to get the appropriate type and load its children. For example, If the parent is a __Team__ then we need to load this __Team’s TeamMembers__ and __Tasks__: -{{source=..\SamplesCS\TreeView\DataBinding\LoadOnDemandWithCrudOperations.cs region=NodesNeeded}} -{{source=..\SamplesVB\TreeView\DataBinding\LoadOnDemandWithCrudOperations.vb region=NodesNeeded}} - -````C# -private void TreeView_NodesNeeded(object sender, NodesNeededEventArgs e) -{ - if (e.Parent == null || e.Parent.Tag == null || e.Parent.Tag is Task) - { - return; - } - Team team = e.Parent.Tag as Team; - if (team != null) - { - foreach (TeamMember member in team.TeamMembers) - { - e.Nodes.Add(this.CreateNode(member.MemberName, member)); - } - foreach (Task task in team.TeamTasks) - { - e.Nodes.Add(this.CreateNode(task.TaskName, task)); - } - } - TeamMember teamMember = e.Parent.Tag as TeamMember; - if (teamMember != null) - { - foreach (Task task in teamMember.MemberTasks) - { - e.Nodes.Add(this.CreateNode(task.TaskName, task)); - } - } -} - -```` -````VB.NET -Private Sub TreeView_NodesNeeded(sender As Object, e As NodesNeededEventArgs) - If e.Parent Is Nothing OrElse e.Parent.Tag Is Nothing OrElse TypeOf e.Parent.Tag Is Task Then - Return - End If - Dim team As Team = TryCast(e.Parent.Tag, Team) - If team IsNot Nothing Then - For Each member As TeamMember In team.TeamMembers - e.Nodes.Add(Me.CreateNode(member.MemberName, member)) - Next - For Each task As Task In team.TeamTasks - e.Nodes.Add(Me.CreateNode(task.TaskName, task)) - Next - End If - Dim teamMember As TeamMember = TryCast(e.Parent.Tag, TeamMember) - If teamMember IsNot Nothing Then - For Each task As Task In teamMember.MemberTasks - e.Nodes.Add(Me.CreateNode(task.TaskName, task)) - Next - End If -End Sub - -```` - -{{endregion}} + + + + ![WinForms RadTreeView NodesNeeded](images/treeview-data-binding-load-on-demand-with-crud-operations002.png) If you run the application now, you will notice that the nodes are loading their children, however there is something which we do not really like. We know that the __Tasks__ do not have any children, yet, they have expanders in front of them. We can easily correct that by using the __NodeFormatting__ event. In the event handler we simply check if the node’s __Tag__ is a __Task__ and if it is __TeamMember__, whether it has any __Tasks__, and if it is a __Team__, whether it has any __TeamMembers__ or __Tasks__ and hide the expander appropriately. -{{source=..\SamplesCS\TreeView\DataBinding\LoadOnDemandWithCrudOperations.cs region=NodeFormatting}} -{{source=..\SamplesVB\TreeView\DataBinding\LoadOnDemandWithCrudOperations.vb region=NodeFormatting}} - -````C# -private void TreeView_NodeFormatting(object sender, TreeNodeFormattingEventArgs e) -{ - Team team = e.Node.Tag as Team; - TeamMember teamMember = e.Node.Tag as TeamMember; - if ((e.Node.Tag == null || e.Node.Tag is Task) || - (team != null && team.TeamMembers.Count == 0 && team.TeamTasks.Count == 0) || - (teamMember != null && teamMember.MemberTasks.Count == 0)) - { - e.NodeElement.ExpanderElement.Visibility = Telerik.WinControls.ElementVisibility.Hidden; - } - else - { - e.NodeElement.ExpanderElement.ResetValue(VisualElement.VisibilityProperty, ValueResetFlags.Local); - } -} - -```` -````VB.NET -Private Sub TreeView_NodeFormatting(sender As Object, e As TreeNodeFormattingEventArgs) - Dim team As Team = TryCast(e.Node.Tag, Team) - Dim teamMember As TeamMember = TryCast(e.Node.Tag, TeamMember) - If (e.Node.Tag Is Nothing OrElse TypeOf e.Node.Tag Is Task) OrElse (team IsNot Nothing AndAlso team.TeamMembers.Count = 0 AndAlso team.TeamTasks.Count = 0) OrElse (teamMember IsNot Nothing AndAlso teamMember.MemberTasks.Count = 0) Then - e.NodeElement.ExpanderElement.Visibility = Telerik.WinControls.ElementVisibility.Hidden - Else - e.NodeElement.ExpanderElement.ResetValue(VisualElement.VisibilityProperty, ValueResetFlags.Local) - End If -End Sub - -```` - -{{endregion}} + + + + Now, our hierarchy is properly visualized, all we have left to do is to implement the CRUD operations which will keep the __RadTreeView__ and the __BindingList__ synchronized. To handle the case where a node is removed/added from/to __RadTreeView__ you will need to subscribe to the __NodeRemoving__ and __NodeAdded__ event handlers, respectively. What will happen in these event handlers is very similar to what is happening in the __NodesNeeded__ event handler from before, where we check the parent and modify its children: -{{source=..\SamplesCS\TreeView\DataBinding\LoadOnDemandWithCrudOperations.cs region=NodeAddedAndNodeRemoving}} -{{source=..\SamplesVB\TreeView\DataBinding\LoadOnDemandWithCrudOperations.vb region=NodeAddedAndNodeRemoving}} - -````C# -private void TreeView_NodeAdded(object sender, RadTreeViewEventArgs e) -{ - if (e.Node.Parent == null) - { - return; - } - Team team = e.Node.Parent.Tag as Team; - if (team != null) - { - TeamMember member = e.Node.Tag as TeamMember; - if (member != null) - { - team.TeamMembers.Add(member); - } - Task task = e.Node.Tag as Task; - if (task != null) - { - team.TeamTasks.Add(task); - } - } - TeamMember teamMember = e.Node.Parent.Tag as TeamMember; - if (teamMember != null) - { - Task task = e.Node.Tag as Task; - if (task != null) - { - teamMember.MemberTasks.Add(task); - } - } -} -private void TreeView_NodeRemoving(object sender, RadTreeViewCancelEventArgs e) -{ - if (e.Node.Parent == null) - { - return; - } - Team team = e.Node.Parent.Tag as Team; - if (team != null) - { - TeamMember member = e.Node.Tag as TeamMember; - if (member != null) - { - team.TeamMembers.Remove(member); - } - Task task = e.Node.Tag as Task; - if (task != null) - { - team.TeamTasks.Remove(task); - } - } - TeamMember teamMember = e.Node.Parent.Tag as TeamMember; - if (teamMember != null) - { - Task task = e.Node.Tag as Task; - if (task != null) - { - teamMember.MemberTasks.Remove(task); - } - } -} - -```` -````VB.NET -Private Sub TreeView_NodeAdded(sender As Object, e As RadTreeViewEventArgs) - If e.Node.Parent Is Nothing Then - Return - End If - Dim team As Team = TryCast(e.Node.Parent.Tag, Team) - If team IsNot Nothing Then - Dim member As TeamMember = TryCast(e.Node.Tag, TeamMember) - If member IsNot Nothing Then - team.TeamMembers.Add(member) - End If - Dim task As Task = TryCast(e.Node.Tag, Task) - If task IsNot Nothing Then - team.TeamTasks.Add(task) - End If - End If - Dim teamMember As TeamMember = TryCast(e.Node.Parent.Tag, TeamMember) - If teamMember IsNot Nothing Then - Dim task As Task = TryCast(e.Node.Tag, Task) - If task IsNot Nothing Then - teamMember.MemberTasks.Add(task) - End If - End If -End Sub -Private Sub TreeView_NodeRemoving(sender As Object, e As RadTreeViewCancelEventArgs) - If e.Node.Parent Is Nothing Then - Return - End If - Dim team As Team = TryCast(e.Node.Parent.Tag, Team) - If team IsNot Nothing Then - Dim member As TeamMember = TryCast(e.Node.Tag, TeamMember) - If member IsNot Nothing Then - team.TeamMembers.Remove(member) - End If - Dim task As Task = TryCast(e.Node.Tag, Task) - If task IsNot Nothing Then - team.TeamTasks.Remove(task) - End If - End If - Dim teamMember As TeamMember = TryCast(e.Node.Parent.Tag, TeamMember) - If teamMember IsNot Nothing Then - Dim task As Task = TryCast(e.Node.Tag, Task) - If task IsNot Nothing Then - teamMember.MemberTasks.Remove(task) - End If - End If -End Sub - -```` - -{{endregion}} - - And to handle the case where something is modified in the data source, we will need to subscribe to the __ListChanged__ event of the __BindingList__ and rebuild the __RadTreeView__ by clearing the nodes and re-adding the first level nodes. You can optionally save the expanded node’s state as per [this article](http://www.telerik.com/help/winforms/treeview-how-to-keep-radtreeview-states-on-reset.html). + + + + + +And to handle the case where something is modified in the data source, we will need to subscribe to the __ListChanged__ event of the __BindingList__ and rebuild the __RadTreeView__ by clearing the nodes and re-adding the first level nodes. You can optionally save the expanded node’s state as per [this article](http://www.telerik.com/help/winforms/treeview-how-to-keep-radtreeview-states-on-reset.html). # See Also diff --git a/controls/treeview/data-binding/load-on-demand.md b/controls/treeview/data-binding/load-on-demand.md index adc636e4c..acbc92dac 100644 --- a/controls/treeview/data-binding/load-on-demand.md +++ b/controls/treeview/data-binding/load-on-demand.md @@ -29,65 +29,10 @@ The event arguments of the __NodesNeeded__ event contain the __Parent__ node tha Here is the result of this code snippet in the context of different lazy modes: -{{source=..\SamplesCS\TreeView\DataBinding\LoadOnDemand.cs region=nodesNodes}} -{{source=..\SamplesVB\TreeView\DataBinding\LoadOnDemand.vb region=nodesNodes}} - -````C# -void radTreeView1_NodesNeeded(object sender, NodesNeededEventArgs e) -{ - if (e.Parent == null) - { - LoadRootNodes(e.Nodes); - return; - } - // If the parent node is one of the "My Computer" children, - // then add sub-nodes to this node depending on its index - if (e.Parent.Level == 1) - { - if (e.Parent.Index % 3 == 0) - { - return; - } - } - for (int i = 0; i < 5; i++) - { - RadTreeNode childNode = new RadTreeNode(string.Format("Node{0}", i)); - e.Nodes.Add(childNode); - } -} -void LoadRootNodes(IList nodes) -{ - RadTreeNode mcNode = new RadTreeNode("My Computer"); - nodes.Add(mcNode); -} - -```` -````VB.NET -Private Sub radTreeView1_NodesNeeded(ByVal sender As Object, ByVal e As NodesNeededEventArgs) - If e.Parent Is Nothing Then - LoadRootNodes(e.Nodes) - Return - End If - ' If the parent node is one of the "My Computer" children, - ' then add sub-nodes to this node depending on its index - If e.Parent.Level = 1 Then - If e.Parent.Index Mod 3 = 0 Then - Return - End If - End If - For i As Integer = 0 To 4 - Dim childNode As New RadTreeNode(String.Format("Node{0}", i)) - e.Nodes.Add(childNode) - Next i -End Sub -Private Sub LoadRootNodes(ByVal nodes As IList(Of RadTreeNode)) - Dim mcNode As New RadTreeNode("My Computer") - nodes.Add(mcNode) -End Sub - -```` - -{{endregion}} + + + + * If __LazyMode__ is *true*, here is the result that we will get. When the end-user tries expanding nodes that do not have any sub-nodes, the plus sign will turn into a minus sign, but nothing else would change: diff --git a/controls/treeview/data-binding/togglestateconverter.md b/controls/treeview/data-binding/togglestateconverter.md index fa008a2e0..adca00207 100644 --- a/controls/treeview/data-binding/togglestateconverter.md +++ b/controls/treeview/data-binding/togglestateconverter.md @@ -37,304 +37,28 @@ Consider the **RadTreeView** is populated with **Item** objects having the follo #### Item class -{{source=..\SamplesCS\TreeView\TreeViewToggleStateConverter.cs region=ItemObject}} -{{source=..\SamplesVB\TreeView\TreeViewToggleStateConverter.vb region=ItemObject}} - -````C# -public class Item : System.ComponentModel.INotifyPropertyChanged -{ - public event PropertyChangedEventHandler PropertyChanged; - protected virtual void OnPropertyChanged(string propertyName) - { - if (PropertyChanged != null) - { - PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); - } - } - int m_id; - int m_parentId; - string m_name; - string m_isActive; - public Item(string name, string isActive, int parent_Id, int id) - { - this.m_name = name; - this.m_isActive = isActive; - this.m_parentId = parent_Id; - this.m_id = id; - } - public int Id - { - get - { - return m_id; - } - set - { - if (this.m_id != value) - { - this.m_id = value; - OnPropertyChanged("Id"); - } - } - } - public int ParentId - { - get - { - return m_parentId; - } - set - { - if (this.m_parentId != value) - { - this.m_parentId = value; - OnPropertyChanged("ParentId"); - } - } - } - public string Name - { - get - { - return m_name; - } - set - { - if (this.m_name != value) - { - this.m_name = value; - OnPropertyChanged("Name"); - } - } - } - public string IsActive - { - get - { - return m_isActive; - } - set - { - if (this.m_isActive != value) - { - this.m_isActive = value; - OnPropertyChanged("IsActive"); - } - } - } -} - -```` -````VB.NET -Public Class Item - Implements System.ComponentModel.INotifyPropertyChanged - Public Event PropertyChanged As PropertyChangedEventHandler Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged - Protected Overridable Sub OnPropertyChanged(ByVal propertyName As String) - RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName)) - End Sub - Private m_id As Integer - Private m_parentId As Integer - Private m_name As String - Private m_isActive As String - Public Sub New(ByVal name As String, ByVal isActive As String, ByVal parent_Id As Integer, ByVal id As Integer) - Me.m_name = name - Me.m_isActive = isActive - Me.m_parentId = parent_Id - Me.m_id = id - End Sub - Public Property Id As Integer - Get - Return m_id - End Get - Set(ByVal value As Integer) - If Me.m_id <> value Then - Me.m_id = value - OnPropertyChanged("Id") - End If - End Set - End Property - Public Property ParentId As Integer - Get - Return m_parentId - End Get - Set(ByVal value As Integer) - If Me.m_parentId <> value Then - Me.m_parentId = value - OnPropertyChanged("ParentId") - End If - End Set - End Property - Public Property Name As String - Get - Return m_name - End Get - Set(ByVal value As String) - If Me.m_name <> value Then - Me.m_name = value - OnPropertyChanged("Name") - End If - End Set - End Property - Public Property IsActive As String - Get - Return m_isActive - End Get - Set(ByVal value As String) - If Me.m_isActive <> value Then - Me.m_isActive = value - OnPropertyChanged("IsActive") - End If - End Set - End Property -End Class - -```` - -{{endregion}} + + + + The tree view is populated with data as follows: #### Bind RadTreeView -{{source=..\SamplesCS\TreeView\TreeViewToggleStateConverter.cs region=PopulateTreeView}} -{{source=..\SamplesVB\TreeView\TreeViewToggleStateConverter.vb region=PopulateTreeView}} - -````C# -BindingList items = new BindingList(); -items.Add(new Item(@"C:\", "false", 0, 1)); -items.Add(new Item(@"Documents", "false", 1, 2)); -items.Add(new Item(@"Program Files (x86)", "false", 1, 3)); -items.Add(new Item(@"D:\", "false", 0, 4)); -items.Add(new Item(@"Projects", "false", 4, 5)); -this.radTreeView1.DisplayMember = "Name"; -this.radTreeView1.ChildMember = "Id"; -this.radTreeView1.ParentMember = "ParentId"; -this.radTreeView1.CheckedMember = "IsActive"; -this.radTreeView1.DataSource = items; -this.radTreeView1.CheckBoxes = true; - -```` -````VB.NET -Dim items As BindingList(Of Item) = New BindingList(Of Item)() -items.Add(New Item("C:\", "false", 0, 1)) -items.Add(New Item("Documents", "false", 1, 2)) -items.Add(New Item("Program Files (x86)", "false", 1, 3)) -items.Add(New Item("D:\", "false", 0, 4)) -items.Add(New Item("Projects", "false", 4, 5)) -Me.RadTreeView1.DisplayMember = "Name" -Me.RadTreeView1.ChildMember = "Id" -Me.RadTreeView1.ParentMember = "ParentId" -Me.RadTreeView1.CheckedMember = "IsActive" -Me.RadTreeView1.DataSource = items -Me.RadTreeView1.CheckBoxes = True - -```` - -{{endregion}} + + + + The specified **CheckedMember** is the Item.**IsActive** property which is typeof(string) indicating the *"true"* / *"false"* values. In order to convert these string values to a valid **ToggleState** you need to use a custom [Type Converter]( https://msdn.microsoft.com/en-us/library/ayybcxe5.aspx). The following code snippet illustrates a sample implementation: #### Custom TypeConverter's implementation -{{source=..\SamplesCS\TreeView\TreeViewToggleStateConverter.cs region=TreeViewToggleConverter}} -{{source=..\SamplesVB\TreeView\TreeViewToggleStateConverter.vb region=TreeViewToggleConverter}} - -````C# -public class CustomTypeConverter : TypeConverter -{ - public CustomTypeConverter() - { - } - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) - { - if (sourceType == typeof(ToggleState)) - { - return true; - } - return base.CanConvertFrom(context, sourceType); - } - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) - { - if (destinationType == typeof(ToggleState)) - { - return true; - } - return base.CanConvertTo(context, destinationType); - } - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) - { - if (value is ToggleState) - { - ToggleState state = (ToggleState)value; - if (state == ToggleState.On) - { - return "true"; - } - else - { - return "false"; - } - } - return base.ConvertFrom(context, culture, value); - } - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) - { - string v = Convert.ToString(value); - if (v.ToLower() == "true" || v.ToLower() == "yes" || v.ToLower() == "on") - { - return ToggleState.On; - } - else if (v.ToLower() == "false" || v.ToLower() == "no" || v.ToLower() == "off") - { - return ToggleState.Off; - } - return base.ConvertTo(context, culture, value, destinationType); - } -} - -```` -````VB.NET -Public Class CustomTypeConverter - Inherits TypeConverter - Public Sub New() - End Sub - Public Overrides Function CanConvertFrom(ByVal context As ITypeDescriptorContext, ByVal sourceType As Type) As Boolean - If sourceType = GetType(ToggleState) Then - Return True - End If - Return MyBase.CanConvertFrom(context, sourceType) - End Function - Public Overrides Function CanConvertTo(ByVal context As ITypeDescriptorContext, ByVal destinationType As Type) As Boolean - If destinationType = GetType(ToggleState) Then - Return True - End If - Return MyBase.CanConvertTo(context, destinationType) - End Function - Public Overrides Function ConvertFrom(ByVal context As ITypeDescriptorContext, ByVal culture As CultureInfo, ByVal value As Object) As Object - If TypeOf value Is ToggleState Then - Dim state As ToggleState = CType(value, ToggleState) - If state = ToggleState.[On] Then - Return "true" - Else - Return "false" - End If - End If - Return MyBase.ConvertFrom(context, culture, value) - End Function - Public Overrides Function ConvertTo(ByVal context As ITypeDescriptorContext, ByVal culture As CultureInfo, ByVal value As Object, ByVal destinationType As Type) As Object - Dim v As String = Convert.ToString(value) - If v.ToLower() = "true" OrElse v.ToLower() = "yes" OrElse v.ToLower() = "on" Then - Return ToggleState.[On] - ElseIf v.ToLower() = "false" OrElse v.ToLower() = "no" OrElse v.ToLower() = "off" Then - Return ToggleState.Off - End If - Return MyBase.ConvertTo(context, culture, value, destinationType) - End Function -End Class - -```` - -{{endregion}} + + + + Now, you need to apply the custom **TypeConverter** to the RadTreeView.**ToggleStateConverter** property: @@ -342,19 +66,10 @@ Now, you need to apply the custom **TypeConverter** to the RadTreeView.**ToggleS #### Set the ToggleStateConverter -{{source=..\SamplesCS\TreeView\TreeViewToggleStateConverter.cs region=SetCustomToggleConverter}} -{{source=..\SamplesVB\TreeView\TreeViewToggleStateConverter.vb region=SetCustomToggleConverter}} - -````C# -this.radTreeView1.ToggleStateConverter = new CustomTypeConverter(); - -```` -````VB.NET -Me.RadTreeView1.ToggleStateConverter = New CustomTypeConverter() + + -```` -{{endregion}} Now, you can toggle/untoggle the nodes and this will be properly reflected to the underlying data object: diff --git a/controls/treeview/drag-and-drop/cancel-a-drag-and-drop-operation.md b/controls/treeview/drag-and-drop/cancel-a-drag-and-drop-operation.md index 0382d61ad..52c6dc53f 100644 --- a/controls/treeview/drag-and-drop/cancel-a-drag-and-drop-operation.md +++ b/controls/treeview/drag-and-drop/cancel-a-drag-and-drop-operation.md @@ -20,117 +20,35 @@ In some cases you may need to impose restrictions on the drag and drop behavior. You can interrupt a drag and drop operation by setting the __AllowDrop__ property of a specific RadTreeNode to *false*. This way you still can drag this particular node, but you cannot add other nodes to it with drag and drop operation. You can set this for any particular node you want. -{{source=..\SamplesCS\TreeView\DragAndDrop\CancelDragAndDropOperation.cs region=AllowDrop}} -{{source=..\SamplesVB\TreeView\DragAndDrop\CancelDragAndDropOperation.vb region=AllowDrop}} + + -````C# - -radTreeView1.Nodes[0].AllowDrop = false; -```` -````VB.NET -RadTreeView1.Nodes(0).AllowDrop = False - -```` - -{{endregion}} ## Restrict the user from changing the node hierarchy level with drag and drop 1\. With the following code we will add some parent and child nodes to the tree view: -{{source=..\SamplesCS\TreeView\DragAndDrop\CancelDragAndDropOperation.cs region=Tag}} -{{source=..\SamplesVB\TreeView\DragAndDrop\CancelDragAndDropOperation.vb region=Tag}} - -````C# -int count = 0; - -for (int i = 0; i < 10; i++) -{ - RadTreeNode parentNode = new RadTreeNode("Parent Node" + i); - parentNode.AllowDrop = false; - for (int j = 0; j < 3; j++) - { - RadTreeNode childNode = new RadTreeNode("Child Node" + count++); - - parentNode.Nodes.Add(childNode); - } - - radTreeView1.Nodes.Add(parentNode); -} - -```` -````VB.NET -Dim count As Integer = 0 -For i As Integer = 0 To 9 - Dim parentNode As New RadTreeNode("Parent Node" & i) - parentNode.AllowDrop = False - For j As Integer = 0 To 2 - Dim childNode As New RadTreeNode("Child Node" & count) - count = count + 1 - parentNode.Nodes.Add(childNode) - Next - RadTreeView1.Nodes.Add(parentNode) -Next - -```` - -{{endregion}} + + + 2\. Now we can subscribe to the __DragEnding__ event and cancel the drop operation if the dragged node and target node have different hierarchy levels. Also we will show an appropriate message: -{{source=..\SamplesCS\TreeView\DragAndDrop\CancelDragAndDropOperation.cs region=DragEnding}} -{{source=..\SamplesVB\TreeView\DragAndDrop\CancelDragAndDropOperation.vb region=DragEnding}} - -````C# - -void radTreeView1_DragEnding(object sender, RadTreeViewDragCancelEventArgs e) -{ - if (e.TargetNode.Level != e.Node.Level) - { - e.Cancel = true; - RadMessageBox.Show("Only nodes from the same level can be dropped here."); - } -} - -```` -````VB.NET -Private Sub radTreeView1_DragEnding(sender As Object, e As RadTreeViewDragCancelEventArgs) - If e.TargetNode.Level <> e.Node.Level Then - e.Cancel = True - RadMessageBox.Show("Only nodes from the same level can be dropped here.") - End If -End Sub - -```` - -{{endregion}} + + -## Cancel Auto Expansion for Dragged Nodes -The default behavior of __RadTreeView__ when a node is dragged over a collapsed node is to automatically expand this node. To suppress this automatic expansion you can keep track of when a drag operation is in progress by using the __DragStarted__ and __DragEnded__ events. Then in the __NodeExpandedChanging__ event handler we can cancel the expanding when drag and drop operation is in progress. -{{source=..\SamplesCS\TreeView\DragAndDrop\CancelDragAndDropOperation.cs region=AutoExpansion}} -{{source=..\SamplesVB\TreeView\DragAndDrop\CancelDragAndDropOperation.vb region=AutoExpansion}} +## Cancel Auto Expansion for Dragged Nodes -````C# - -void radTreeView1_NodeExpandedChanging(object sender, RadTreeViewCancelEventArgs e) -{ - e.Cancel = radTreeView1.TreeViewElement.DragDropService.State == RadServiceState.Working; -} +The default behavior of __RadTreeView__ when a node is dragged over a collapsed node is to automatically expand this node. To suppress this automatic expansion you can keep track of when a drag operation is in progress by using the __DragStarted__ and __DragEnded__ events. Then in the __NodeExpandedChanging__ event handler we can cancel the expanding when drag and drop operation is in progress. -```` -````VB.NET - -Private Sub radTreeView1_NodeExpandedChanging(sender As Object, e As RadTreeViewCancelEventArgs) - e.Cancel = RadTreeView1.TreeViewElement.DragDropService.State = RadServiceState.Working -End Sub + + -```` -{{endregion}} # See Also * [Drag and Drop in bound mode]({%slug winforms/treeview/drag-and-drop/drag-and-drop-in-bound-mode%}) diff --git a/controls/treeview/drag-and-drop/drag-and-drop-in-bound-mode.md b/controls/treeview/drag-and-drop/drag-and-drop-in-bound-mode.md index 9e71c5760..bab56715d 100644 --- a/controls/treeview/drag-and-drop/drag-and-drop-in-bound-mode.md +++ b/controls/treeview/drag-and-drop/drag-and-drop-in-bound-mode.md @@ -27,445 +27,36 @@ For this purpose, it is necessary to create a custom __TreeViewDragDropService__ 1\. Consider the __RadTreeView__ is bound to the following [self-referencing data]({%slug winforms/treeview/data-binding/binding-to-self-referencing-data%}). -{{source=..\SamplesCS\TreeView\DragAndDrop\DragAndDropInBoundMode.cs region=SelfRefData}} -{{source=..\SamplesVB\TreeView\DragAndDrop\DragAndDropInBoundMode.vb region=SelfRefData}} + + -````C# - -protected void BindRadTreeView() -{ - DataTable dt = new DataTable(); - dt.Columns.Add("Id", typeof(string)); - dt.Columns.Add("Title", typeof(string)); - dt.Columns.Add("ParentId", typeof(string)); - - string parentId = string.Empty; - string childId = string.Empty; - for (int i = 0; i < 3; i++) - { - parentId = Guid.NewGuid().ToString(); - dt.Rows.Add(parentId, "Node" + i, null); - for (int j = 0; j < 5; j++) - { - childId = Guid.NewGuid().ToString(); - dt.Rows.Add(childId, "SubNode" + i + "." + j, parentId); - } - } - - this.radTreeView1.ChildMember = "Id"; - this.radTreeView1.ParentMember = "ParentId"; - this.radTreeView1.DisplayMember = "Title"; - this.radTreeView1.DataSource = dt; -} -```` -````VB.NET -Protected Sub BindRadTreeView() - Dim dt As New DataTable() - dt.Columns.Add("Id", GetType(String)) - dt.Columns.Add("Title", GetType(String)) - dt.Columns.Add("ParentId", GetType(String)) - Dim parentId As String = String.Empty - Dim childId As String = String.Empty - For i As Integer = 0 To 2 - parentId = Guid.NewGuid().ToString() - dt.Rows.Add(parentId, "Node" & i, Nothing) - For j As Integer = 0 To 4 - childId = Guid.NewGuid().ToString() - dt.Rows.Add(childId, "SubNode" & i & "." & j, parentId) - Next - Next - Me.radTreeView1.ChildMember = "Id" - Me.radTreeView1.ParentMember = "ParentId" - Me.radTreeView1.DisplayMember = "Title" - Me.radTreeView1.DataSource = dt -End Sub - -```` - -{{endregion}} 2\. Enable multiple [selection]({%slug winforms/treeview/working-with-nodes/selecting-nodes%}) by setting the __MultiSelect__ property to *true*. 3\. Create a derivative of the __TreeViewDragDropService__ which should perform the desired drag and drop functionality. The __OnPreviewDragOver__ method allows you to control on what targets the nodes, being dragged, can be dropped on. The __OnPreviewDragDrop__ method initiates the actual physical move of the nodes from one position to another. -{{source=..\SamplesCS\TreeView\DragAndDrop\DragAndDropInBoundMode.cs region=CustomService}} -{{source=..\SamplesVB\TreeView\DragAndDrop\DragAndDropInBoundMode.vb region=CustomService}} - -````C# - -class CustomDragDropService : TreeViewDragDropService -{ - private RadTreeViewElement owner; - private List draggedNodes; - - public CustomDragDropService(RadTreeViewElement owner) : base(owner) - { - this.owner = owner; - } - - //Save the dragged nodes - protected override void PerformStart() - { - base.PerformStart(); - - draggedNodes = new List(); - foreach (RadTreeNode selectedNode in this.owner.SelectedNodes) - { - draggedNodes.Add(selectedNode); - } - } - - //Clean the saved nodes - protected override void PerformStop() - { - base.PerformStop(); - draggedNodes.Clear(); - } - - //If tree element or node element is hovered, allow drop - protected override void OnPreviewDragOver(RadDragOverEventArgs e) - { - base.OnPreviewDragOver(e); - - RadTreeViewElement targetElement = e.HitTarget as RadTreeViewElement; - if (targetElement != null && targetElement.Equals(this.owner)) - { - e.CanDrop = true; - } - else if (e.HitTarget is TreeNodeElement) - { - e.CanDrop = true; - - foreach (RadTreeNode draggedNode in draggedNodes) - { - RadTreeNode targetNode = (e.HitTarget as TreeNodeElement).Data.Parent; - if (draggedNode == targetNode) - { - //prevent dragging of a parent node over some of its child nodes - e.CanDrop = false; - break; - } - } - } - } - - //Create copies of the selected node(s) and add them to the hovered node/tree - protected override void OnPreviewDragDrop(RadDropEventArgs e) - { - TreeNodeElement targetNodeElement = e.HitTarget as TreeNodeElement; - RadTreeViewElement targetTreeView = targetNodeElement == null ? e.HitTarget as RadTreeViewElement - : targetNodeElement.TreeViewElement; - - if (targetTreeView == null) - { - return; - } - - targetTreeView.BeginUpdate(); - - foreach (RadTreeNode node in draggedNodes) - { - DataRowView rowView = node.DataBoundItem as DataRowView; - DataRow row = rowView.Row; - DataTable dt = targetTreeView.DataSource as DataTable; - if (dt == null) - { - return; - } - - //save expanded state and vertical scrollbar value - - if (targetNodeElement != null) - { - if (CanShowDropHint(Cursor.Position, targetNodeElement)) - { - //change node' parent - RadTreeNode nodeOver = targetNodeElement.Data.Parent; - - if (nodeOver == null) - { - nodeOver = targetNodeElement.Data; - } - - DataRowView targetRowView = (DataRowView)nodeOver.DataBoundItem; - DataRow targetRow = targetRowView.Row; - if (row["ParentId"] != targetRow["ParentId"]) - { - row["ParentId"] = targetRow["Id"]; - } - - DataRow rowToInsert = dt.NewRow(); - rowToInsert["ParentId"] = row["ParentId"]; - rowToInsert["Id"] = row["Id"]; - rowToInsert["Title"] = row["Title"]; - dt.Rows.Remove(row); - int targetIndex = GetTargetIndex(dt, targetNodeElement); - - DropPosition position = this.GetDropPosition(e.DropLocation, targetNodeElement); - if (position == DropPosition.AfterNode) - { - targetIndex++; - } - dt.Rows.InsertAt(rowToInsert, targetIndex); - } - else - { - RadTreeNode nodeOver = targetNodeElement.Data; - DataRowView targetRowView = (DataRowView)nodeOver.DataBoundItem; - DataRow targetRow = targetRowView.Row; - row["ParentId"] = targetRow["Id"]; - } - } - else - { - //make the node "root node" - row["ParentId"] = null; - } - - object ds = targetTreeView.DataSource; - targetTreeView.DataSource = null; - targetTreeView.DataSource = ds; - - targetTreeView.Update(RadTreeViewElement.UpdateActions.ItemAdded); - //restore expanded state and vertical scrollbar value - } - targetTreeView.EndUpdate(); - } - - private int GetTargetIndex(DataTable dt, TreeNodeElement targetNodeElement) - { - int index = 0; - DataRowView targetRowView = (DataRowView)targetNodeElement.Data.DataBoundItem; - DataRow targetRow = targetRowView.Row; - index = dt.Rows.IndexOf(targetRow); - - return index; - } - - private bool CanShowDropHint(Point point, TreeNodeElement nodeElement) - { - if (nodeElement == null) - { - return false; - } - - Point client = nodeElement.PointFromScreen(point); - int part = nodeElement.Size.Height / 3; - return client.Y < part || client.Y > part * 2; - } -} - -```` -````VB.NET -Private Class CustomDragDropService - Inherits TreeViewDragDropService - Private owner As RadTreeViewElement - Private draggedNodes As List(Of RadTreeNode) - Public Sub New(owner As RadTreeViewElement) - MyBase.New(owner) - Me.owner = owner - End Sub - 'Save the dragged nodes - Protected Overrides Sub PerformStart() - MyBase.PerformStart() - draggedNodes = New List(Of RadTreeNode)() - For Each selectedNode As RadTreeNode In Me.owner.SelectedNodes - draggedNodes.Add(selectedNode) - Next - End Sub - 'Clean the saved nodes - Protected Overrides Sub PerformStop() - MyBase.PerformStop() - draggedNodes.Clear() - End Sub - 'If tree element or node element is hovered, allow drop - Protected Overrides Sub OnPreviewDragOver(e As RadDragOverEventArgs) - MyBase.OnPreviewDragOver(e) - Dim targetElement As RadTreeViewElement = TryCast(e.HitTarget, RadTreeViewElement) - If targetElement IsNot Nothing AndAlso targetElement.Equals(Me.owner) Then - e.CanDrop = True - ElseIf TypeOf e.HitTarget Is TreeNodeElement Then - e.CanDrop = True - For Each draggedNode As RadTreeNode In draggedNodes - Dim targetNode As RadTreeNode = TryCast(e.HitTarget, TreeNodeElement).Data.Parent - If draggedNode.Equals(targetNode) Then - 'prevent dragging of a parent node over some of its child nodes - e.CanDrop = False - Exit For - End If - Next - End If - End Sub - 'Create copies of the selected node(s) and add them to the hovered node/tree - Protected Overrides Sub OnPreviewDragDrop(e As RadDropEventArgs) - Dim targetNodeElement As TreeNodeElement = TryCast(e.HitTarget, TreeNodeElement) - Dim targetTreeView As RadTreeViewElement = If(targetNodeElement Is Nothing, TryCast(e.HitTarget, RadTreeViewElement), targetNodeElement.TreeViewElement) - If targetTreeView Is Nothing Then - Return - End If - targetTreeView.BeginUpdate() - For Each node As RadTreeNode In draggedNodes - Dim rowView As DataRowView = TryCast(node.DataBoundItem, DataRowView) - Dim row As DataRow = rowView.Row - Dim dt As DataTable = TryCast(targetTreeView.DataSource, DataTable) - If dt Is Nothing Then - Return - End If - 'save expanded state and vertical scrollbar value - If targetNodeElement IsNot Nothing Then - If CanShowDropHint(Cursor.Position, targetNodeElement) Then - 'change node' parent - Dim nodeOver As RadTreeNode = targetNodeElement.Data.Parent - If nodeOver Is Nothing Then - nodeOver = targetNodeElement.Data - End If - Dim targetRowView As DataRowView = DirectCast(nodeOver.DataBoundItem, DataRowView) - Dim targetRow As DataRow = targetRowView.Row - If Not row("ParentId").Equals(targetRow("ParentId")) Then - row("ParentId") = targetRow("Id") - End If - Dim rowToInsert As DataRow = dt.NewRow() - rowToInsert("ParentId") = row("ParentId") - rowToInsert("Id") = row("Id") - rowToInsert("Title") = row("Title") - dt.Rows.Remove(row) - Dim targetIndex As Integer = GetTargetIndex(dt, targetNodeElement) - Dim position As DropPosition = Me.GetDropPosition(e.DropLocation, targetNodeElement) - If position = DropPosition.AfterNode Then - targetIndex += 1 - End If - dt.Rows.InsertAt(rowToInsert, targetIndex) - Else - Dim nodeOver As RadTreeNode = targetNodeElement.Data - Dim targetRowView As DataRowView = DirectCast(nodeOver.DataBoundItem, DataRowView) - Dim targetRow As DataRow = targetRowView.Row - row("ParentId") = targetRow("Id") - End If - Else - 'make the node "root node" - row("ParentId") = Nothing - End If - Dim ds As Object = targetTreeView.DataSource - targetTreeView.DataSource = Nothing - targetTreeView.DataSource = ds - 'restore expanded state and vertical scrollbar value - targetTreeView.Update(RadTreeViewElement.UpdateActions.ItemAdded) - Next - targetTreeView.EndUpdate() - End Sub - Private Function GetTargetIndex(dt As DataTable, targetNodeElement As TreeNodeElement) As Integer - Dim index As Integer = 0 - Dim targetRowView As DataRowView = DirectCast(targetNodeElement.Data.DataBoundItem, DataRowView) - Dim targetRow As DataRow = targetRowView.Row - index = dt.Rows.IndexOf(targetRow) - Return index - End Function - Private Function CanShowDropHint(point As Point, nodeElement As TreeNodeElement) As Boolean - If nodeElement Is Nothing Then - Return False - End If - Dim client As Point = nodeElement.PointFromScreen(point) - Dim part As Integer = nodeElement.Size.Height / 3 - Return client.Y < part OrElse client.Y > part * 2 - End Function -End Class + + -```` -{{endregion}} >note When a change in the underlying data source occurs, the tree needs to repopulate itself in order to get the latest changes. As a result, the expanded state of the available nodes, selection and scroll bar position are not kept. [Keep RadTreeView states on reset]({%slug winforms/treeview/how-to/keep-radtreeview-states-on-reset%}) help article explains how to save the tree state prior the change and restore it afterwards. > 4\. The custom __TreeViewDragDropService__ is ready. Now, we need to replace the default one. For this purpose, it is necessary to create a derivative of the __RadTreeViewElement__ and override the __CreateDragDropService__ method. -{{source=..\SamplesCS\TreeView\DragAndDrop\DragAndDropInBoundMode.cs region=CustomTreeViewElement}} -{{source=..\SamplesVB\TreeView\DragAndDrop\DragAndDropInBoundMode.vb region=CustomTreeViewElement}} + + -````C# - -class CustomTreeViewElement : RadTreeViewElement -{ - protected override Type ThemeEffectiveType - { - get - { - return typeof(RadTreeViewElement); - } - } - - protected override TreeViewDragDropService CreateDragDropService() - { - return new CustomDragDropService(this); - } -} -```` -````VB.NET -Private Class CustomTreeViewElement - Inherits RadTreeViewElement - Protected Overrides ReadOnly Property ThemeEffectiveType() As Type - Get - Return GetType(RadTreeViewElement) - End Get - End Property - Protected Overrides Function CreateDragDropService() As TreeViewDragDropService - Return New CustomDragDropService(Me) - End Function -End Class - -```` - -{{endregion}} 5\. Finally, replace the default __RadTreeViewElement__ in the tree with the custom one. -{{source=..\SamplesCS\TreeView\DragAndDrop\DragAndDropInBoundMode.cs region=TreeView}} -{{source=..\SamplesVB\TreeView\DragAndDrop\DragAndDropInBoundMode.vb region=TreeView}} - -````C# - -class CustomTreeView : RadTreeView -{ - protected override RadTreeViewElement CreateTreeViewElement() - { - return new CustomTreeViewElement(); - } - - public override string ThemeClassName - { - get - { - return typeof(RadTreeView).FullName; - } - set - { - base.ThemeClassName = value; - } - } -} - -```` -````VB.NET -Private Class CustomTreeView - Inherits RadTreeView - Protected Overrides Function CreateTreeViewElement() As RadTreeViewElement - Return New CustomTreeViewElement() - End Function - Public Overrides Property ThemeClassName() As String - Get - Return GetType(RadTreeView).FullName - End Get - Set(value As String) - MyBase.ThemeClassName = value - End Set - End Property -End Class + + -```` -{{endregion}} # See Also * [Cancel a Drag and Drop Operation]({%slug winforms/treeview/drag-and-drop/cancel-a-drag-and-drop-operation%}) diff --git a/controls/treeview/drag-and-drop/enabling-drag-and-drop.md b/controls/treeview/drag-and-drop/enabling-drag-and-drop.md index 0fe9ab26b..549faa3fa 100644 --- a/controls/treeview/drag-and-drop/enabling-drag-and-drop.md +++ b/controls/treeview/drag-and-drop/enabling-drag-and-drop.md @@ -50,79 +50,10 @@ To implement this functionality: * Implement the RadTreeView DragDrop event handler to react to the drop operation. In the code sample below the RadTreeView __PointToClient()__ and __GetNodeAt()__ methods are used to retrieve the dropped node. -{{source=..\SamplesCS\TreeView\DragAndDrop\EnablingDragAndDrop.cs region=dragDrop}} -{{source=..\SamplesVB\TreeView\DragAndDrop\EnablingDragAndDrop.vb region=dragDrop}} - -````C# -public EnablingDragAndDrop() -{ - InitializeComponent(); - radTextBox1.TextBoxElement.TextBoxItem.HostedControl.MouseDown +=new MouseEventHandler(textBox1_MouseDown); - radTreeView1.DragEnter+=new DragEventHandler(radTreeView_DragEnter); - radTreeView1.DragDrop+=new DragEventHandler(radTreeView_DragDrop); - radTreeView1.AllowDrop = true; - this.radTextBox1.AllowDrop = true; -} -private void textBox1_MouseDown(object sender, MouseEventArgs e) -{ - this.radTextBox1.DoDragDrop(this.radTextBox1.Text, DragDropEffects.Copy | DragDropEffects.Move); -} -private void radTreeView_DragEnter(object sender, DragEventArgs e) -{ - if (e.Data.GetDataPresent(DataFormats.Text)) - { - e.Effect = DragDropEffects.Copy; - } - else - { - e.Effect = DragDropEffects.None; - } -} -private void radTreeView_DragDrop(object sender, DragEventArgs e) -{ - Point p = radTreeView1.PointToClient(new Point(e.X, e.Y)); - RadTreeNode hoverNode = radTreeView1.GetNodeAt(p.X, p.Y); - if (hoverNode == null) - { - radTreeView1.Nodes.Add(e.Data.GetData(DataFormats.Text).ToString()); - return; - } - hoverNode.Nodes.Add(e.Data.GetData(DataFormats.Text).ToString()); -} - -```` -````VB.NET -Public Sub New() - InitializeComponent() - AddHandler RadTextBox1.TextBoxElement.TextBoxItem.HostedControl.MouseDown, AddressOf textBox1_MouseDown - AddHandler RadTreeView1.DragEnter, AddressOf radTreeView_DragEnter - AddHandler RadTreeView1.DragDrop, AddressOf radTreeView_DragDrop - RadTreeView1.AllowDrop = True - Me.RadTextBox1.AllowDrop = True -End Sub -Private Sub textBox1_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) - Me.RadTextBox1.DoDragDrop(Me.RadTextBox1.Text, DragDropEffects.Copy Or DragDropEffects.Move) -End Sub -Private Sub radTreeView_DragEnter(ByVal sender As Object, ByVal e As DragEventArgs) - If e.Data.GetDataPresent(DataFormats.Text) Then - e.Effect = DragDropEffects.Copy - Else - e.Effect = DragDropEffects.None - End If -End Sub -Private Sub radTreeView_DragDrop(ByVal sender As Object, ByVal e As DragEventArgs) - Dim p As Point = RadTreeView1.PointToClient(New Point(e.X, e.Y)) - Dim hoverNode As RadTreeNode = RadTreeView1.GetNodeAt(p.X, p.Y) - If hoverNode Is Nothing Then - RadTreeView1.Nodes.Add(e.Data.GetData(DataFormats.Text).ToString()) - Return - End If - hoverNode.Nodes.Add(e.Data.GetData(DataFormats.Text).ToString()) -End Sub - -```` - -{{endregion}} + + + + # See Also * [Cancel a Drag and Drop Operation]({%slug winforms/treeview/drag-and-drop/cancel-a-drag-and-drop-operation%}) diff --git a/controls/treeview/drag-and-drop/modify-the-dragdropservice-behavior.md b/controls/treeview/drag-and-drop/modify-the-dragdropservice-behavior.md index 3faa9b82b..d22377e50 100644 --- a/controls/treeview/drag-and-drop/modify-the-dragdropservice-behavior.md +++ b/controls/treeview/drag-and-drop/modify-the-dragdropservice-behavior.md @@ -20,273 +20,31 @@ To achieve this scenario we will need to create a descendant of TreeViewDragDrop Next we need to override the __OnPreviewDragOver__ method, where we will specify upon what conditions a drop will be allowed and finally, in the __OnPreviewDragDrop__ method override, we will add the logic for copying the selected nodes instead of moving them: -{{source=..\SamplesCS\TreeView\DragAndDrop\ModifyTheDragDropServiceBehavior\CustomDragDropService.cs region=CustomDragDropService}} -{{source=..\SamplesVB\TreeView\DragAndDrop\ModifyTheDragDropServiceBehavior\CustomDragDropService.vb region=CustomDragDropService}} + + -````C# -class CustomDragDropService : TreeViewDragDropService -{ - RadTreeViewElement owner; - RadTreeNode draggedNode; - //Initialize the service - public CustomDragDropService(RadTreeViewElement owner) - : base(owner) - { - this.owner = owner; - } - //Save the dragged node - protected override void PerformStart() - { - base.PerformStart(); - TreeNodeElement draggedNodeElement = this.Context as TreeNodeElement; - this.draggedNode = draggedNodeElement.Data; - } - //Clean the saved node - protected override void PerformStop() - { - base.PerformStop(); - this.draggedNode = null; - } - //If tree element is hovered, allow drop - protected override void OnPreviewDragOver(RadDragOverEventArgs e) - { - base.OnPreviewDragOver(e); - RadTreeViewElement targetElement = e.HitTarget as RadTreeViewElement; - if (targetElement != null && targetElement != this.owner) - { - e.CanDrop = true; - } - } - //Create copies of the selected node(s) and add them to the hovered node/tree - protected override void OnPreviewDragDrop(RadDropEventArgs e) - { - TreeNodeElement targetNodeElement = e.HitTarget as TreeNodeElement; - RadTreeViewElement targetTreeView = targetNodeElement == null ? e.HitTarget as RadTreeViewElement : targetNodeElement.TreeViewElement; - if (targetTreeView == this.owner) - { - base.OnPreviewDragDrop(e); - return; - } - if (targetTreeView == null) - { - return; - } - List draggedNodes = this.GetDraggedNodes(draggedNode); - targetTreeView.BeginUpdate(); - this.owner.BeginUpdate(); - bool copyNodes = this.IsCopyingNodes; - foreach (RadTreeNode node in draggedNodes) - { - RadTreeNode newNode = CreateNewTreeNode(node); - if (targetNodeElement != null) - { - targetNodeElement.Data.Nodes.Add(newNode); - } - else - { - targetTreeView.Nodes.Add(newNode); - } - } - this.owner.EndUpdate(); - targetTreeView.EndUpdate(); - } - //Return a copy of a node - protected virtual RadTreeNode CreateNewTreeNode(RadTreeNode node) - { - return node.Clone() as RadTreeNode; - } -} -```` -````VB.NET -Class CustomDragDropService - Inherits TreeViewDragDropService - Private owner As RadTreeViewElement - Private draggedNode As RadTreeNode - 'Initialize the service - Public Sub New(ByVal owner As RadTreeViewElement) - MyBase.New(owner) - Me.owner = owner - End Sub - 'Save the dragged node - Protected Overrides Sub PerformStart() - MyBase.PerformStart() - Dim draggedNodeElement As TreeNodeElement = TryCast(Me.Context, TreeNodeElement) - Me.draggedNode = draggedNodeElement.Data - End Sub - 'Clean the saved node - Protected Overrides Sub PerformStop() - MyBase.PerformStop() - Me.draggedNode = Nothing - End Sub - 'If tree element is hovered, allow drop - Protected Overrides Sub OnPreviewDragOver(ByVal e As RadDragOverEventArgs) - MyBase.OnPreviewDragOver(e) - Dim targetElement As RadTreeViewElement = TryCast(e.HitTarget, RadTreeViewElement) - If Not targetElement Is Nothing AndAlso Not targetElement Is Me.owner Then - e.CanDrop = True - End If - End Sub - 'Create copies of the selected node(s) and add them to the hovered node/tree - Protected Overrides Sub OnPreviewDragDrop(ByVal e As RadDropEventArgs) - Dim targetNodeElement As TreeNodeElement = TryCast(e.HitTarget, TreeNodeElement) - Dim targetTreeView As RadTreeViewElement - If targetNodeElement Is Nothing Then - targetTreeView = TryCast(e.HitTarget, RadTreeViewElement) - Else - targetTreeView = targetNodeElement.TreeViewElement - End If - If targetTreeView Is Me.owner Then - MyBase.OnPreviewDragDrop(e) - Return - End If - If targetTreeView Is Nothing Then - Return - End If - Dim draggedNodes As List(Of RadTreeNode) = Me.GetDraggedNodes(draggedNode) - targetTreeView.BeginUpdate() - Me.owner.BeginUpdate() - Dim copyNodes As Boolean = Me.IsCopyingNodes - For Each node As RadTreeNode In draggedNodes - Dim newNode As RadTreeNode = CreateNewTreeNode(node) - If Not targetNodeElement Is Nothing Then - targetNodeElement.Data.Nodes.Add(newNode) - Else - targetTreeView.Nodes.Add(newNode) - End If - Next node - Me.owner.EndUpdate() - targetTreeView.EndUpdate() - End Sub - 'Return a copy of a node - Protected Overridable Function CreateNewTreeNode(ByVal node As RadTreeNode) As RadTreeNode - Return TryCast(node.Clone(), RadTreeNode) - End Function -End Class - -```` - -{{endregion}} After the custom drag and drop behavior is created, we need to replace the default one. This can be achieved in the __CreateDragDropService__ method of RadTreeViewElement, so we create a new element for the purpose: -{{source=..\SamplesCS\TreeView\DragAndDrop\ModifyTheDragDropServiceBehavior\CustomTreeViewElement.cs region=CustomTreeViewElement}} -{{source=..\SamplesVB\TreeView\DragAndDrop\ModifyTheDragDropServiceBehavior\CustomTreeViewElement.vb region=CustomTreeViewElement}} - -````C# -class CustomTreeViewElement : RadTreeViewElement -{ - //Enable themeing for the element - protected override Type ThemeEffectiveType - { - get - { - return typeof(RadTreeViewElement); - } - } - //Replace the default drag drop service with the custom one - protected override TreeViewDragDropService CreateDragDropService() - { - return new CustomDragDropService(this); - } -} - -```` -````VB.NET -Class CustomTreeViewElement - Inherits RadTreeViewElement - 'Enable themeing for the element - Protected Overrides ReadOnly Property ThemeEffectiveType() As Type - Get - Return GetType(RadTreeViewElement) - End Get - End Property - 'Replace the default drag drop service with the custom one - Protected Overrides Function CreateDragDropService() As TreeViewDragDropService - Return New CustomDragDropService(Me) - End Function -End Class + + -```` -{{endregion}} Now we need to use this CustomTreeViewElement in the tree. To do that we need to pass a new instance of this element in the __CreateTreeViewElement__ method of RadTreeView descendant: -{{source=..\SamplesCS\TreeView\DragAndDrop\ModifyTheDragDropServiceBehavior\CustomTreeView.cs region=CustomTreeView}} -{{source=..\SamplesVB\TreeView\DragAndDrop\ModifyTheDragDropServiceBehavior\CustomTreeView.vb region=CustomTreeView}} + + -````C# -class CustomTreeView : RadTreeView -{ - //Replace the default element with the custom one - protected override RadTreeViewElement CreateTreeViewElement() - { - return new CustomTreeViewElement(); - } - //Enable theming for the control - public override string ThemeClassName - { - get - { - return typeof(RadTreeView).FullName; - } - } -} -```` -````VB.NET -Class CustomTreeView - Inherits RadTreeView - 'Replace the default element with the custom one - Protected Overrides Function CreateTreeViewElement() As RadTreeViewElement - Return New CustomTreeViewElement() - End Function - 'Enable theming for the control - Public Overrides Property ThemeClassName As String - Get - Return GetType(RadTreeView).FullName - End Get - Set(value As String) - MyBase.ThemeClassName = value - End Set - End Property -End Class - -```` - -{{endregion}} Finally, lets populate the tree and test the new behavior: -{{source=..\SamplesCS\TreeView\DragAndDrop\ModifyTheDragDropServiceBehavior\ModifyTheDragDropServiceBehavior.cs region=PopulateTheTree}} -{{source=..\SamplesVB\TreeView\DragAndDrop\ModifyTheDragDropServiceBehavior\ModifyTheDragDropServiceBehavior.vb region=PopulateTheTree}} - -````C# -customTreeView1.AllowDragDrop = true; -customTreeView1.MultiSelect = true; -customTreeView2.AllowDragDrop = true; -customTreeView2.MultiSelect = true; -for (int i = 0; i < 10; i++) -{ - customTreeView1.Nodes.Add("First tree node " + i); - customTreeView2.Nodes.Add("Second tree node " + i); -} - -```` -````VB.NET -CustomTreeView1.AllowDragDrop = True -CustomTreeView1.MultiSelect = True -CustomTreeView2.AllowDragDrop = True -CustomTreeView2.MultiSelect = True -For i As Integer = 0 To 9 - CustomTreeView1.Nodes.Add("First tree node " & i) - CustomTreeView2.Nodes.Add("Second tree node " & i) -Next i + + -```` -{{endregion}} The result can be observed at the screen shot at the top. diff --git a/controls/treeview/editing/custom-editors.md b/controls/treeview/editing/custom-editors.md index aa11b6f87..db9d5758e 100644 --- a/controls/treeview/editing/custom-editors.md +++ b/controls/treeview/editing/custom-editors.md @@ -27,208 +27,24 @@ Our editor and its element will derive from __BaseTextBoxEditor__ and __BaseText In the __EditorElement__ we will add a __RadDropDownListElement__. The DropDownList will be bound to the same data source as the RadTreeView control for the purpose of the example follows the EditorElement: -{{source=..\SamplesCS\TreeView\WorkingWithNodes\EditingNodes.cs region=CustomTreeViewEditorElement}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\EditingNodes.vb region=CustomTreeViewEditorElement}} - -````C# -public class CustomRadTreeViewEditorElement : BaseTextBoxEditorElement -{ - private RadDropDownListElement dropDownList; - private DockLayoutPanel dockPanel; - public RadDropDownListElement DropDownList - { - get { return this.dropDownList; } - } - protected override void OnLoaded() //use OnLoaded as here the text editor will exist - { - base.OnLoaded(); - if (this.Children.Contains(this.TextBoxItem)) - { - this.dropDownList = new RadDropDownListElement(); - this.dropDownList.DropDownStyle = RadDropDownStyle.DropDownList; - this.dropDownList.MinSize = new Size(55, 0); - this.dockPanel = new DockLayoutPanel(); - this.dockPanel.LastChildFill = true; - this.Children.Add(this.dockPanel); - this.dockPanel.Children.Add(this.dropDownList); - DockLayoutPanel.SetDock(this.dropDownList, Telerik.WinControls.Layouts.Dock.Right); - this.Children.Remove(this.TextBoxItem); - this.dockPanel.Children.Add(this.TextBoxItem); - } - } -} - -```` -````VB.NET -Public Class CustomRadTreeViewEditorElement -Inherits BaseTextBoxEditorElement - Private m_dropDownList As RadDropDownListElement - Private dockPanel As DockLayoutPanel - Public ReadOnly Property DropDownList() As RadDropDownListElement - Get - Return Me.m_dropDownList - End Get - End Property - Protected Overrides Sub OnLoaded() - 'use OnLoaded as here the text editor will exist - MyBase.OnLoaded() - If Me.Children.Contains(Me.TextBoxItem) Then - Me.m_dropDownList = New RadDropDownListElement() - Me.m_dropDownList.DropDownStyle = RadDropDownStyle.DropDownList - Me.m_dropDownList.MinSize = New Size(55, 0) - Me.dockPanel = New DockLayoutPanel() - Me.dockPanel.LastChildFill = True - Me.Children.Add(Me.dockPanel) - Me.dockPanel.Children.Add(Me.m_dropDownList) - DockLayoutPanel.SetDock(Me.m_dropDownList, Telerik.WinControls.Layouts.Dock.Right) - Me.Children.Remove(Me.TextBoxItem) - Me.dockPanel.Children.Add(Me.TextBoxItem) - End If - End Sub -End Class - -```` - -{{endregion}} + + + + The __EditorElement__ encapsulates the visual appearance of the element, we will need the actual editor which will encapsulate the functionality: -{{source=..\SamplesCS\TreeView\WorkingWithNodes\EditingNodes.cs region=CustomTreeViewEditor}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\EditingNodes.vb region=CustomTreeViewEditor}} - -````C# -public class CustomRadTreeViewEditor : BaseTextBoxEditor -{ - protected override RadElement CreateEditorElement() - { - return new CustomRadTreeViewEditorElement(); - } - public new CustomRadTreeViewEditorElement EditorElement - { - get { return base.EditorElement as CustomRadTreeViewEditorElement; } - } - public override bool EndEdit() - { - this.EditorElement.DropDownList.SelectedValueChanged -= DropDownList_SelectedIndexChanged; - return base.EndEdit(); - } - public override void BeginEdit() - { - base.BeginEdit(); - TreeNodeElement nodeElement = this.OwnerElement as TreeNodeElement; - this.EditorElement.DropDownList.BindingContext = new BindingContext(); - this.EditorElement.DropDownList.DataSource = nodeElement.TreeViewElement.DataSource; - this.EditorElement.DropDownList.DisplayMember = nodeElement.TreeViewElement.ValueMember; - this.EditorElement.DropDownList.ValueMember = nodeElement.TreeViewElement.DisplayMember; - this.EditorElement.DropDownList.SelectedIndex = this.EditorElement.DropDownList.FindStringExact(nodeElement.Data.Value.ToString()); - this.Value = nodeElement.Data.Text; - this.EditorElement.DropDownList.SelectedIndexChanged += DropDownList_SelectedIndexChanged; - } - void DropDownList_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e) - { - TreeNodeElement nodeElement = this.OwnerElement as TreeNodeElement; - nodeElement.Data.Value = this.EditorElement.DropDownList.Items[e.Position].Text; - this.Value = this.EditorElement.DropDownList.Items[e.Position].Value; - } -} - -```` -````VB.NET -Public Class CustomRadTreeViewEditor -Inherits BaseTextBoxEditor - Protected Overrides Function CreateEditorElement() As RadElement - Return New CustomRadTreeViewEditorElement() - End Function - Public Shadows ReadOnly Property EditorElement() As CustomRadTreeViewEditorElement - Get - Return TryCast(MyBase.EditorElement, CustomRadTreeViewEditorElement) - End Get - End Property - Public Overrides Function EndEdit() As Boolean - RemoveHandler Me.EditorElement.DropDownList.SelectedValueChanged, AddressOf DropDownList_SelectedIndexChanged - Return MyBase.EndEdit() - End Function - Public Overrides Sub BeginEdit() - MyBase.BeginEdit() - Dim nodeElement As TreeNodeElement = TryCast(Me.OwnerElement, TreeNodeElement) - Me.EditorElement.DropDownList.BindingContext = New BindingContext() - Me.EditorElement.DropDownList.DataSource = nodeElement.TreeViewElement.DataSource - Me.EditorElement.DropDownList.DisplayMember = nodeElement.TreeViewElement.ValueMember - Me.EditorElement.DropDownList.ValueMember = nodeElement.TreeViewElement.DisplayMember - Me.EditorElement.DropDownList.SelectedIndex = Me.EditorElement.DropDownList.FindStringExact(nodeElement.Data.Value.ToString()) - Me.Value = nodeElement.Data.Text - AddHandler Me.EditorElement.DropDownList.SelectedIndexChanged, AddressOf DropDownList_SelectedIndexChanged - End Sub - Private Sub DropDownList_SelectedIndexChanged(sender As Object, e As Telerik.WinControls.UI.Data.PositionChangedEventArgs) - Dim nodeElement As TreeNodeElement = TryCast(Me.OwnerElement, TreeNodeElement) - nodeElement.Data.Value = Me.EditorElement.DropDownList.Items(e.Position).Text - Me.Value = Me.EditorElement.DropDownList.Items(e.Position).Value - End Sub -End Class - -```` - -{{endregion}} + + + + Now all that is left is to drag a RadTreeView to a form, populate it with data and enable the custom editor. -{{source=..\SamplesCS\TreeView\WorkingWithNodes\EditingNodes.cs region=Initialization}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\EditingNodes.vb region=Initialization}} - -````C# -public EditingNodes() -{ - InitializeComponent(); - DataTable table = new DataTable(); - table.Columns.Add("Abbreviation"); - table.Columns.Add("State"); - table.Rows.Add("AL", "Alabama"); - table.Rows.Add("AK", "Alaska"); - table.Rows.Add("AZ", "Arizona"); - table.Rows.Add("AR", "Arkansas"); - table.Rows.Add("CA", "California"); - table.Rows.Add("CO", "Colorado"); - table.Rows.Add("CT", "Connecticut"); - this.Controls.Add(this.radTreeView1); - this.radTreeView1.AllowEdit = true; - this.radTreeView1.DataSource = table; - this.radTreeView1.DisplayMember = "State"; - this.radTreeView1.ValueMember = "Abbreviation"; - this.radTreeView1.EditorRequired += TreeViewEditorRequired; -} -private void TreeViewEditorRequired(object sender, TreeNodeEditorRequiredEventArgs e) -{ - e.EditorType = typeof(CustomRadTreeViewEditor); -} - -```` -````VB.NET -Public Sub New() - InitializeComponent() - Dim table As New DataTable() - table.Columns.Add("Abbreviation") - table.Columns.Add("State") - table.Rows.Add("AL", "Alabama") - table.Rows.Add("AK", "Alaska") - table.Rows.Add("AZ", "Arizona") - table.Rows.Add("AR", "Arkansas") - table.Rows.Add("CA", "California") - table.Rows.Add("CO", "Colorado") - table.Rows.Add("CT", "Connecticut") - Me.Controls.Add(Me.radTreeView1) - Me.radTreeView1.AllowEdit = True - Me.radTreeView1.DataSource = table - Me.radTreeView1.DisplayMember = "State" - Me.radTreeView1.ValueMember = "Abbreviation" - AddHandler Me.radTreeView1.EditorRequired, AddressOf TreeViewEditorRequired -End Sub -Private Sub TreeViewEditorRequired(sender As Object, e As TreeNodeEditorRequiredEventArgs) - e.EditorType = GetType(CustomRadTreeViewEditor) -End Sub - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/treeview/editing/editing-nodes.md b/controls/treeview/editing/editing-nodes.md index 542d06774..ae823bc69 100644 --- a/controls/treeview/editing/editing-nodes.md +++ b/controls/treeview/editing/editing-nodes.md @@ -19,27 +19,10 @@ By default __RadTreeView__ does not allow node editing. If the __AllowEditing__ The sample code below shows how to start editing using the API: -{{source=..\SamplesCS\TreeView\WorkingWithNodes\WorkingWithNodes1.cs region=editing}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\WorkingWithNodes1.vb region=editing}} - -````C# -radTreeView1.AllowEdit = true; -// set the SelectedNode - this node will be edited -radTreeView1.SelectedNode = radTreeView1.Nodes[0]; -// this will start edit on selected node -radTreeView1.BeginEdit(); - -```` -````VB.NET -RadTreeView1.AllowEdit = True -' set the SelectedNode - this node will be edited -RadTreeView1.SelectedNode = RadTreeView1.Nodes(0) -' this will start edit on selected node -RadTreeView1.BeginEdit() - -```` - -{{endregion}} + + + + ## The Editing Lifecycle diff --git a/controls/treeview/export-data/spread-export.md b/controls/treeview/export-data/spread-export.md index 5db9b663e..5bc9d69e2 100644 --- a/controls/treeview/export-data/spread-export.md +++ b/controls/treeview/export-data/spread-export.md @@ -48,59 +48,18 @@ To use the spread export functionality, an instance of the __TreeViewSpreadExpor You should pass an instance of a [SpreadExportRenderer]({%slug winforms/telerik-presentation-framework/export-renderers/spreadexportrenderer%}) to the export method as well. -{{source=..\SamplesCS\TreeView\SpreadExportCode.cs region=Export}} -{{source=..\SamplesVB\TreeView\SpreadExportCode.vb region=Export}} + + -````C# -TreeViewSpreadExport exporter = new TreeViewSpreadExport(this.radTreeView1); -SpreadExportRenderer renderer = new SpreadExportRenderer(); -exporter.RunExport(@"C:\ExportedFile.xlsx", renderer); -```` -````VB.NET -Dim exporter As New TreeViewSpreadExport(Me.radTreeView1) -Dim renderer As New SpreadExportRenderer() -exporter.RunExport("C:\ExportedFile.xlsx", renderer) - -```` - -{{endregion}} The __RunExport__ method has several overloads allowing the user to export using a stream as well. #### Running export synchronously using a stream -{{source=..\SamplesCS\TreeView\SpreadExportCode.cs region=StreamRunExport}} -{{source=..\SamplesVB\TreeView\SpreadExportCode.vb region=StreamRunExport}} - -````C# -string exportFile = @"..\..\exportedData.xlsx"; -using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) -{ - Telerik.WinControls.Export.TreeViewSpreadExport spreadExporter = new Telerik.WinControls.Export.TreeViewSpreadExport(this.radTreeView1); - Telerik.WinControls.Export.SpreadExportRenderer spreadRenderer = new Telerik.WinControls.Export.SpreadExportRenderer(); - spreadExporter.RunExport(ms, spreadRenderer); - using (System.IO.FileStream fileStream = new System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write)) - { - ms.WriteTo(fileStream); - } -} + + -```` -````VB.NET -Dim exportFile As String = "..\..\exportedData.xlsx" -Using ms As New System.IO.MemoryStream() - Dim spreadExporter As New Telerik.WinControls.Export.TreeViewSpreadExport(Me.radTreeView1) - Dim spreadRenderer As New Telerik.WinControls.Export.SpreadExportRenderer() - spreadExporter.RunExport(ms, spreadRenderer) - Using fileStream As New System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write) - ms.WriteTo(fileStream) - End Using -End Using - -```` - -{{endregion}} ## Properties @@ -146,26 +105,10 @@ End Using * __ExportCell:__ Allows you to set the styles of the exported cell. * __RowIndex:__ The index of the currently exported row. Here is an example of formatting the exported TreeView -{{source=..\SamplesCS\TreeView\SpreadExportCode.cs region=Formatting}} -{{source=..\SamplesVB\TreeView\SpreadExportCode.vb region=Formatting}} - -````C# -void exporter_CellFormatting(object sender, TreeViewSpreadExportCellFormattingEventArgs e) -{ - e.ExportCell.BackColor = ColorTranslator.FromHtml("#F4FFEC"); - e.ExportCell.Font = new Font("Consolas", 10, FontStyle.Underline); -} - -```` -````VB.NET -Private Sub exporter_CellFormatting(ByVal sender As Object, ByVal e As TreeViewSpreadExportCellFormattingEventArgs) - e.ExportCell.BackColor = ColorTranslator.FromHtml("#F4FFEC") - e.ExportCell.Font = New Font("Consolas", 10, FontStyle.Underline) -End Sub + + -```` -{{endregion}} >caption Figure 2: Export using formating @@ -189,114 +132,26 @@ The following example will demonstrate how the async spread export feature can b 1.The following code shows how you can subscribe to the notification events and start the async export operation. -{{source=..\SamplesCS\TreeView\SpreadExportCode.cs region=AsyncExport}} -{{source=..\SamplesVB\TreeView\SpreadExportCode.vb region=AsyncExport}} + + -````C# -private void btnExportAsync_Click(object sender, EventArgs e) -{ - TreeViewSpreadExport spreadExporter = new TreeViewSpreadExport(this.radTreeView1); - spreadExporter.AsyncExportProgressChanged += spreadExporter_AsyncExportProgressChanged; - spreadExporter.AsyncExportCompleted += spreadExporter_AsyncExportCompleted; - SpreadExportRenderer exportRenderer = new SpreadExportRenderer(); - spreadExporter.RunExportAsync(@"..\..\ExportedFile.xlsx", exportRenderer); -} -```` -````VB.NET -Private Sub btnExportAsync_Click(ByVal sender As Object, ByVal e As EventArgs) - Dim spreadExporter As New TreeViewSpreadExport(Me.radTreeView1) - AddHandler spreadExporter.AsyncExportProgressChanged, AddressOf spreadExporter_AsyncExportProgressChanged - AddHandler spreadExporter.AsyncExportCompleted, AddressOf spreadExporter_AsyncExportCompleted - Dim exportRenderer As New SpreadExportRenderer() - spreadExporter.RunExportAsync("..\..\ExportedFile.xlsx", exportRenderer) -End Sub - -```` - -{{endregion}} 2.Handle the notification events and report progress. -{{source=..\SamplesCS\TreeView\SpreadExportCode.cs region=ReportProgress}} -{{source=..\SamplesVB\TreeView\SpreadExportCode.vb region=ReportProgress}} + + -````C# -private void spreadExporter_AsyncExportProgressChanged(object sender, ProgressChangedEventArgs e) -{ - this.radProgressBar1.Value1 = e.ProgressPercentage; -} -private void spreadExporter_AsyncExportCompleted(object sender, AsyncCompletedEventArgs e) -{ - RadMessageBox.Show("Async Spread Export Completed!"); - this.radProgressBar1.Value1 = 0; -} -```` -````VB.NET -Private Sub spreadExporter_AsyncExportProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) - Me.radProgressBar1.Value1 = e.ProgressPercentage -End Sub -Private Sub spreadExporter_AsyncExportCompleted(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs) - RadMessageBox.Show("Async Spread Export Completed!") - Me.radProgressBar1.Value1 = 0 -End Sub - -```` -{{endregion}} The __RunExportAsync__ method has several overloads allowing the user to export using a stream as well: #### Running export asynchronously using a stream -{{source=..\SamplesCS\TreeView\SpreadExportCode.cs region=StreamRunExportAsync}} -{{source=..\SamplesVB\TreeView\SpreadExportCode.vb region=StreamRunExportAsync}} + + -````C# - -private void buttonRunExportAsync_Click(object sender, EventArgs e) -{ - System.IO.MemoryStream ms = new System.IO.MemoryStream(); - Telerik.WinControls.Export.TreeViewSpreadExport spreadExporter = new Telerik.WinControls.Export.TreeViewSpreadExport (this.radTreeView1); - Telerik.WinControls.Export.SpreadExportRenderer spreadRenderer = new Telerik.WinControls.Export.SpreadExportRenderer(); - spreadExporter.AsyncExportCompleted += exporter_AsyncExportCompleted; - spreadExporter.RunExportAsync(ms, spreadRenderer); -} - -private void exporter_AsyncExportCompleted(object sender, AsyncCompletedEventArgs e) -{ - RunWorkerCompletedEventArgs args = e as RunWorkerCompletedEventArgs; - string exportFile = @"..\..\exportedAsyncData.xlsx"; - using (System.IO.FileStream fileStream = new System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write)) - { - MemoryStream ms = args.Result as MemoryStream; - ms.WriteTo(fileStream); - ms.Close(); - } -} - -```` -````VB.NET -Private Sub buttonRunExportAsync_Click(sender As Object, e As EventArgs) - Dim ms As New System.IO.MemoryStream() - Dim spreadExporter As New Telerik.WinControls.Export.TreeViewSpreadExport(Me.radTreeView1) - Dim spreadRenderer As New Telerik.WinControls.Export.SpreadExportRenderer() - AddHandler spreadExporter.AsyncExportCompleted, AddressOf exporter_AsyncExportCompleted - spreadExporter.RunExportAsync(ms, spreadRenderer) -End Sub -Private Sub exporter_AsyncExportCompleted(sender As Object, e As AsyncCompletedEventArgs) - Dim args As RunWorkerCompletedEventArgs = TryCast(e, RunWorkerCompletedEventArgs) - Dim exportFile As String = "..\..\exportedAsyncData.xlsx" - Using fileStream As New System.IO.FileStream(exportFile, FileMode.Create, FileAccess.Write) - Dim ms As MemoryStream = TryCast(args.Result, MemoryStream) - ms.WriteTo(fileStream) - ms.Close() - End Using -End Sub - -```` -{{endregion}} ## Async Export Methods and Events diff --git a/controls/treeview/getting-started.md b/controls/treeview/getting-started.md index 9d5014629..4266a5213 100644 --- a/controls/treeview/getting-started.md +++ b/controls/treeview/getting-started.md @@ -80,42 +80,10 @@ The following tutorial will help you get started working with the __RadTreeView_ 1. In the form's constructor add the code appearing below the __InitializeComponent()__ method call. This code creates new __RadTreeNode__ objects, populates them with text and attaches them to parent nodes. -{{source=..\SamplesCS\TreeView\GettingStarted.cs region=GettingStarted}} -{{source=..\SamplesVB\TreeView\TreeViewGettingStarted.vb region=GettingStarted}} + + + -````C# - -RadTreeNode node = radTreeView1.Nodes["Email Contacts"].Nodes.Add("Bob Tony"); -node.Selected = true; - -radTreeView1.Nodes["Email Contacts"].Nodes.Add("Sue Winchell"); -radTreeView1.Nodes["Email Contacts"].Nodes.Add("Lui Sang"); -radTreeView1.Nodes["Lists"].Nodes.Add("Priorities"); -radTreeView1.Nodes["Lists"].Nodes.Add("Opportunities"); -radTreeView1.Nodes["Lists"].Nodes.Add("Issues"); - -node = radTreeView1.Nodes["Reports"].Nodes.Add("June Sales"); -node = radTreeView1.Nodes["Reports"].Nodes.Add("July Sales"); -node = radTreeView1.Nodes["Reports"].Nodes.Add("First Quarter Summary"); -node = radTreeView1.Nodes["Reports"].Nodes.Add("Second Quarter Summary"); - -```` -````VB.NET -Dim node As RadTreeNode = RadTreeView1.Nodes("Email Contacts").Nodes.Add("Bob Tony") -node.Selected = True -RadTreeView1.Nodes("Email Contacts").Nodes.Add("Sue Winchell") -RadTreeView1.Nodes("Email Contacts").Nodes.Add("Lui Sang") -RadTreeView1.Nodes("Lists").Nodes.Add("Priorities") -RadTreeView1.Nodes("Lists").Nodes.Add("Opportunities") -RadTreeView1.Nodes("Lists").Nodes.Add("Issues") -node = RadTreeView1.Nodes("Reports").Nodes.Add("June Sales") -node = RadTreeView1.Nodes("Reports").Nodes.Add("July Sales") -node = RadTreeView1.Nodes("Reports").Nodes.Add("First Quarter Summary") -node = RadTreeView1.Nodes("Reports").Nodes.Add("Second Quarter Summary") - -```` - -{{endregion}} 14\. Run the application. diff --git a/controls/treeview/how-to/assign-radscreentip-to-nodes.md b/controls/treeview/how-to/assign-radscreentip-to-nodes.md index eed59cb2f..f6840d50a 100644 --- a/controls/treeview/how-to/assign-radscreentip-to-nodes.md +++ b/controls/treeview/how-to/assign-radscreentip-to-nodes.md @@ -17,57 +17,9 @@ If the item which needs a ScreenTip is a TreeNodeElement, you set the necessary ![WinForms RadTreeView RadOffice2007ScreenTip](images/treeview-how-to-assign-radscreentip-to-nodes001.png) -{{source=..\SamplesCS\TreeView\HowTo\TreeScreenTips.cs region=screenTip}} -{{source=..\SamplesVB\TreeView\HowTo\TreeScreenTips.vb region=screenTip}} + + -````C# -RadOffice2007ScreenTipElement screenTip = new RadOffice2007ScreenTipElement(); -Size size = new Size(120, 70); -Padding pad = new Padding(2); -void radTreeView1_ScreenTipNeeded(object sender, Telerik.WinControls.ScreenTipNeededEventArgs e) -{ - TreeNodeElement node = e.Item as TreeNodeElement; - if (node != null) - { - screenTip.MainTextLabel.Image = node.ImageElement.Image; - screenTip.MainTextLabel.TextImageRelation = TextImageRelation.ImageBeforeText; - screenTip.MainTextLabel.Padding = pad; - screenTip.MainTextLabel.Text = "This is " + node.ContentElement.Text; - screenTip.MainTextLabel.Margin = new System.Windows.Forms.Padding(10); - screenTip.CaptionLabel.Padding = pad; - screenTip.CaptionLabel.Text = node.ContentElement.Text; - screenTip.EnableCustomSize = true; - screenTip.AutoSize = false; - screenTip.Size = size; - node.ScreenTip = this.screenTip; - } -} - -```` -````VB.NET -Private screenTip As New RadOffice2007ScreenTipElement() -Private Shadows size As New Size(120, 70) -Private pad As New Padding(2) -Private Sub radTreeView1_ScreenTipNeeded(ByVal sender As Object, ByVal e As Telerik.WinControls.ScreenTipNeededEventArgs) - Dim node As TreeNodeElement = TryCast(e.Item, TreeNodeElement) - If node IsNot Nothing Then - screenTip.MainTextLabel.Image = node.ImageElement.Image - screenTip.MainTextLabel.TextImageRelation = TextImageRelation.ImageBeforeText - screenTip.MainTextLabel.Padding = pad - screenTip.MainTextLabel.Text = "This is " & node.ContentElement.Text - screenTip.MainTextLabel.Margin = New System.Windows.Forms.Padding(10) - screenTip.CaptionLabel.Padding = pad - screenTip.CaptionLabel.Text = node.ContentElement.Text - screenTip.EnableCustomSize = True - screenTip.AutoSize = False - screenTip.Size = size - node.ScreenTip = Me.screenTip - End If -End Sub - -```` - -{{endregion}} # See Also diff --git a/controls/treeview/how-to/keep-radtreeview-states-on-reset.md b/controls/treeview/how-to/keep-radtreeview-states-on-reset.md index 5e4b68131..a2fce27d2 100644 --- a/controls/treeview/how-to/keep-radtreeview-states-on-reset.md +++ b/controls/treeview/how-to/keep-radtreeview-states-on-reset.md @@ -15,188 +15,10 @@ The __RadTreeView__ is a control that allows you to visualize hierarchical struc The following code snippet demonstrates how to populate the __RadTreeView__ with hierarchical data. -{{source=..\SamplesCS\TreeView\HowTo\KeepTreeViewStates.cs region=BindToObjectRelationalData}} -{{source=..\SamplesVB\TreeView\HowTo\KeepTreeViewStates.vb region=BindToObjectRelationalData}} + + -````C# - -public KeepTreeViewStates() -{ - InitializeComponent(); - - BindingList bikesChildren = new BindingList(); - bikesChildren.Add(new ChildObject(567, "Bicycle")); - bikesChildren.Add(new ChildObject(456, "Car")); - bikesChildren.Add(new ChildObject(789, "Bike")); - - BindingList clothingChildren = new BindingList(); - clothingChildren.Add(new ChildObject(352, "T-shirt")); - clothingChildren.Add(new ChildObject(981, "Dress")); - - List parents = new List(); - parents.Add(new ParentObject(182,"Bikes", bikesChildren)); - parents.Add(new ParentObject(346,"Accessories", null)); - parents.Add(new ParentObject(291,"Clothing", clothingChildren)); - - radTreeView1.DataSource = parents; - radTreeView1.DisplayMember = "Title\\Description"; - radTreeView1.ChildMember = "Parents\\Children"; - radTreeView1.MultiSelect = true; -} - -public class ParentObject -{ - public int ID { get; set; } - - public string Title { get; set; } - - public BindingList Children { get; set; } - - public ParentObject(int iD, string title, BindingList children) - { - this.ID = iD; - this.Title = title; - this.Children = children; - } -} - -public class ChildObject: INotifyPropertyChanged -{ - public event PropertyChangedEventHandler PropertyChanged; - - private int id; - private string description; - - public int ID - { - get - { - return this.id; - } - set - { - this.id = value; - OnPropertyChanged("ID"); - } - } - - public string Description - { - get - { - return this.description; - } - set - { - this.description = value; - OnPropertyChanged("Description"); - } - } - - public ChildObject(int iD, string description) - { - this.id = iD; - this.description = description; - } - - protected virtual void OnPropertyChanged(string propertyName) - { - if (PropertyChanged != null) - { - PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); - } - } -} -```` -````VB.NET -Public Sub New() - InitializeComponent() - Dim bikesChildren As New BindingList(Of ChildObject)() - bikesChildren.Add(New ChildObject(567, "Bicycle")) - bikesChildren.Add(New ChildObject(456, "Car")) - bikesChildren.Add(New ChildObject(789, "Bike")) - Dim clothingChildren As New BindingList(Of ChildObject)() - clothingChildren.Add(New ChildObject(352, "T-shirt")) - clothingChildren.Add(New ChildObject(981, "Dress")) - Dim parents As New List(Of ParentObject)() - parents.Add(New ParentObject(182, "Bikes", bikesChildren)) - parents.Add(New ParentObject(346, "Accessories", Nothing)) - parents.Add(New ParentObject(291, "Clothing", clothingChildren)) - RadTreeView1.DataSource = parents - RadTreeView1.DisplayMember = "Title\Description" - RadTreeView1.ChildMember = "Parents\Children" - RadTreeView1.MultiSelect = True -End Sub -Public Class ParentObject - Public Property ID() As Integer - Get - Return m_ID - End Get - Set(value As Integer) - m_ID = value - End Set - End Property - Private m_ID As Integer - Public Property Title() As String - Get - Return m_Title - End Get - Set(value As String) - m_Title = value - End Set - End Property - Private m_Title As String - Public Property Children() As BindingList(Of ChildObject) - Get - Return m_Children - End Get - Set(value As BindingList(Of ChildObject)) - m_Children = value - End Set - End Property - Private m_Children As BindingList(Of ChildObject) - Public Sub New(iD As Integer, title As String, children As BindingList(Of ChildObject)) - Me.ID = iD - Me.Title = title - Me.Children = children - End Sub -End Class -Public Class ChildObject -Implements System.ComponentModel.INotifyPropertyChanged - Public Event PropertyChanged As PropertyChangedEventHandler Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged - Private m_id As Integer - Private m_description As String - Public Property ID() As Integer - Get - Return Me.m_id - End Get - Set(value As Integer) - Me.m_id = value - OnPropertyChanged("ID") - End Set - End Property - Public Property Description() As String - Get - Return Me.m_description - End Get - Set(value As String) - Me.m_description = value - OnPropertyChanged("Description") - End Set - End Property - Public Sub New(iD As Integer, description As String) - Me.m_id = iD - Me.m_description = description - End Sub - Protected Overridable Sub OnPropertyChanged(propertyName As String) - RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName)) - End Sub -End Class - -```` - -{{endregion}} On the left figure, you can see the tree with some selected and expanded nodes and the scroll bar in the middle of the tree. On the right figure, you see how the tree is collapsed after we add a node to its data source. @@ -206,226 +28,17 @@ On the left figure, you can see the tree with some selected and expanded nodes a Unfortunately, a solution of this cannot be added to the control as it depends on the case and there has to be logic added for the specific case to be handled. To keep the expanded and selected state of RadTreeView after a change in the data source occurs, we can use a Dictionary with some unique value for a key i.e. this could be the node’s Text, DataBoundItem, Value, or even an ID taken from the DataBoundItem and store the state for the node in it. The following example demonstrates how to create a simple structure - State, which will hold and describe the state of a node. The __SaveExpandedStates__ method is used to recursively iterate all nodes in RadTreeView and populate a dictionary with the nodes information. The __RestoreExpandedStates__ method is used to read the saved states from the dictionary, find the respective node and restore its state. -{{source=..\SamplesCS\TreeView\HowTo\KeepTreeViewStates.cs region=SaveRestore}} -{{source=..\SamplesVB\TreeView\HowTo\KeepTreeViewStates.vb region=SaveRestore}} - -````C# - -Dictionary nodeStates = new Dictionary(); - -struct State -{ - public bool Expanded { get; set; } - - public bool Selected { get; set; } - - public State(bool expanded, bool selected) : this() - { - this.Expanded = expanded; - this.Selected = selected; - } -} - -private void SaveExpandedStates(RadTreeNode nodeToSave) -{ - { - if (nodeToSave != null && nodeToSave.DataBoundItem != null) - { - if (! nodeStates.ContainsKey(nodeToSave.DataBoundItem)) - { - nodeStates.Add(nodeToSave.DataBoundItem, new State(nodeToSave.Expanded, nodeToSave.Selected)); - } - else - { - nodeStates[nodeToSave.DataBoundItem] = new State(nodeToSave.Expanded, nodeToSave.Selected); - } - } - foreach (RadTreeNode childNode in nodeToSave.Nodes) - { - SaveExpandedStates(childNode); - } - } -} - -private void RestoreExpandedStates(RadTreeNode nodeToRestore) -{ - if (nodeToRestore != null && nodeToRestore.DataBoundItem != null && - nodeStates.ContainsKey(nodeToRestore.DataBoundItem)) - { - nodeToRestore.Expanded = nodeStates[nodeToRestore.DataBoundItem].Expanded; - nodeToRestore.Selected = nodeStates[nodeToRestore.DataBoundItem].Selected; - } - - foreach (RadTreeNode childNode in nodeToRestore.Nodes) - { - RestoreExpandedStates(childNode); - } -} + + -```` -````VB.NET -Private nodeStates As New Dictionary(Of Object, State)() -Private Structure State - Public Property Expanded() As Boolean - Get - Return m_Expanded - End Get - Set(value As Boolean) - m_Expanded = value - End Set - End Property - Private m_Expanded As Boolean - Public Property Selected() As Boolean - Get - Return m_Selected - End Get - Set(value As Boolean) - m_Selected = value - End Set - End Property - Private m_Selected As Boolean - Public Sub New(expanded As Boolean, selected As Boolean) - Me.Expanded = expanded - Me.Selected = selected - End Sub -End Structure -Private Sub SaveExpandedStates(nodeToSave As RadTreeNode) - If True Then - If nodeToSave IsNot Nothing AndAlso nodeToSave.DataBoundItem IsNot Nothing Then - If Not nodeStates.ContainsKey(nodeToSave.DataBoundItem) Then - nodeStates.Add(nodeToSave.DataBoundItem, New State(nodeToSave.Expanded, nodeToSave.Selected)) - Else - nodeStates(nodeToSave.DataBoundItem) = New State(nodeToSave.Expanded, nodeToSave.Selected) - End If - End If - For Each childNode As RadTreeNode In nodeToSave.Nodes - SaveExpandedStates(childNode) - Next - End If -End Sub -Private Sub RestoreExpandedStates(nodeToRestore As RadTreeNode) - If nodeToRestore IsNot Nothing AndAlso nodeToRestore.DataBoundItem IsNot Nothing AndAlso nodeStates.ContainsKey(nodeToRestore.DataBoundItem) Then - nodeToRestore.Expanded = nodeStates(nodeToRestore.DataBoundItem).Expanded - nodeToRestore.Selected = nodeStates(nodeToRestore.DataBoundItem).Selected - End If - For Each childNode As RadTreeNode In nodeToRestore.Nodes - RestoreExpandedStates(childNode) - Next -End Sub -```` - -{{endregion}} Once we have these methods implemented, we can use the dictionary to save the RadTreeView state prior the change occurs and restore it afterwards. In the example below, we are also saving and restoring the scroll bar position. -{{source=..\SamplesCS\TreeView\HowTo\KeepTreeViewStates.cs region=KeepTreeViewStates}} -{{source=..\SamplesVB\TreeView\HowTo\KeepTreeViewStates.vb region=KeepTreeViewStates}} - -````C# - -private void radButtonAdd_Click(object sender, EventArgs e) -{ - int scrollBarValue = radTreeView1.VScrollBar.Value; - foreach (RadTreeNode nodeToSave in radTreeView1.Nodes) - { - SaveExpandedStates(nodeToSave); - } - - ParentObject parent = radTreeView1.Nodes[0].DataBoundItem as ParentObject; - parent.Children.Add(new ChildObject(673,"New child")); - - radTreeView1.TreeViewElement.Update(RadTreeViewElement.UpdateActions.ItemAdded); - - foreach (RadTreeNode nodeToRestore in radTreeView1.Nodes) - { - RestoreExpandedStates(nodeToRestore); - } - radTreeView1.VScrollBar.Value = scrollBarValue; -} - -private void radButtonDelete_Click(object sender, EventArgs e) -{ - int scrollBarValue = radTreeView1.VScrollBar.Value; - foreach (RadTreeNode nodeToSave in radTreeView1.Nodes) - { - SaveExpandedStates(nodeToSave); - } - - ParentObject parent = radTreeView1.Nodes[0].DataBoundItem as ParentObject; - parent.Children.Clear(); - - radTreeView1.TreeViewElement.Update(RadTreeViewElement.UpdateActions.ItemRemoved); - - foreach (RadTreeNode nodeToRestore in radTreeView1.Nodes) - { - RestoreExpandedStates(nodeToRestore); - } - radTreeView1.VScrollBar.Value = scrollBarValue; -} - -private void radButtonUpdate_Click(object sender, EventArgs e) -{ - int scrollBarValue = radTreeView1.VScrollBar.Value; - foreach (RadTreeNode nodeToSave in radTreeView1.Nodes) - { - SaveExpandedStates(nodeToSave); - } - - ParentObject parent = radTreeView1.Nodes[2].DataBoundItem as ParentObject; - parent.Children[1].Description = "New description"; - - foreach (RadTreeNode nodeToRestore in radTreeView1.Nodes) - { - RestoreExpandedStates(nodeToRestore); - } - radTreeView1.VScrollBar.Value = scrollBarValue; -} - -```` -````VB.NET -Private Sub radButtonAdd_Click(sender As Object, e As EventArgs) Handles RadButtonAdd.Click - Dim scrollBarValue As Integer = RadTreeView1.VScrollBar.Value - For Each nodeToSave As RadTreeNode In RadTreeView1.Nodes - SaveExpandedStates(nodeToSave) - Next - Dim parent As ParentObject = TryCast(RadTreeView1.Nodes(0).DataBoundItem, ParentObject) - parent.Children.Add(New ChildObject(673, "New child")) - RadTreeView1.TreeViewElement.Update(RadTreeViewElement.UpdateActions.ItemAdded) - For Each nodeToRestore As RadTreeNode In RadTreeView1.Nodes - RestoreExpandedStates(nodeToRestore) - Next - RadTreeView1.VScrollBar.Value = scrollBarValue -End Sub -Private Sub radButtonDelete_Click(sender As Object, e As EventArgs) Handles RadButtonDelete.Click - Dim scrollBarValue As Integer = RadTreeView1.VScrollBar.Value - For Each nodeToSave As RadTreeNode In RadTreeView1.Nodes - SaveExpandedStates(nodeToSave) - Next - Dim parent As ParentObject = TryCast(RadTreeView1.Nodes(0).DataBoundItem, ParentObject) - parent.Children.Clear() - RadTreeView1.TreeViewElement.Update(RadTreeViewElement.UpdateActions.ItemRemoved) - For Each nodeToRestore As RadTreeNode In RadTreeView1.Nodes - RestoreExpandedStates(nodeToRestore) - Next - RadTreeView1.VScrollBar.Value = scrollBarValue -End Sub -Private Sub radButtonUpdate_Click(sender As Object, e As EventArgs) Handles RadButtonUpdate.Click - Dim scrollBarValue As Integer = RadTreeView1.VScrollBar.Value - For Each nodeToSave As RadTreeNode In RadTreeView1.Nodes - SaveExpandedStates(nodeToSave) - Next - Dim parent As ParentObject = TryCast(RadTreeView1.Nodes(2).DataBoundItem, ParentObject) - parent.Children(1).Description = "New description" - For Each nodeToRestore As RadTreeNode In RadTreeView1.Nodes - RestoreExpandedStates(nodeToRestore) - Next - RadTreeView1.VScrollBar.Value = scrollBarValue -End Sub + + -```` -{{endregion}} Now, using these methods the tree states will be restored accordingly. diff --git a/controls/treeview/localization/localization.md b/controls/treeview/localization/localization.md index d9fcb3320..54227cedc 100644 --- a/controls/treeview/localization/localization.md +++ b/controls/treeview/localization/localization.md @@ -23,76 +23,19 @@ To localize RadTreeView to display control text and messages in a specific langu Below is a sample implementation of an English localization provider: #### Localizing RadTreeView Strings -{{source=..\SamplesCS\TreeView\MyEnglishTreeViewLocalizationProvider.cs region=LocProvider}} -{{source=..\SamplesVB\TreeView\MyEnglishTreeViewLocalizationProvider.vb region=LocProvider}} -````C# -public class MyEnglishTreeViewLocalizationProvider : TreeViewLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case TreeViewStringId.ContextMenuCollapse: - return "Collapse"; - case TreeViewStringId.ContextMenuDelete: - return "Delete"; - case TreeViewStringId.ContextMenuEdit: - return "Edit"; - case TreeViewStringId.ContextMenuExpand: - return "Expand"; - case TreeViewStringId.ContextMenuNew: - return "New"; - default: - base.GetLocalizedString(id); - break; - } - return ""; - } -} - -```` -````VB.NET -Public Overrides Function GetLocalizedString(ByVal id As String) As String - Select Case id - Case TreeViewStringId.ContextMenuCollapse - Return "Collapse" - Case TreeViewStringId.ContextMenuDelete - Return "Delete" - Case TreeViewStringId.ContextMenuEdit - Return "Edit" - Case TreeViewStringId.ContextMenuExpand - Return "Expand" - Case TreeViewStringId.ContextMenuNew - Return "New" - Case Else - MyBase.GetLocalizedString(id) - End Select - Return "" -End Function - -```` - - - -{{endregion}} + + -To apply the custom localization provider, instantiate and assign it to the current localization provider: -#### Assigning the Current Localization Provider -{{source=..\SamplesCS\TreeView\TreeLocalization.cs region=localization}} -{{source=..\SamplesVB\TreeView\TreeLocalization.vb region=localization}} +To apply the custom localization provider, instantiate and assign it to the current localization provider: -````C# -TreeViewLocalizationProvider.CurrentProvider = new MyEnglishTreeViewLocalizationProvider(); +#### Assigning the Current Localization Provider -```` -````VB.NET -TreeViewLocalizationProvider.CurrentProvider = New MyEnglishTreeViewLocalizationProvider() + + -```` -{{endregion}} The code provided above illustrates the approach to be used to localize the __RadTreeView__ and is not intended as a full translation. diff --git a/controls/treeview/localization/right-to-left-support.md b/controls/treeview/localization/right-to-left-support.md index cbcb306e9..9430f52bb 100644 --- a/controls/treeview/localization/right-to-left-support.md +++ b/controls/treeview/localization/right-to-left-support.md @@ -14,19 +14,10 @@ previous_url: treeview-localization-rtl You can present the content of your tree view instance in a right-to-left direction by setting the __RightToLeft__ property to *Yes*: -{{source=..\SamplesCS\TreeView\TreeLocalization.cs region=rtl}} -{{source=..\SamplesVB\TreeView\TreeLocalization.vb region=rtl}} + + -````C# -this.radTreeView1.RightToLeft = System.Windows.Forms.RightToLeft.Yes; -```` -````VB.NET -Me.RadTreeView1.RightToLeft = Windows.Forms.RightToLeft.Yes - -```` - -{{endregion}} ![WinForms RadTreeView RTL](images/treeview-localization-rtl001.png) diff --git a/controls/treeview/styling-and-appearance/tree-lines-and-rows.md b/controls/treeview/styling-and-appearance/tree-lines-and-rows.md index e7c061a4a..ecd9e9b6c 100644 --- a/controls/treeview/styling-and-appearance/tree-lines-and-rows.md +++ b/controls/treeview/styling-and-appearance/tree-lines-and-rows.md @@ -15,44 +15,18 @@ previous_url: treeview-styling-and-appearance-tree-lines-and-rows To display lines connecting nodes in RadTreeView set the __ShowLines__ property to *true*. Control the appearance of the lines using the __LineStyle__ and __LineColor__ properties. __LineStyle__ is of type __TreeLineStyle__ and includes the following members __Solid__, __Dash__, __Dot__, __DashDot__, __DashDotDot__. -{{source=..\SamplesCS\TreeView\GettingStarted.cs region=lines}} -{{source=..\SamplesVB\TreeView\TreeViewGettingStarted.vb region=lines}} + + -````C# - -radTreeView1.ShowLines = true; -radTreeView1.LineStyle = TreeLineStyle.DashDot; - -```` -````VB.NET -RadTreeView1.ShowLines = True -RadTreeView1.LineStyle = TreeLineStyle.DashDot - -```` - -{{endregion}} ![WinForms RadTreeView Tree Lines and Rows](images/treeview-styling-and-appearance-tree-lines-and-rows001.png) To select rows spanning the entire width of RadTreeView (rather than just the node label), set the __FullRowSelect__ property to *true* and __ShowLines__ to *false*. In addition you can set the alternating row color by setting the __AllowAlternatingRowColor__ and __AlternatingRowColor__ properties. -{{source=..\SamplesCS\TreeView\GettingStarted.cs region=AlternatingRowColor}} -{{source=..\SamplesVB\TreeView\TreeViewGettingStarted.vb region=AlternatingRowColor}} - -````C# - -radTreeView1.TreeViewElement.AllowAlternatingRowColor = true; -radTreeView1.TreeViewElement.AlternatingRowColor = Color.LightBlue; - -```` -````VB.NET -RadTreeView1.TreeViewElement.AllowAlternatingRowColor = True -RadTreeView1.TreeViewElement.AlternatingRowColor = Color.LightBlue - -```` + + -{{endregion}} ![WinForms AlternatingRowColor](images/treeview-styling-and-appearance-tree-lines-and-rows002.png) diff --git a/controls/treeview/usability/keyboard-navigation.md b/controls/treeview/usability/keyboard-navigation.md index 5a1d9c72e..1415ddadd 100644 --- a/controls/treeview/usability/keyboard-navigation.md +++ b/controls/treeview/usability/keyboard-navigation.md @@ -44,35 +44,17 @@ RadTreeView allows navigation through the visible nodes by using keyboard. Two s To enable this functionality a single property setting is needed: -{{source=..\SamplesCS\TreeView\Usability1\TreeViewUsabilityKeyboardNavigation.cs region=KeyboardSearchEnabled}} -{{source=..\SamplesVB\TreeView\Usability1\TreeViewUsabilityKeyboardNavigation.vb region=KeyboardSearchEnabled}} + + -````C# -radTreeView1.KeyboardSearchEnabled = true; -```` -````VB.NET -radTreeView1.KeyboardSearchEnabled = True - -```` - -{{endregion}} Another property of interest is the __KeyboardSearchResetInterval__. It is used to determine what time between keystrokes will be considered as typing. Consequent keystrokes with performed faster than the specified interval will be considered typing and once the time elapses, the matching node (if such) will be selected. Here is how to access this property to change the value of the timer: -{{source=..\SamplesCS\TreeView\Usability1\TreeViewUsabilityKeyboardNavigation.cs region=KeyboardSearchResetInterval}} -{{source=..\SamplesVB\TreeView\Usability1\TreeViewUsabilityKeyboardNavigation.vb region=KeyboardSearchResetInterval}} - -````C# -radTreeView1.TreeViewElement.KeyboardSearchResetInterval = 500; - -```` -````VB.NET -radTreeView1.KeyboardSearchResetInterval = 500 + + -```` -{{endregion}} # See Also diff --git a/controls/treeview/working-with-nodes/adding-and-removing-nodes.md b/controls/treeview/working-with-nodes/adding-and-removing-nodes.md index b65a94772..8b12eddc6 100644 --- a/controls/treeview/working-with-nodes/adding-and-removing-nodes.md +++ b/controls/treeview/working-with-nodes/adding-and-removing-nodes.md @@ -1,175 +1,61 @@ ---- -title: Adding and Removing Nodes -page_title: Adding and Removing Nodes - WinForms TreeView Control -description: Learn how you can add or remove nodes in code and the events that are fired when add/remove action is performed in WinForms TreeView. -slug: winforms/treeview/working-with-nodes/adding-and-removing-nodes -tags: adding,and,removing,nodes -published: True -position: 0 -previous_url: treeview-working-with-nodes-adding-and-removing-nodes ---- - -# Adding and Removing Nodes - -## Adding Nodes - -RadTreeView nodes are arranged in a hierarchical structure. To add a node to the first level in a __RadTreeView__ use the __Nodes.Add()__ method. To add a child node to another node use the parent nodes __Nodes.Add()__ method. __Nodes.Add()__ places the node at the end of the __Nodes__ collection. You may also use __Nodes.Insert()__ to place the node anywhere in the __Nodes__ collection. - - -The following example demonstrates how to add nodes using code: - -{{source=..\SamplesCS\TreeView\WorkingWithNodes\WorkingWithNodes1.cs region=addNodes}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\WorkingWithNodes1.vb region=addNodes}} - -````C# -private void AddNodes() -{ - RadTreeNode Node1 = new RadTreeNode("Node1"); - Node1.Tag = 1234; - Node1.BackColor = Color.Blue; - RadTreeNode Node2 = new RadTreeNode("Node2"); - RadTreeNode Node3 = new RadTreeNode("Node3"); - RadTreeNode Node4 = new RadTreeNode("Node4"); - radTreeView1.Nodes.Add(Node1); - radTreeView1.Nodes.Add(Node2); - Node1.Nodes.Add(Node3); - Node2.Nodes.Add(Node4); - //Alternative methods for adding nodes - //RadTreeNode Node1 = radTreeView1.Nodes.Add("Node1"); - //RadTreeNode Node2 = radTreeView1.Nodes.Add("Node2"); - //Node1.Nodes.Add("Node3"); - //Node2.Nodes.Add("Node4"); -} - -```` -````VB.NET -Private Sub AddNodes() - Dim Node1 As New RadTreeNode("Node1") - Node1.Tag = 1234 - Node1.BackColor = Color.Blue - Dim Node2 As New RadTreeNode("Node2") - Dim Node3 As New RadTreeNode("Node3") - Dim Node4 As New RadTreeNode("Node4") - RadTreeView1.Nodes.Add(Node1) - RadTreeView1.Nodes.Add(Node2) - Node1.Nodes.Add(Node3) - Node2.Nodes.Add(Node4) - 'Alternative methods for adding nodes - 'RadTreeNode Node1 = radTreeView1.Nodes.Add("Node1"); - 'RadTreeNode Node2 = radTreeView1.Nodes.Add("Node2"); - 'Node1.Nodes.Add("Node3"); - 'Node2.Nodes.Add("Node4"); -End Sub - -```` - -{{endregion}} - -Just before a node is added, the __NodeAdding__ event is fired. The event arguments of this event allow you to cancel the adding of the node. If the operation was not canceled, then the node will be added to the RadTreeView and the __NodeAdded__ event will be fired. The following code snippet demonstrates the usage of these events: - -{{source=..\SamplesCS\TreeView\WorkingWithNodes\WorkingWithNodes1.cs region=NodeAdding}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\WorkingWithNodes1.vb region=NodeAdding}} - -````C# -void radTreeView1_NodeAdding(object sender, RadTreeViewCancelEventArgs e) -{ - if (e.Node.Text.Contains("Non-insertable")) - { - e.Cancel = true; - } -} -void radTreeView1_NodeAdded(object sender, RadTreeViewEventArgs e) -{ - RadMessageBox.Show("Node {" + e.Node.Text + "} was added"); -} - -```` -````VB.NET -Private Sub RadTreeView1_NodeAdding(sender As Object, e As RadTreeViewCancelEventArgs) Handles RadTreeView1.NodeAdding - If e.Node.Text.Contains("Non-insertable") Then - e.Cancel = True - End If -End Sub -Private Sub RadTreeView1_NodeAdded(sender As Object, e As RadTreeViewEventArgs) Handles RadTreeView1.NodeAdded - RadMessageBox.Show("Node {" + e.Node.Text + "} was added") -End Sub - -```` - -{{endregion}} - -## Removing Nodes - -To remove a single node use the __Remove()__ method of the node. To remove all nodes of the RadTreeView use the __Nodes.Clear()__ method. - -{{source=..\SamplesCS\TreeView\WorkingWithNodes\WorkingWithNodes1.cs region=removeNodes}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\WorkingWithNodes1.vb region=removeNodes}} - -````C# -private void RemoveNodes() -{ - //Remove a single node - radTreeView1.Nodes[0].Remove(); - // removes all nodes from TreeView - radTreeView1.Nodes.Clear(); -} - -```` -````VB.NET -Private Sub RemoveNodes() - 'Remove a single node - RadTreeView1.Nodes(0).Remove() - ' removes all nodes from TreeView - RadTreeView1.Nodes.Clear() -End Sub - -```` - -{{endregion}} - -Just before a node is removed, the __NodeRemoving__ event is fired. The event arguments of this event allow you to cancel the remove operation. If the operation was not canceled, then the node will be removed from RadTreeView and the __NodeRemoved__ event will be fired. The following code snippet demonstrates the usage of these events: - -{{source=..\SamplesCS\TreeView\WorkingWithNodes\WorkingWithNodes1.cs region=NodeRemoving}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\WorkingWithNodes1.vb region=NodeRemoving}} - -````C# -void radTreeView1_NodeRemoving(object sender, RadTreeViewCancelEventArgs e) -{ - if (e.Node.Text.Contains("Unremovable")) - { - e.Cancel = true; - } -} -void radTreeView1_NodeRemoved(object sender, RadTreeViewEventArgs e) -{ - RadMessageBox.Show("Node {" + e.Node.Text + "} was removed"); -} - -```` -````VB.NET -Private Sub RadTreeView1_NodeRemoving(sender As Object, e As RadTreeViewCancelEventArgs) Handles RadTreeView1.NodeRemoving - If e.Node.Text.Contains("Unremovable") Then - e.Cancel = True - End If -End Sub -Private Sub RadTreeView1_NodeRemoved(sender As Object, e As RadTreeViewEventArgs) Handles RadTreeView1.NodeRemoved - RadMessageBox.Show("Node {" + e.Node.Text + "} was removed") -End Sub - -```` - -{{endregion}} - -# See Also -* [Bring a Node into View]({%slug winforms/treeview/working-with-nodes/bring-a-node-into-view%}) - -* [Custom Filtering]({%slug winforms/treeview/working-with-nodes/custom-filtering%}) - -* [Custom Nodes]({%slug winforms/treeview/working-with-nodes/custom-nodes%}) - -* [Custom Sorting]({%slug winforms/treeview/working-with-nodes/custom-sorting%}) - -* [Events]({%slug winforms/treeview/working-with-nodes/events%}) - -* [Filtering Nodes]({%slug winforms/treeview/working-with-nodes/filtering-nodes%}) - +--- +title: Adding and Removing Nodes +page_title: Adding and Removing Nodes - WinForms TreeView Control +description: Learn how you can add or remove nodes in code and the events that are fired when add/remove action is performed in WinForms TreeView. +slug: winforms/treeview/working-with-nodes/adding-and-removing-nodes +tags: adding,and,removing,nodes +published: True +position: 0 +previous_url: treeview-working-with-nodes-adding-and-removing-nodes +--- + +# Adding and Removing Nodes + +## Adding Nodes + +RadTreeView nodes are arranged in a hierarchical structure. To add a node to the first level in a __RadTreeView__ use the __Nodes.Add()__ method. To add a child node to another node use the parent nodes __Nodes.Add()__ method. __Nodes.Add()__ places the node at the end of the __Nodes__ collection. You may also use __Nodes.Insert()__ to place the node anywhere in the __Nodes__ collection. + + +The following example demonstrates how to add nodes using code: + + + + + + +Just before a node is added, the __NodeAdding__ event is fired. The event arguments of this event allow you to cancel the adding of the node. If the operation was not canceled, then the node will be added to the RadTreeView and the __NodeAdded__ event will be fired. The following code snippet demonstrates the usage of these events: + + + + + + +## Removing Nodes + +To remove a single node use the __Remove()__ method of the node. To remove all nodes of the RadTreeView use the __Nodes.Clear()__ method. + + + + + + +Just before a node is removed, the __NodeRemoving__ event is fired. The event arguments of this event allow you to cancel the remove operation. If the operation was not canceled, then the node will be removed from RadTreeView and the __NodeRemoved__ event will be fired. The following code snippet demonstrates the usage of these events: + + + + + + +# See Also +* [Bring a Node into View]({%slug winforms/treeview/working-with-nodes/bring-a-node-into-view%}) + +* [Custom Filtering]({%slug winforms/treeview/working-with-nodes/custom-filtering%}) + +* [Custom Nodes]({%slug winforms/treeview/working-with-nodes/custom-nodes%}) + +* [Custom Sorting]({%slug winforms/treeview/working-with-nodes/custom-sorting%}) + +* [Events]({%slug winforms/treeview/working-with-nodes/events%}) + +* [Filtering Nodes]({%slug winforms/treeview/working-with-nodes/filtering-nodes%}) + diff --git a/controls/treeview/working-with-nodes/bring-a-node-into-view.md b/controls/treeview/working-with-nodes/bring-a-node-into-view.md index d8841ead6..26f410fff 100644 --- a/controls/treeview/working-with-nodes/bring-a-node-into-view.md +++ b/controls/treeview/working-with-nodes/bring-a-node-into-view.md @@ -1,52 +1,41 @@ ---- -title: Bring a Node into View -page_title: Bring a Node into View - WinForms TreeView Control -description: Get familiar how to use the BringIntoView method in order to navigate to a particular node in WinForms TreeView. -slug: winforms/treeview/working-with-nodes/bring-a-node-into-view -tags: bring,a,node,into,view -published: True -position: 3 -previous_url: treeview-working-with-nodes-bring-a-node-into-view ---- - -# Bring a Node into View - - -In cases where you have a tree view with many nodes and limited space on the form, you need to scroll the control in order to find a specific node. __RadTreeView__ control handles this automatically for you. To scroll the control to a node use the __BringIntoView__ method. - -{{source=..\SamplesCS\TreeView\WorkingWithNodes\WorkingWithNodes1.cs region=bringIntoView}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\WorkingWithNodes1.vb region=bringIntoView}} - -````C# -RadTreeNode lastRootNode = radTreeView1.Nodes[radTreeView1.Nodes.Count - 1]; -radTreeView1.BringIntoView(lastRootNode.Nodes[lastRootNode.Nodes.Count - 1]); - -```` -````VB.NET -Dim lastRootNode As RadTreeNode = RadTreeView1.Nodes(RadTreeView1.Nodes.Count - 1) -RadTreeView1.BringIntoView(lastRootNode.Nodes(lastRootNode.Nodes.Count - 1)) - -```` - -{{endregion}} - ->important The **BringIntoView** method does not select the node! -> - ->note The **RadTreeViewElement** class defines an **AutoScrollOnClick** property which is by default set to *true*. This property determines whether to scroll horizontally the control ensuring that the clicked node is visible. -> - -# See Also -* [Adding and Removing Nodes]({%slug winforms/treeview/working-with-nodes/adding-and-removing-nodes%}) - -* [Custom Filtering]({%slug winforms/treeview/working-with-nodes/custom-filtering%}) - -* [Custom Nodes]({%slug winforms/treeview/working-with-nodes/custom-nodes%}) - -* [Custom Sorting]({%slug winforms/treeview/working-with-nodes/custom-sorting%}) - -* [Events]({%slug winforms/treeview/working-with-nodes/events%}) - -* [Filtering Nodes]({%slug winforms/treeview/working-with-nodes/filtering-nodes%}) - - \ No newline at end of file +--- +title: Bring a Node into View +page_title: Bring a Node into View - WinForms TreeView Control +description: Get familiar how to use the BringIntoView method in order to navigate to a particular node in WinForms TreeView. +slug: winforms/treeview/working-with-nodes/bring-a-node-into-view +tags: bring,a,node,into,view +published: True +position: 3 +previous_url: treeview-working-with-nodes-bring-a-node-into-view +--- + +# Bring a Node into View + + +In cases where you have a tree view with many nodes and limited space on the form, you need to scroll the control in order to find a specific node. __RadTreeView__ control handles this automatically for you. To scroll the control to a node use the __BringIntoView__ method. + + + + + + +>important The **BringIntoView** method does not select the node! +> + +>note The **RadTreeViewElement** class defines an **AutoScrollOnClick** property which is by default set to *true*. This property determines whether to scroll horizontally the control ensuring that the clicked node is visible. +> + +# See Also +* [Adding and Removing Nodes]({%slug winforms/treeview/working-with-nodes/adding-and-removing-nodes%}) + +* [Custom Filtering]({%slug winforms/treeview/working-with-nodes/custom-filtering%}) + +* [Custom Nodes]({%slug winforms/treeview/working-with-nodes/custom-nodes%}) + +* [Custom Sorting]({%slug winforms/treeview/working-with-nodes/custom-sorting%}) + +* [Events]({%slug winforms/treeview/working-with-nodes/events%}) + +* [Filtering Nodes]({%slug winforms/treeview/working-with-nodes/filtering-nodes%}) + + diff --git a/controls/treeview/working-with-nodes/custom-filtering.md b/controls/treeview/working-with-nodes/custom-filtering.md index 531068d13..52acf444b 100644 --- a/controls/treeview/working-with-nodes/custom-filtering.md +++ b/controls/treeview/working-with-nodes/custom-filtering.md @@ -18,31 +18,10 @@ In order to apply custom logic for filtering, you have to create a [Predicate](h #### Creating predicate -{{source=..\SamplesCS\TreeView\WorkingWithNodes\TreeCustomFiltering.cs region=CustomFiltering2}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\TreeCustomFiltering.vb region=CustomFiltering2}} - -````C# -private bool FilterNode(RadTreeNode node) -{ - if (node.Text.Length > 1) - { - return true; - } - return false; -} - -```` -````VB.NET -Private Function FilterNode(node As RadTreeNode) As Boolean - If node.Text.Length > 1 Then - Return True - End If - Return False -End Function - -```` - -{{endregion}} + + + + | Here you have nodes from 1-100 | After the filtering the nodes are only from 10-100, since nodes 1-9 contain just one char as text | | ------ | ------ | @@ -52,42 +31,17 @@ To set the __Predicate__ to RadTreeView, use the __FilterPredicate__ property of #### Applying predicate -{{source=..\SamplesCS\TreeView\WorkingWithNodes\TreeCustomFiltering.cs region=CustomFiltering1}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\TreeCustomFiltering.vb region=CustomFiltering1}} - -````C# -radTreeView1.TreeViewElement.FilterPredicate = FilterNode; - -```` -````VB.NET -RadTreeView1.TreeViewElement.FilterPredicate = AddressOf FilterNode + + -```` -{{endregion}} At the end, in order to apply the filter to the control, just set the __Filter__ property to any string, which will invoke the filtering operation: #### Invoke filtering -{{source=..\SamplesCS\TreeView\WorkingWithNodes\TreeCustomFiltering.cs region=CustomFiltering3}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\TreeCustomFiltering.vb region=CustomFiltering3}} - -````C# -private void radButton1_Click(object sender, EventArgs e) -{ - this.radTreeView1.Filter = "Custom"; -} - -```` -````VB.NET -Private Sub RadButton1_Click(sender As System.Object, e As System.EventArgs) Handles RadButton1.Click - Me.RadTreeView1.Filter = "Custom" -End Sub - -```` - -{{endregion}} + + diff --git a/controls/treeview/working-with-nodes/custom-nodes.md b/controls/treeview/working-with-nodes/custom-nodes.md index 486c00a08..25e2400a6 100644 --- a/controls/treeview/working-with-nodes/custom-nodes.md +++ b/controls/treeview/working-with-nodes/custom-nodes.md @@ -21,360 +21,24 @@ To create this example you can first prepare a project by following the steps in 1\. First we can create a custom __TreeNodeContentElement__ class which contains the main elements for the custom node. These elements are created and initialized in the __CreateChildElements__ method. Also the __Synchronize__ method is overridden for setting the elements properties in accordance with the corresponding data: -{{source=..\SamplesCS\TreeView\WorkingWithNodes\CustomNodes.cs region=CustomContentElement}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\CustomNodes.vb region=CustomContentElement}} + + -````C# - -class CustomContentElement : TreeNodeContentElement -{ - StackLayoutElement nodeContentContainer; - LinePrimitive lineElement; - LightVisualElement textElement; - RadButtonElement buttonElement; - - protected override Type ThemeEffectiveType - { - get - { - return typeof(TreeNodeContentElement); - } - } - protected override void InitializeFields() - { - base.InitializeFields(); - this.DrawBorder = true; - this.NumberOfColors = 2; - this.GradientStyle = GradientStyles.Linear; - this.Margin = new Padding(5, 5, 5, 5); - this.Shape = new RoundRectShape(2); - this.StretchHorizontally = true; - } - public override void Synchronize() - { - this.DrawFill = true; - - TreeNodeElement treeNodeElement = this.NodeElement; - RadTreeNode node = treeNodeElement.Data; - DataRowView rowView = (DataRowView)node.DataBoundItem; - - if (node.Level == 0) - { - this.textElement.Text = "" + rowView["ArtistName"]; - if (node.Expanded == false) - { - buttonElement.Text = "Show Albums"; - } - else - { - buttonElement.Text = "Hide Albums"; - } - - this.BorderColor = Color.FromArgb(110, 153, 210); - this.BackColor = Color.FromArgb(174, 190, 217); - this.BackColor2 = Color.FromArgb(168, 183, 210); - } - else if (node.Level == 1) - { - this.textElement.Text = "" + rowView["AlbumName"]; - this.buttonElement.Text = "Play Album"; - - this.BorderColor = Color.FromArgb(210, 153, 210); - this.BackColor = Color.FromArgb(74, 190, 217); - this.BackColor2 = Color.FromArgb(50, 150, 190); - } - else - { - this.textElement.Text = "" + rowView["SongName"]; - this.buttonElement.Text = "Play Song"; - - this.BorderColor = Color.FromArgb(110, 153, 110); - this.BackColor = Color.FromArgb(234, 190, 117); - this.BackColor2 = Color.FromArgb(208, 183, 110); - } - } - - protected override void CreateChildElements() - { - nodeContentContainer = new StackLayoutElement(); - nodeContentContainer.Orientation = Orientation.Vertical; - nodeContentContainer.StretchHorizontally = true; - nodeContentContainer.StretchVertically = false; - - textElement = new LightVisualElement(); - textElement.ShouldHandleMouseInput = false; - textElement.NotifyParentOnMouseInput = true; - textElement.StretchVertically = false; - this.nodeContentContainer.Children.Add(textElement); - - lineElement = new LinePrimitive(); - lineElement.BackColor = Color.Black; - lineElement.Margin = new Padding(10, 0, 10, 0); - lineElement.StretchVertically = false; - this.nodeContentContainer.Children.Add(lineElement); - - buttonElement = new RadButtonElement(); - buttonElement.Margin = new Padding(20, 3, 20, 3); - buttonElement.Click += buttonElement_Click; - buttonElement.StretchVertically = false; - this.nodeContentContainer.Children.Add(buttonElement); - - this.Children.Add(nodeContentContainer); - } - - void buttonElement_Click(object sender, EventArgs e) - { - TreeNodeElement treeNodeElement = this.NodeElement; - RadTreeNode node = treeNodeElement.Data; - if (node.Level == 0) - { - if (node.Expanded == true) - { - node.Collapse(); - buttonElement.Text = "Show Albums"; - } - else - { - node.Expand(); - buttonElement.Text = "Hide Albums"; - } - } - } -} -```` -````VB.NET -Class CustomContentElement - Inherits TreeNodeContentElement - Private nodeContentContainer As StackLayoutElement - Private lineElement As LinePrimitive - Private textElement As LightVisualElement - Private buttonElement As RadButtonElement - Protected Overrides ReadOnly Property ThemeEffectiveType() As Type - Get - Return GetType(TreeNodeContentElement) - End Get - End Property - Protected Overrides Sub InitializeFields() - MyBase.InitializeFields() - Me.DrawBorder = True - Me.NumberOfColors = 2 - Me.GradientStyle = GradientStyles.Linear - Me.Margin = New Padding(5, 5, 5, 5) - Me.Shape = New RoundRectShape(2) - Me.StretchHorizontally = True - End Sub - Public Overrides Sub Synchronize() - Me.DrawFill = True - Dim treeNodeElement As TreeNodeElement = Me.NodeElement - Dim node As RadTreeNode = treeNodeElement.Data - Dim rowView As DataRowView = DirectCast(node.DataBoundItem, DataRowView) - If node.Level = 0 Then - Me.textElement.Text = rowView("ArtistName") - If node.Expanded = False Then - buttonElement.Text = "Show Albums" - Else - buttonElement.Text = "Hide Albums" - End If - Me.BorderColor = Color.FromArgb(110, 153, 210) - Me.BackColor = Color.FromArgb(174, 190, 217) - Me.BackColor2 = Color.FromArgb(168, 183, 210) - ElseIf node.Level = 1 Then - Me.textElement.Text = rowView("AlbumName") - Me.buttonElement.Text = "Play Album" - Me.BorderColor = Color.FromArgb(210, 153, 210) - Me.BackColor = Color.FromArgb(74, 190, 217) - Me.BackColor2 = Color.FromArgb(50, 150, 190) - Else - Me.textElement.Text = rowView("SongName") - Me.buttonElement.Text = "Play Song" - Me.BorderColor = Color.FromArgb(110, 153, 110) - Me.BackColor = Color.FromArgb(234, 190, 117) - Me.BackColor2 = Color.FromArgb(208, 183, 110) - End If - End Sub - Protected Overrides Sub CreateChildElements() - nodeContentContainer = New StackLayoutElement() - nodeContentContainer.Orientation = Orientation.Vertical - nodeContentContainer.StretchHorizontally = True - nodeContentContainer.StretchVertically = False - textElement = New LightVisualElement() - textElement.ShouldHandleMouseInput = False - textElement.NotifyParentOnMouseInput = True - textElement.StretchVertically = False - Me.nodeContentContainer.Children.Add(textElement) - lineElement = New LinePrimitive() - lineElement.BackColor = Color.Black - lineElement.Margin = New Padding(10, 0, 10, 0) - lineElement.StretchVertically = False - Me.nodeContentContainer.Children.Add(lineElement) - buttonElement = New RadButtonElement() - buttonElement.Margin = New Padding(20, 3, 20, 3) - AddHandler buttonElement.Click, AddressOf buttonElement_Click - buttonElement.StretchVertically = False - Me.nodeContentContainer.Children.Add(buttonElement) - Me.Children.Add(nodeContentContainer) - Me.Shape = New RoundRectShape(2) - Me.StretchHorizontally = True - End Sub - Private Sub buttonElement_Click(sender As Object, e As EventArgs) - Dim treeNodeElement As TreeNodeElement = Me.NodeElement - Dim node As RadTreeNode = treeNodeElement.Data - If node.Level = 0 Then - If node.Expanded = True Then - node.Collapse() - buttonElement.Text = "Show Albums" - Else - node.Expand() - buttonElement.Text = "Hide Albums" - End If - End If - End Sub -End Class - -```` - -{{endregion}} 2\. Now we can use the already created __CustomContentElement__ and create a custom __TreeNodeElement__ class. Also here the __Synchronize__ method is overridden in order to set the picture of the node: -{{source=..\SamplesCS\TreeView\WorkingWithNodes\CustomNodes.cs region=CustomTreeNodeElement}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\CustomNodes.vb region=CustomTreeNodeElement}} - -````C# - -public class CustomTreeNodeElement : TreeNodeElement -{ - - protected override TreeNodeContentElement CreateContentElement() - { - return new CustomContentElement(); - } - public override void Synchronize() - { - base.Synchronize(); - - RadTreeNode node = this.Data; - DataRowView rowView = (DataRowView)node.DataBoundItem; - if (node.Level != 2) - { - this.ImageElement.Image = ImageHelper.GetImageFromBytes((byte[])rowView["Image"]).GetThumbnailImage(50, 50, null, IntPtr.Zero); - } - else - { - this.ImageElement.Image = Resources.the_music_icon.GetThumbnailImage(50, 50, null, IntPtr.Zero); - } - } - - protected override Type ThemeEffectiveType - { - get - { - return typeof(TreeNodeElement); - } - } -} + + -```` -````VB.NET -Public Class CustomTreeNodeElement - Inherits TreeNodeElement - Protected Overrides Function CreateContentElement() As TreeNodeContentElement - Return New CustomContentElement() - End Function - Public Overrides Sub Synchronize() - MyBase.Synchronize() - Dim node As RadTreeNode = Me.Data - Dim rowView As DataRowView = DirectCast(node.DataBoundItem, DataRowView) - If node.Level <> 2 Then - Me.ImageElement.Image = ImageHelper.GetImageFromBytes(DirectCast(rowView("Image"), Byte())).GetThumbnailImage(50, 50, Nothing, IntPtr.Zero) - Else - Me.ImageElement.Image = My.Resources.the_music_icon.GetThumbnailImage(50, 50, Nothing, IntPtr.Zero) - End If - End Sub - Protected Overrides ReadOnly Property ThemeEffectiveType() As Type - Get - Return GetType(TreeNodeElement) - End Get - End Property -End Class -```` - -{{endregion}} 3\. Finally, we can add a little bit more customization by setting some of the __RadTreeView__ properties in the form's Load event handler. And also we need to subscribe to the __CreateNodeElement__ event in order to use the newly created custom nodes: -{{source=..\SamplesCS\TreeView\WorkingWithNodes\CustomNodes.cs region=CustomNodesLoad}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\CustomNodes.vb region=CustomNodesLoad}} - -````C# - -private void CustomNodes_Load(object sender, EventArgs e) -{ - // TODO: This line of code loads data into the 'musicCollectionDataSet.Artists' table. You can move, or remove it, as needed. - this.artistsTableAdapter.Fill(this.musicCollectionDataSet.Artists); - // TODO: This line of code loads data into the 'musicCollectionDataSet.Albums' table. You can move, or remove it, as needed. - this.albumsTableAdapter.Fill(this.musicCollectionDataSet.Albums); - // TODO: This line of code loads data into the 'musicCollectionDataSet.Songs' table. You can move, or remove it, as needed. - this.songsTableAdapter.Fill(this.musicCollectionDataSet.Songs); - - this.radTreeView1.DataSource = this.artistsBindingSource; - this.radTreeView1.DisplayMember = "ArtistName"; - this.radTreeView1.ValueMember = "ArtistID"; - this.radTreeView1.RelationBindings.Add(new RelationBinding(this.albumsBindingSource, "AlbumName", "ArtistID", "ArtistID", "AlbumID")); - this.radTreeView1.RelationBindings.Add(new RelationBinding(this.songsBindingSource, "SongName", "AlbumID", "AlbumID", "SongID")); - this.radTreeView1.TreeViewElement.CreateNodeElement += TreeViewElement_CreateNodeElement; - this.radTreeView1.TreeViewElement.AutoSizeItems = true; - this.radTreeView1.ShowRootLines = false; - this.radTreeView1.FullRowSelect = false; - this.radTreeView1.ShowLines = true; - this.radTreeView1.LineStyle = TreeLineStyle.Solid; - this.radTreeView1.LineColor = Color.FromArgb(110, 153, 210); - this.radTreeView1.TreeIndent = 50; - radTreeView1.TreeViewElement.CollapseImage = Resources.toggle_expand_basic_blue.GetThumbnailImage(20, 20, null, IntPtr.Zero); - radTreeView1.TreeViewElement.ExpandImage = Resources.toggle_collapse_basic_blue.GetThumbnailImage(20, 20, null, IntPtr.Zero); - this.radTreeView1.ExpandAll(); -} - -void TreeViewElement_CreateNodeElement(object sender, Telerik.WinControls.UI.CreateTreeNodeElementEventArgs e) -{ - e.NodeElement = new CustomTreeNodeElement(); -} - -```` -````VB.NET -Private Sub CustomNodes_Load(sender As Object, e As EventArgs) Handles Me.Load - Me.ArtistsTableAdapter.Fill(Me.MusicCollectionDataSet.Artists) - 'TODO: This line of code loads data into the 'MusicCollectionDataSet.Songs' table. You can move, or remove it, as needed. - Me.SongsTableAdapter.Fill(Me.MusicCollectionDataSet.Songs) - 'TODO: This line of code loads data into the 'MusicCollectionDataSet.Albums' table. You can move, or remove it, as needed. - Me.AlbumsTableAdapter.Fill(Me.MusicCollectionDataSet.Albums) - 'TODO: This line of code loads data into the 'MusicCollectionDataSet.Artists' table. You can move, or remove it, as needed. - Me.RadTreeView1.DataSource = Me.ArtistsBindingSource - Me.RadTreeView1.DisplayMember = "ArtistName" - Me.RadTreeView1.ValueMember = "ArtistID" - Me.RadTreeView1.RelationBindings.Add(New RelationBinding(Me.AlbumsBindingSource, "AlbumName", "ArtistID", "ArtistID", "AlbumID")) - Me.RadTreeView1.RelationBindings.Add(New RelationBinding(Me.SongsBindingSource, "SongName", "AlbumID", "AlbumID", "SongID")) - AddHandler Me.RadTreeView1.TreeViewElement.CreateNodeElement, AddressOf TreeViewElement_CreateNodeElement - Me.RadTreeView1.TreeViewElement.AutoSizeItems = True - Me.RadTreeView1.ShowRootLines = False - Me.RadTreeView1.TreeIndent = 50 - Me.RadTreeView1.FullRowSelect = False - Me.RadTreeView1.ShowLines = True - Me.RadTreeView1.LineStyle = TreeLineStyle.Solid - Me.RadTreeView1.LineColor = Color.FromArgb(110, 153, 210) - RadTreeView1.TreeViewElement.CollapseImage = My.Resources.toggle_expand_basic_blue.GetThumbnailImage(20, 20, Nothing, IntPtr.Zero) - RadTreeView1.TreeViewElement.ExpandImage = My.Resources.toggle_collapse_basic_blue.GetThumbnailImage(20, 20, Nothing, IntPtr.Zero) - Me.RadTreeView1.ExpandAll() -End Sub -Private Sub TreeViewElement_CreateNodeElement(sender As Object, e As Telerik.WinControls.UI.CreateTreeNodeElementEventArgs) - e.NodeElement = New CustomTreeNodeElement() -End Sub + + -```` -{{endregion}} # See Also * [Adding and Removing Nodes]({%slug winforms/treeview/working-with-nodes/adding-and-removing-nodes%}) diff --git a/controls/treeview/working-with-nodes/custom-sorting.md b/controls/treeview/working-with-nodes/custom-sorting.md index d5a6975ea..651fe687d 100644 --- a/controls/treeview/working-with-nodes/custom-sorting.md +++ b/controls/treeview/working-with-nodes/custom-sorting.md @@ -17,106 +17,26 @@ To apply your own logic for sorting, you have to create a class which inherits f #### Creating custom comparer -{{source=..\SamplesCS\TreeView\WorkingWithNodes\TreeCustomSorting.cs region=CustomSorting3}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\TreeCustomSorting.vb region=CustomSorting3}} - -````C# -class MyComparer : TreeNodeComparer -{ - public MyComparer(RadTreeViewElement treeView) - : base(treeView) - { - } - public override int Compare(RadTreeNode x, RadTreeNode y) - { - if (this.TreeViewElement.SortOrder == SortOrder.Descending) - { - return x.Text.CompareTo(y.Text); - } - return x.Text.CompareTo(y.Text) * -1; - } -} - -```` -````VB.NET -Class MyComparer - Inherits TreeNodeComparer - Public Sub New(treeView As RadTreeViewElement) - MyBase.New(treeView) - End Sub - Public Overrides Function Compare(x As RadTreeNode, y As RadTreeNode) As Integer - If Me.TreeViewElement.SortOrder = SortOrder.Descending Then - Return x.Text.CompareTo(y.Text) - End If - Return x.Text.CompareTo(y.Text) * -1 - End Function -End Class - -```` - -{{endregion}} + + + + Once the comparer is created we have to assign it to the RadTreeView control: #### Assign the custom comparer -{{source=..\SamplesCS\TreeView\WorkingWithNodes\TreeCustomSorting.cs region=CustomSorting1}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\TreeCustomSorting.vb region=CustomSorting1}} + + -````C# -radTreeView1.TreeViewElement.Comparer = new MyComparer(this.radTreeView1.TreeViewElement); -```` -````VB.NET -RadTreeView1.TreeViewElement.Comparer = New MyComparer(Me.RadTreeView1.TreeViewElement) -```` +To test this scenario, you can add a button and a label to the form, where you will change and print the sort order. This will allow you to check whether the sorting is reversed: -{{endregion}} + + -To test this scenario, you can add a button and a label to the form, where you will change and print the sort order. This will allow you to check whether the sorting is reversed: -{{source=..\SamplesCS\TreeView\WorkingWithNodes\TreeCustomSorting.cs region=CustomSorting2}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\TreeCustomSorting.vb region=CustomSorting2}} - -````C# -private void radButton1_Click(object sender, EventArgs e) -{ - if (radTreeView1.SortOrder == SortOrder.None) - { - radTreeView1.SortOrder = SortOrder.Ascending; - radLabel1.Text = "Sorting: Ascending"; - } - else if (radTreeView1.SortOrder == SortOrder.Ascending) - { - radTreeView1.SortOrder = SortOrder.Descending; - radLabel1.Text = "Sorting: Descending"; - } - else - { - radTreeView1.SortOrder = SortOrder.None; - radLabel1.Text = "Sorting: None"; - } -} - -```` -````VB.NET -Private Sub RadButton1_Click(sender As System.Object, e As System.EventArgs) - If RadTreeView1.SortOrder = SortOrder.None Then - RadTreeView1.SortOrder = SortOrder.Ascending - radLabel1.Text = "Sorting: Ascending" - ElseIf RadTreeView1.SortOrder = SortOrder.Ascending Then - RadTreeView1.SortOrder = SortOrder.Descending - radLabel1.Text = "Sorting: Descending" - Else - RadTreeView1.SortOrder = SortOrder.None - RadLabel1.Text = "None" - End If -End Sub - -```` - -{{endregion}} ![WinForms RadTreeView Custom Sorting](images/treeview-working-with-nodes-custom-sorting001.png) diff --git a/controls/treeview/working-with-nodes/events.md b/controls/treeview/working-with-nodes/events.md index a00edc816..4506163d6 100644 --- a/controls/treeview/working-with-nodes/events.md +++ b/controls/treeview/working-with-nodes/events.md @@ -32,30 +32,10 @@ __RadTreeView__ provides a large set of events which allows you to respond to no * __SelectedNodesChanged__ - the event occurs when SelectedNodes collection has been changed. -{{source=..\SamplesCS\TreeView\WorkingWithNodes\WorkingWithNodes1.cs region=NodeMouseClick}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\WorkingWithNodes1.vb region=NodeMouseClick}} - -````C# -private void RadTreeView1_NodeMouseClick(object sender, RadTreeViewEventArgs e) -{ - RadTreeViewMouseEventArgs args = e as RadTreeViewMouseEventArgs; - if (args.OriginalEventArgs.Button == MouseButtons.Right) - { - //TO DO - } -} - -```` -````VB.NET -Private Sub RadTreeView1_NodeMouseClick(ByVal sender As Object, ByVal e As RadTreeViewEventArgs) - Dim args As RadTreeViewMouseEventArgs = TryCast(e, RadTreeViewMouseEventArgs) - - If args.OriginalEventArgs.Button = MouseButtons.Right Then - ' TO DO - End If -End Sub - -```` + + + + The above events are using __RadTreeViewEventArgs__ and __RadTreeViewCancelEventArgs__ objects to provide you with useful information inside the events. The main difference is that you can cancel the interaction in the second case. These objects are exposing the following information: diff --git a/controls/treeview/working-with-nodes/filtering-nodes.md b/controls/treeview/working-with-nodes/filtering-nodes.md index a3eb3f70e..17bb9e91a 100644 --- a/controls/treeview/working-with-nodes/filtering-nodes.md +++ b/controls/treeview/working-with-nodes/filtering-nodes.md @@ -19,19 +19,10 @@ For example, if we have this RadTreeView instance: and we set the __Filter__ property as shown below: -{{source=..\SamplesCS\TreeView\WorkingWithNodes\WorkingWithNodes1.cs region=filter}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\WorkingWithNodes1.vb region=filter}} + + -````C# -this.radTreeView1.Filter = "new"; -```` -````VB.NET -Me.RadTreeView1.Filter = "new" - -```` - -{{endregion}} we will get this look of RadTreeView at the end: diff --git a/controls/treeview/working-with-nodes/finding-nodes.md b/controls/treeview/working-with-nodes/finding-nodes.md index 5a12cc3cb..4461ed24b 100644 --- a/controls/treeview/working-with-nodes/finding-nodes.md +++ b/controls/treeview/working-with-nodes/finding-nodes.md @@ -19,27 +19,10 @@ When searching for node(s) you have several options that you can use The following example demonstrates how to search for a single node by its text and how to get all nodes whose __Tag__ is not null by using a __Predicate__: -{{source=..\SamplesCS\TreeView\WorkingWithNodes\WorkingWithNodes1.cs region=find}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\WorkingWithNodes1.vb region=find}} - -````C# -RadTreeNode resultOfSearch = radTreeView1.Find("Child Node"); - -Predicate match = new Predicate(delegate(RadTreeNode node) -{ - return node.Tag != null ? true : false; -}); -RadTreeNode[] result = radTreeView1.FindNodes(match); - -```` -````VB.NET -Dim resultOfSearch As RadTreeNode = RadTreeView1.Find("Child Node") -Dim match As New Predicate(Of RadTreeNode)(Function(node As RadTreeNode) If(node.Tag IsNot Nothing, True, False)) -Dim result As RadTreeNode() = RadTreeView1.FindNodes(match) - -```` - -{{endregion}} + + + + # See Also * [Adding and Removing Nodes]({%slug winforms/treeview/working-with-nodes/adding-and-removing-nodes%}) diff --git a/controls/treeview/working-with-nodes/formatting-nodes.md b/controls/treeview/working-with-nodes/formatting-nodes.md index 4a57b8220..f0d73b26f 100644 --- a/controls/treeview/working-with-nodes/formatting-nodes.md +++ b/controls/treeview/working-with-nodes/formatting-nodes.md @@ -25,58 +25,10 @@ Each __TreeNodeElement__ contains the following elements: The bellow example shows how you can access and format the main node elements: -{{source=..\SamplesCS\TreeView\WorkingWithNodes\NodeFormatting.cs region=nodeFormatting}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\NodeFormatting.vb region=nodeFormatting}} -````C# - -Bitmap file = SamplesCS.Properties.Resources.file; -private void radTreeView1_NodeFormatting(object sender, TreeNodeFormattingEventArgs e) -{ - if (e.Node.Level > 0) - { - e.NodeElement.BorderColor = Color.Blue; - e.NodeElement.BorderBoxStyle = Telerik.WinControls.BorderBoxStyle.SingleBorder; - e.NodeElement.BorderGradientStyle = Telerik.WinControls.GradientStyles.Solid; - e.NodeElement.BackColor = Color.LightBlue; - e.NodeElement.ContentElement.ForeColor = Color.White; - e.NodeElement.ImageElement.Image = file; - } - else - { - e.NodeElement.ResetValue(LightVisualElement.BorderColorProperty, ValueResetFlags.Local); - e.NodeElement.ResetValue(LightVisualElement.BorderBoxStyleProperty, ValueResetFlags.Local); - e.NodeElement.ResetValue(LightVisualElement.BorderGradientStyleProperty, ValueResetFlags.Local); - e.NodeElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local); - e.NodeElement.ContentElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local); - e.NodeElement.ImageElement.ResetValue(LightVisualElement.ImageProperty, ValueResetFlags.Local); - } -} - -```` -````VB.NET -Private file As Bitmap = My.Resources.file -Private Sub radTreeView1_NodeFormatting(ByVal sender As Object, ByVal e As TreeNodeFormattingEventArgs) - If e.Node.Level > 0 Then - e.NodeElement.BorderColor = Color.Blue - e.NodeElement.BorderBoxStyle = Telerik.WinControls.BorderBoxStyle.SingleBorder - e.NodeElement.BorderGradientStyle = Telerik.WinControls.GradientStyles.Solid - e.NodeElement.BackColor = Color.LightBlue - e.NodeElement.ContentElement.ForeColor = Color.White - e.NodeElement.ImageElement.Image = file - Else - e.NodeElement.ResetValue(LightVisualElement.BorderColorProperty, ValueResetFlags.Local) - e.NodeElement.ResetValue(LightVisualElement.BorderBoxStyleProperty, ValueResetFlags.Local) - e.NodeElement.ResetValue(LightVisualElement.BorderGradientStyleProperty, ValueResetFlags.Local) - e.NodeElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local) - e.NodeElement.ContentElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local) - e.NodeElement.ImageElement.ResetValue(LightVisualElement.ImageProperty, ValueResetFlags.Local) - End If -End Sub - -```` - - -{{endregion}} + + + + >caption Figure 1: Nodes formated with the above code. @@ -94,27 +46,10 @@ End Sub To enable wrapping text of the nodes in RadTreeView, you can set the __TextWrap__ property of the visual node element in the __NodeFormatting__ event handler. -{{source=..\SamplesCS\TreeView\WorkingWithNodes\NodeFormatting.cs region=nodeFormatting}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\NodeFormatting.vb region=nodeFormatting}} -````C# - -void radTreeView_NodeFormatting(object sender, TreeNodeFormattingEventArgs e) -{ - e.NodeElement.ContentElement.TextWrap = true; -} - -```` -````VB.NET - -Private Sub radTreeView_NodeFormatting(ByVal sender As Object, ByVal e As TreeNodeFormattingEventArgs) - e.NodeElement.ContentElement.TextWrap = True -End Sub - - -```` + + -{{endregion}} # See Also * [Adding and Removing Nodes]({%slug winforms/treeview/working-with-nodes/adding-and-removing-nodes%}) diff --git a/controls/treeview/working-with-nodes/reordering-nodes.md b/controls/treeview/working-with-nodes/reordering-nodes.md index 795840013..4945984fa 100644 --- a/controls/treeview/working-with-nodes/reordering-nodes.md +++ b/controls/treeview/working-with-nodes/reordering-nodes.md @@ -22,43 +22,10 @@ There are two methods for reordering nodes: Use the __Insert__ and __Add__ methods of the RadTreeView Nodes collection to reorder nodes programmatically. The code snippet below demonstrates how this is done using the __Add__ method. -{{source=..\SamplesCS\TreeView\WorkingWithNodes\WorkingWithNodes1.cs region=reordering}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\WorkingWithNodes1.vb region=reordering}} - -````C# -// Create two parent nodes -RadTreeNode parentNode1 = new RadTreeNode("First Parent"); -RadTreeNode parentNode2 = new RadTreeNode("Second Parent"); -// Add the parent nodes to tree view's nodes collection -this.radTreeView1.Nodes.Add(parentNode1); -this.radTreeView1.Nodes.Add(parentNode2); -// Create a child node -RadTreeNode childNode = new RadTreeNode("Child Node"); -// Add the child node to the first parent's nodes collection -parentNode1.Nodes.Add(childNode); -// Remove the child from the first parent collection and add it to the second parent nodes collection -parentNode1.Nodes.Remove(childNode); -parentNode2.Nodes.Add(childNode); - -```` -````VB.NET -' Create two parent nodes -Dim parentNode1 As New RadTreeNode("First Parent") -Dim parentNode2 As New RadTreeNode("Second Parent") -' Add the parent nodes to tree view's nodes collection -Me.RadTreeView1.Nodes.Add(parentNode1) -Me.RadTreeView1.Nodes.Add(parentNode2) -' Create a child node -Dim childNode As New RadTreeNode("Child Node") -' Add the child node to the first parent's nodes collection -parentNode1.Nodes.Add(childNode) -' Remove the child from the first parent collection and add it to the second parent nodes collection -parentNode1.Nodes.Remove(childNode) -parentNode2.Nodes.Add(childNode) - -```` - -{{endregion}} + + + + The highlights of the code snippet are the last three lines where a __RadTreeNode__ is created, added to the "First Parent", then added to the "Second Parent". The result is that the "Child Node" is moved to the nodes collection of the "Second Parent". @@ -70,61 +37,9 @@ In the sample code below, two parent nodes are created, a single node is added t ![WinForms RadTreeView Child Nodes](images/treeview-working-with-nodes-reordering-nodes002.png) -{{source=..\SamplesCS\TreeView\WorkingWithNodes\WorkingWithNodes1.cs region=insertingNodes}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\WorkingWithNodes1.vb region=insertingNodes}} - -````C# -// Create two parent nodes -RadTreeNode parentNode1 = new RadTreeNode("First Parent"); -RadTreeNode parentNode2 = new RadTreeNode("Second Parent"); -// Add the parent nodes to tree view's nodes collection -this.radTreeView1.Nodes.Add(parentNode1); -this.radTreeView1.Nodes.Add(parentNode2); -// Create child nodes -RadTreeNode childNode = new RadTreeNode("Child Node"); -RadTreeNode childNode2 = new RadTreeNode("Child Node2"); -RadTreeNode childNode3 = new RadTreeNode("Child Node3"); -RadTreeNode childNode4 = new RadTreeNode("Child Node4"); -RadTreeNode childNode5 = new RadTreeNode("Child Node5"); -// Add a single child node to the parentNode1 nodes collection and -// multiple nodes to the parentNode2 nodes collection -parentNode1.Nodes.Add(childNode); -parentNode2.Nodes.Add(childNode2); -parentNode2.Nodes.Add(childNode3); -parentNode2.Nodes.Add(childNode4); -parentNode2.Nodes.Add(childNode5); -// Insert the childNode instance to the parentNode2 nodes collection -parentNode1.Nodes.Remove(childNode); -parentNode2.Nodes.Insert(1, childNode); - -```` -````VB.NET -' Create two parent nodes -Dim parentNode1 As New RadTreeNode("First Parent") -Dim parentNode2 As New RadTreeNode("Second Parent") -' Add the parent nodes to tree view's nodes collection -Me.RadTreeView1.Nodes.Add(parentNode1) -Me.RadTreeView1.Nodes.Add(parentNode2) -' Create child nodes -Dim childNode As New RadTreeNode("Child Node") -Dim childNode2 As New RadTreeNode("Child Node2") -Dim childNode3 As New RadTreeNode("Child Node3") -Dim childNode4 As New RadTreeNode("Child Node4") -Dim childNode5 As New RadTreeNode("Child Node5") -' Add a single child node to the parentNode1 nodes collection and -' multiple nodes to the parentNode2 nodes collection -parentNode1.Nodes.Add(childNode) -parentNode2.Nodes.Add(childNode2) -parentNode2.Nodes.Add(childNode3) -parentNode2.Nodes.Add(childNode4) -parentNode2.Nodes.Add(childNode5) -' Insert the childNode instance to the parentNode2 nodes collection -parentNode1.Nodes.Remove(childNode) -parentNode2.Nodes.Insert(1, childNode) - -```` - -{{endregion}} + + + # See Also diff --git a/controls/treeview/working-with-nodes/selecting-nodes.md b/controls/treeview/working-with-nodes/selecting-nodes.md index fd0606a53..ce7c867e7 100644 --- a/controls/treeview/working-with-nodes/selecting-nodes.md +++ b/controls/treeview/working-with-nodes/selecting-nodes.md @@ -15,19 +15,10 @@ previous_url: treeview-working-with-nodes-selecting-nodes To select a node use the __Selected__ property of __RadTreeNode__. The following example demonstrates how to do it. -{{source=..\SamplesCS\TreeView\WorkingWithNodes\WorkingWithNodes1.cs region=selectedNode}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\WorkingWithNodes1.vb region=selectedNode}} + + -````C# -radTreeView1.SelectedNode = radTreeView1.Nodes[0]; -```` -````VB.NET -RadTreeView1.SelectedNode = RadTreeView1.Nodes(0) - -```` - -{{endregion}} ## Selecting Multiple Nodes @@ -44,93 +35,26 @@ To enable the multiple selection the __MultiSelect__ property must be set to *tr To select multiple nodes through the API, just set the Selected property of the desired nodes to true. The example below adds four nodes, then selects the last two nodes. -{{source=..\SamplesCS\TreeView\WorkingWithNodes\WorkingWithNodes1.cs region=selectMultiNodes}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\WorkingWithNodes1.vb region=selectMultiNodes}} - -````C# -radTreeView1.MultiSelect = true; -RadTreeNode Node1 = new RadTreeNode("Inbox"); -RadTreeNode Node2 = new RadTreeNode("Deleted Items"); -RadTreeNode Node3 = new RadTreeNode("Outbox"); -RadTreeNode Node4 = new RadTreeNode("Sent"); -radTreeView1.Nodes.Add(Node1); -radTreeView1.Nodes.Add(Node2); -radTreeView1.Nodes.Add(Node3); -radTreeView1.Nodes.Add(Node4); -Node3.Selected = true; -Node4.Selected = true; - -```` -````VB.NET -RadTreeView1.MultiSelect = True -Dim Node1 As New RadTreeNode("Inbox") -Dim Node2 As New RadTreeNode("Deleted Items") -Dim Node3 As New RadTreeNode("Outbox") -Dim Node4 As New RadTreeNode("Sent") -RadTreeView1.Nodes.Add(Node1) -RadTreeView1.Nodes.Add(Node2) -RadTreeView1.Nodes.Add(Node3) -RadTreeView1.Nodes.Add(Node4) -Node3.Selected = True -Node4.Selected = True - -```` - -{{endregion}} + + + + ## SelectedNodeChanged Event When multiple selection functionality is turned on, the __SelectedNodeChanged__ event will be called twice: first for the previously selected node first and one more time for the newly selected node. In the RadTreeViewEventArgs you can distinguish the two event firings by the __Action__ property which is set to __Unknown__ when the selection is cleared. -{{source=..\SamplesCS\TreeView\WorkingWithNodes\WorkingWithNodes1.cs region=selectedNodeEvent}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\WorkingWithNodes1.vb region=selectedNodeEvent}} + + -````C# -private void radTreeView1_SelectedNodeChanged(object sender, Telerik.WinControls.UI.RadTreeViewEventArgs e) -{ - if (e.Action != Telerik.WinControls.UI.RadTreeViewAction.ByMouse) - { - Console.WriteLine(e.Node.Text); - } -} -```` -````VB.NET -Private Sub RadTreeView1_SelectedNodeChanged(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.RadTreeViewEventArgs) - If e.Action <> Telerik.WinControls.UI.RadTreeViewAction.ByMouse Then - Console.WriteLine(e.Node.Text) - End If -End Sub -```` +Another approach will be to check the __Selected__ property of the node. If it is true, execute your logic. -{{endregion}} + + -Another approach will be to check the __Selected__ property of the node. If it is true, execute your logic. -{{source=..\SamplesCS\TreeView\WorkingWithNodes\WorkingWithNodes1.cs region=selectedPropertyOfTheNode}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\WorkingWithNodes1.vb region=selectedPropertyOfTheNode}} - -````C# -private void radTreeView2_SelectedNodeChanged(object sender, RadTreeViewEventArgs e) -{ - if (e.Node.Selected == true) - { - Console.WriteLine(e.Node.Text); - } -} - -```` -````VB.NET -Private Sub RadTreeView2_SelectedNodeChanged(ByVal sender As Object, ByVal e As RadTreeViewEventArgs) - If e.Node.Selected = True Then - Console.WriteLine(e.Node.Text) - End If -End Sub - -```` - -{{endregion}} # See Also * [Adding and Removing Nodes]({%slug winforms/treeview/working-with-nodes/adding-and-removing-nodes%}) diff --git a/controls/treeview/working-with-nodes/sorting-nodes.md b/controls/treeview/working-with-nodes/sorting-nodes.md index c18413143..30e84dbcb 100644 --- a/controls/treeview/working-with-nodes/sorting-nodes.md +++ b/controls/treeview/working-with-nodes/sorting-nodes.md @@ -20,19 +20,10 @@ For example, if we have this RadTreeView instance: and we set the __SortOrder__ as shown below: -{{source=..\SamplesCS\TreeView\WorkingWithNodes\WorkingWithNodes1.cs region=sort}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\WorkingWithNodes1.vb region=sort}} + + -````C# -this.radTreeView1.SortOrder = SortOrder.Ascending; -```` -````VB.NET -Me.RadTreeView1.SortOrder = SortOrder.Ascending - -```` - -{{endregion}} we will get this look of RadTreeView at the end: diff --git a/controls/treeview/working-with-nodes/tooltips.md b/controls/treeview/working-with-nodes/tooltips.md index 34ac6708d..e5798b2d8 100644 --- a/controls/treeview/working-with-nodes/tooltips.md +++ b/controls/treeview/working-with-nodes/tooltips.md @@ -14,64 +14,26 @@ position: 15 To enable the tooltips you need to set the __ShowNodeToolTips__ property. -{{source=..\SamplesCS\TreeView\WorkingWithNodes\NodesTooltips.cs region=Unlock}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\NodesTooltips.vb region=Unlock}} -````C# -radTreeView1.TreeViewElement.ShowNodeToolTips = true; + + -```` -````VB.NET -radTreeView1.TreeViewElement.ShowNodeToolTips = True -```` - - -{{endregion}} ### Setting Tooltips You can directly assign a tooltip to each node in RadTreeView. -{{source=..\SamplesCS\TreeView\WorkingWithNodes\NodesTooltips.cs region=SetTooltip}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\NodesTooltips.vb region=SetTooltip}} -````C# -radTreeView1.Nodes[3].ToolTipText = "Node 3"; - -```` -````VB.NET -radTreeView1.Nodes(3).ToolTipText = "Node 3" - -```` + + -{{endregion}} ### Using the ToolTipTextNeeded event You can dynamically set the tooltips at runtime. This is achieved by using the __ToolTipTextNeeded__ event. -{{source=..\SamplesCS\TreeView\WorkingWithNodes\NodesTooltips.cs region=AtRuntime}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\NodesTooltips.vb region=AtRuntime}} -````C# -private void RadTreeView1_ToolTipTextNeeded(object sender, Telerik.WinControls.ToolTipTextNeededEventArgs e) -{ - var node = sender as TreeNodeElement; - if (node != null) - { - e.ToolTipText = node.Data.Text; - } -} - -```` -````VB.NET -Private Sub RadTreeView1_ToolTipTextNeeded(ByVal sender As Object, ByVal e As Telerik.WinControls.ToolTipTextNeededEventArgs) - Dim node = TryCast(sender, TreeNodeElement) - If node IsNot Nothing Then - e.ToolTipText = node.Data.Text - End If -End Sub - -```` - - -{{endregion}} + + + + + diff --git a/controls/treeview/working-with-nodes/treenode-text-value.md b/controls/treeview/working-with-nodes/treenode-text-value.md index 4823a0c91..1c401efb5 100644 --- a/controls/treeview/working-with-nodes/treenode-text-value.md +++ b/controls/treeview/working-with-nodes/treenode-text-value.md @@ -27,33 +27,10 @@ The property has the following values: * **TextAndValue**: When the user performs edit, both the Text and the Value will be changed. -{{source=..\SamplesCS\TreeView\WorkingWithNodes\WorkingWithNodes1.cs region=UnboundTextValue}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\WorkingWithNodes1.vb region=UnboundTextValue}} + + -````C# -RadTreeNode node = new RadTreeNode(); -node.Text = "Text"; -node.Value = "Value"; -this.radTreeView1.Nodes.Add(node); - -this.radTreeView1.AllowEdit = true; -this.radTreeView1.TreeViewElement.EditMode = TreeNodeEditMode.Value; - - -```` -````VB.NET -Dim node As RadTreeNode = New RadTreeNode() -node.Text = "Text" -node.Value = "Value" -Me.RadTreeView1.Nodes.Add(node) -Me.RadTreeView1.AllowEdit = True -Me.RadTreeView1.TreeViewElement.EditMode = TreeNodeEditMode.Value - - -```` - -{{endregion}} ### Specifying Text and Value in bound mode diff --git a/controls/treeview/working-with-nodes/using-checkboxes.md b/controls/treeview/working-with-nodes/using-checkboxes.md index 0a1945bca..5ae360f2b 100644 --- a/controls/treeview/working-with-nodes/using-checkboxes.md +++ b/controls/treeview/working-with-nodes/using-checkboxes.md @@ -33,37 +33,10 @@ __RadTreeView__ the supports option trees that allows radio buttons and check b ![WinForms RadTreeView Option Tree Support](images/treeview-working-with-nodes-using-checkboxes003.png) -{{source=..\SamplesCS\TreeView\WorkingWithNodes\WorkingWithNodes1.cs region=optionList}} -{{source=..\SamplesVB\TreeView\WorkingWithNodes\WorkingWithNodes1.vb region=optionList}} - -````C# -RadTreeNode Node1 = new RadTreeNode("Node1"); -Node1.Expanded = true; -Node1.CheckType = CheckType.RadioButton; -RadTreeNode Node2 = new RadTreeNode("Node2"); -RadTreeNode Node3 = new RadTreeNode("Node3"); -RadTreeNode Node4 = new RadTreeNode("Node4"); -radTreeView1.Nodes.Add(Node1); -radTreeView1.Nodes.Add(Node2); -Node1.Nodes.Add(Node3); -Node1.Nodes.Add(Node4); - -```` -````VB.NET -Dim Node1 As New RadTreeNode("Node1") -Node1.Expanded = True -Node1.CheckType = ChildListType.OptionList -Dim Node2 As New RadTreeNode("Node2") -Dim Node3 As New RadTreeNode("Node3") -Dim Node4 As New RadTreeNode("Node4") -RadTreeView1.Nodes.Add(Node1) -RadTreeView1.Nodes.Add(Node2) -Node1.Nodes.Add(Node3) -Node1.Nodes.Add(Node4) - -```` - -{{endregion}} + + + + # See Also * [Adding and Removing Nodes]({%slug winforms/treeview/working-with-nodes/adding-and-removing-nodes%}) diff --git a/controls/validation-provider/customizing-error-indication.md b/controls/validation-provider/customizing-error-indication.md index eb9096127..f2f4ef3b8 100644 --- a/controls/validation-provider/customizing-error-indication.md +++ b/controls/validation-provider/customizing-error-indication.md @@ -33,71 +33,10 @@ In addition, the **ControlValidation** event is fired. The **RadValidationEventA The **ToolTip** argument is represented by System.Windows.Forms.[ToolTip](https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.tooltip?view=netcore-3.1). Hence, in order to change its font, fill color, etc, we will follow a standard approach with enabling the [OwnerDraw](https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.tooltip.ownerdraw?view=netcore-3.1) property: -{{source=..\SamplesCS\ValidationProvider\ValidationProviderGettingStarted.cs region=CustomizingErrorIndication}} -{{source=..\SamplesVB\ValidationProvider\ValidationProviderGettingStarted.vb region=CustomizingErrorIndication}} + + -````C# -private void radValidationProvider1_ControlValidation(object sender, RadValidationEventArgs e) -{ - e.ToolTip = new ToolTip(); - e.ToolTip.OwnerDraw = true; - e.ToolTip.Draw += ToolTip_Draw; - e.ToolTip.Popup += ToolTip_Popup; - toolTipText = e.ValidationRule.ToolTipText; -} - -private void ToolTip_Popup(object sender, PopupEventArgs e) -{ - Graphics g = e.AssociatedControl.CreateGraphics(); - Size preferredSize = g.MeasureString(toolTipText, f).ToSize(); - e.ToolTipSize = preferredSize; - g.Dispose(); -} - -Font f = new Font("Arial", 16.0f); -string toolTipText = string.Empty; -private void ToolTip_Draw(object sender, DrawToolTipEventArgs e) -{ - ToolTip toolTip = sender as ToolTip; - toolTip.BackColor = System.Drawing.Color.Green; - e.DrawBackground(); - e.DrawBorder(); - e.Graphics.DrawString(e.ToolTipText, f, Brushes.Pink, new PointF(1, 1)); -} - - -```` -````VB.NET -Private Sub radValidationProvider1_ControlValidation(ByVal sender As Object, ByVal e As RadValidationEventArgs) - e.ToolTip = New ToolTip() - e.ToolTip.OwnerDraw = True - AddHandler e.ToolTip.Draw, AddressOf ToolTip_Draw - AddHandler e.ToolTip.Popup, AddressOf ToolTip_Popup - toolTipText = e.ValidationRule.ToolTipText -End Sub - -Private Sub ToolTip_Popup(ByVal sender As Object, ByVal e As PopupEventArgs) - Dim g As Graphics = e.AssociatedControl.CreateGraphics() - Dim preferredSize As Size = g.MeasureString(toolTipText, f).ToSize() - e.ToolTipSize = preferredSize - g.Dispose() -End Sub - -Private f As Font = New Font("Arial", 16.0F) -Private toolTipText As String = String.Empty - -Private Sub ToolTip_Draw(ByVal sender As Object, ByVal e As DrawToolTipEventArgs) - Dim toolTip As ToolTip = TryCast(sender, ToolTip) - toolTip.BackColor = System.Drawing.Color.Green - e.DrawBackground() - e.DrawBorder() - e.Graphics.DrawString(e.ToolTipText, f, Brushes.Pink, New PointF(1, 1)) -End Sub - -```` - -{{endregion}} ![WinForms RadValidationProvider ValidationProviderGettingStarted](images/validation-provider-customizing-error-indication002.png) diff --git a/controls/validation-provider/validation-rules.md b/controls/validation-provider/validation-rules.md index d1728a14d..c08a52798 100644 --- a/controls/validation-provider/validation-rules.md +++ b/controls/validation-provider/validation-rules.md @@ -33,34 +33,10 @@ The following code snippet demonstrates how to add a validation rule ensuring th ![WinForms RadValidationProvider with RadTextBox](images/validation-provider-validation-rules001.png) -{{source=..\SamplesCS\ValidationProvider\ValidationProviderGettingStarted.cs region=SimpleRule}} -{{source=..\SamplesVB\ValidationProvider\ValidationProviderGettingStarted.vb region=SimpleRule}} + + -````C# -RadValidationRule radValidationRule1 = new RadValidationRule(); -radValidationRule1.AutoToolTip = true; -radValidationRule1.Controls.Add(this.radTextBox1); -radValidationRule1.Operator = Telerik.WinControls.Data.FilterOperator.IsNotLike; -radValidationRule1.ToolTipText = "Location can\'t be empty!"; -radValidationRule1.Value = ""; -radValidationProvider1.ValidationRules.Add(radValidationRule1); - - -```` -````VB.NET -Dim radValidationRule1 As RadValidationRule = New RadValidationRule() -radValidationRule1.AutoToolTip = True -radValidationRule1.Controls.Add(Me.RadTextBox1) -radValidationRule1.[Operator] = Telerik.WinControls.Data.FilterOperator.IsNotLike -radValidationRule1.ToolTipText = "Location can't be empty!" -radValidationRule1.Value = "" -radValidationProvider1.ValidationRules.Add(radValidationRule1) - - -```` - -{{endregion}} ## RadValidationRuleWithTargetControl @@ -79,77 +55,17 @@ The following rule will ensure that the first **RadDateTimePicker**'s value is l ![WinForms RadValidationProvider with RadDateTimePicker LessThan](images/validation-provider-validation-rules002.png) -{{source=..\SamplesCS\ValidationProvider\ValidationProviderGettingStarted.cs region=SecondControl}} -{{source=..\SamplesVB\ValidationProvider\ValidationProviderGettingStarted.vb region=SecondControl}} - -````C# - - RadValidationRuleWithTargetControl radValidationRuleWithTargetControl1 = new RadValidationRuleWithTargetControl(); - radValidationRuleWithTargetControl1.AutoToolTip = true; - radValidationRuleWithTargetControl1.Controls.Add(this.radDateTimePicker1); - radValidationRuleWithTargetControl1.Operator = Telerik.WinControls.Data.FilterOperator.IsLessThan; - radValidationRuleWithTargetControl1.PropertyName = "Value"; - radValidationRuleWithTargetControl1.TargetControl = this.radDateTimePicker2; - radValidationRuleWithTargetControl1.TargetControlPropertyName = "Value"; - radValidationRuleWithTargetControl1.ToolTipText = "Start date should be less than End date!"; - - radValidationProvider1.ValidationRules.Add(radValidationRuleWithTargetControl1); - + + -```` -````VB.NET - Dim radValidationRuleWithTargetControl1 As RadValidationRuleWithTargetControl = New RadValidationRuleWithTargetControl() - radValidationRuleWithTargetControl1.AutoToolTip = True - radValidationRuleWithTargetControl1.Controls.Add(Me.RadDateTimePicker1) - radValidationRuleWithTargetControl1.[Operator] = Telerik.WinControls.Data.FilterOperator.IsLessThan - radValidationRuleWithTargetControl1.PropertyName = "Value" - radValidationRuleWithTargetControl1.TargetControl = Me.RadDateTimePicker2 - radValidationRuleWithTargetControl1.TargetControlPropertyName = "Value" - radValidationRuleWithTargetControl1.ToolTipText = "Start date should be less than End date!" - radValidationProvider1.ValidationRules.Add(radValidationRuleWithTargetControl1) -```` - -{{endregion}} - In order to cover the case that the second **RadDateTimePicker** is greater than the first one, you will need to add one more **RadValidationRuleWithTargetControl**: ![WinForms RadValidationProvider with RadDateTimePicker GreaterThan](images/validation-provider-validation-rules003.png) -{{source=..\SamplesCS\ValidationProvider\ValidationProviderGettingStarted.cs region=TargetControl}} -{{source=..\SamplesVB\ValidationProvider\ValidationProviderGettingStarted.vb region=TargetControl}} - -````C# - - RadValidationRuleWithTargetControl radValidationRuleWithTargetControl2 = new RadValidationRuleWithTargetControl(); - radValidationRuleWithTargetControl2.AutoToolTip = true; - radValidationRuleWithTargetControl2.Controls.Add(this.radDateTimePicker2); - radValidationRuleWithTargetControl2.Operator = Telerik.WinControls.Data.FilterOperator.IsGreaterThan; - radValidationRuleWithTargetControl2.PropertyName = "Value"; - radValidationRuleWithTargetControl2.TargetControl = this.radDateTimePicker1; - radValidationRuleWithTargetControl2.TargetControlPropertyName = "Value"; - radValidationRuleWithTargetControl2.ToolTipText = "End date should be greater than Start date!"; - - radValidationProvider1.ValidationRules.Add(radValidationRuleWithTargetControl2); - - -```` -````VB.NET - - Dim radValidationRuleWithTargetControl2 As RadValidationRuleWithTargetControl = New RadValidationRuleWithTargetControl() - radValidationRuleWithTargetControl2.AutoToolTip = True - radValidationRuleWithTargetControl2.Controls.Add(Me.RadDateTimePicker2) - radValidationRuleWithTargetControl2.[Operator] = Telerik.WinControls.Data.FilterOperator.IsGreaterThan - radValidationRuleWithTargetControl2.PropertyName = "Value" - radValidationRuleWithTargetControl2.TargetControl = Me.RadDateTimePicker1 - radValidationRuleWithTargetControl2.TargetControlPropertyName = "Value" - radValidationRuleWithTargetControl2.ToolTipText = "End date should be greater than Start date!" - radValidationProvider1.ValidationRules.Add(radValidationRuleWithTargetControl2) - -```` - -{{endregion}} + + @@ -164,97 +80,10 @@ The following code snippet demonstrates how to define a **RadCompositeValidation None of the associated controls (e.g. radSpinEditor1) of a composite rule should be added as a target in any of the nested rules! Please be careful when defining composite rules in order to get the proper validation logic. Usually, it is even possible to simplify the validation logic and define separate **RadValidationRuleWithTargetControls** outside a composite rule. > -{{source=..\SamplesCS\ValidationProvider\ValidationProviderGettingStarted.cs region=CompositeRule}} -{{source=..\SamplesVB\ValidationProvider\ValidationProviderGettingStarted.vb region=CompositeRule}} - -````C# - this.radSpinEditor2.Minimum = 0; - this.radSpinEditor2.Maximum = 10000; - this.radSpinEditor2.Value = 1000; - - this.radSpinEditor3.Minimum = 0; - this.radSpinEditor3.Maximum = 10000; - this.radSpinEditor3.Value = 10000; - - this.radSpinEditor1.Maximum = 10000; - - RadCompositeValidationRule compositeValidationRule = new RadCompositeValidationRule(); - compositeValidationRule.LogicalOperator = Telerik.WinControls.Data.FilterLogicalOperator.And; - compositeValidationRule.ToolTipText = "Car price should be greater than Minimum and less than Maximum price!"; - - RadValidationRuleWithTargetControl radValidationRuleWithTargetControl1 = new RadValidationRuleWithTargetControl(); - radValidationRuleWithTargetControl1.AutoToolTip = true; - radValidationRuleWithTargetControl1.PropertyName = "Value"; - radValidationRuleWithTargetControl1.AddControl(this.radSpinEditor1); - radValidationRuleWithTargetControl1.Operator = Telerik.WinControls.Data.FilterOperator.IsGreaterThan; - radValidationRuleWithTargetControl1.TargetControl = this.radSpinEditor2; - radValidationRuleWithTargetControl1.TargetControlPropertyName = "Value"; - - compositeValidationRule.ValidationRules.Add(radValidationRuleWithTargetControl1); + + - RadValidationRuleWithTargetControl radValidationRuleWithTargetControl2 = new RadValidationRuleWithTargetControl(); - radValidationRuleWithTargetControl2.AutoToolTip = true; - radValidationRuleWithTargetControl2.PropertyName = "Value"; - radValidationRuleWithTargetControl2.AddControl(this.radSpinEditor1); - radValidationRuleWithTargetControl2.Operator = Telerik.WinControls.Data.FilterOperator.IsLessThan; - radValidationRuleWithTargetControl2.TargetControl = this.radSpinEditor3; - radValidationRuleWithTargetControl2.TargetControlPropertyName = "Value"; - compositeValidationRule.ValidationRules.Add(radValidationRuleWithTargetControl2); - - RadValidationRule radValidationRule3 = new RadValidationRule(); - radValidationRule3.AutoToolTip = true; - radValidationRule3.AddControl(this.radSpinEditor1); - radValidationRule3.PropertyName = "Value"; - radValidationRule3.Operator = Telerik.WinControls.Data.FilterOperator.IsNotEqualTo; - radValidationRule3.Value = 5000; - - compositeValidationRule.ValidationRules.Add(radValidationRule3); - - this.radValidationProvider1.ValidationRules.Add(compositeValidationRule); - - -```` -````VB.NET - - Me.radSpinEditor2.Minimum = 0 - Me.radSpinEditor2.Maximum = 10000 - Me.radSpinEditor2.Value = 1000 - Me.radSpinEditor3.Minimum = 0 - Me.radSpinEditor3.Maximum = 10000 - Me.radSpinEditor3.Value = 10000 - Me.radSpinEditor1.Maximum = 10000 - Dim compositeValidationRule As RadCompositeValidationRule = New RadCompositeValidationRule() - compositeValidationRule.LogicalOperator = Telerik.WinControls.Data.FilterLogicalOperator.[And] - compositeValidationRule.ToolTipText = "Car price should be greater than Minimum and less than Maximum price!" - Dim radValidationRuleWithTargetControl1 As RadValidationRuleWithTargetControl = New RadValidationRuleWithTargetControl() - radValidationRuleWithTargetControl1.AutoToolTip = True - radValidationRuleWithTargetControl1.PropertyName = "Value" - radValidationRuleWithTargetControl1.AddControl(Me.radSpinEditor1) - radValidationRuleWithTargetControl1.[Operator] = Telerik.WinControls.Data.FilterOperator.IsGreaterThan - radValidationRuleWithTargetControl1.TargetControl = Me.radSpinEditor2 - radValidationRuleWithTargetControl1.TargetControlPropertyName = "Value" - compositeValidationRule.ValidationRules.Add(radValidationRuleWithTargetControl1) - Dim radValidationRuleWithTargetControl2 As RadValidationRuleWithTargetControl = New RadValidationRuleWithTargetControl() - radValidationRuleWithTargetControl2.AutoToolTip = True - radValidationRuleWithTargetControl2.PropertyName = "Value" - radValidationRuleWithTargetControl2.AddControl(Me.radSpinEditor1) - radValidationRuleWithTargetControl2.[Operator] = Telerik.WinControls.Data.FilterOperator.IsLessThan - radValidationRuleWithTargetControl2.TargetControl = Me.radSpinEditor3 - radValidationRuleWithTargetControl2.TargetControlPropertyName = "Value" - compositeValidationRule.ValidationRules.Add(radValidationRuleWithTargetControl2) - Dim radValidationRule3 As RadValidationRule = New RadValidationRule() - radValidationRule3.AutoToolTip = True - radValidationRule3.AddControl(Me.radSpinEditor1) - radValidationRule3.PropertyName = "Value" - radValidationRule3.[Operator] = Telerik.WinControls.Data.FilterOperator.IsNotEqualTo - radValidationRule3.Value = 5000 - compositeValidationRule.ValidationRules.Add(radValidationRule3) - Me.radValidationProvider1.ValidationRules.Add(compositeValidationRule) - -```` - -{{endregion}} ![WinForms RadValidationProvider between Minimum and Maximum](images/validation-provider-validation-rules004.png) @@ -283,61 +112,10 @@ You can add a **RadValidationRule** for empty Text for example and in addition t #### Custom Validation in the ControlValidation Event -{{source=..\SamplesCS\ValidationProvider\ValidationProviderGettingStarted.cs region=CustomValidation}} -{{source=..\SamplesVB\ValidationProvider\ValidationProviderGettingStarted.vb region=CustomValidation}} - -````C# - public void CustomValidation() - { - RadValidationRule radValidationRule1 = new RadValidationRule(); - radValidationRule1.AutoToolTip = true; - radValidationRule1.AddControl(this.radTextBox1); - radValidationRule1.Operator = Telerik.WinControls.Data.FilterOperator.IsNotLike; - radValidationRule1.PropertyName = "Text"; - radValidationRule1.ToolTipText = "Text is empty!"; - radValidationRule1.Value = ""; - - radValidationProvider1.ValidationRules.Add(radValidationRule1); - - this.radValidationProvider1.ControlValidation += radValidationProvider_ControlValidation; - } - private void radValidationProvider_ControlValidation(object sender, RadValidationEventArgs e) - { - if (e.Control == this.radTextBox1 && this.radTextBox1.Text != string.Empty && - this.radTextBox1.TextBoxElement.TextBoxItem.TextLength < 20) - { - e.ErrorText = "Text is less than 20 characters !"; - e.IsValid = false; - } - } - - -```` -````VB.NET - Public Sub CustomValidation() - Dim radValidationRule1 As RadValidationRule = New RadValidationRule() - radValidationRule1.AutoToolTip = True - radValidationRule1.AddControl(Me.RadTextBox1) - radValidationRule1.[Operator] = Telerik.WinControls.Data.FilterOperator.IsNotLike - radValidationRule1.PropertyName = "Text" - radValidationRule1.ToolTipText = "Text is empty!" - radValidationRule1.Value = "" - radValidationProvider1.ValidationRules.Add(radValidationRule1) - AddHandler Me.radValidationProvider1.ControlValidation, AddressOf radValidationProvider_ControlValidation - End Sub - - Private Sub radValidationProvider_ControlValidation(ByVal sender As Object, ByVal e As RadValidationEventArgs) - If e.Control.Equals(Me.RadTextBox1) AndAlso Me.RadTextBox1.Text <> String.Empty _ - AndAlso Me.RadTextBox1.TextBoxElement.TextBoxItem.TextLength < 20 Then - e.ErrorText = "Text is less than 20 characters !" - e.IsValid = False - End If - End Sub - - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/virtual-keyboard/customizing-appearance/accessing-and-customizing-elements.md b/controls/virtual-keyboard/customizing-appearance/accessing-and-customizing-elements.md index 737aab976..58f922419 100644 --- a/controls/virtual-keyboard/customizing-appearance/accessing-and-customizing-elements.md +++ b/controls/virtual-keyboard/customizing-appearance/accessing-and-customizing-elements.md @@ -20,51 +20,9 @@ The following code snippet demonstrates how to customize the `F1` button from th -{{source=..\SamplesCS\VirtualKeyboard\KeyboardGettingStarted.cs region=CustomizeKeys}} -{{source=..\SamplesVB\VirtualKeyboard\KeyboardGettingStarted.vb region=CustomizeKeys}} + + -````C# - -this.radVirtualKeyboard1.LayoutType = Telerik.WinControls.VirtualKeyboard.KeyboardLayoutType.Extended; -ExtendedVirtualKeyboardLayoutPanel extendedKeyboard = radVirtualKeyboard1.MainLayoutPanel as ExtendedVirtualKeyboardLayoutPanel; -VirtualKeyboardLayout functionsLayout = extendedKeyboard.FunctionButtonsLayout; -VirtualKeyboardLayout numpadLayout = extendedKeyboard.NumpadButtonsLayout; -Key key = functionsLayout.Rows[0].Keys[2] as Key; -key.BackColor = Color.Yellow; -key.BorderBoxStyle = BorderBoxStyle.SingleBorder; -key.BorderColor = Color.Red; -key.BorderGradientStyle = GradientStyles.Solid; -key = numpadLayout.Rows[1].Keys[3] as Key; -key.BackColor = Color.Fuchsia; -key.BorderBoxStyle = BorderBoxStyle.SingleBorder; -key.BorderColor = Color.Blue; -key.BorderGradientStyle = GradientStyles.Solid; - - -```` -````VB.NET - -Me.radVirtualKeyboard1.LayoutType = Telerik.WinControls.VirtualKeyboard.KeyboardLayoutType.Extended -Dim extendedKeyboard As ExtendedVirtualKeyboardLayoutPanel = TryCast(radVirtualKeyboard1.MainLayoutPanel, ExtendedVirtualKeyboardLayoutPanel) -Dim functionsLayout As VirtualKeyboardLayout = extendedKeyboard.FunctionButtonsLayout -Dim numpadLayout As VirtualKeyboardLayout = extendedKeyboard.NumpadButtonsLayout -Dim key As Key = TryCast(functionsLayout.Rows(0).Keys(2), Key) -key.BackColor = Color.Yellow -key.BorderBoxStyle = BorderBoxStyle.SingleBorder -key.BorderColor = Color.Red -key.BorderGradientStyle = GradientStyles.Solid -key = TryCast(numpadLayout.Rows(1).Keys(3), Key) -key.BackColor = Color.Fuchsia -key.BorderBoxStyle = BorderBoxStyle.SingleBorder -key.BorderColor = Color.Blue -key.BorderGradientStyle = GradientStyles.Solid - - -```` - -{{endregion}} - - # See Also diff --git a/controls/virtual-keyboard/default-layouts.md b/controls/virtual-keyboard/default-layouts.md index 1c5205118..e51044276 100644 --- a/controls/virtual-keyboard/default-layouts.md +++ b/controls/virtual-keyboard/default-layouts.md @@ -48,31 +48,10 @@ The following code snippet demonstrates how to add a **Z** button in the *Home* #### Adding a key to the default Home layout -{{source=..\SamplesCS\VirtualKeyboard\KeyboardGettingStarted.cs region=AddKeyToHome}} -{{source=..\SamplesVB\VirtualKeyboard\KeyboardGettingStarted.vb region=AddKeyToHome}} - -````C# -radVirtualKeyboard1.LayoutType = Telerik.WinControls.VirtualKeyboard.KeyboardLayoutType.Extended; -ExtendedVirtualKeyboardLayoutPanel extendedLayoutPanel = radVirtualKeyboard1.MainLayoutPanel as ExtendedVirtualKeyboardLayoutPanel; -int keysRowIndex = 2; -int keyColSpan = 3; -int KeyRowSpan = 1; -extendedLayoutPanel.HomeButtonsLayout.Rows[keysRowIndex].Keys.Add(new Key((int)Keys.Z, KeyType.Normal, keyColSpan, KeyRowSpan)); -extendedLayoutPanel.ResetLayout(); - -```` -````VB.NET -Me.radVirtualKeyboard1.LayoutType = Telerik.WinControls.VirtualKeyboard.KeyboardLayoutType.Extended -Dim extendedLayoutPanel As ExtendedVirtualKeyboardLayoutPanel = TryCast(radVirtualKeyboard1.MainLayoutPanel, ExtendedVirtualKeyboardLayoutPanel) -Dim keysRowIndex As Integer = 2 -Dim keyColSpan As Integer = 3 -Dim KeyRowSpan As Integer = 1 -extendedLayoutPanel.HomeButtonsLayout.Rows(keysRowIndex).Keys.Add(New Key(CInt(Keys.Z), KeyType.Normal, keyColSpan, KeyRowSpan)) -extendedLayoutPanel.ResetLayout() - -```` - -{{endregion}} + + + + # See Also diff --git a/controls/virtual-keyboard/localization.md b/controls/virtual-keyboard/localization.md index a65e64ecf..6160fa155 100644 --- a/controls/virtual-keyboard/localization.md +++ b/controls/virtual-keyboard/localization.md @@ -22,194 +22,17 @@ Below is a sample implementation of an English localization provider: #### English localization provider -{{source=..\SamplesCS\VirtualKeyboard\VirtualKeyboardLocalization.cs region=Localization}} -{{source=..\SamplesVB\VirtualKeyboard\VirtualKeyboardLocalization.vb region=Localization}} - -````C# -public class EnglishVirtualKeyboardLocalizationProvider : VirtualKeyboardLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case VirtualKeyboardStringId.KeyEscape: return "Esc"; - case VirtualKeyboardStringId.KeyTab: return "Tab"; - case VirtualKeyboardStringId.KeyCapsLock: return "CapsLock"; - case VirtualKeyboardStringId.KeyLeftShift: return "Shift"; - case VirtualKeyboardStringId.KeyLeftControl: return "Ctrl"; - case VirtualKeyboardStringId.KeyLeftWin: return "Win"; - case VirtualKeyboardStringId.KeyAlt: return "Alt"; - case VirtualKeyboardStringId.KeySpace: return ""; - case VirtualKeyboardStringId.KeyAltGr: return "AltGr"; - case VirtualKeyboardStringId.KeyRightWin: return "Win"; - case VirtualKeyboardStringId.KeyRightControl: return "Ctrl"; - case VirtualKeyboardStringId.KeyRightShift: return "Shift"; - case VirtualKeyboardStringId.KeyEnter: return "Enter"; - case VirtualKeyboardStringId.KeyBackspace: return "Back"; - case VirtualKeyboardStringId.KeyNumLock: return "NumLock"; - case VirtualKeyboardStringId.KeyNumpadEnter: return "Enter"; - case VirtualKeyboardStringId.KeyInsert: return "Ins"; - case VirtualKeyboardStringId.KeyDelete: return "Del"; - case VirtualKeyboardStringId.KeyHome: return "Home"; - case VirtualKeyboardStringId.KeyEnd: return "End"; - case VirtualKeyboardStringId.KeyPageUp: return "PgUp"; - case VirtualKeyboardStringId.KeyPageDown: return "PgDn"; - case VirtualKeyboardStringId.KeyUp: return '\ue013'.ToString(); - case VirtualKeyboardStringId.KeyDown: return '\ue015'.ToString(); - case VirtualKeyboardStringId.KeyLeft: return '\ue016'.ToString(); - case VirtualKeyboardStringId.KeyRight: return '\ue014'.ToString(); - - case VirtualKeyboardStringId.KeyF1: return "F1"; - case VirtualKeyboardStringId.KeyF2: return "F2"; - case VirtualKeyboardStringId.KeyF3: return "F3"; - case VirtualKeyboardStringId.KeyF4: return "F4"; - case VirtualKeyboardStringId.KeyF5: return "F5"; - case VirtualKeyboardStringId.KeyF6: return "F6"; - case VirtualKeyboardStringId.KeyF7: return "F7"; - case VirtualKeyboardStringId.KeyF8: return "F8"; - case VirtualKeyboardStringId.KeyF9: return "F9"; - case VirtualKeyboardStringId.KeyF10: return "F10"; - case VirtualKeyboardStringId.KeyF11: return "F11"; - case VirtualKeyboardStringId.KeyF12: return "F12"; - - case VirtualKeyboardStringId.ErrorBoxTitle: return "Error!"; - case VirtualKeyboardStringId.ErrorFileNotFoundMessage: return "File not found!"; - case VirtualKeyboardStringId.ErrorLoadingLayoutMessage: return "Error loading layout!"; - - case VirtualKeyboardStringId.FormText: return "Virtual Keyboard"; - default: - return id; - } - } -} - - - -```` -````VB.NET - -Public Class EnglishVirtualKeyboardLocalizationProvider - Inherits VirtualKeyboardLocalizationProvider - - Public Overrides Function GetLocalizedString(ByVal id As String) As String - Select Case id - Case VirtualKeyboardStringId.KeyEscape - Return "Esc" - Case VirtualKeyboardStringId.KeyTab - Return "Tab" - Case VirtualKeyboardStringId.KeyCapsLock - Return "CapsLock" - Case VirtualKeyboardStringId.KeyLeftShift - Return "Shift" - Case VirtualKeyboardStringId.KeyLeftControl - Return "Ctrl" - Case VirtualKeyboardStringId.KeyLeftWin - Return "Win" - Case VirtualKeyboardStringId.KeyAlt - Return "Alt" - Case VirtualKeyboardStringId.KeySpace - Return "" - Case VirtualKeyboardStringId.KeyAltGr - Return "AltGr" - Case VirtualKeyboardStringId.KeyRightWin - Return "Win" - Case VirtualKeyboardStringId.KeyRightControl - Return "Ctrl" - Case VirtualKeyboardStringId.KeyRightShift - Return "Shift" - Case VirtualKeyboardStringId.KeyEnter - Return "Enter" - Case VirtualKeyboardStringId.KeyBackspace - Return "Back" - Case VirtualKeyboardStringId.KeyNumLock - Return "NumLock" - Case VirtualKeyboardStringId.KeyNumpadEnter - Return "Enter" - Case VirtualKeyboardStringId.KeyInsert - Return "Ins" - Case VirtualKeyboardStringId.KeyDelete - Return "Del" - Case VirtualKeyboardStringId.KeyHome - Return "Home" - Case VirtualKeyboardStringId.KeyEnd - Return "End" - Case VirtualKeyboardStringId.KeyPageUp - Return "PgUp" - Case VirtualKeyboardStringId.KeyPageDown - Return "PgDn" - Case VirtualKeyboardStringId.KeyUp - Return ""c.ToString() - Case VirtualKeyboardStringId.KeyDown - Return ""c.ToString() - Case VirtualKeyboardStringId.KeyLeft - Return ""c.ToString() - Case VirtualKeyboardStringId.KeyRight - Return ""c.ToString() - Case VirtualKeyboardStringId.KeyF1 - Return "F1" - Case VirtualKeyboardStringId.KeyF2 - Return "F2" - Case VirtualKeyboardStringId.KeyF3 - Return "F3" - Case VirtualKeyboardStringId.KeyF4 - Return "F4" - Case VirtualKeyboardStringId.KeyF5 - Return "F5" - Case VirtualKeyboardStringId.KeyF6 - Return "F6" - Case VirtualKeyboardStringId.KeyF7 - Return "F7" - Case VirtualKeyboardStringId.KeyF8 - Return "F8" - Case VirtualKeyboardStringId.KeyF9 - Return "F9" - Case VirtualKeyboardStringId.KeyF10 - Return "F10" - Case VirtualKeyboardStringId.KeyF11 - Return "F11" - Case VirtualKeyboardStringId.KeyF12 - Return "F12" - Case VirtualKeyboardStringId.ErrorBoxTitle - Return "Error!" - Case VirtualKeyboardStringId.ErrorFileNotFoundMessage - Return "File not found!" - Case VirtualKeyboardStringId.ErrorLoadingLayoutMessage - Return "Error loading layout!" - Case VirtualKeyboardStringId.FormText - Return "Virtual Keyboard" - Case Else - Return id - End Select - End Function -End Class - - -```` - -{{endregion}} + + -To apply the custom localization provider, instantiate and assign it to the current localization provider: - -#### Apply the custom provider - -{{source=..\SamplesCS\VirtualKeyboard\VirtualKeyboardLocalization.cs region=ApplyProvider}} -{{source=..\SamplesVB\VirtualKeyboard\VirtualKeyboardLocalization.vb region=ApplyProvider}} -````C# -VirtualKeyboardLocalizationProvider.CurrentProvider = new EnglishVirtualKeyboardLocalizationProvider(); - - -```` -````VB.NET -VirtualKeyboardLocalizationProvider.CurrentProvider = New EnglishVirtualKeyboardLocalizationProvider() +To apply the custom localization provider, instantiate and assign it to the current localization provider: -```` +#### Apply the custom provider -{{endregion}} + + - - - diff --git a/controls/virtual-keyboard/logical-keyboard-layout.md b/controls/virtual-keyboard/logical-keyboard-layout.md index 51d0989bb..5fe4e3e04 100644 --- a/controls/virtual-keyboard/logical-keyboard-layout.md +++ b/controls/virtual-keyboard/logical-keyboard-layout.md @@ -23,78 +23,19 @@ The **VirtualKeyboardLayout** offers a public **Rows** property which is an **Ob #### Accessing the logical layout and iterating the keys in the Home layout -{{source=..\SamplesCS\VirtualKeyboard\KeyboardGettingStarted.cs region=LogicalLayouts}} -{{source=..\SamplesVB\VirtualKeyboard\KeyboardGettingStarted.vb region=LogicalLayouts}} - -````C# -this.radVirtualKeyboard1.LayoutType = Telerik.WinControls.VirtualKeyboard.KeyboardLayoutType.Extended; -ExtendedVirtualKeyboardLayoutPanel extendedKeyboard = radVirtualKeyboard1.MainLayoutPanel as ExtendedVirtualKeyboardLayoutPanel; -VirtualKeyboardLayout simplifiedLayout = extendedKeyboard.MainButtonsLayout; -VirtualKeyboardLayout homeLayout = extendedKeyboard.HomeButtonsLayout; -VirtualKeyboardLayout numpadLayout = extendedKeyboard.NumpadButtonsLayout; -StringBuilder homeKeys = new StringBuilder(); -foreach (Row rows in homeLayout.Rows) - { - foreach (IKey key in rows.Keys) - { - Key k = key as Key; - if (k != null) - { - homeKeys.AppendLine(k.Text); - } - } - } - -RadMessageBox.Show(homeKeys.ToString()); - -```` -````VB.NET -Me.radVirtualKeyboard1.LayoutType = Telerik.WinControls.VirtualKeyboard.KeyboardLayoutType.Extended -Dim extendedKeyboard As ExtendedVirtualKeyboardLayoutPanel = TryCast(radVirtualKeyboard1.MainLayoutPanel, ExtendedVirtualKeyboardLayoutPanel) -Dim simplifiedLayout As VirtualKeyboardLayout = extendedKeyboard.MainButtonsLayout -Dim homeLayout As VirtualKeyboardLayout = extendedKeyboard.HomeButtonsLayout -Dim numpadLayout As VirtualKeyboardLayout = extendedKeyboard.NumpadButtonsLayout -Dim homeKeys As StringBuilder = New StringBuilder() -For Each rows As Row In homeLayout.Rows - For Each key As IKey In rows.Keys - Dim k As Key = TryCast(key, Key) - If k IsNot Nothing Then - homeKeys.AppendLine(k.Name) - End If - Next -Next - -RadMessageBox.Show(homeKeys.ToString()) - -```` - -{{endregion}} + + ->note As of **R3 2021 SP1** we introduced new API, the **GetAllRows** and **FindRowByKey** methods, which don't require knowing in which LayoutPanel and the exact row which is the owner of the key, to be able to remove it. -#### API for Adding/Removing keys -{{source=..\SamplesCS\VirtualKeyboard\KeyboardGettingStarted.cs region=AddRemoAPI}} -{{source=..\SamplesVB\VirtualKeyboard\KeyboardGettingStarted.vb region=AddRemoAPI}} +>note As of **R3 2021 SP1** we introduced new API, the **GetAllRows** and **FindRowByKey** methods, which don't require knowing in which LayoutPanel and the exact row which is the owner of the key, to be able to remove it. -````C# -var allKeys = this.radVirtualKeyboard1.MainLayoutPanel.GetAllKeys(); -Key Qkey = allKeys.FirstOrDefault(k => k.VirtualKey == (int)Keys.Q) as Key; -Row row = this.radVirtualKeyboard1.MainLayoutPanel.FindRowByKey(Qkey); -row.Keys.Remove(Qkey); -this.radVirtualKeyboard1.MainLayoutPanel.ResetLayout(true); +#### API for Adding/Removing keys -```` -````VB.NET -Dim allKeys = Me.radVirtualKeyboard1.MainLayoutPanel.GetAllKeys() -Dim Qkey As Key = TryCast(allKeys.FirstOrDefault(Function(k) k.VirtualKey = CInt(Keys.Q)), Key) -Dim row As Row = Me.radVirtualKeyboard1.MainLayoutPanel.FindRowByKey(Qkey) -row.Keys.Remove(Qkey) -Me.radVirtualKeyboard1.MainLayoutPanel.ResetLayout(True) + + -```` -{{endregion}} # See Also diff --git a/controls/virtual-keyboard/save-and-load-layout.md b/controls/virtual-keyboard/save-and-load-layout.md index 9d72039e9..a41f205be 100644 --- a/controls/virtual-keyboard/save-and-load-layout.md +++ b/controls/virtual-keyboard/save-and-load-layout.md @@ -18,76 +18,19 @@ Here is a sample demonstrating how you can implement a Save Layout button event #### Save custom defined layout -{{source=..\SamplesCS\VirtualKeyboard\KeyboardGettingStarted.cs region=Save}} -{{source=..\SamplesVB\VirtualKeyboard\KeyboardGettingStarted.vb region=Save}} + + -````C# -string s = "default.xml"; -SaveFileDialog dialog = new SaveFileDialog(); -dialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*"; -dialog.Title = "Select a xml file"; -if (dialog.ShowDialog() == DialogResult.OK) -{ - s = dialog.FileName; -} -this.radVirtualKeyboard1.SaveLayout(s); -```` -````VB.NET - -Dim s As String = "default.xml" -Dim dialog As SaveFileDialog = New SaveFileDialog() -dialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*" -dialog.Title = "Select a xml file" - -If dialog.ShowDialog() = DialogResult.OK Then - s = dialog.FileName -End If - -Me.radVirtualKeyboard1.SaveLayout(s) - -```` - -{{endregion}} - The code snippets below demonstrates how you can implement a Load Layout button event handler: #### Load custom defined layout -{{source=..\SamplesCS\VirtualKeyboard\KeyboardGettingStarted.cs region=Load}} -{{source=..\SamplesVB\VirtualKeyboard\KeyboardGettingStarted.vb region=Load}} - -````C# - -string s = "default.xml"; -OpenFileDialog dialog = new OpenFileDialog(); -dialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*"; -dialog.Title = "Select a xml file"; -if (dialog.ShowDialog() == DialogResult.OK) -{ - s = dialog.FileName; -} -this.radVirtualKeyboard1.LoadLayout(s); - - -```` -````VB.NET - -Dim s As String = "default.xml" -Dim dialog As OpenFileDialog = New OpenFileDialog() -dialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*" -dialog.Title = "Select a xml file" - -If dialog.ShowDialog() = DialogResult.OK Then - s = dialog.FileName -End If - -Me.radVirtualKeyboard1.LoadLayout(s) + + -```` -{{endregion}} **RadVirtualKeyboard** provides three overloads for the **SaveLayout** and **LoadLayout** methods: diff --git a/controls/virtual-keyboard/virtual-keyboard-form.md b/controls/virtual-keyboard/virtual-keyboard-form.md index a8f95425a..c196e8af1 100644 --- a/controls/virtual-keyboard/virtual-keyboard-form.md +++ b/controls/virtual-keyboard/virtual-keyboard-form.md @@ -25,38 +25,11 @@ The following tutorial will demonstrate how to associate a **RadVirtualKeyboardF #### Associated grid editor with RadVirtualKeyboardForm -{{source=..\SamplesCS\VirtualKeyboard\KeyboardGettingStarted.cs region=AssociatedGridEditor}} -{{source=..\SamplesVB\VirtualKeyboard\KeyboardGettingStarted.vb region=AssociatedGridEditor}} + + -````C# - private void radGridView1_CellEditorInitialized(object sender, GridViewCellEventArgs e) - { - RadTextBoxEditor editor = e.ActiveEditor as RadTextBoxEditor; - if (editor != null) - { - RadTextBoxEditorElement element = editor.EditorElement as RadTextBoxEditorElement; - this.radVirtualKeyboardForm1.SetAssociatedKeyboardType(element.TextBoxItem.HostedControl, AssociatedKeyboardType.AssociatedControl); - } - } -```` -````VB.NET - - Private Sub radGridView1_CellEditorInitialized(ByVal sender As Object, ByVal e As GridViewCellEventArgs) - Dim editor As RadTextBoxEditor = TryCast(e.ActiveEditor, RadTextBoxEditor) - - If editor IsNot Nothing Then - Dim element As RadTextBoxEditorElement = TryCast(editor.EditorElement, RadTextBoxEditorElement) - Me.RadVirtualKeyboardForm1.SetAssociatedKeyboardType(element.TextBoxItem.HostedControl, AssociatedKeyboardType.AssociatedControl) - End If - End Sub - -```` - -{{endregion}} - - >note It is possible to associate a **RadTextBox** or any input control with the **RadVirtualKeyboardForm** by setting the **AssociatedKeyboardType** property of the respective input control. In other words, set the RadTextBox.**AssociatedKeyboardType** property to *AssociatedControl*. Thus, the **RadTextBox** control is associated with the virtual keyboard. When the control gets focus, the keyboard will be shown. # Methods diff --git a/controls/virtualgrid/end-user-capabilities/resizing-rows.md b/controls/virtualgrid/end-user-capabilities/resizing-rows.md index c5a6abcb8..e36416b22 100644 --- a/controls/virtualgrid/end-user-capabilities/resizing-rows.md +++ b/controls/virtualgrid/end-user-capabilities/resizing-rows.md @@ -12,20 +12,10 @@ position: 5 __RadVirtualGrid__ exposes an API allowing resizing of its rows. In order to utilize it we need to set the __AllowRowResize__ property to *true*. -{{source=..\SamplesCS\VirtualGrid\Rows\VirtualGridResizingRows.cs region=AllowRowResize}} -{{source=..\SamplesVB\VirtualGrid\Rows\VirtualGridResizingRows.vb region=AllowRowResize}} -````C# -this.radVirtualGrid1.AllowRowResize = true; + + -```` -````VB.NET -Me.RadVirtualGrid1.AllowRowResize = True -```` - - - -{{endregion}} The grid rows can be resized by end users simply by positioning the mouse over the horizontal grid line and dragging it to a desired size. diff --git a/controls/virtualgrid/features/busy-indicators.md b/controls/virtualgrid/features/busy-indicators.md index 624087e1e..8e1d67e5a 100644 --- a/controls/virtualgrid/features/busy-indicators.md +++ b/controls/virtualgrid/features/busy-indicators.md @@ -22,20 +22,9 @@ While this indicator is shown the entire grid is disabled. It is useful when the The following snippet shows how you can show/hide the waiting bar: -{{source=..\SamplesCS\VirtualGrid\VirtualGridWaitingIndicators.cs region=WaitingBar}} -{{source=..\SamplesVB\VirtualGrid\VirtualGridWaitingIndicators.vb region=WaitingBar}} -````C# -radVirtualGrid1.MasterViewInfo.IsWaiting = true; -radVirtualGrid1.MasterViewInfo.IsWaiting = false; + + -```` -````VB.NET -radVirtualGrid1.MasterViewInfo.IsWaiting = True -radVirtualGrid1.MasterViewInfo.IsWaiting = False - -```` - -{{endregion}} ## Waiting icon @@ -49,20 +38,10 @@ The waiting icon can be shown in each row header. With it you can indicate that The following snippet shows how you can show/hide the waiting icon: -{{source=..\SamplesCS\VirtualGrid\VirtualGridWaitingIndicators.cs region=icon}} -{{source=..\SamplesVB\VirtualGrid\VirtualGridWaitingIndicators.vb region=icon}} -````C# -radVirtualGrid1.MasterViewInfo.StartRowWaiting(5); -radVirtualGrid1.MasterViewInfo.StopRowWaiting(5); - -```` -````VB.NET -radVirtualGrid1.MasterViewInfo.StartRowWaiting(5) -radVirtualGrid1.MasterViewInfo.StopRowWaiting(5) + + -```` -{{endregion}} # See Also * [Copy/Paste/Cut]({%slug winforms/virtualgrid/copy-paste-cut%}) diff --git a/controls/virtualgrid/features/context-menu/context-menu.md b/controls/virtualgrid/features/context-menu/context-menu.md index 78e885fd9..f407540a0 100644 --- a/controls/virtualgrid/features/context-menu/context-menu.md +++ b/controls/virtualgrid/features/context-menu/context-menu.md @@ -28,43 +28,18 @@ You can control whether the context menu will be displayed by the __AllowColumnH #### Disable context menu for data cells -{{source=..\SamplesCS\VirtualGrid\ContextMenu\VirtualGridContextMenu.cs region=CellContextMenu}} -{{source=..\SamplesVB\VirtualGrid\ContextMenu\VirtualGridContextMenu.vb region=CellContextMenu}} + + -````C# - -this.radVirtualGrid1.AllowCellContextMenu = false; -```` -````VB.NET -Me.RadVirtualGrid1.AllowCellContextMenu = False - -```` - -{{endregion}} #### Disable context menu for header cells -{{source=..\SamplesCS\VirtualGrid\ContextMenu\VirtualGridContextMenu.cs region=HeaderContextMenu}} -{{source=..\SamplesVB\VirtualGrid\ContextMenu\VirtualGridContextMenu.vb region=HeaderContextMenu}} - -````C# - -this.radVirtualGrid1.AllowColumnHeaderContextMenu = false; - -```` -````VB.NET -Me.RadVirtualGrid1.AllowColumnHeaderContextMenu = False - -```` + + -{{endregion}} - - - - # See Also * [Custom Context Menu]({%slug winforms/virtualgrid/context-menu/custom-context-menu%}) diff --git a/controls/virtualgrid/features/context-menu/custom-context-menu.md b/controls/virtualgrid/features/context-menu/custom-context-menu.md index b93b19422..e783e7552 100644 --- a/controls/virtualgrid/features/context-menu/custom-context-menu.md +++ b/controls/virtualgrid/features/context-menu/custom-context-menu.md @@ -18,85 +18,19 @@ Start by creating a __RadContextMenu__, initializing its items, and subscribing #### Create a RadContextMenu and initialize its items -{{source=..\SamplesCS\VirtualGrid\ContextMenu\VirtualGridContextMenu.cs region=InitializeContextMenu}} -{{source=..\SamplesVB\VirtualGrid\ContextMenu\VirtualGridContextMenu.vb region=InitializeContextMenu}} - -````C# - -RadContextMenu contextMenu = new RadContextMenu(); - -public VirtualGridContextMenu() -{ - InitializeComponent(); - - RadMenuItem menuItem1 = new RadMenuItem("Item 1"); - menuItem1.ForeColor = Color.Red; - menuItem1.Click += menuItem1_Click; - RadMenuItem menuItem2 = new RadMenuItem("Item 2"); - menuItem2.Click += menuItem2_Click; - contextMenu.Items.Add(menuItem1); - contextMenu.Items.Add(menuItem2); - this.radVirtualGrid1.ContextMenuOpening += radVirtualGrid1_ContextMenuOpening; -} - -private void menuItem1_Click(object sender, EventArgs e) -{ - RadMessageBox.Show("Item1"); -} - -private void menuItem2_Click(object sender, EventArgs e) -{ - RadMessageBox.Show("Item2"); -} - -```` -````VB.NET -Private contextMenu As New RadContextMenu() -Public Sub New() - InitializeComponent() - Dim menuItem1 As New RadMenuItem("Item 1") - menuItem1.ForeColor = Color.Red - AddHandler menuItem1.Click, AddressOf menuItem1_Click - Dim menuItem2 As New RadMenuItem("Item 2") - AddHandler menuItem2.Click, AddressOf menuItem2_Click - contextMenu.Items.Add(menuItem1) - contextMenu.Items.Add(menuItem2) - AddHandler Me.RadVirtualGrid1.ContextMenuOpening, AddressOf radVirtualGrid1_ContextMenuOpening -End Sub -Private Sub menuItem1_Click(sender As Object, e As EventArgs) - RadMessageBox.Show("Item1") -End Sub -Private Sub menuItem2_Click(sender As Object, e As EventArgs) - RadMessageBox.Show("Item2") -End Sub - -```` - -{{endregion}} + + -Once the menu object has been initialized and populated with menu items, it is ready to be attached to the __RadVirtualGrid__. To do that, subscribe to the __ContextMenuOpening__ event and set the context menu to be displayed: -#### Apply the custom context menu -{{source=..\SamplesCS\VirtualGrid\ContextMenu\VirtualGridContextMenu.cs region=ApplyCustomContextMenu}} -{{source=..\SamplesVB\VirtualGrid\ContextMenu\VirtualGridContextMenu.vb region=ApplyCustomContextMenu}} +Once the menu object has been initialized and populated with menu items, it is ready to be attached to the __RadVirtualGrid__. To do that, subscribe to the __ContextMenuOpening__ event and set the context menu to be displayed: -````C# - -private void radVirtualGrid1_ContextMenuOpening(object sender, VirtualGridContextMenuOpeningEventArgs e) -{ - e.ContextMenu = contextMenu.DropDown; -} +#### Apply the custom context menu -```` -````VB.NET -Private Sub radVirtualGrid1_ContextMenuOpening(sender As Object, e As VirtualGridContextMenuOpeningEventArgs) - e.ContextMenu = contextMenu.DropDown -End Sub + + -```` -{{endregion}} # Conditional Custom Context Menus @@ -104,118 +38,17 @@ Applications may need to provide specific individual context menus depending on #### Create custom context menus -{{source=..\SamplesCS\VirtualGrid\ContextMenu\VirtualGridContextMenu.cs region=ConditionalMenus}} -{{source=..\SamplesVB\VirtualGrid\ContextMenu\VirtualGridContextMenu.vb region=ConditionalMenus}} - -````C# - -RadContextMenu contextMenu1 = new RadContextMenu(); -RadContextMenu contextMenu2 = new RadContextMenu(); - -public void BuildCustomContextMenus() -{ - RadMenuItem item1 = new RadMenuItem("Data item 1"); - item1.Click += item1_Click; - RadMenuItem item2 = new RadMenuItem("Data item 2"); - item2.Click += item2_Click; - contextMenu1.Items.Add(item1); - contextMenu1.Items.Add(item2); - - RadMenuItem item3 = new RadMenuItem("Header item 1"); - item3.Click += item3_Click; - RadMenuItem item4 = new RadMenuItem("Header item 2"); - item4.Click += item4_Click; - contextMenu2.Items.Add(item3); - contextMenu2.Items.Add(item4); -} - -private void item4_Click(object sender, EventArgs e) -{ - RadMessageBox.Show("Header item 2"); -} - -private void item3_Click(object sender, EventArgs e) -{ - RadMessageBox.Show("Header item 1"); -} - -private void item2_Click(object sender, EventArgs e) -{ - RadMessageBox.Show("Data item 2"); -} - -private void item1_Click(object sender, EventArgs e) -{ - RadMessageBox.Show("Data item 1"); -} - -```` -````VB.NET -Private contextMenu1 As New RadContextMenu() -Private contextMenu2 As New RadContextMenu() -Public Sub BuildCustomContextMenus() - Dim item1 As New RadMenuItem("Data item 1") - AddHandler item1.Click, AddressOf item1_Click - Dim item2 As New RadMenuItem("Data item 2") - AddHandler item2.Click, AddressOf item2_Click - contextMenu1.Items.Add(item1) - contextMenu1.Items.Add(item2) - Dim item3 As New RadMenuItem("Header item 1") - AddHandler item3.Click, AddressOf item3_Click - Dim item4 As New RadMenuItem("Header item 2") - AddHandler item4.Click, AddressOf item4_Click - contextMenu2.Items.Add(item3) - contextMenu2.Items.Add(item4) -End Sub -Private Sub item4_Click(sender As Object, e As EventArgs) - RadMessageBox.Show("Header item 2") -End Sub -Private Sub item3_Click(sender As Object, e As EventArgs) - RadMessageBox.Show("Header item 1") -End Sub -Private Sub item2_Click(sender As Object, e As EventArgs) - RadMessageBox.Show("Data item 2") -End Sub -Private Sub item1_Click(sender As Object, e As EventArgs) - RadMessageBox.Show("Data item 1") -End Sub - -```` - -{{endregion}} + + + + #### Apply the relevant menu -{{source=..\SamplesCS\VirtualGrid\ContextMenu\VirtualGridContextMenu.cs region=SetConditionalMenus}} -{{source=..\SamplesVB\VirtualGrid\ContextMenu\VirtualGridContextMenu.vb region=SetConditionalMenus}} - -````C# - -private void ConditionalCustom_ContextMenuOpening(object sender, VirtualGridContextMenuOpeningEventArgs e) -{ - if (e.RowIndex == -1) - { - e.ContextMenu = contextMenu2.DropDown; - } - else if (e.RowIndex >= 0) - { - e.ContextMenu = contextMenu1.DropDown; - } -} - -```` -````VB.NET -Private Sub ConditionalCustom_ContextMenuOpening(sender As Object, e As VirtualGridContextMenuOpeningEventArgs) - If e.RowIndex = -1 Then - e.ContextMenu = contextMenu2.DropDown - ElseIf e.RowIndex >= 0 Then - e.ContextMenu = contextMenu1.DropDown - End If -End Sub - -```` - -{{endregion}} + + + + |Data Cells Menu|Header Cells Menu| |----|----| diff --git a/controls/virtualgrid/features/context-menu/modifying-the-default-context-menu.md b/controls/virtualgrid/features/context-menu/modifying-the-default-context-menu.md index fab47ab52..67023b923 100644 --- a/controls/virtualgrid/features/context-menu/modifying-the-default-context-menu.md +++ b/controls/virtualgrid/features/context-menu/modifying-the-default-context-menu.md @@ -12,41 +12,10 @@ The default __RadVirtualGrid__ context menu can be customized in the __ContextMe # Removing an item from the default RadVirtualGrid context menu: -{{source=..\SamplesCS\VirtualGrid\ContextMenu\VirtualGridContextMenu.cs region=RemoveItem}} -{{source=..\SamplesVB\VirtualGrid\ContextMenu\VirtualGridContextMenu.vb region=RemoveItem}} + + -````C# - -private void Remove_ContextMenuOpening(object sender, VirtualGridContextMenuOpeningEventArgs e) -{ - for (int i = 0; i < e.ContextMenu.Items.Count; i++) - { - if (e.ContextMenu.Items[i].Text == "Delete") - { - // hide the Delete option from the context menu - e.ContextMenu.Items[i].Visibility = Telerik.WinControls.ElementVisibility.Collapsed; - // hide the separator before the Delete option - e.ContextMenu.Items[i - 1].Visibility = Telerik.WinControls.ElementVisibility.Collapsed; - } - } -} -```` -````VB.NET -Private Sub Remove_ContextMenuOpening(sender As Object, e As VirtualGridContextMenuOpeningEventArgs) - For i As Integer = 0 To e.ContextMenu.Items.Count - 1 - If e.ContextMenu.Items(i).Text = "Delete" Then - ' hide the Delete option from the context menu - e.ContextMenu.Items(i).Visibility = Telerik.WinControls.ElementVisibility.Collapsed - ' hide the separator before the Delete option - e.ContextMenu.Items(i - 1).Visibility = Telerik.WinControls.ElementVisibility.Collapsed - End If - Next -End Sub - -```` - -{{endregion}} |Default Context Menu|Modified Context Menu| |----|----| @@ -58,33 +27,10 @@ In order to add custom menu items to the default context menu, you should create #### Adding items to the default RadVirtualGrid context menu: -{{source=..\SamplesCS\VirtualGrid\ContextMenu\VirtualGridContextMenu.cs region=AddItem}} -{{source=..\SamplesVB\VirtualGrid\ContextMenu\VirtualGridContextMenu.vb region=AddItem}} - -````C# - -private void Add_ContextMenuOpening(object sender, VirtualGridContextMenuOpeningEventArgs e) -{ - RadMenuItem customMenuItem = new RadMenuItem(); - customMenuItem.Text = "Custom Data Operation"; - RadMenuSeparatorItem separator = new RadMenuSeparatorItem(); - e.ContextMenu.Items.Add(separator); - e.ContextMenu.Items.Add(customMenuItem); -} - -```` -````VB.NET -Private Sub Add_ContextMenuOpening(sender As Object, e As VirtualGridContextMenuOpeningEventArgs) - Dim customMenuItem As New RadMenuItem() - customMenuItem.Text = "Custom Data Operation" - Dim separator As New RadMenuSeparatorItem() - e.ContextMenu.Items.Add(separator) - e.ContextMenu.Items.Add(customMenuItem) -End Sub + + -```` -{{endregion}} |Default Context Menu|Modified Context Menu| |----|----| diff --git a/controls/virtualgrid/features/copy-paste-cut.md b/controls/virtualgrid/features/copy-paste-cut.md index 7333e6af5..ae1648dc9 100644 --- a/controls/virtualgrid/features/copy-paste-cut.md +++ b/controls/virtualgrid/features/copy-paste-cut.md @@ -20,29 +20,10 @@ Copying is a pretty simple operation. After cell/row is selected, right clicking __RadVirtualGrid__ introduces __Copying__ event which occurs when the grid has prepared appropriate data formats that represent the copy selection. This event is fired once for each supported format: DataFormats.Text, DataFormats.HTML, DataFormats.CommaSeparatedValue. You can cancel this event if the data is not allowed to be stored to Clipboard in a specific format, e.g. HTML format: -{{source=..\SamplesCS\VirtualGrid\CopyPasteCutCode.cs region=copy}} -{{source=..\SamplesVB\VirtualGrid\CopyPasteCutCode.vb region=copy}} -````C# -void radVirtualGrid1_Copying(object sender, VirtualGridClipboardEventArgs e) -{ - if (e.Format == DataFormats.Html) - { - e.Cancel = true; - } -} - -```` -````VB.NET -Private Sub radVirtualGrid1_Copying(ByVal sender As Object, ByVal e As VirtualGridClipboardEventArgs) - If e.Format = DataFormats.Html Then - e.Cancel = True - End If -End Sub - -```` - - -{{endregion}} + + + + >note Additionally, you can use the __RadVirtualGrid.VirtualGridElement.CopySelection__ method in order to perform the copy operation programmatically. > @@ -55,36 +36,10 @@ The default context menu for data cells offers paste possibility, except when th The __Pasting__ event is appropriate for modifying the Clipboard data before pasting it in the grid. -{{source=..\SamplesCS\VirtualGrid\CopyPasteCutCode.cs region=paste}} -{{source=..\SamplesVB\VirtualGrid\CopyPasteCutCode.vb region=paste}} -````C# -void radVirtualGrid1_Pasting(object sender, VirtualGridClipboardEventArgs e) -{ - if (Clipboard.ContainsData(DataFormats.Text)) - { - string data = Clipboard.GetData(DataFormats.Text).ToString(); - if (data != string.Empty) - { - Clipboard.SetData(DataFormats.Text, data.ToUpper()); - } - } -} - -```` -````VB.NET -Private Sub radVirtualGrid1_Pasting(ByVal sender As Object, ByVal e As VirtualGridClipboardEventArgs) - If Clipboard.ContainsData(DataFormats.Text) Then - Dim data As String = Clipboard.GetData(DataFormats.Text).ToString() - If data <> String.Empty Then - Clipboard.SetData(DataFormats.Text, data.ToUpper()) - End If - End If -End Sub - -```` - - -{{endregion}} + + + + >note Additionally, you can use the __RadVirtualGrid.VirtualGridElement.Paste__ method in order to perform the paste operation programmatically. > diff --git a/controls/virtualgrid/features/editing/changing-default-editor.md b/controls/virtualgrid/features/editing/changing-default-editor.md index 8e5cbab8c..c958053f0 100644 --- a/controls/virtualgrid/features/editing/changing-default-editor.md +++ b/controls/virtualgrid/features/editing/changing-default-editor.md @@ -12,38 +12,8 @@ position: 4 By default the grid is using the underlying field data type to determine the editor type. If you want to change the default editor you should use the __EditorReqired__ event. For example the following snippet shows how you can change the default text editor to __VirtualGridDropDownListEditor__. -{{source=..\SamplesCS\VirtualGrid\Editing\EditorsProperties.cs region=ChangeEditor}} -{{source=..\SamplesVB\VirtualGrid\Editing\EditorsProperties.vb region=ChangeEditor}} -````C# - -private void RadVirtualGrid1_EditorRequired(object sender, VirtualGridEditorRequiredEventArgs e) -{ - if (e.ColumnIndex == 1) - { - VirtualGridDropDownListEditor dropDownListEditor = new VirtualGridDropDownListEditor(); - RadDropDownListEditorElement element = dropDownListEditor.EditorElement as RadDropDownListEditorElement; - element.DataSource = new string[] { "Mr.", "Mrs.", "Ms.", "Dr." }; - e.Editor = dropDownListEditor; - } -} - -```` -````VB.NET -Private Sub RadVirtualGrid1_EditorRequired(ByVal sender As Object, ByVal e As VirtualGridEditorRequiredEventArgs) - If e.ColumnIndex = 1 Then - Dim dropDownListEditor As New VirtualGridDropDownListEditor() - Dim element As RadDropDownListEditorElement = TryCast(dropDownListEditor.EditorElement, RadDropDownListEditorElement) - element.DataSource = New String() {"Mr.", "Mrs.", "Ms.", "Dr."} - e.Editor = dropDownListEditor - End If -End Sub -Private Sub DefineColumnDataType() - '#Region "DefineColumnDataType" - Me.radVirtualGrid1.MasterViewInfo.ColumnDataTypes(0) = GetType(Integer) - -```` - -{{endregion}} + + diff --git a/controls/virtualgrid/features/editing/changing-editors-properties.md b/controls/virtualgrid/features/editing/changing-editors-properties.md index 977a56678..77ac7ad11 100644 --- a/controls/virtualgrid/features/editing/changing-editors-properties.md +++ b/controls/virtualgrid/features/editing/changing-editors-properties.md @@ -12,64 +12,9 @@ position: 5 Since the editors are created each time when the user starts edit operation, they can by accessed in the __CellEditorInitialized__ event. The following example shows how you can access some of the editors and change their properties. -{{source=..\SamplesCS\VirtualGrid\Editing\EditorsProperties.cs region=AccessProperties}} -{{source=..\SamplesVB\Virtualgrid\Editing\EditorsProperties.vb region=AccessProperties}} -````C# - -void radVirtualGrid1_CellEditorInitialized(object sender, VirtualGridCellEditorInitializedEventArgs e) -{ - var dateTimeEditor = e.ActiveEditor as VirtualGridDateTimeEditor; - if (dateTimeEditor != null) - { - var editorElement = dateTimeEditor.EditorElement as RadDateTimeEditorElement; - editorElement.Format = DateTimePickerFormat.Custom; - editorElement.CustomFormat = "dd/MM/yyyy"; - } - - var dropDownListEditor = e.ActiveEditor as VirtualGridDropDownListEditor; - if (dropDownListEditor != null) - { - RadDropDownListEditorElement element = dropDownListEditor.EditorElement as RadDropDownListEditorElement; - element.DisplayMember = "Name"; - element.ValueMember = "Name"; - - element.DataSource = GetTable(); - } - - var textBoxEditor = e.ActiveEditor as VirtualGridTextBoxEditor; - if (textBoxEditor != null) - { - var editorElement = textBoxEditor.EditorElement as RadTextBoxEditorElement; - editorElement.TextBoxItem.ForeColor = Color.Red; - } -} + + -```` -````VB.NET -Private Sub radVirtualGrid1_CellEditorInitialized(ByVal sender As Object, ByVal e As VirtualGridCellEditorInitializedEventArgs) - Dim dateTimeEditor = TryCast(e.ActiveEditor, VirtualGridDateTimeEditor) - If dateTimeEditor IsNot Nothing Then - Dim editorElement = TryCast(dateTimeEditor.EditorElement, RadDateTimeEditorElement) - editorElement.Format = DateTimePickerFormat.Custom - editorElement.CustomFormat = "dd/MM/yyyy" - End If - Dim dropDownListEditor = TryCast(e.ActiveEditor, VirtualGridDropDownListEditor) - If dropDownListEditor IsNot Nothing Then - Dim element As RadDropDownListEditorElement = TryCast(dropDownListEditor.EditorElement, RadDropDownListEditorElement) - element.DisplayMember = "Name" - element.ValueMember = "Name" - element.DataSource = GetTable() - End If - Dim textBoxEditor = TryCast(e.ActiveEditor, VirtualGridTextBoxEditor) - If textBoxEditor IsNot Nothing Then - Dim editorElement = TryCast(textBoxEditor.EditorElement, RadTextBoxEditorElement) - editorElement.TextBoxItem.ForeColor = Color.Red - End If -End Sub - -```` - -{{endregion}} # See Also diff --git a/controls/virtualgrid/features/editing/data-validation.md b/controls/virtualgrid/features/editing/data-validation.md index 2bb075caa..cbdfba5ba 100644 --- a/controls/virtualgrid/features/editing/data-validation.md +++ b/controls/virtualgrid/features/editing/data-validation.md @@ -30,44 +30,10 @@ The code snippet below demonstrates simple data validation scenario. It is enabl ![WinForms RadVirtualGrid Cell validation](images/virtualgrid-editing-data-validation001.png) -{{source=..\SamplesCS\VirtualGrid\Editing\EditorsProperties.cs region=CellValidating}} -{{source=..\SamplesVB\VirtualGrid\Editing\EditorsProperties.vb region=CellValidating}} -````C# - -private void radVirtualGrid1_CellValidating(object sender, VirtualGridCellValidatingEventArgs e) -{ - if (e.RowIndex >= 0 && e.ColumnIndex == 2) - { - e.ViewInfo.SetRowErrorText(e.RowIndex, "Validation error!"); - if (string.IsNullOrEmpty((string)e.NewValue) || ((string)e.NewValue).Trim() == string.Empty) - { - e.Cancel = true; - e.ViewInfo.SetRowErrorText(e.RowIndex, "Validation error!"); - } - else - { - e.ViewInfo.ClearRowErrorText(e.RowIndex); - } - } -} - -```` -````VB.NET -Private Sub radVirtualGrid1_CellValidating(sender As Object, e As VirtualGridCellValidatingEventArgs) - If e.RowIndex >= 0 AndAlso e.ColumnIndex = 2 Then - e.ViewInfo.SetRowErrorText(e.RowIndex, "Validation error!") - If String.IsNullOrEmpty(DirectCast(e.NewValue, String)) OrElse DirectCast(e.NewValue, String).Trim() = String.Empty Then - e.Cancel = True - e.ViewInfo.SetRowErrorText(e.RowIndex, "Validation error!") - Else - e.ViewInfo.ClearRowErrorText(e.RowIndex) - End If - End If -End Sub - -```` - -{{endregion}} + + + + # See Also * [API]({%slug winforms/virtualgrid/cells/api%}) diff --git a/controls/virtualgrid/features/editing/editors.md b/controls/virtualgrid/features/editing/editors.md index 798182a02..35b6aaeec 100644 --- a/controls/virtualgrid/features/editing/editors.md +++ b/controls/virtualgrid/features/editing/editors.md @@ -41,33 +41,17 @@ __RadVirtualGrid__ exposes an API for defining the data types of its columns. If #### Defining a Columns`s Data Type -{{source=..\SamplesCS\VirtualGrid\Editing\EditorsProperties.cs region=DefineColumnDataType}} -{{source=..\SamplesVB\Virtualgrid\Editing\EditorsProperties.vb region=DefineColumnDataType}} -````C# -this.radVirtualGrid1.MasterViewInfo.ColumnDataTypes[0] = typeof(int); + + -```` -````VB.NET -Me.radVirtualGrid1.MasterViewInfo.ColumnDataTypes(0) = GetType(Integer) -```` - -{{endregion}} #### Reading a Columns`s Data Type -{{source=..\SamplesCS\VirtualGrid\Editing\EditorsProperties.cs region=ReadColumnDataType}} -{{source=..\SamplesVB\Virtualgrid\Editing\EditorsProperties.vb region=ReadColumnDataType}} -````C# -Type dataType = this.radVirtualGrid1.MasterViewInfo.GetColumnDataType(1); - -```` -````VB.NET -Dim dataType As Type = Me.radVirtualGrid1.MasterViewInfo.GetColumnDataType(1) + + -```` -{{endregion}} # See Also * [API]({%slug winforms/virtualgrid/cells/api%}) diff --git a/controls/virtualgrid/features/editing/using-custom-editors.md b/controls/virtualgrid/features/editing/using-custom-editors.md index 0a7b54ade..01cbf692e 100644 --- a/controls/virtualgrid/features/editing/using-custom-editors.md +++ b/controls/virtualgrid/features/editing/using-custom-editors.md @@ -22,186 +22,10 @@ Most of the grid editors inherit from __BaseVirtualGridEditor__. The following s #### Creating MultiColumnComboBoxVirtualGridEditor -{{source=..\SamplesCS\VirtualGrid\Editing\VirtualGridCustomEditor.cs region=MyEditor}} -{{source=..\SamplesVB\Virtualgrid\Editing\VirtualGridCustomEditor.vb region=MyEditor}} -````C# -public class MultiColumnComboBoxVirtualGridEditor : BaseVirtualGridEditor -{ - protected override Telerik.WinControls.RadElement CreateEditorElement() - { - return new RadMultiColumnComboBoxElement(); - } - public override object Value - { - get - { - RadMultiColumnComboBoxElement editor = this.EditorElement as RadMultiColumnComboBoxElement; - if (editor.SelectedValue != null) - { - if (!string.IsNullOrEmpty(editor.ValueMember)) - { - return editor.SelectedValue; - } - } - return -1; - } - set - { - RadMultiColumnComboBoxElement editor = this.EditorElement as RadMultiColumnComboBoxElement; - if (value == null) - { - editor.SelectedIndex = -1; - } - else if (editor.ValueMember != null) - { - editor.SelectedValue = value; - } - } - } - public object DataSource - { - get - { - RadMultiColumnComboBoxElement editorElement = this.EditorElement as RadMultiColumnComboBoxElement; - return editorElement.DataSource; - } - set - { - RadMultiColumnComboBoxElement editorElement = this.EditorElement as RadMultiColumnComboBoxElement; - if (editorElement.BindingContext == null) - { - editorElement.BindingContext = new BindingContext(); - } - editorElement.DataSource = value; - } - } - public string ValueMember - { - get - { - RadMultiColumnComboBoxElement editorElement = this.EditorElement as RadMultiColumnComboBoxElement; - return editorElement.ValueMember; - } - set - { - RadMultiColumnComboBoxElement editorElement = this.EditorElement as RadMultiColumnComboBoxElement; - editorElement.ValueMember = value; - } - } - public string DisplayMember - { - get - { - RadMultiColumnComboBoxElement editorElement = this.EditorElement as RadMultiColumnComboBoxElement; - return editorElement.DisplayMember; - } - set - { - RadMultiColumnComboBoxElement editorElement = this.EditorElement as RadMultiColumnComboBoxElement; - editorElement.DisplayMember = value; - } - } -} -private void radVirtualGrid1_EditorRequired(object sender, Telerik.WinControls.UI.VirtualGridEditorRequiredEventArgs e) -{ - if (e.ColumnIndex == 2) - { - MultiColumnComboBoxVirtualGridEditor editor = new MultiColumnComboBoxVirtualGridEditor(); - DataTable dt = new DataTable(); - dt.Columns.Add("Id", typeof(int)); - dt.Columns.Add("Name", typeof(string)); - dt.Rows.Add(-1, ""); - for (int i = 0; i <= 9; i++) - { - dt.Rows.Add(i, "Item" + i); - } - editor.DataSource = dt; - editor.ValueMember = "Id"; - editor.DisplayMember = "Name"; - e.Editor = editor; - } -} + + -```` -````VB.NET -Public Class MultiColumnComboBoxVirtualGridEditor - Inherits BaseVirtualGridEditor - Protected Overrides Function CreateEditorElement() As Telerik.WinControls.RadElement - Return New RadMultiColumnComboBoxElement() - End Function - Public Overrides Property Value() As Object - Get - Dim editor As RadMultiColumnComboBoxElement = TryCast(Me.EditorElement, RadMultiColumnComboBoxElement) - If editor.SelectedValue IsNot Nothing Then - If Not String.IsNullOrEmpty(editor.ValueMember) Then - Return editor.SelectedValue - End If - End If - Return -1 - End Get - Set(value As Object) - Dim editor As RadMultiColumnComboBoxElement = TryCast(Me.EditorElement, RadMultiColumnComboBoxElement) - If value Is Nothing Then - editor.SelectedIndex = -1 - ElseIf editor.ValueMember IsNot Nothing Then - editor.SelectedValue = value - End If - End Set - End Property - Public Property DataSource() As Object - Get - Dim editorElement As RadMultiColumnComboBoxElement = TryCast(Me.EditorElement, RadMultiColumnComboBoxElement) - Return editorElement.DataSource - End Get - Set(value As Object) - Dim editorElement As RadMultiColumnComboBoxElement = TryCast(Me.EditorElement, RadMultiColumnComboBoxElement) - If editorElement.BindingContext Is Nothing Then - editorElement.BindingContext = New BindingContext() - End If - editorElement.DataSource = value - End Set - End Property - Public Property ValueMember() As String - Get - Dim editorElement As RadMultiColumnComboBoxElement = TryCast(Me.EditorElement, RadMultiColumnComboBoxElement) - Return editorElement.ValueMember - End Get - Set(value As String) - Dim editorElement As RadMultiColumnComboBoxElement = TryCast(Me.EditorElement, RadMultiColumnComboBoxElement) - editorElement.ValueMember = value - End Set - End Property - Public Property DisplayMember() As String - Get - Dim editorElement As RadMultiColumnComboBoxElement = TryCast(Me.EditorElement, RadMultiColumnComboBoxElement) - Return editorElement.DisplayMember - End Get - Set(value As String) - Dim editorElement As RadMultiColumnComboBoxElement = TryCast(Me.EditorElement, RadMultiColumnComboBoxElement) - editorElement.DisplayMember = value - End Set - End Property -End Class -Private Sub radVirtualGrid1_EditorRequired(sender As Object, e As Telerik.WinControls.UI.VirtualGridEditorRequiredEventArgs) - If e.ColumnIndex = 2 Then - Dim editor As New MultiColumnComboBoxVirtualGridEditor() - Dim dt As New DataTable() - dt.Columns.Add("Id", GetType(Integer)) - dt.Columns.Add("Name", GetType(String)) - dt.Rows.Add(-1, "") - For i As Integer = 0 To 9 - dt.Rows.Add(i, "Item" & i) - Next - editor.DataSource = dt - editor.ValueMember = "Id" - editor.DisplayMember = "Name" - e.Editor = editor - End If -End Sub -```` - -{{endregion}} ## See Also diff --git a/controls/virtualgrid/features/filtering/filtering.md b/controls/virtualgrid/features/filtering/filtering.md index ab37e0560..f76a73f9b 100644 --- a/controls/virtualgrid/features/filtering/filtering.md +++ b/controls/virtualgrid/features/filtering/filtering.md @@ -18,20 +18,10 @@ __RadVirtualGrid__ supports data filtering. Set the RadVirtualGrid.__AllowFilter #### Enabling the user filtering -{{source=..\SamplesCS\VirtualGrid\Filtering\VirtualGridFiltering.cs region=AllowFiltering}} -{{source=..\SamplesVB\VirtualGrid\Filtering\VirtualGridFiltering.vb region=AllowFiltering}} + + -````C# - -this.radVirtualGrid1.AllowFiltering = true; -```` -````VB.NET -Me.RadVirtualGrid1.AllowFiltering = True - -```` - -{{endregion}} When filtering is enabled, each column displays a filter button beneath the corresponding header which controls the filter operator: @@ -47,264 +37,10 @@ It is necessary to handle the __FilterChanged__ event which is fired once the __ The following example demonstrates how to achieve filtering functionality in __RadVirtualGrid__ filled with Northwind.Customers table: -{{source=..\SamplesCS\VirtualGrid\Filtering\VirtualGridFiltering.cs region=Filtering}} -{{source=..\SamplesVB\VirtualGrid\Filtering\VirtualGridFiltering.vb region=Filtering}} - -````C# - -private void radVirtualGrid1_FilterChanged(object sender, VirtualGridEventArgs e) -{ - SelectData(); -} - -private readonly string selectCommand = "SELECT CustomerID, CompanyName, ContactName, ContactTitle, Address, PostalCode FROM Customers"; -private string[] columnNames = new string[] { "CompanyName", "ContactName", "ContactTitle", "Address", "PostalCode" }; -List data = new List(); - -private void SelectData() -{ - string filterExpression = this.radVirtualGrid1.FilterDescriptors.Expression; - - if (!string.IsNullOrEmpty(filterExpression)) - { - filterExpression = "WHERE " + filterExpression; - } - - string commandString = String.Format("{0} {1}", selectCommand, filterExpression); - using (System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand(commandString)) - { - command.Connection = new System.Data.OleDb.OleDbConnection(Settings.Default.NwindConnectionString); - command.Connection.Open(); - IDataReader reader = command.ExecuteReader(); - data.Clear(); - - while (reader.Read()) - { - Customer customer = new Customer( - Convert.ToString(reader[0]), - Convert.ToString(reader[1]), - Convert.ToString(reader[2]), - Convert.ToString(reader[3]), - Convert.ToString(reader[4]), - Convert.ToString(reader[5])); - data.Add(customer); - } - - command.Connection.Close(); - } - - this.radVirtualGrid1.RowCount = data.Count; -} - -private void radVirtualGrid1_CellValueNeeded(object sender, Telerik.WinControls.UI.VirtualGridCellValueNeededEventArgs e) -{ - if (e.ColumnIndex < 0) - return; - if (e.RowIndex == RadVirtualGrid.HeaderRowIndex) - { - e.Value = columnNames[e.ColumnIndex]; - } - - if (e.RowIndex < 0) - { - e.FieldName = columnNames[e.ColumnIndex]; - } - - if (e.RowIndex >= 0 && e.RowIndex < data.Count) - { - e.Value = data[e.RowIndex][e.ColumnIndex]; - } -} - -private void VirtualGridFiltering_Load(object sender, EventArgs e) -{ - this.radVirtualGrid1.ColumnCount = columnNames.Length; - this.radVirtualGrid1.CellValueNeeded += radVirtualGrid1_CellValueNeeded; - this.radVirtualGrid1.FilterChanged += radVirtualGrid1_FilterChanged; - SelectData(); -} - -public class Customer -{ - public string CustomerId { get; set; } - - public string CompanyName { get; set; } - - public string ContactName { get; set; } - - public string ContactTitle { get; set; } - - public string Address { get; set; } - - public string PostalCode { get; set; } - - public Customer(string customerId, string companyName, string contactName, string contactTitle, string address, string postalCode) - { - this.CustomerId = customerId; - this.CompanyName = companyName; - this.ContactName = contactName; - this.ContactTitle = contactTitle; - this.Address = address; - this.PostalCode = postalCode; - } - - public string this[int i] - { - get - { - switch (i) - { - case 0: - return CompanyName; - case 1: - return ContactName; - case 2: - return ContactTitle; - case 3: - return Address; - case 4: - return PostalCode; - default: - return String.Empty; - } - } - } -} - -```` -````VB.NET -Private Sub radVirtualGrid1_FilterChanged(sender As Object, e As VirtualGridEventArgs) - SelectData() -End Sub -Private ReadOnly selectCommand As String = "SELECT CustomerID, CompanyName, ContactName, ContactTitle, Address, PostalCode FROM Customers" -Private columnNames As String() = New String() {"CompanyName", "ContactName", "ContactTitle", "Address", "PostalCode"} -Private data As New List(Of Customer)() -Private Sub SelectData() - Dim filterExpression As String = Me.RadVirtualGrid1.FilterDescriptors.Expression - If Not String.IsNullOrEmpty(filterExpression) Then - filterExpression = Convert.ToString("WHERE ") & filterExpression - End If - Dim commandString As String = [String].Format("{0} {1}", selectCommand, filterExpression) - Using command As New System.Data.OleDb.OleDbCommand(commandString) - command.Connection = New System.Data.OleDb.OleDbConnection(My.Settings.NwindConnectionString) - command.Connection.Open() - Dim reader As IDataReader = command.ExecuteReader() - data.Clear() - While reader.Read() - Dim customer As New Customer(Convert.ToString(reader(0)), Convert.ToString(reader(1)), Convert.ToString(reader(2)), _ - Convert.ToString(reader(3)), Convert.ToString(reader(4)), Convert.ToString(reader(5))) - data.Add(customer) - End While - command.Connection.Close() - End Using - Me.RadVirtualGrid1.RowCount = data.Count -End Sub -Private Sub radVirtualGrid1_CellValueNeeded(sender As Object, e As Telerik.WinControls.UI.VirtualGridCellValueNeededEventArgs) - If e.ColumnIndex < 0 Then - Return - End If - If e.RowIndex = RadVirtualGrid.HeaderRowIndex Then - e.Value = columnNames(e.ColumnIndex) - End If - If e.RowIndex < 0 Then - e.FieldName = columnNames(e.ColumnIndex) - End If - If e.RowIndex >= 0 AndAlso e.RowIndex < data.Count Then - e.Value = data(e.RowIndex)(e.ColumnIndex) - End If -End Sub -Private Sub VirtualGridFiltering_Load(sender As Object, e As EventArgs) Handles Me.Load - Me.RadVirtualGrid1.ColumnCount = columnNames.Length - AddHandler Me.RadVirtualGrid1.CellValueNeeded, AddressOf radVirtualGrid1_CellValueNeeded - AddHandler Me.RadVirtualGrid1.FilterChanged, AddressOf radVirtualGrid1_FilterChanged - SelectData() -End Sub -Public Class Customer - Public Property CustomerId() As String - Get - Return m_CustomerId - End Get - Set(value As String) - m_CustomerId = value - End Set - End Property - Private m_CustomerId As String - Public Property CompanyName() As String - Get - Return m_CompanyName - End Get - Set(value As String) - m_CompanyName = value - End Set - End Property - Private m_CompanyName As String - Public Property ContactName() As String - Get - Return m_ContactName - End Get - Set(value As String) - m_ContactName = value - End Set - End Property - Private m_ContactName As String - Public Property ContactTitle() As String - Get - Return m_ContactTitle - End Get - Set(value As String) - m_ContactTitle = value - End Set - End Property - Private m_ContactTitle As String - Public Property Address() As String - Get - Return m_Address - End Get - Set(value As String) - m_Address = value - End Set - End Property - Private m_Address As String - Public Property PostalCode() As String - Get - Return m_PostalCode - End Get - Set(value As String) - m_PostalCode = value - End Set - End Property - Private m_PostalCode As String - Public Sub New(customerId As String, companyName As String, contactName As String, contactTitle As String, address As String, postalCode As String) - Me.CustomerId = customerId - Me.CompanyName = companyName - Me.ContactName = contactName - Me.ContactTitle = contactTitle - Me.Address = address - Me.PostalCode = postalCode - End Sub - Default Public ReadOnly Property Item(i As Integer) As String - Get - Select Case i - Case 0 - Return CompanyName - Case 1 - Return ContactName - Case 2 - Return ContactTitle - Case 3 - Return Address - Case 4 - Return PostalCode - Case Else - Return [String].Empty - End Select - End Get - End Property -End Class + + -```` -{{endregion}} >note It is necessary to specify the __FieldName__ property for the filter cells. diff --git a/controls/virtualgrid/features/filtering/setting-filters-programmatically.md b/controls/virtualgrid/features/filtering/setting-filters-programmatically.md index 6d1fe769f..fc1a7f7b1 100644 --- a/controls/virtualgrid/features/filtering/setting-filters-programmatically.md +++ b/controls/virtualgrid/features/filtering/setting-filters-programmatically.md @@ -34,30 +34,10 @@ When you add a new descriptor to the collection, the data is automatically filte #### Using simple filter descriptor -{{source=..\SamplesCS\VirtualGrid\Filtering\VirtualGridFiltering.cs region=SimpleDescriptors}} -{{source=..\SamplesVB\VirtualGrid\Filtering\VirtualGridFiltering.vb region=SimpleDescriptors}} - -````C# - -FilterDescriptor filter = new FilterDescriptor(); -filter.PropertyName = "ContactName"; -filter.Operator = FilterOperator.StartsWith ; -filter.Value = "p"; -filter.IsFilterEditor = true; - this.radVirtualGrid1.FilterDescriptors.Add(filter); - -```` -````VB.NET -Dim filter As New FilterDescriptor() -filter.PropertyName = "ContactName" -filter.[Operator] = FilterOperator.StartsWith -filter.Value = "p" -filter.IsFilterEditor = True -Me.RadVirtualGrid1.FilterDescriptors.Add(filter) - -```` - -{{endregion}} + + + + # Composite descriptors @@ -68,30 +48,10 @@ To filter a single data field by multiple values, you have to use the __Composit #### Using CompositeFilterDescriptor -{{source=..\SamplesCS\VirtualGrid\Filtering\VirtualGridFiltering.cs region=CompositeDescriptors}} -{{source=..\SamplesVB\VirtualGrid\Filtering\VirtualGridFiltering.vb region=CompositeDescriptors}} - -````C# - -CompositeFilterDescriptor compositeFilter = new CompositeFilterDescriptor(); -compositeFilter.FilterDescriptors.Add(new FilterDescriptor("ContactName", FilterOperator.StartsWith,"p")); -compositeFilter.FilterDescriptors.First().IsFilterEditor = true; -compositeFilter.FilterDescriptors.Add(new FilterDescriptor("CompanyName", FilterOperator.Contains, "w")); -compositeFilter.LogicalOperator = FilterLogicalOperator.And; -this.radVirtualGrid1.FilterDescriptors.Add(compositeFilter); - -```` -````VB.NET -Dim compositeFilter As New CompositeFilterDescriptor() -compositeFilter.FilterDescriptors.Add(New FilterDescriptor("ContactName", FilterOperator.StartsWith, "p")) -compositeFilter.FilterDescriptors.First().IsFilterEditor = True -compositeFilter.FilterDescriptors.Add(New FilterDescriptor("CompanyName", FilterOperator.Contains, "w")) -compositeFilter.LogicalOperator = FilterLogicalOperator.[And] -Me.RadVirtualGrid1.FilterDescriptors.Add(compositeFilter) - -```` - -{{endregion}} + + + + # See Also * [Filtering Overview]({%slug winforms/virtualgrid/filtering/filtering%}) diff --git a/controls/virtualgrid/features/input-behavior.md b/controls/virtualgrid/features/input-behavior.md index a4dfd667a..bc02f32bd 100644 --- a/controls/virtualgrid/features/input-behavior.md +++ b/controls/virtualgrid/features/input-behavior.md @@ -18,83 +18,17 @@ You can find below a sample code snippet demonstrating how to override the defau #### Custom VirtualGridInputBehavior -{{source=..\SamplesCS\VirtualGrid\HandlingUserInput\VirtualGridInputBehaviorForm.cs region=CustomInputBehavior}} -{{source=..\SamplesVB\VirtualGrid\HandlingUserInput\VirtualGridInputBehaviorForm.vb region=CustomInputBehavior}} + + -````C# - -public class CustomVirtualGridInputBehavior : VirtualGridInputBehavior -{ - public CustomVirtualGridInputBehavior(RadVirtualGridElement gridElement) : base(gridElement) - { - } - - protected override bool HandleUpKey(KeyEventArgs keys) - { - DialogResult dr = RadMessageBox.Show("Please confirm the move up operation!", "Confirmation", MessageBoxButtons.YesNo); - if (dr == DialogResult.Yes) - { - return base.HandleUpKey(keys); - } - return false; - } - - protected override bool HandleDownKey(KeyEventArgs keys) - { - DialogResult dr = RadMessageBox.Show("Please confirm the move down operation!", "Confirmation", MessageBoxButtons.YesNo); - if (dr == DialogResult.Yes) - { - return base.HandleDownKey(keys); - } - return false; - } -} - -```` -````VB.NET -Public Class CustomVirtualGridInputBehavior -Inherits VirtualGridInputBehavior - Public Sub New(gridElement As RadVirtualGridElement) - MyBase.New(gridElement) - End Sub - Protected Overrides Function HandleUpKey(keys As KeyEventArgs) As Boolean - Dim dr As DialogResult = RadMessageBox.Show("Please confirm the move up operation!", "Confirmation", MessageBoxButtons.YesNo) - If dr = DialogResult.Yes Then - Return MyBase.HandleUpKey(keys) - End If - Return False - End Function - Protected Overrides Function HandleDownKey(keys As KeyEventArgs) As Boolean - Dim dr As DialogResult = RadMessageBox.Show("Please confirm the move down operation!", "Confirmation", MessageBoxButtons.YesNo) - If dr = DialogResult.Yes Then - Return MyBase.HandleDownKey(keys) - End If - Return False - End Function -End Class - -```` - -{{endregion}} #### Apply the custom VirtualGridInputBehavior -{{source=..\SamplesCS\VirtualGrid\HandlingUserInput\VirtualGridInputBehaviorForm.cs region=ApplyInputBehavior}} -{{source=..\SamplesVB\VirtualGrid\HandlingUserInput\VirtualGridInputBehaviorForm.vb region=ApplyInputBehavior}} - - -````C# - -this.radVirtualGrid1.VirtualGridElement.InputBehavior = new CustomVirtualGridInputBehavior(this.radVirtualGrid1.VirtualGridElement); - -```` -````VB.NET -Me.RadVirtualGrid1.VirtualGridElement.InputBehavior = New CustomVirtualGridInputBehavior(Me.RadVirtualGrid1.VirtualGridElement) + + -```` -{{endregion}} >note You can follow a similar approach to customize any of the methods that handle the mouse and keyboard user input. diff --git a/controls/virtualgrid/features/save-and-load-layout/advanced.md b/controls/virtualgrid/features/save-and-load-layout/advanced.md index 8943cf4cf..7aa620ba1 100644 --- a/controls/virtualgrid/features/save-and-load-layout/advanced.md +++ b/controls/virtualgrid/features/save-and-load-layout/advanced.md @@ -26,26 +26,10 @@ Here is a snippet clearing the default settings: #### Clear Default Settings -{{source=..\SamplesCS\VirtualGrid\SaveLoadLayout\VirtualGridSaveLoadLayout.cs region=ClearSettings}} -{{source=..\SamplesVB\VirtualGrid\SaveLoadLayout\VirtualGridSaveLoadLayout.vb region=ClearSettings}} + + -````C# -private void ClearSettings(object sender, EventArgs e) -{ - this.radVirtualGrid1.XmlSerializationInfo.DisregardOriginalSerializationVisibility = true; - this.radVirtualGrid1.XmlSerializationInfo.SerializationMetadata.Clear(); -} -```` -````VB.NET -Private Sub ClearSettings(sender As Object, e As EventArgs) - Me.RadVirtualGrid1.XmlSerializationInfo.DisregardOriginalSerializationVisibility = True - Me.RadVirtualGrid1.XmlSerializationInfo.SerializationMetadata.Clear() -End Sub - -```` - -{{endregion}} >note Clearing the default settings would require all the serialization meta data to be loaded manually. > @@ -54,50 +38,10 @@ The code snippets below demonstrates how you can hide a particular information t #### Define Data -{{source=..\SamplesCS\VirtualGrid\SaveLoadLayout\VirtualGridSaveLoadLayout.cs region=DefineData}} -{{source=..\SamplesVB\VirtualGrid\SaveLoadLayout\VirtualGridSaveLoadLayout.vb region=DefineData}} - -````C# -private void DefineData(object sender, EventArgs e) -{ - //Hide items - this.radVirtualGrid1.XmlSerializationInfo.SerializationMetadata.Add(typeof(VirtualGridViewInfo), "CustomColumns", new DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)); - this.radVirtualGrid1.XmlSerializationInfo.SerializationMetadata.Add(typeof(VirtualGridViewInfo), "ColumnDataTypes", new DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)); - this.radVirtualGrid1.XmlSerializationInfo.SerializationMetadata.Add(typeof(VirtualGridTableViewState), "ItemSizes", new DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)); - this.radVirtualGrid1.XmlSerializationInfo.SerializationMetadata.Add(typeof(VirtualGridTableViewState), "ItemCount", new DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)); - //Sort Descriptors - this.radVirtualGrid1.XmlSerializationInfo.SerializationMetadata.Add(typeof(VirtualGridViewInfo), "SortDescriptors", DesignerSerializationVisibilityAttribute.Hidden); - this.radVirtualGrid1.XmlSerializationInfo.SerializationMetadata.Add(typeof(SortDescriptor), "Direction", DesignerSerializationVisibilityAttribute.Hidden); - //Filter Descriptors - this.radVirtualGrid1.XmlSerializationInfo.SerializationMetadata.Add(typeof(VirtualGridViewInfo), "FilterDescriptors", DesignerSerializationVisibilityAttribute.Hidden); - this.radVirtualGrid1.XmlSerializationInfo.SerializationMetadata.Add(typeof(FilterDescriptor), "PropertyName", DesignerSerializationVisibilityAttribute.Hidden); - this.radVirtualGrid1.XmlSerializationInfo.SerializationMetadata.Add(typeof(FilterDescriptor), "Operator", DesignerSerializationVisibilityAttribute.Hidden); - this.radVirtualGrid1.XmlSerializationInfo.SerializationMetadata.Add(typeof(FilterDescriptor), "Value", DesignerSerializationVisibilityAttribute.Hidden); - this.radVirtualGrid1.XmlSerializationInfo.SerializationMetadata.Add(typeof(FilterDescriptor), "IsFilterEditor", DesignerSerializationVisibilityAttribute.Hidden); -} - -```` -````VB.NET -Private Sub DefineData(sender As Object, e As EventArgs) - 'Hide items - Me.RadVirtualGrid1.XmlSerializationInfo.SerializationMetadata.Add(GetType(VirtualGridViewInfo), "CustomColumns", New DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)) - Me.RadVirtualGrid1.XmlSerializationInfo.SerializationMetadata.Add(GetType(VirtualGridViewInfo), "ColumnDataTypes", New DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)) - Me.RadVirtualGrid1.XmlSerializationInfo.SerializationMetadata.Add(GetType(VirtualGridTableViewState), "ItemSizes", New DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)) - Me.RadVirtualGrid1.XmlSerializationInfo.SerializationMetadata.Add(GetType(VirtualGridTableViewState), "ItemCount", New DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)) - 'Sort Descriptors - Me.RadVirtualGrid1.XmlSerializationInfo.SerializationMetadata.Add(GetType(VirtualGridViewInfo), "SortDescriptors", DesignerSerializationVisibilityAttribute.Hidden) - Me.RadVirtualGrid1.XmlSerializationInfo.SerializationMetadata.Add(GetType(SortDescriptor), "Direction", DesignerSerializationVisibilityAttribute.Hidden) - 'Filter Descriptors - Me.RadVirtualGrid1.XmlSerializationInfo.SerializationMetadata.Add(GetType(VirtualGridViewInfo), "FilterDescriptors", DesignerSerializationVisibilityAttribute.Hidden) - Me.RadVirtualGrid1.XmlSerializationInfo.SerializationMetadata.Add(GetType(FilterDescriptor), "PropertyName", DesignerSerializationVisibilityAttribute.Hidden) - Me.RadVirtualGrid1.XmlSerializationInfo.SerializationMetadata.Add(GetType(FilterDescriptor), "Operator", DesignerSerializationVisibilityAttribute.Hidden) - Me.RadVirtualGrid1.XmlSerializationInfo.SerializationMetadata.Add(GetType(FilterDescriptor), "Value", DesignerSerializationVisibilityAttribute.Hidden) - Me.RadVirtualGrid1.XmlSerializationInfo.SerializationMetadata.Add(GetType(FilterDescriptor), "IsFilterEditor", DesignerSerializationVisibilityAttribute.Hidden) -End Sub - -```` - -{{endregion}} + + + + >note Once the layout is being loaded the __LayoutLoaded__ event is being thrown in order to notify that the load process is being finished. > diff --git a/controls/virtualgrid/features/save-and-load-layout/overview.md b/controls/virtualgrid/features/save-and-load-layout/overview.md index e51c8c22a..7a0d79c97 100644 --- a/controls/virtualgrid/features/save-and-load-layout/overview.md +++ b/controls/virtualgrid/features/save-and-load-layout/overview.md @@ -16,77 +16,19 @@ Here is a sample demonstrating how you can implement a *Save Layout* button even #### Save layout -{{source=..\SamplesCS\VirtualGrid\SaveLoadLayout\VirtualGridSaveLoadLayout.cs region=SaveLayout}} -{{source=..\SamplesVB\VirtualGrid\SaveLoadLayout\VirtualGridSaveLoadLayout.vb region=SaveLayout}} - -````C# -private void SaveButton_Click(object sender, EventArgs e) -{ - string s = "default.xml"; - SaveFileDialog dialog = new SaveFileDialog(); - dialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*"; - dialog.Title = "Select a xml file"; - if (dialog.ShowDialog() == DialogResult.OK) - { - s = dialog.FileName; - } - this.radVirtualGrid1.SaveLayout(s); -} - -```` -````VB.NET -Private Sub SaveButton_Click(sender As Object, e As EventArgs) Handles RadButton1.Click - Dim s As String = "default.xml" - Dim dialog As New SaveFileDialog() - dialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*" - dialog.Title = "Select a xml file" - If dialog.ShowDialog() = DialogResult.OK Then - s = dialog.FileName - End If - Me.RadVirtualGrid1.SaveLayout(s) -End Sub - -```` - -{{endregion}} + + + + The code snippets below demonstrates how you can implement a *Load Layout* button event handler:  #### Load layout -{{source=..\SamplesCS\VirtualGrid\SaveLoadLayout\VirtualGridSaveLoadLayout.cs region=LoadLayout}} -{{source=..\SamplesVB\VirtualGrid\SaveLoadLayout\VirtualGridSaveLoadLayout.vb region=LoadLayout}} - -````C# -private void LoadButton_Click(object sender, EventArgs e) -{ - string s = "default.xml"; - OpenFileDialog dialog = new OpenFileDialog(); - dialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*"; - dialog.Title = "Select a xml file"; - if (dialog.ShowDialog() == DialogResult.OK) - { - s = dialog.FileName; - } - this.radVirtualGrid1.LoadLayout(s); -} - -```` -````VB.NET -Private Sub LoadButton_Click(sender As Object, e As EventArgs) Handles RadButton2.Click - Dim s As String = "default.xml" - Dim dialog As New OpenFileDialog() - dialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*" - dialog.Title = "Select a xml file" - If dialog.ShowDialog() = DialogResult.OK Then - s = dialog.FileName - End If - Me.RadVirtualGrid1.LoadLayout(s) -End Sub - -```` - -{{endregion}} + + + + >note Once the layout is being loaded the __LayoutLoaded__ event is being thrown in order to notify that the load process is being finished. > diff --git a/controls/virtualgrid/features/scrolling.md b/controls/virtualgrid/features/scrolling.md index 9667627d0..85ddf00af 100644 --- a/controls/virtualgrid/features/scrolling.md +++ b/controls/virtualgrid/features/scrolling.md @@ -23,58 +23,27 @@ __RadVirtualGrid__ allows three types of scroll modes: ![WinForms RadVirtualGrid Smooth Scrolling](images/virtualgrid-scrolling001.gif) -{{source=..\SamplesCS\VirtualGrid\Rows\VirtualGridResizingRows.cs region=SmoothScrolling}} -{{source=..\SamplesVB\VirtualGrid\Rows\VirtualGridResizingRows.vb region=SmoothScrolling}} -````C# -this.radVirtualGrid1.TableElement.RowScroller.ScrollMode = ItemScrollerScrollModes.Smooth; + + -```` -````VB.NET -Me.RadVirtualGrid1.TableElement.RowScroller.ScrollMode = ItemScrollerScrollModes.Smooth -```` - - - -{{endregion}} >caption Figure 2: Discrete Scrolling ![WinForms RadVirtualGrid Discrete Scrolling](images/virtualgrid-scrolling002.gif) -{{source=..\SamplesCS\VirtualGrid\Rows\VirtualGridResizingRows.cs region=DiscreteScrolling}} -{{source=..\SamplesVB\VirtualGrid\Rows\VirtualGridResizingRows.vb region=DiscreteScrolling}} -````C# -this.radVirtualGrid1.TableElement.RowScroller.ScrollMode = ItemScrollerScrollModes.Discrete; - -```` -````VB.NET -Me.RadVirtualGrid1.TableElement.RowScroller.ScrollMode = ItemScrollerScrollModes.Discrete - -```` + + -{{endregion}} - >caption Figure 3: Deferred Scrolling ![WinForms RadVirtualGrid Deferred Scrolling](images/virtualgrid-scrolling003.gif) -{{source=..\SamplesCS\VirtualGrid\Rows\VirtualGridResizingRows.cs region=DeferredScrolling}} -{{source=..\SamplesVB\VirtualGrid\Rows\VirtualGridResizingRows.vb region=DeferredScrolling}} -````C# -this.radVirtualGrid1.TableElement.RowScroller.ScrollMode = ItemScrollerScrollModes.Deferred; - -```` -````VB.NET -Me.RadVirtualGrid1.TableElement.RowScroller.ScrollMode = ItemScrollerScrollModes.Deferred - -```` - - + + -{{endregion}} The __RadVirtualGrid.UseScrollBarsInHierarchy__ property is responsible for defining whether vertical scrollbars will appear for the inner child views. By default the property is set to *false*. diff --git a/controls/virtualgrid/features/selection/multi-select.md b/controls/virtualgrid/features/selection/multi-select.md index ff0780ad3..2c159d746 100644 --- a/controls/virtualgrid/features/selection/multi-select.md +++ b/controls/virtualgrid/features/selection/multi-select.md @@ -16,21 +16,10 @@ __RadVirtualGrid__ allows the user to select more than one item at a time from t In order to enable multiple row selection, after setting the __MultiSelect__ property to *true*, you have to set the __SelectionMode__ to __FullRowSelect__: -{{source=..\SamplesCS\VirtualGrid\VirtualGridSelection.cs region=multiSelect}} -{{source=..\SamplesVB\VirtualGrid\VirtualGridSelection.vb region=multiSelect}} -````C# - -radVirtualGrid1.MultiSelect = true; -radVirtualGrid1.SelectionMode = VirtualGridSelectionMode.FullRowSelect; + + -```` -````VB.NET -radVirtualGrid1.MultiSelect = True -radVirtualGrid1.SelectionMode = VirtualGridSelectionMode.FullRowSelect -```` - -{{endregion}} When these settings are applied, you have several options to make a multiple selection: * Press Ctrl + A to select all rows. @@ -44,21 +33,10 @@ When these settings are applied, you have several options to make a multiple sel In order to enable multiple cell selection, after setting the __MultiSelect__ property to true, you have to set the __SelectionMode__ to __CellSelect__: -{{source=..\SamplesCS\VirtualGrid\VirtualGridSelection.cs region=multiCell}} -{{source=..\SamplesVB\VirtualGrid\VirtualGridSelection.vb region=multiCell}} -````C# - -radVirtualGrid1.MultiSelect = true; -radVirtualGrid1.SelectionMode = VirtualGridSelectionMode.CellSelect; - -```` -````VB.NET -radVirtualGrid1.MultiSelect = True -radVirtualGrid1.SelectionMode = VirtualGridSelectionMode.CellSelect + + -```` -{{endregion}} Once you have applied these setting, the options for selection are: diff --git a/controls/virtualgrid/features/selection/selecting-progrmmatically.md b/controls/virtualgrid/features/selection/selecting-progrmmatically.md index 21db08366..e1fd3881d 100644 --- a/controls/virtualgrid/features/selection/selecting-progrmmatically.md +++ b/controls/virtualgrid/features/selection/selecting-progrmmatically.md @@ -14,40 +14,17 @@ position: 2 You can use the following method to select a cell in the code: -{{source=..\SamplesCS\VirtualGrid\VirtualGridSelection.cs region=changeCurentCell}} -{{source=..\SamplesVB\VirtualGrid\VirtualGridSelection.vb region=changeCurentCell}} -````C# -this.radVirtualGrid1.SelectCell(5, 2); + + -```` -````VB.NET -Me.radVirtualGrid1.SelectCell(5, 2) - -```` - -{{endregion}} ## Multiple Cells Select You can select multiple cells with code as well. This can be achieved by using the __BeginSelection__ and __ExtendCurrentRegion__ methods. For example: -{{source=..\SamplesCS\VirtualGrid\VirtualGridSelection.cs region=selectMultipleCells}} -{{source=..\SamplesVB\VirtualGrid\VirtualGridSelection.vb region=selectMultipleCells}} -````C# -radVirtualGrid1.VirtualGridElement.Selection.BeginSelection(3, 1, radVirtualGrid1.MasterViewInfo, true); -radVirtualGrid1.VirtualGridElement.Selection.ExtendCurrentRegion(6, 3); - -```` -````VB.NET -radVirtualGrid1.VirtualGridElement.Selection.BeginSelection(3, 1, radVirtualGrid1.MasterViewInfo, True) -radVirtualGrid1.VirtualGridElement.Selection.ExtendCurrentRegion(6, 3) - -```` - -{{endregion}} - - + + diff --git a/controls/virtualgrid/features/selection/selection.md b/controls/virtualgrid/features/selection/selection.md index 7bc810c7d..f0cf6416c 100644 --- a/controls/virtualgrid/features/selection/selection.md +++ b/controls/virtualgrid/features/selection/selection.md @@ -23,19 +23,10 @@ To select an item in __RadVirtualGrid__ click in the rectangle area of the desir ## Cell Selection You can modify __RadVirtualGrid__ to select single cell instead of entire row by setting its __SelectionMode__ property to __CellSelect__: -{{source=..\SamplesCS\VirtualGrid\VirtualGridSelection.cs region=cellSelect}} -{{source=..\SamplesVB\VirtualGrid\VirtualGridSelection.vb region=cellSelect}} -````C# - -this.radVirtualGrid1.SelectionMode = VirtualGridSelectionMode.CellSelect; + + -```` -````VB.NET -Me.radVirtualGrid1.SelectionMode = VirtualGridSelectionMode.CellSelect -```` - -{{endregion}} After setting this property, to select a cell in __RadVirtualGrid__, click the desired cell. diff --git a/controls/virtualgrid/features/sorting/setting-sorting-programmatically.md b/controls/virtualgrid/features/sorting/setting-sorting-programmatically.md index 648dc7bc3..241573661 100644 --- a/controls/virtualgrid/features/sorting/setting-sorting-programmatically.md +++ b/controls/virtualgrid/features/sorting/setting-sorting-programmatically.md @@ -20,33 +20,10 @@ Here is how to create and add two __SortDescriptors__. The __PropertyName__ prop #### Using SortDescriptor -{{source=..\SamplesCS\VirtualGrid\Sorting\VirtualGridSorting.cs region=RunTimeSorting}} -{{source=..\SamplesVB\VirtualGrid\Sorting\VirtualGridSorting.vb region=RunTimeSorting}} - -````C# -SortDescriptor descriptorContactTitle = new SortDescriptor(); -descriptorContactTitle.PropertyName = "ContactTitle"; -descriptorContactTitle.Direction = ListSortDirection.Ascending; -SortDescriptor descriptorContactName = new SortDescriptor(); -descriptorContactName.PropertyName = "ContactName"; -descriptorContactName.Direction = ListSortDirection.Descending; -this.radVirtualGrid1.SortDescriptors.Add(descriptorContactTitle); -this.radVirtualGrid1.SortDescriptors.Add(descriptorContactName); - -```` -````VB.NET -Dim descriptorContactTitle As New SortDescriptor() -descriptorContactTitle.PropertyName = "ContactTitle" -descriptorContactTitle.Direction = ListSortDirection.Ascending -Dim descriptorContactName As New SortDescriptor() -descriptorContactName.PropertyName = "ContactName" -descriptorContactName.Direction = ListSortDirection.Descending -Me.RadVirtualGrid1.SortDescriptors.Add(descriptorContactTitle) -Me.RadVirtualGrid1.SortDescriptors.Add(descriptorContactName) - -```` - -{{endregion}} + + + + >note The RadVirtualGrid.__AllowMultiColumnSorting__ property should be set to *true* in order to achieve multiple columns sorting. Otherwise, __RadVirtualGrid__ will be sorted by a single column. diff --git a/controls/virtualgrid/features/sorting/sorting.md b/controls/virtualgrid/features/sorting/sorting.md index a47cc58d3..5edaa3b40 100644 --- a/controls/virtualgrid/features/sorting/sorting.md +++ b/controls/virtualgrid/features/sorting/sorting.md @@ -16,19 +16,10 @@ __RadVirtualGrid__ supports data sorting. Set the RadVirtualGrid.__AllowSorting #### Enabling the user sorting -{{source=..\SamplesCS\VirtualGrid\Sorting\VirtualGridSorting.cs region=AllowSorting}} -{{source=..\SamplesVB\VirtualGrid\Sorting\VirtualGridSorting.vb region=AllowSorting}} + + -````C# -this.radVirtualGrid1.AllowSorting = true; -```` -````VB.NET -Me.RadVirtualGrid1.AllowSorting = True - -```` - -{{endregion}} ![WinForms RadVirtualGrid AllowMultiColumnSorting](images/virtualgrid-sorting002.png) @@ -43,35 +34,19 @@ When sorting is enabled, the user can click on the column headers to control the * __false__ : Clicking the header cycles through __Ascending → Descending → Ascending__. Users cannot return to unsorted state. Sorting always remains active. -{{source=..\SamplesCS\VirtualGrid\Sorting\VirtualGridSorting.cs region=AllowNaturalSorting}} -{{source=..\SamplesVB\VirtualGrid\Sorting\VirtualGridSorting.vb region=AllowNaturalSorting}} - -````C# -this.radVirtualGrid1.MasterViewInfo.SetColumnAllowNaturalSort(0, false); + + -```` -````VB.NET -Me.RadVirtualGrid1.MasterViewInfo.SetColumnAllowNaturalSort(0, False) -```` ![WinForms RadVirtualGrid AllowNaturalSorting](images/virtualgrid-sort-allownaturalsort.gif) #### Enabling multiple columns sorting -{{source=..\SamplesCS\VirtualGrid\Sorting\VirtualGridSorting.cs region=MultiColumnSorting}} -{{source=..\SamplesVB\VirtualGrid\Sorting\VirtualGridSorting.vb region=MultiColumnSorting}} - -````C# -this.radVirtualGrid1.AllowMultiColumnSorting = true; - -```` -````VB.NET -Me.RadVirtualGrid1.AllowMultiColumnSorting = True + + -```` -{{endregion}} It is necessary to handle the __SortChanged__ event which is fired once the __SortDescriptors__ collection is changed. In the event handler you should extract the sorted data from the external data source. @@ -80,264 +55,10 @@ It is necessary to handle the __SortChanged__ event which is fired once the __So The following example demonstrates how to achieve sorting functionality in __RadVirtualGrid__ filled with Northwind.Customers table: -{{source=..\SamplesCS\VirtualGrid\Sorting\VirtualGridSorting.cs region=Sorting}} -{{source=..\SamplesVB\VirtualGrid\Sorting\VirtualGridSorting.vb region=Sorting}} + + -````C# - -private void radVirtualGrid1_SortChanged(object sender, VirtualGridEventArgs e) -{ - SelectData(); -} - -private readonly string selectCommand = "SELECT CustomerID, CompanyName, ContactName, ContactTitle, Address, PostalCode FROM Customers"; -private string[] columnNames = new string[] { "CompanyName", "ContactName", "ContactTitle", "Address", "PostalCode" }; -List data = new List(); - -private void SelectData() -{ - string sortExpression = this.radVirtualGrid1.SortDescriptors.Expression; - if (!string.IsNullOrEmpty(sortExpression)) - { - sortExpression = "ORDER BY " + sortExpression; - } - - string commandString = String.Format("{0} {1}", selectCommand, sortExpression); - using (System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand(commandString)) - { - command.Connection = new System.Data.OleDb.OleDbConnection(Settings.Default.NwindConnectionString); - command.Connection.Open(); - IDataReader reader = command.ExecuteReader(); - data.Clear(); - - while (reader.Read()) - { - Customer customer = new Customer( - Convert.ToString(reader[0]), - Convert.ToString(reader[1]), - Convert.ToString(reader[2]), - Convert.ToString(reader[3]), - Convert.ToString(reader[4]), - Convert.ToString(reader[5])); - data.Add(customer); - } - - command.Connection.Close(); - } - - this.radVirtualGrid1.RowCount = data.Count; -} - -private void radVirtualGrid1_CellValueNeeded(object sender, Telerik.WinControls.UI.VirtualGridCellValueNeededEventArgs e) -{ - if (e.ColumnIndex < 0) - return; - if (e.RowIndex == RadVirtualGrid.HeaderRowIndex) - { - e.Value = columnNames[e.ColumnIndex]; - } - - if (e.RowIndex < 0) - { - e.FieldName = columnNames[e.ColumnIndex]; - } - - if (e.RowIndex >= 0 && e.RowIndex < data.Count) - { - e.Value = data[e.RowIndex][e.ColumnIndex]; - } -} - -private void VirtualGridSorting_Load(object sender, EventArgs e) -{ - this.radVirtualGrid1.ColumnCount = columnNames.Length; - this.radVirtualGrid1.CellValueNeeded += radVirtualGrid1_CellValueNeeded; - SelectData(); -} - -public class Customer -{ - public string CustomerId { get; set; } - - public string CompanyName { get; set; } - - public string ContactName { get; set; } - - public string ContactTitle { get; set; } - - public string Address { get; set; } - - public string PostalCode { get; set; } - - public Customer(string customerId, string companyName, string contactName, string contactTitle, string address, string postalCode) - { - this.CustomerId = customerId; - this.CompanyName = companyName; - this.ContactName = contactName; - this.ContactTitle = contactTitle; - this.Address = address; - this.PostalCode = postalCode; - } - - public string this[int i] - { - get - { - switch (i) - { - case 0: - return CompanyName; - case 1: - return ContactName; - case 2: - return ContactTitle; - case 3: - return Address; - case 4: - return PostalCode; - default: - return String.Empty; - } - } - } -} -```` -````VB.NET -Private Sub radVirtualGrid1_SortChanged(sender As Object, e As VirtualGridEventArgs) - SelectData() -End Sub -Private ReadOnly selectCommand As String = "SELECT CustomerID, CompanyName, ContactName, ContactTitle, Address, PostalCode FROM Customers" -Private columnNames As String() = New String() {"CompanyName", "ContactName", "ContactTitle", "Address", "PostalCode"} -Private data As New List(Of Customer)() -Private Sub SelectData() - Dim sortExpression As String = Me.RadVirtualGrid1.SortDescriptors.Expression - If Not String.IsNullOrEmpty(sortExpression) Then - sortExpression = Convert.ToString("ORDER BY ") & sortExpression - End If - Dim commandString As String = [String].Format("{0} {1}", selectCommand, sortExpression) - Using command As New System.Data.OleDb.OleDbCommand(commandString) - command.Connection = New System.Data.OleDb.OleDbConnection(My.Settings.NwindConnectionString) - command.Connection.Open() - Dim reader As IDataReader = command.ExecuteReader() - data.Clear() - While reader.Read() - Dim customer As New Customer(Convert.ToString(reader(0)), Convert.ToString(reader(1)), Convert.ToString(reader(2)), _ - Convert.ToString(reader(3)), Convert.ToString(reader(4)), Convert.ToString(reader(5))) - data.Add(customer) - End While - command.Connection.Close() - End Using - Me.RadVirtualGrid1.RowCount = data.Count -End Sub -Private Sub radVirtualGrid1_CellValueNeeded(sender As Object, e As Telerik.WinControls.UI.VirtualGridCellValueNeededEventArgs) - If e.ColumnIndex < 0 Then - Return - End If - If e.RowIndex = RadVirtualGrid.HeaderRowIndex Then - e.Value = columnNames(e.ColumnIndex) - End If - If e.RowIndex < 0 Then - e.FieldName = columnNames(e.ColumnIndex) - End If - If e.RowIndex >= 0 AndAlso e.RowIndex < data.Count Then - e.Value = data(e.RowIndex)(e.ColumnIndex) - End If -End Sub -Private Sub VirtualGridSorting_Load(sender As Object, e As EventArgs) Handles Me.Load - Me.RadVirtualGrid1.ColumnCount = columnNames.Length - AddHandler Me.RadVirtualGrid1.CellValueNeeded, AddressOf radVirtualGrid1_CellValueNeeded - SelectData() -End Sub -Public Class Customer - Public Property CustomerId() As String - Get - Return m_CustomerId - End Get - Set(value As String) - m_CustomerId = value - End Set - End Property - Private m_CustomerId As String - Public Property CompanyName() As String - Get - Return m_CompanyName - End Get - Set(value As String) - m_CompanyName = value - End Set - End Property - Private m_CompanyName As String - Public Property ContactName() As String - Get - Return m_ContactName - End Get - Set(value As String) - m_ContactName = value - End Set - End Property - Private m_ContactName As String - Public Property ContactTitle() As String - Get - Return m_ContactTitle - End Get - Set(value As String) - m_ContactTitle = value - End Set - End Property - Private m_ContactTitle As String - Public Property Address() As String - Get - Return m_Address - End Get - Set(value As String) - m_Address = value - End Set - End Property - Private m_Address As String - Public Property PostalCode() As String - Get - Return m_PostalCode - End Get - Set(value As String) - m_PostalCode = value - End Set - End Property - Private m_PostalCode As String - Public Sub New(customerId As String, companyName As String, contactName As String, contactTitle As String, address As String, postalCode As String) - Me.CustomerId = customerId - Me.CompanyName = companyName - Me.ContactName = contactName - Me.ContactTitle = contactTitle - Me.Address = address - Me.PostalCode = postalCode - End Sub - Default Public ReadOnly Property Item(i As Integer) As String - Get - Select Case i - Case 0 - Return CompanyName - Case 1 - Return ContactName - Case 2 - Return ContactTitle - Case 3 - Return Address - Case 4 - Return PostalCode - Case Else - Return [String].Empty - End Select - End Get - End Property -End Class - -```` - -{{endregion}} - - - ## See Also * [Setting Sorting Programmatically]({%slug winforms/virtualgrid/sorting/setting-sorting-programmatically%}) diff --git a/controls/virtualgrid/getting-started.md b/controls/virtualgrid/getting-started.md index 431092621..6572a52d1 100644 --- a/controls/virtualgrid/getting-started.md +++ b/controls/virtualgrid/getting-started.md @@ -45,214 +45,40 @@ The example bellow demonstrates how one can use __RadVirtualGrid__ with a list w 1\. Add a __RadVirtualGrid__ to a form and set its __Dock__ property to *Fill* . 2\. Add the following sample class to the project. -{{source=..\SamplesCS\VirtualGrid\VirtualGridGettingStarted.cs region=SampleClass}} -{{source=..\SamplesVB\VirtualGrid\VirtualGridGettingStarted.vb region=SampleClass}} -````C# - -public class CarPart -{ - public string Name { get; set; } - - public string Make { get; set; } - - public int PartID { get; set; } - - public string this[int i] - { - get - { - switch (i) - { - case 0: - return Name; - case 1: - return Make; - case 2: - return PartID.ToString(); - default: - return string.Empty; - } - } - } -} - -```` -````VB.NET -Public Class CarPart - Public Property Name() As String - Public Property Make() As String - Public Property PartID() As Integer - Default Public ReadOnly Property Item(ByVal i As Integer) As String - Get - Select Case i - Case 0 - Return Name - Case 1 - Return Make - Case 2 - Return PartID.ToString() - Case Else - Return String.Empty - End Select - End Get - End Property -End Class - -```` - -{{endregion}} + + + + 3\. Now you can create the list of objects which will be used as data source. In addition you can create an array that contains the column names. -{{source=..\SamplesCS\VirtualGrid\VirtualGridGettingStarted.cs region=CreateData}} -{{source=..\SamplesVB\VirtualGrid\VirtualGridGettingStarted.vb region=CreateData}} -````C# - -List data = new List(); -private string[] columnNames = new string[] -{ - "Name", - "Make", - "PartId" -}; - -public VirtualGridGettingStarted() -{ - InitializeComponent(); - for (int i = 0; i < 1000000; i++) - { - data.Add(new CarPart() - { - Name = "Name " + i, - Make = "Tesla", - PartID = i - }); - } -} - -```` -````VB.NET -Private data As New List(Of CarPart)() -Private columnNames() As String = {"Name", "Make", "PartId"} -Public Sub New() - InitializeComponent() - For i As Integer = 0 To 999999 - data.Add(New CarPart() With { - .Name = "Name " & i, - .Make = "Tesla", - .PartID = i - }) - Next i -End Sub - -```` - -{{endregion}} + + + + ### Using the virtual grid 1\. To use the grid you should first specify the count of columns and rows. In addition, you should subscribe to the __CellValueNeeded__ and __CellValuePushed__ events which are used for populating the grid with data and updating the data source when values are changed: -{{source=..\SamplesCS\VirtualGrid\VirtualGridGettingStarted.cs region=InitGrid}} -{{source=..\SamplesVB\VirtualGrid\VirtualGridGettingStarted.vb region=InitGrid}} -````C# - -radVirtualGrid1.CellValueNeeded += RadVirtualGrid1_CellValueNeeded; -radVirtualGrid1.CellValuePushed += RadVirtualGrid1_CellValuePushed; -radVirtualGrid1.ColumnCount = columnNames.Length; -radVirtualGrid1.RowCount = data.Count; - -```` -````VB.NET -AddHandler radVirtualGrid1.CellValueNeeded, AddressOf RadVirtualGrid1_CellValueNeeded -AddHandler radVirtualGrid1.CellValuePushed, AddressOf RadVirtualGrid1_CellValuePushed -radVirtualGrid1.ColumnCount = columnNames.Length -radVirtualGrid1.RowCount = data.Count + + -```` -{{endregion}} 2\. Now you can add the __CellValueNeeded__ event handler. In it we will retrieve the cell value and pass it to the grid according to the current row/column index. The event is fired for the header row so you can set the header cells text as well. -{{source=..\SamplesCS\VirtualGrid\VirtualGridGettingStarted.cs region=SetValue}} -{{source=..\SamplesVB\VirtualGrid\VirtualGridGettingStarted.vb region=SetValue}} -````C# - -private void RadVirtualGrid1_CellValueNeeded(object sender, VirtualGridCellValueNeededEventArgs e) -{ - if (e.ColumnIndex < 0) - return; - - if (e.RowIndex == RadVirtualGrid.HeaderRowIndex) - { - e.Value = columnNames[e.ColumnIndex]; - } - if (e.RowIndex >= 0 && e.RowIndex < data.Count) - { - e.Value = data[e.RowIndex][e.ColumnIndex]; - } -} - -```` -````VB.NET -Private Sub RadVirtualGrid1_CellValueNeeded(ByVal sender As Object, ByVal e As VirtualGridCellValueNeededEventArgs) - If e.ColumnIndex < 0 Then - Return - End If - If e.RowIndex = RadVirtualGrid.HeaderRowIndex Then - e.Value = columnNames(e.ColumnIndex) - End If - If e.RowIndex >= 0 AndAlso e.RowIndex < data.Count Then - e.Value = data(e.RowIndex)(e.ColumnIndex) - End If -End Sub - -```` - -{{endregion}} + + + + 3\. When a cell value is changed the __CellValuePushed__ event will fire. This will allow you to update the value in the data source: -{{source=..\SamplesCS\VirtualGrid\VirtualGridGettingStarted.cs region=UpdateValue}} -{{source=..\SamplesVB\VirtualGrid\VirtualGridGettingStarted.vb region=UpdateValue}} -````C# - -private void RadVirtualGrid1_CellValuePushed(object sender, VirtualGridCellValuePushedEventArgs e) -{ - switch (e.ColumnIndex) - { - case 0: - data[e.RowIndex].Name = e.Value.ToString(); - break; - case 1: - data[e.RowIndex].Make = e.Value.ToString(); - break; - case 2: - data[e.RowIndex].PartID = Convert.ToInt32(e.Value.ToString()); - break; - default: - break; - } -} - -```` -````VB.NET -Private Sub RadVirtualGrid1_CellValuePushed(ByVal sender As Object, ByVal e As VirtualGridCellValuePushedEventArgs) - Select Case e.ColumnIndex - Case 0 - data(e.RowIndex).Name = e.Value.ToString() - Case 1 - data(e.RowIndex).Make = e.Value.ToString() - Case 2 - data(e.RowIndex).PartID = Convert.ToInt32(e.Value.ToString()) - Case Else - End Select -End Sub - -```` - -{{endregion}} + + + + ### Add or remove rows @@ -262,48 +88,9 @@ By default the end user can add or remove rows with the UI. When such operation > The following example shows how you can handle the above events and properly update the data source. -{{source=..\SamplesCS\VirtualGrid\VirtualGridGettingStarted.cs region=AddRemove}} -{{source=..\SamplesVB\VirtualGrid\VirtualGridGettingStarted.vb region=AddRemove}} -````C# - -private void RadVirtualGrid1_UserAddedRow(object sender, VirtualGridNewRowEventArgs e) -{ - data.Add(new CarPart() - { - Name = e.NewValues[0].ToString(), - Make = e.NewValues[1].ToString(), - PartID = Convert.ToInt32(e.NewValues[2].ToString()) - }); -} -private void RadVirtualGrid1_UserDeletedRow(object sender, VirtualGridRowsEventArgs e) -{ - var indexesToRemove = e.RowIndices.ToList(); - - for (int i = indexesToRemove.Count - 1; i >= 0; i--) - { - data.RemoveAt(indexesToRemove[i]); - } -} - -```` -````VB.NET -Private Sub RadVirtualGrid1_UserAddedRow(ByVal sender As Object, ByVal e As VirtualGridNewRowEventArgs) - data.Add(New CarPart() With { - .Name = e.NewValues(0).ToString(), - .Make = e.NewValues(1).ToString(), - .PartID = Convert.ToInt32(e.NewValues(2).ToString()) - }) -End Sub -Private Sub RadVirtualGrid1_UserDeletedRow(ByVal sender As Object, ByVal e As VirtualGridRowsEventArgs) - Dim indexesToRemove = e.RowIndices.ToList() - For i As Integer = indexesToRemove.Count - 1 To 0 Step -1 - data.RemoveAt(indexesToRemove(i)) - Next i -End Sub - -```` - -{{endregion}} + + + ## See Also diff --git a/controls/virtualgrid/hierarchical-virtual-grid/hierarchical-data.md b/controls/virtualgrid/hierarchical-virtual-grid/hierarchical-data.md index 54fcd8283..9cdeda38e 100644 --- a/controls/virtualgrid/hierarchical-virtual-grid/hierarchical-data.md +++ b/controls/virtualgrid/hierarchical-virtual-grid/hierarchical-data.md @@ -30,514 +30,15 @@ The following example demonstrates how to setup the hierarchy in __RadVirtualGri #### Setup hierarchy -{{source=..\SamplesCS\VirtualGrid\Hierarchy\VirtualGridHierarchy.cs region=SetupHierarchy}} -{{source=..\SamplesVB\VirtualGrid\Hierarchy\VirtualGridHierarchy.vb region=SetupHierarchy}} + + -````C# - -List data = new List(); -private void VirtualGridHierarchy_Load(object sender, EventArgs e) -{ - this.employeesTableAdapter.Fill(this.nwindDataSet.Employees); - this.radVirtualGrid1.CellValueNeeded += radVirtualGrid1_CellValueNeeded; - this.radVirtualGrid1.QueryHasChildRows += radVirtualGrid1_QueryHasChildRows; - this.radVirtualGrid1.RowExpanding += radVirtualGrid1_RowExpanding; - this.radVirtualGrid1.CellFormatting += radVirtualGrid1_CellFormatting; - LoadData(); - this.radVirtualGrid1.TableElement.RowHeight = 120; -} - -private void radVirtualGrid1_RowExpanding(object sender, VirtualGridRowExpandingEventArgs e) -{ - e.ChildViewInfo.ColumnCount = Sale.FieldNames.Length; - e.ChildViewInfo.RowCount = data[e.ChildViewInfo.ParentRowIndex].Sales.Count; -} - -private void radVirtualGrid1_CellFormatting(object sender, VirtualGridCellElementEventArgs e) -{ - //display the Employee's image - if (e.CellElement.ColumnIndex < 0) - { - return; - } - - if (e.CellElement.Value is Image) - { - e.CellElement.Image = (Image)e.CellElement.Value; - e.CellElement.ImageLayout = ImageLayout.Zoom; - e.CellElement.Text = ""; - } - else - { - e.CellElement.ResetValue(LightVisualElement.ImageProperty, Telerik.WinControls.ValueResetFlags.Local); - } -} - -private void radVirtualGrid1_QueryHasChildRows(object sender, VirtualGridQueryHasChildRowsEventArgs e) -{ - e.HasChildRows = (e.ViewInfo == this.radVirtualGrid1.MasterViewInfo); -} - -private void radVirtualGrid1_CellValueNeeded(object sender, VirtualGridCellValueNeededEventArgs e) -{ - if (e.ViewInfo == this.radVirtualGrid1.MasterViewInfo) - { - if (e.ColumnIndex < 0) - { - return; - } - - e.FieldName = Employee.FieldNames[e.ColumnIndex]; - - if (e.RowIndex == RadVirtualGrid.HeaderRowIndex) - { - e.Value = e.FieldName; - } - else if (e.RowIndex >= 0) - { - e.Value = data[e.RowIndex][e.ColumnIndex]; - if (e.ColumnIndex == 2) - { - e.FormatString = "${0:#,###}"; - } - else if (e.ColumnIndex == 3) - { - e.FormatString = "{0:MM/dd/yy}"; - } - } - } - else - { - if (e.ColumnIndex < 0) - { - return; - } - - e.FieldName = Sale.FieldNames[e.ColumnIndex]; - - if (e.RowIndex == RadVirtualGrid.HeaderRowIndex) - { - e.Value = e.FieldName; - } - else if (e.RowIndex >= 0) - { - e.Value = data[e.ViewInfo.ParentRowIndex].Sales[e.RowIndex][e.ColumnIndex]; - if (e.ColumnIndex == 1) - { - e.FormatString = "#{0}"; - } - else if (e.ColumnIndex == 3) - { - e.FormatString = "{0:F2}%"; - } - else if (e.ColumnIndex == 4) - { - e.FormatString = "${0}"; - } - } - } -} - -private void LoadData() -{ - Random random = new Random(); - for (int i = 0; i < this.nwindDataSet.Employees.Count; i++) - { - DataSources.NwindDataSet.EmployeesRow row = this.nwindDataSet.Employees[i]; - Employee employee = new Employee(); - employee.Name = row.FirstName + " " + row.LastName; - employee.Photo = GetImageFromBytes(row.Photo); - employee.Salary = random.Next(45000); - employee.HireDate = row.HireDate; - employee.Title = row.Title; - int rowCount = random.Next(20) + 1; - for (int j = 0; j < rowCount; j++) - { - employee.Sales.Add(new Sale() - { - Name = employee.Name, ProductNumber = random.Next(1000), - Quantity = random.Next(50), Discount = random.Next(100), Total = random.Next(10000) - }); - } - data.Add(employee); - } - this.radVirtualGrid1.RowCount = data.Count; - this.radVirtualGrid1.ColumnCount = Employee.FieldNames.Length; -} - -private Image GetImageFromBytes(byte[] bytes) -{ - Image result = null; - MemoryStream stream = null; - - try - { - stream = new MemoryStream(bytes, 78, bytes.Length - 78); - result = Image.FromStream(stream); - } - catch - { - try - { - stream = new MemoryStream(bytes, 0, bytes.Length); - result = Image.FromStream(stream); - } - catch - { - result = null; - } - } - finally - { - if (stream != null) - stream.Close(); - } - - return result; -} -```` -````VB.NET -Private data As New List(Of Employee)() -Private Sub VirtualGridHierarchy_Load(sender As Object, e As EventArgs) Handles MyBase.Load - Me.EmployeesTableAdapter.Fill(Me.NwindDataSet.Employees) - AddHandler Me.RadVirtualGrid1.CellValueNeeded, AddressOf radVirtualGrid1_CellValueNeeded - AddHandler Me.RadVirtualGrid1.QueryHasChildRows, AddressOf radVirtualGrid1_QueryHasChildRows - AddHandler Me.RadVirtualGrid1.RowExpanding, AddressOf radVirtualGrid1_RowExpanding - AddHandler Me.RadVirtualGrid1.CellFormatting, AddressOf radVirtualGrid1_CellFormatting - LoadData() - Me.RadVirtualGrid1.TableElement.RowHeight = 120 -End Sub -Private Sub radVirtualGrid1_RowExpanding(sender As Object, e As VirtualGridRowExpandingEventArgs) - e.ChildViewInfo.ColumnCount = Sale.FieldNames.Length - e.ChildViewInfo.RowCount = data(e.ChildViewInfo.ParentRowIndex).Sales.Count -End Sub -Private Sub radVirtualGrid1_CellFormatting(sender As Object, e As VirtualGridCellElementEventArgs) - 'display the Employee's image - If e.CellElement.ColumnIndex < 0 Then - Return - End If - If TypeOf e.CellElement.Value Is Image Then - e.CellElement.Image = DirectCast(e.CellElement.Value, Image) - e.CellElement.ImageLayout = ImageLayout.Zoom - e.CellElement.Text = "" - Else - e.CellElement.ResetValue(LightVisualElement.ImageProperty, Telerik.WinControls.ValueResetFlags.Local) - End If -End Sub -Private Sub radVirtualGrid1_QueryHasChildRows(sender As Object, e As VirtualGridQueryHasChildRowsEventArgs) - e.HasChildRows = (e.ViewInfo.Equals(Me.RadVirtualGrid1.MasterViewInfo)) -End Sub -Private Sub radVirtualGrid1_CellValueNeeded(sender As Object, e As VirtualGridCellValueNeededEventArgs) - If e.ViewInfo.Equals(Me.RadVirtualGrid1.MasterViewInfo) Then - If e.ColumnIndex < 0 Then - Return - End If - e.FieldName = Employee.FieldNames(e.ColumnIndex) - If e.RowIndex = RadVirtualGrid.HeaderRowIndex Then - e.Value = e.FieldName - ElseIf e.RowIndex >= 0 Then - e.Value = data(e.RowIndex)(e.ColumnIndex) - If e.ColumnIndex = 2 Then - e.FormatString = "${0:#,###}" - ElseIf e.ColumnIndex = 3 Then - e.FormatString = "{0:MM/dd/yy}" - End If - End If - Else - If e.ColumnIndex < 0 Then - Return - End If - e.FieldName = Sale.FieldNames(e.ColumnIndex) - If e.RowIndex = RadVirtualGrid.HeaderRowIndex Then - e.Value = e.FieldName - ElseIf e.RowIndex >= 0 Then - e.Value = data(e.ViewInfo.ParentRowIndex).Sales(e.RowIndex)(e.ColumnIndex) - If e.ColumnIndex = 1 Then - e.FormatString = "#{0}" - ElseIf e.ColumnIndex = 3 Then - e.FormatString = "{0:F2}%" - ElseIf e.ColumnIndex = 4 Then - e.FormatString = "${0}" - End If - End If - End If -End Sub -Private Sub LoadData() - Dim random As New Random() - For i As Integer = 0 To Me.NwindDataSet.Employees.Count - 1 - Dim row As SamplesVB.NwindDataSet.EmployeesRow = Me.NwindDataSet.Employees(i) - Dim employee__1 As New Employee() - employee__1.Name = row.FirstName + " " + row.LastName - employee__1.Photo = GetImageFromBytes(row.Photo) - employee__1.Salary = random.[Next](45000) - employee__1.HireDate = row.HireDate - employee__1.Title = row.Title - Dim rowCount As Integer = random.[Next](20) + 1 - For j As Integer = 0 To rowCount - 1 - employee__1.Sales.Add(New Sale() With { _ - .Name = employee__1.Name, _ - .ProductNumber = random.[Next](1000), _ - .Quantity = random.[Next](50), _ - .Discount = random.[Next](100), _ - .Total = random.[Next](10000) _ - }) - Next - data.Add(employee__1) - Next - Me.RadVirtualGrid1.RowCount = data.Count - Me.RadVirtualGrid1.ColumnCount = Employee.FieldNames.Length -End Sub -Private Function GetImageFromBytes(bytes As Byte()) As Image - Dim result As Image = Nothing - Dim stream As MemoryStream = Nothing - Try - stream = New MemoryStream(bytes, 78, bytes.Length - 78) - result = Image.FromStream(stream) - Catch - Try - stream = New MemoryStream(bytes, 0, bytes.Length) - result = Image.FromStream(stream) - Catch - result = Nothing - End Try - Finally - If stream IsNot Nothing Then - stream.Close() - End If - End Try - Return result -End Function - -```` - -{{endregion}} #### *Employee* and *Sale* classes implementation -{{source=..\SamplesCS\VirtualGrid\Hierarchy\VirtualGridHierarchy.cs region=HelpClasses}} -{{source=..\SamplesVB\VirtualGrid\Hierarchy\VirtualGridHierarchy.vb region=HelpClasses}} - -````C# - -public class Employee -{ - public static readonly string[] FieldNames = { "Photo", "Name", "Salary", "HireDate", "Title" }; - public Image Photo { get; set; } - public string Name { get; set; } - public decimal Salary { get; set; } - public DateTime HireDate { get; set; } - public string Title { get; set; } - public List Sales { get; private set; } - - public object this[int index] - { - get - { - switch (index) - { - case 0: - return Photo; - case 1: - return Name; - case 2: - return Salary; - case 3: - return HireDate; - case 4: - return Title; - default: - return null; - } - } - } - - public Employee() - { - Sales = new List(); - } -} - -public class Sale -{ - public static readonly string[] FieldNames = { "Name", "ProductNumber", "Quantity", "Discount", "Total" }; - public string Name { get; set; } - public int ProductNumber { get; set; } - public int Quantity { get; set; } - public int Discount { get; set; } - public int Total { get; set; } - - public object this[int index] - { - get - { - switch (index) - { - case 0: - return Name; - case 1: - return ProductNumber; - case 2: - return Quantity; - case 3: - return Discount; - case 4: - return Total; - default: - return null; - } - } - } -} - -```` -````VB.NET -Public Class Employee - Public Shared ReadOnly FieldNames As String() = {"Photo", "Name", "Salary", "HireDate", "Title"} - Public Property Photo() As Image - Get - Return m_Photo - End Get - Set(value As Image) - m_Photo = value - End Set - End Property - Private m_Photo As Image - Public Property Name() As String - Get - Return m_Name - End Get - Set(value As String) - m_Name = value - End Set - End Property - Private m_Name As String - Public Property Salary() As Decimal - Get - Return m_Salary - End Get - Set(value As Decimal) - m_Salary = value - End Set - End Property - Private m_Salary As Decimal - Public Property HireDate() As DateTime - Get - Return m_HireDate - End Get - Set(value As DateTime) - m_HireDate = value - End Set - End Property - Private m_HireDate As DateTime - Public Property Title() As String - Get - Return m_Title - End Get - Set(value As String) - m_Title = value - End Set - End Property - Private m_Title As String - Public Property Sales() As List(Of Sale) - Get - Return m_Sales - End Get - Private Set(value As List(Of Sale)) - m_Sales = value - End Set - End Property - Private m_Sales As List(Of Sale) - Default Public ReadOnly Property Item(index As Integer) As Object - Get - Select Case index - Case 0 - Return Photo - Case 1 - Return Name - Case 2 - Return Salary - Case 3 - Return HireDate - Case 4 - Return Title - Case Else - Return Nothing - End Select - End Get - End Property - Public Sub New() - Sales = New List(Of Sale)() - End Sub -End Class -Public Class Sale - Public Shared ReadOnly FieldNames As String() = {"Name", "ProductNumber", "Quantity", "Discount", "Total"} - Public Property Name() As String - Get - Return m_Name - End Get - Set(value As String) - m_Name = value - End Set - End Property - Private m_Name As String - Public Property ProductNumber() As Integer - Get - Return m_ProductNumber - End Get - Set(value As Integer) - m_ProductNumber = value - End Set - End Property - Private m_ProductNumber As Integer - Public Property Quantity() As Integer - Get - Return m_Quantity - End Get - Set(value As Integer) - m_Quantity = value - End Set - End Property - Private m_Quantity As Integer - Public Property Discount() As Integer - Get - Return m_Discount - End Get - Set(value As Integer) - m_Discount = value - End Set - End Property - Private m_Discount As Integer - Public Property Total() As Integer - Get - Return m_Total - End Get - Set(value As Integer) - m_Total = value - End Set - End Property - Private m_Total As Integer - Default Public ReadOnly Property Item(index As Integer) As Object - Get - Select Case index - Case 0 - Return Name - Case 1 - Return ProductNumber - Case 2 - Return Quantity - Case 3 - Return Discount - Case 4 - Return Total - Case Else - Return Nothing - End Select - End Get - End Property -End Class + + -```` -{{endregion}} diff --git a/controls/virtualgrid/how-to/summary-rows.md b/controls/virtualgrid/how-to/summary-rows.md index d2956c3af..ad1bf35f0 100644 --- a/controls/virtualgrid/how-to/summary-rows.md +++ b/controls/virtualgrid/how-to/summary-rows.md @@ -21,306 +21,10 @@ We will use a sample DataTable to populate the __RadVirtualGrid__ with data by u You can find below a complete code snippet which result is illustrated on the above figure: -{{source=..\SamplesCS\VirtualGrid\HowTo\VirtualGridSummaryRows.cs region=SummaryRows}} -{{source=..\SamplesVB\VirtualGrid\HowTo\VirtualGridSummaryRows.vb region=SummaryRows}} + + -````C# - -private DataTable table = new DataTable(); -private List summaryRowIndices = new List(); - -public VirtualGridSummaryRows() -{ - InitializeComponent(); - - this.table = this.GenerateData(); - - this.summaryRowIndices.AddRange(new int[] { 5, 11, 14, 20, 25, 35 }); - - this.radVirtualGrid1.RowCount = table.Rows.Count + summaryRowIndices.Count; - this.radVirtualGrid1.ColumnCount = table.Columns.Count; - this.radVirtualGrid1.CellValueNeeded += VirtualGridElement_CellValueNeeded; - this.radVirtualGrid1.CellValuePushed += VirtualGridElement_CellValuePushed; - this.radVirtualGrid1.CellFormatting += radVirtualGrid1_CellFormatting; -} - -private DataTable GenerateData() -{ - DataTable table = new DataTable(); - - for (int i = 0; i < 4; i++) - { - table.Columns.Add("Column" + i, typeof(decimal)); - } - - for (int i = 0; i < 30; i++) - { - table.Rows.Add(i, i, i, i); - } - - return table; -} - -private void VirtualGridElement_CellValueNeeded(object sender, VirtualGridCellValueNeededEventArgs e) -{ - if (e.RowIndex < 0 && e.ColumnIndex >= 0) - { - if (e.RowIndex == RadVirtualGrid.HeaderRowIndex) - { - e.Value = table.Columns[e.ColumnIndex].ColumnName; - } - } - else if (e.RowIndex >= 0 && e.ColumnIndex >= 0) - { - if (this.IsSummaryRow(e.RowIndex)) - { - e.Value = this.GetSummaryValue(e.RowIndex, e.ColumnIndex); - } - else - { - e.Value = this.table.Rows[this.GetDataSourceRowIndex(e.RowIndex)][e.ColumnIndex]; - } - } -} - -private void radVirtualGrid1_CellFormatting(object sender, VirtualGridCellElementEventArgs e) -{ - if (this.IsSummaryRow(e.CellElement.RowIndex)) - { - e.CellElement.BackColor = Color.LightBlue; - e.CellElement.DrawFill = true; - e.CellElement.GradientStyle = GradientStyles.Solid; - } - else - { - e.CellElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local); - } -} - -private void VirtualGridElement_CellValuePushed(object sender, VirtualGridCellValuePushedEventArgs e) -{ - this.table.Rows[this.GetDataSourceRowIndex(e.RowIndex)][e.ColumnIndex] = e.Value; - this.radVirtualGrid1.TableElement.SynchronizeRows(); -} - -private bool IsSummaryRow(int virtualGridRowIndex) -{ - return this.summaryRowIndices.BinarySearch(virtualGridRowIndex) >= 0; -} - -private int GetDataSourceRowIndex(int virtualGridRowIndex) -{ - int result = virtualGridRowIndex; - - for (int i = 0; i < this.summaryRowIndices.Count; i++) - { - if (virtualGridRowIndex >= this.summaryRowIndices[i]) - { - result--; - } - else - { - break; - } - } - - return result; -} - -private object GetSummaryValue(int virtualGridRowIndex, int virtualGridcolumnIndex) -{ - int index = this.summaryRowIndices.BinarySearch(virtualGridRowIndex); - - if (index < 0) - { - return null; - } - - int startIndex = 0; - int endIndex = 0; - - if (index == 0) - { - startIndex = 0; - endIndex = this.summaryRowIndices[index] - 1; - } - else - { - startIndex = this.summaryRowIndices[index - 1] + 1; - endIndex = this.summaryRowIndices[index] - 1; - } - - startIndex = this.GetDataSourceRowIndex(startIndex); - endIndex = this.GetDataSourceRowIndex(endIndex); - - return this.ExecuteSummaryFunction(startIndex, endIndex, virtualGridcolumnIndex); -} - -private object ExecuteSummaryFunction(int startRowIndex, int endRowIndex, int columnIndex) -{ - switch (columnIndex) - { - case 0: - decimal sum = 0; - - for (int i = startRowIndex; i <= endRowIndex; i++) - { - sum += (decimal)this.table.Rows[i][columnIndex]; - } - - return "Sum = " + sum; - case 1: - decimal avgSum = 0; - - for (int i = startRowIndex; i <= endRowIndex; i++) - { - avgSum += (decimal)this.table.Rows[i][columnIndex]; - } - - return "Avg = " + (avgSum / (endRowIndex - startRowIndex + 1)); - case 2: - decimal min = int.MaxValue; - - for (int i = startRowIndex; i <= endRowIndex; i++) - { - min = Math.Min(min, (decimal)this.table.Rows[i][columnIndex]); - } - - return "Min = " + min; - case 3: - decimal max = int.MinValue; - - for (int i = startRowIndex; i <= endRowIndex; i++) - { - max = Math.Max(max, (decimal)this.table.Rows[i][columnIndex]); - } - - return "Max = " + max; - default: - return null; - } -} -```` -````VB.NET -Private table As New DataTable() -Private summaryRowIndices As New List(Of Integer)() -Public Sub New() - InitializeComponent() - Me.table = Me.GenerateData() - Me.summaryRowIndices.AddRange(New Integer() {5, 11, 14, 20, 25, 35}) - Me.RadVirtualGrid1.RowCount = table.Rows.Count + summaryRowIndices.Count - Me.RadVirtualGrid1.ColumnCount = table.Columns.Count - AddHandler Me.RadVirtualGrid1.CellValueNeeded, AddressOf VirtualGridElement_CellValueNeeded - AddHandler Me.RadVirtualGrid1.CellValuePushed, AddressOf VirtualGridElement_CellValuePushed - AddHandler Me.RadVirtualGrid1.CellFormatting, AddressOf radVirtualGrid1_CellFormatting -End Sub -Private Function GenerateData() As DataTable - Dim table As New DataTable() - For i As Integer = 0 To 3 - table.Columns.Add("Column" & i, GetType(Decimal)) - Next - For i As Integer = 0 To 29 - table.Rows.Add(i, i, i, i) - Next - Return table -End Function -Private Sub VirtualGridElement_CellValueNeeded(sender As Object, e As VirtualGridCellValueNeededEventArgs) - If e.RowIndex < 0 AndAlso e.ColumnIndex >= 0 Then - If e.RowIndex = RadVirtualGrid.HeaderRowIndex Then - e.Value = table.Columns(e.ColumnIndex).ColumnName - End If - ElseIf e.RowIndex >= 0 AndAlso e.ColumnIndex >= 0 Then - If Me.IsSummaryRow(e.RowIndex) Then - e.Value = Me.GetSummaryValue(e.RowIndex, e.ColumnIndex) - Else - e.Value = Me.table.Rows(Me.GetDataSourceRowIndex(e.RowIndex))(e.ColumnIndex) - End If - End If -End Sub -Private Sub radVirtualGrid1_CellFormatting(sender As Object, e As VirtualGridCellElementEventArgs) - If Me.IsSummaryRow(e.CellElement.RowIndex) Then - e.CellElement.BackColor = Color.LightBlue - e.CellElement.DrawFill = True - e.CellElement.GradientStyle = GradientStyles.Solid - Else - e.CellElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local) - End If -End Sub -Private Sub VirtualGridElement_CellValuePushed(sender As Object, e As VirtualGridCellValuePushedEventArgs) - Me.table.Rows(Me.GetDataSourceRowIndex(e.RowIndex))(e.ColumnIndex) = e.Value - Me.RadVirtualGrid1.TableElement.SynchronizeRows() -End Sub -Private Function IsSummaryRow(virtualGridRowIndex As Integer) As Boolean - Return Me.summaryRowIndices.BinarySearch(virtualGridRowIndex) >= 0 -End Function -Private Function GetDataSourceRowIndex(virtualGridRowIndex As Integer) As Integer - Dim result As Integer = virtualGridRowIndex - For i As Integer = 0 To Me.summaryRowIndices.Count - 1 - If virtualGridRowIndex >= Me.summaryRowIndices(i) Then - result -= 1 - Else - Exit For - End If - Next - Return result -End Function -Private Function GetSummaryValue(virtualGridRowIndex As Integer, virtualGridcolumnIndex As Integer) As Object - Dim index As Integer = Me.summaryRowIndices.BinarySearch(virtualGridRowIndex) - If index < 0 Then - Return Nothing - End If - Dim startIndex As Integer = 0 - Dim endIndex As Integer = 0 - If index = 0 Then - startIndex = 0 - endIndex = Me.summaryRowIndices(index) - 1 - Else - startIndex = Me.summaryRowIndices(index - 1) + 1 - endIndex = Me.summaryRowIndices(index) - 1 - End If - startIndex = Me.GetDataSourceRowIndex(startIndex) - endIndex = Me.GetDataSourceRowIndex(endIndex) - Return Me.ExecuteSummaryFunction(startIndex, endIndex, virtualGridcolumnIndex) -End Function -Private Function ExecuteSummaryFunction(startRowIndex As Integer, endRowIndex As Integer, columnIndex As Integer) As Object - Select Case columnIndex - Case 0 - Dim sum As Decimal = 0 - For i As Integer = startRowIndex To endRowIndex - sum += CDec(Me.table.Rows(i)(columnIndex)) - Next - Return "Sum = " & sum - Case 1 - Dim avgSum As Decimal = 0 - For i As Integer = startRowIndex To endRowIndex - avgSum += CDec(Me.table.Rows(i)(columnIndex)) - Next - Return "Avg = " & (avgSum / (endRowIndex - startRowIndex + 1)) - Case 2 - Dim min As Decimal = Integer.MaxValue - For i As Integer = startRowIndex To endRowIndex - min = Math.Min(min, CDec(Me.table.Rows(i)(columnIndex))) - Next - Return "Min = " & min - Case 3 - Dim max As Decimal = Integer.MinValue - For i As Integer = startRowIndex To endRowIndex - max = Math.Max(max, CDec(Me.table.Rows(i)(columnIndex))) - Next - Return "Max = " & max - Case Else - Return Nothing - End Select -End Function - -```` - -{{endregion}} # See Also diff --git a/controls/virtualgrid/localization/localization.md b/controls/virtualgrid/localization/localization.md index a0b077dce..3d6420820 100644 --- a/controls/virtualgrid/localization/localization.md +++ b/controls/virtualgrid/localization/localization.md @@ -22,228 +22,19 @@ Below is a sample implementation of an English localization provider: #### Localizing RadVirtualGrid Strings -{{source=..\SamplesCS\VirtualGrid\Localization\MyRadVirtualGridLocalizationProvider.cs region=MyLocalizationProvider}} -{{source=..\SamplesVB\VirtualGrid\Localization\MyRadVirtualGridLocalizationProvider.vb region=MyLocalizationProvider}} -````C# -public class MyRadVirtualGridLocalizationProvider : RadVirtualGridLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case RadVirtualGridStringId.NoDataText: return "No data to display"; - case RadVirtualGridStringId.FilterFunctionBetween: return "Between"; - case RadVirtualGridStringId.FilterFunctionContains: return "Contains"; - case RadVirtualGridStringId.FilterFunctionDoesNotContain: return "Does not contain"; - case RadVirtualGridStringId.FilterFunctionEndsWith: return "Ends with"; - case RadVirtualGridStringId.FilterFunctionEqualTo: return "Equals"; - case RadVirtualGridStringId.FilterFunctionGreaterThan: return "Greater than"; - case RadVirtualGridStringId.FilterFunctionGreaterThanOrEqualTo: return "Greater than or equal to"; - case RadVirtualGridStringId.FilterFunctionIsEmpty: return "Is empty"; - case RadVirtualGridStringId.FilterFunctionIsNull: return "Is null"; - case RadVirtualGridStringId.FilterFunctionLessThan: return "Less than"; - case RadVirtualGridStringId.FilterFunctionLessThanOrEqualTo: return "Less than or equal to"; - case RadVirtualGridStringId.FilterFunctionNoFilter: return "No filter"; - case RadVirtualGridStringId.FilterFunctionNotBetween: return "Not between"; - case RadVirtualGridStringId.FilterFunctionNotEqualTo: return "Not equal to"; - case RadVirtualGridStringId.FilterFunctionNotIsEmpty: return "Is not empty"; - case RadVirtualGridStringId.FilterFunctionNotIsNull: return "Is not null"; - case RadVirtualGridStringId.FilterFunctionStartsWith: return "Starts with"; - case RadVirtualGridStringId.FilterFunctionCustom: return "Custom"; - case RadVirtualGridStringId.FilterOperatorNoFilter: return "No filter"; - case RadVirtualGridStringId.FilterOperatorCustom: return "Custom"; - case RadVirtualGridStringId.FilterOperatorIsLike: return "Like"; - case RadVirtualGridStringId.FilterOperatorNotIsLike: return "NotLike"; - case RadVirtualGridStringId.FilterOperatorLessThan: return "LessThan"; - case RadVirtualGridStringId.FilterOperatorLessThanOrEqualTo: return "LessThanOrEquals"; - case RadVirtualGridStringId.FilterOperatorEqualTo: return "Equals"; - case RadVirtualGridStringId.FilterOperatorNotEqualTo: return "NotEquals"; - case RadVirtualGridStringId.FilterOperatorGreaterThanOrEqualTo: return "GreaterThanOrEquals"; - case RadVirtualGridStringId.FilterOperatorGreaterThan: return "GreaterThan"; - case RadVirtualGridStringId.FilterOperatorStartsWith: return "StartsWith"; - case RadVirtualGridStringId.FilterOperatorEndsWith: return "EndsWith"; - case RadVirtualGridStringId.FilterOperatorContains: return "Contains"; - case RadVirtualGridStringId.FilterOperatorDoesNotContain: return "NotContains"; - case RadVirtualGridStringId.FilterOperatorIsNull: return "IsNull"; - case RadVirtualGridStringId.FilterOperatorNotIsNull: return "NotNull"; - case RadVirtualGridStringId.FilterOperatorIsContainedIn: return "ContainedIn"; - case RadVirtualGridStringId.FilterOperatorNotIsContainedIn: return "NotContainedIn"; - case RadVirtualGridStringId.AddNewRowString: return "Click here to add a new row"; - case RadVirtualGridStringId.PagingPanelPagesLabel: return "Page"; - case RadVirtualGridStringId.PagingPanelOfPagesLabel: return "of"; - case RadVirtualGridStringId.BestFitMenuItem: return "Best Fit"; - case RadVirtualGridStringId.ClearSortingMenuItem: return "Clear Sorting"; - case RadVirtualGridStringId.SortDescendingMenuItem: return "Sort Descending"; - case RadVirtualGridStringId.SortAscendingMenuItem: return "Sort Ascending"; - case RadVirtualGridStringId.PinAtRightMenuItem: return "Pin at right"; - case RadVirtualGridStringId.PinAtLeftMenuItem: return "Pin at left"; - case RadVirtualGridStringId.PinAtBottomMenuItem: return "Pin at bottom"; - case RadVirtualGridStringId.PinAtTopMenuItem: return "Pin at top"; - case RadVirtualGridStringId.UnpinColumnMenuItem: return "Unpin Column"; - case RadVirtualGridStringId.UnpinRowMenuItem: return "Unpin Row"; - case RadVirtualGridStringId.PinMenuItem: return "Pinned state"; - case RadVirtualGridStringId.DeleteRowMenuItem: return "Delete Row"; - case RadVirtualGridStringId.ClearValueMenuItem: return "Clear Value"; - case RadVirtualGridStringId.EditMenuItem: return "Edit"; - case RadVirtualGridStringId.PasteMenuItem: return "Paste"; - case RadVirtualGridStringId.CutMenuItem: return "Cut"; - case RadVirtualGridStringId.CopyMenuItem: return "Copy"; - default: - return base.GetLocalizedString(id); - } - } -} - -```` -````VB.NET -Public Class MyRadVirtualGridLocalizationProvider - Inherits RadVirtualGridLocalizationProvider - Public Overrides Function GetLocalizedString(id As String) As String - Select Case id - Case RadVirtualGridStringId.NoDataText - Return "No data to display" - Case RadVirtualGridStringId.FilterFunctionBetween - Return "Between" - Case RadVirtualGridStringId.FilterFunctionContains - Return "Contains" - Case RadVirtualGridStringId.FilterFunctionDoesNotContain - Return "Does not contain" - Case RadVirtualGridStringId.FilterFunctionEndsWith - Return "Ends with" - Case RadVirtualGridStringId.FilterFunctionEqualTo - Return "Equals" - Case RadVirtualGridStringId.FilterFunctionGreaterThan - Return "Greater than" - Case RadVirtualGridStringId.FilterFunctionGreaterThanOrEqualTo - Return "Greater than or equal to" - Case RadVirtualGridStringId.FilterFunctionIsEmpty - Return "Is empty" - Case RadVirtualGridStringId.FilterFunctionIsNull - Return "Is null" - Case RadVirtualGridStringId.FilterFunctionLessThan - Return "Less than" - Case RadVirtualGridStringId.FilterFunctionLessThanOrEqualTo - Return "Less than or equal to" - Case RadVirtualGridStringId.FilterFunctionNoFilter - Return "No filter" - Case RadVirtualGridStringId.FilterFunctionNotBetween - Return "Not between" - Case RadVirtualGridStringId.FilterFunctionNotEqualTo - Return "Not equal to" - Case RadVirtualGridStringId.FilterFunctionNotIsEmpty - Return "Is not empty" - Case RadVirtualGridStringId.FilterFunctionNotIsNull - Return "Is not null" - Case RadVirtualGridStringId.FilterFunctionStartsWith - Return "Starts with" - Case RadVirtualGridStringId.FilterFunctionCustom - Return "Custom" - Case RadVirtualGridStringId.FilterOperatorNoFilter - Return "No filter" - Case RadVirtualGridStringId.FilterOperatorCustom - Return "Custom" - Case RadVirtualGridStringId.FilterOperatorIsLike - Return "Like" - Case RadVirtualGridStringId.FilterOperatorNotIsLike - Return "NotLike" - Case RadVirtualGridStringId.FilterOperatorLessThan - Return "LessThan" - Case RadVirtualGridStringId.FilterOperatorLessThanOrEqualTo - Return "LessThanOrEquals" - Case RadVirtualGridStringId.FilterOperatorEqualTo - Return "Equals" - Case RadVirtualGridStringId.FilterOperatorNotEqualTo - Return "NotEquals" - Case RadVirtualGridStringId.FilterOperatorGreaterThanOrEqualTo - Return "GreaterThanOrEquals" - Case RadVirtualGridStringId.FilterOperatorGreaterThan - Return "GreaterThan" - Case RadVirtualGridStringId.FilterOperatorStartsWith - Return "StartsWith" - Case RadVirtualGridStringId.FilterOperatorEndsWith - Return "EndsWith" - Case RadVirtualGridStringId.FilterOperatorContains - Return "Contains" - Case RadVirtualGridStringId.FilterOperatorDoesNotContain - Return "NotContains" - Case RadVirtualGridStringId.FilterOperatorIsNull - Return "IsNull" - Case RadVirtualGridStringId.FilterOperatorNotIsNull - Return "NotNull" - Case RadVirtualGridStringId.FilterOperatorIsContainedIn - Return "ContainedIn" - Case RadVirtualGridStringId.FilterOperatorNotIsContainedIn - Return "NotContainedIn" - Case RadVirtualGridStringId.AddNewRowString - Return "Click here to add a new row" - Case RadVirtualGridStringId.PagingPanelPagesLabel - Return "Page" - Case RadVirtualGridStringId.PagingPanelOfPagesLabel - Return "of" - Case RadVirtualGridStringId.BestFitMenuItem - Return "Best Fit" - Case RadVirtualGridStringId.ClearSortingMenuItem - Return "Clear Sorting" - Case RadVirtualGridStringId.SortDescendingMenuItem - Return "Sort Descending" - Case RadVirtualGridStringId.SortAscendingMenuItem - Return "Sort Ascending" - Case RadVirtualGridStringId.PinAtRightMenuItem - Return "Pin at right" - Case RadVirtualGridStringId.PinAtLeftMenuItem - Return "Pin at left" - Case RadVirtualGridStringId.PinAtBottomMenuItem - Return "Pin at bottom" - Case RadVirtualGridStringId.PinAtTopMenuItem - Return "Pin at top" - Case RadVirtualGridStringId.UnpinColumnMenuItem - Return "Unpin Column" - Case RadVirtualGridStringId.UnpinRowMenuItem - Return "Unpin Row" - Case RadVirtualGridStringId.PinMenuItem - Return "Pinned state" - Case RadVirtualGridStringId.DeleteRowMenuItem - Return "Delete Row" - Case RadVirtualGridStringId.ClearValueMenuItem - Return "Clear Value" - Case RadVirtualGridStringId.EditMenuItem - Return "Edit" - Case RadVirtualGridStringId.PasteMenuItem - Return "Paste" - Case RadVirtualGridStringId.CutMenuItem - Return "Cut" - Case RadVirtualGridStringId.CopyMenuItem - Return "Copy" - Case Else - Return MyBase.GetLocalizedString(id) - End Select - End Function -End Class - -```` - - - -{{endregion}} + + -To apply the custom localization provider, instantiate and assign it to the current localization provider: - -#### Assigning the Current Localization Provider -{{source=..\SamplesCS\VirtualGrid\Localization\VirtualGridLocalization.cs region=LocalizeGrid}} -{{source=..\SamplesVB\VirtualGrid\Localization\VirtualGridLocalization.vb region=LocalizeGrid}} -````C# -RadVirtualGridLocalizationProvider.CurrentProvider = new MyRadVirtualGridLocalizationProvider(); -```` -````VB.NET -RadVirtualGridLocalizationProvider.CurrentProvider = New MyRadVirtualGridLocalizationProvider() +To apply the custom localization provider, instantiate and assign it to the current localization provider: -```` +#### Assigning the Current Localization Provider + + -{{endregion}} The code provided above illustrates the approach to be used to localize the __RadVirtualGrid__ and is not intended as a full translation. diff --git a/controls/virtualgrid/visual-elements/cells/creating-custom-cells.md b/controls/virtualgrid/visual-elements/cells/creating-custom-cells.md index 29db6044f..4dcbfba24 100644 --- a/controls/virtualgrid/visual-elements/cells/creating-custom-cells.md +++ b/controls/virtualgrid/visual-elements/cells/creating-custom-cells.md @@ -38,232 +38,33 @@ You can use the following approach to create a custom data cell with a check box #### Custom VirtualGridCellElement -{{source=..\SamplesCS\VirtualGrid\Cells\VirtualGridCustomCells.cs region=CustomCell}} -{{source=..\SamplesVB\VirtualGrid\Cells\VirtualGridCustomCells.vb region=CustomCell}} - - -````C# - -public class MyVirtualGridCheckBoxCellElement : VirtualGridCellElement -{ - private RadCheckBoxElement checkBox; - - protected override void CreateChildElements() - { - base.CreateChildElements(); - - this.checkBox = new RadCheckBoxElement(); - this.Children.Add(this.checkBox); - } - - protected override void UpdateInfo(VirtualGridCellValueNeededEventArgs args) - { - base.UpdateInfo(args); - - if (args.Value is bool) - { - this.checkBox.Checked = (bool)args.Value; - } - - this.Text = String.Empty; - } - - public override bool IsCompatible(int data, object context) - { - VirtualGridRowElement rowElement = context as VirtualGridRowElement; - - return data == 3 && rowElement.RowIndex >= 0; - } - - public override void Attach(int data, object context) - { - base.Attach(data, context); - - this.checkBox.ToggleStateChanged += checkBox_ToggleStateChanged; - } - - public override void Detach() - { - this.checkBox.ToggleStateChanged -= checkBox_ToggleStateChanged; - - base.Detach(); - } - - protected override SizeF ArrangeOverride(SizeF finalSize) - { - SizeF size = base.ArrangeOverride(finalSize); - - this.checkBox.Arrange(new RectangleF((finalSize.Width - this.checkBox.DesiredSize.Width) / 2f, - (finalSize.Height - this.checkBox.DesiredSize.Height) / 2f, this.checkBox.DesiredSize.Width, this.checkBox.DesiredSize.Height)); - - return size; - } - - protected override Type ThemeEffectiveType - { - get - { - return typeof(VirtualGridCellElement); - } - } - - private void checkBox_ToggleStateChanged(object sender, StateChangedEventArgs args) - { - this.TableElement.GridElement.SetCellValue(this.checkBox.Checked, this.RowIndex, this.ColumnIndex, this.ViewInfo); - } -} - -```` -````VB.NET -Public Class MyVirtualGridCheckBoxCellElement - Inherits VirtualGridCellElement - Private checkBox As RadCheckBoxElement - Protected Overrides Sub CreateChildElements() - MyBase.CreateChildElements() - Me.checkBox = New RadCheckBoxElement() - Me.Children.Add(Me.checkBox) - End Sub - Protected Overrides Sub UpdateInfo(args As VirtualGridCellValueNeededEventArgs) - MyBase.UpdateInfo(args) - If TypeOf args.Value Is Boolean Then - Me.checkBox.Checked = CBool(args.Value) - End If - Me.Text = [String].Empty - End Sub - Public Overrides Function IsCompatible(data As Integer, context As Object) As Boolean - Dim rowElement As VirtualGridRowElement = TryCast(context, VirtualGridRowElement) - Return data = 3 AndAlso rowElement.RowIndex = 0 - End Function - Public Overrides Sub Attach(data As Integer, context As Object) - MyBase.Attach(data, context) - AddHandler Me.checkBox.ToggleStateChanged, AddressOf checkBox_ToggleStateChanged - End Sub - Public Overrides Sub Detach() - RemoveHandler Me.checkBox.ToggleStateChanged, AddressOf checkBox_ToggleStateChanged - MyBase.Detach() - End Sub - Protected Overrides Function ArrangeOverride(finalSize As SizeF) As SizeF - Dim size As SizeF = MyBase.ArrangeOverride(finalSize) - Me.checkBox.Arrange(New RectangleF((finalSize.Width - Me.checkBox.DesiredSize.Width) / 2.0F, _ - (finalSize.Height - Me.checkBox.DesiredSize.Height) / 2.0F, Me.checkBox.DesiredSize.Width, Me.checkBox.DesiredSize.Height)) - Return size - End Function - Protected Overrides ReadOnly Property ThemeEffectiveType() As Type - Get - Return GetType(VirtualGridCellElement) - End Get - End Property - Private Sub checkBox_ToggleStateChanged(sender As Object, args As StateChangedEventArgs) - Me.TableElement.GridElement.SetCellValue(Me.checkBox.Checked, Me.RowIndex, Me.ColumnIndex, Me.ViewInfo) - End Sub -End Class - -```` - -{{endregion}} + + + + 8\. Once, you are ready with the implementation for the custom data cell, you should create the default cell: -{{source=..\SamplesCS\VirtualGrid\Cells\VirtualGridCustomCells.cs region=UsingDefaultCustomCell}} -{{source=..\SamplesVB\VirtualGrid\Cells\VirtualGridCustomCells.vb region=UsingDefaultCustomCell}} - -````C# -public class DefaultVirtualGridCellElement : VirtualGridCellElement -{ - public override bool IsCompatible(int data, object context) - { - VirtualGridRowElement rowElement = context as VirtualGridRowElement; - - return data != 3 && rowElement.RowIndex >= 0; - } - protected override Type ThemeEffectiveType - { - get - { - return typeof(VirtualGridCellElement); - } - } -} - -```` -````VB.NET -Public Class DefaultVirtualGridCellElement - Inherits VirtualGridCellElement - - Public Overrides Function IsCompatible(ByVal data As Integer, ByVal context As Object) As Boolean - Dim rowElement As VirtualGridRowElement = TryCast(context, VirtualGridRowElement) - Return data <> 3 AndAlso rowElement.RowIndex >= 0 - End Function - - Protected Overrides ReadOnly Property ThemeEffectiveType As Type - Get - Return GetType(VirtualGridCellElement) - End Get - End Property -End Class - -```` - -{{endregion}} + + + + 9\. Subscribe to the __CreateCellElement__ event where we should replace the default __VirtualGridCellElement__ with the custom one: #### Apply the custom cell -{{source=..\SamplesCS\VirtualGrid\Cells\VirtualGridCustomCells.cs region=ApplyCustomCell}} -{{source=..\SamplesVB\VirtualGrid\Cells\VirtualGridCustomCells.vb region=ApplyCustomCell}} - - -````C# -private void radVirtualGrid1_CreateCellElement(object sender, VirtualGridCreateCellEventArgs e) -{ - if (e.CellType == typeof(VirtualGridCellElement)) - { - if (e.ColumnIndex == 3 && e.RowIndex >= 0) - { - e.CellElement = new MyVirtualGridCheckBoxCellElement(); - } - else - { - e.CellElement = new DefaultVirtualGridCellElement(); - } - } -} - -```` -````VB.NET -Private Sub radVirtualGrid1_CreateCellElement(ByVal sender As Object, ByVal e As VirtualGridCreateCellEventArgs) - If e.CellType = GetType(VirtualGridCellElement) Then - If e.ColumnIndex = 3 AndAlso e.RowIndex >= 0 Then - e.CellElement = New MyVirtualGridCheckBoxCellElement() - Else - e.CellElement = New DefaultVirtualGridCellElement() - End If - End If -End Sub - - -```` - -{{endregion}} - -9\. Register the custom cell for the specified column index: + + -{{source=..\SamplesCS\VirtualGrid\Cells\VirtualGridCustomCells.cs region=RegisterCustomColumn}} -{{source=..\SamplesVB\VirtualGrid\Cells\VirtualGridCustomCells.vb region=RegisterCustomColumn}} -````C# - -this.radVirtualGrid1.MasterViewInfo.RegisterCustomColumn(3); +9\. Register the custom cell for the specified column index: -```` -````VB.NET -Me.RadVirtualGrid1.MasterViewInfo.RegisterCustomColumn(3) + + -```` -{{endregion}} >note Use the __UnregisterCustomColumn__ method if you need to unregister the custom cell for the specified column index. You can detect whether a custom cell is used for a certain column index by using the RadVirtualGrid.MasterViewInfo.__IsCustomColumn__ method. @@ -271,31 +72,9 @@ Me.RadVirtualGrid1.MasterViewInfo.RegisterCustomColumn(3) #### Prevent entering edit mode -{{source=..\SamplesCS\VirtualGrid\Cells\VirtualGridCustomCells.cs region=CancelEditor}} -{{source=..\SamplesVB\VirtualGrid\Cells\VirtualGridCustomCells.vb region=CancelEditor}} - - -````C# - -private void radVirtualGrid1_EditorRequired(object sender, VirtualGridEditorRequiredEventArgs e) -{ - if (e.ColumnIndex == 3) - { - e.Cancel = true; - } -} - -```` -````VB.NET -Private Sub radVirtualGrid1_EditorRequired(sender As Object, e As VirtualGridEditorRequiredEventArgs) - If e.ColumnIndex = 3 Then - e.Cancel = True - End If -End Sub - -```` + + -{{endregion}} >note The __RadCheckBoxElement__ can be replaced with any other __RadElement__ according to the user's requirement. diff --git a/controls/virtualgrid/visual-elements/cells/formatting-data-cells.md b/controls/virtualgrid/visual-elements/cells/formatting-data-cells.md index 757dea6d9..dad093686 100644 --- a/controls/virtualgrid/visual-elements/cells/formatting-data-cells.md +++ b/controls/virtualgrid/visual-elements/cells/formatting-data-cells.md @@ -14,54 +14,10 @@ The __CellFormatting__ event is used to add formatting to grid cells. For exampl ![WinForms RadVirtualGrid Formatting Data Cells](images/virtualgrid-cells-formatting-data-cells001.png) -{{source=..\SamplesCS\VirtualGrid\Cells\VirtualGridFormattingCells.cs region=FormattingCells}} -{{source=..\SamplesVB\VirtualGrid\Cells\VirtualGridFormattingCells.vb region=FormattingCells}} + + -````C# - -private void radVirtualGrid1_CellFormatting(object sender, VirtualGridCellElementEventArgs e) -{ - if (e.CellElement.RowIndex > -1) - { - if (e.CellElement.ColumnIndex == 3 && e.CellElement.Value != null && e.CellElement.Value.ToString() == "Owner") - { - e.CellElement.DrawFill = true; - e.CellElement.BackColor = Color.Yellow; - e.CellElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid; - e.CellElement.ForeColor = Color.Red; - } - else - { - e.CellElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local); - } - } -} -```` -````VB.NET -Private Sub radVirtualGrid1_CellFormatting(sender As Object, e As VirtualGridCellElementEventArgs) - If e.CellElement.RowIndex > -1 Then - If e.CellElement.ColumnIndex = 3 AndAlso e.CellElement.Value IsNot Nothing _ - AndAlso e.CellElement.Value.ToString() = "Owner" Then - e.CellElement.DrawFill = True - e.CellElement.BackColor = Color.Yellow - e.CellElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid - e.CellElement.ForeColor = Color.Red - Else - e.CellElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local) - End If - End If -End Sub - -```` - -{{endregion}} >caution Due to the UI virtualization in __RadVirtualGrid__, cell elements are created only for currently visible cells and are being reused during operations like scrolling, filtering, sorting and so on. In order to prevent applying the formatting to other columns' cell elements (because of the cell reuse) all customization should be reset for the rest of the cell elements. diff --git a/controls/virtualgrid/visual-elements/cells/formatting-system-cells.md b/controls/virtualgrid/visual-elements/cells/formatting-system-cells.md index a36c2f696..e4999861b 100644 --- a/controls/virtualgrid/visual-elements/cells/formatting-system-cells.md +++ b/controls/virtualgrid/visual-elements/cells/formatting-system-cells.md @@ -22,114 +22,10 @@ For example, the code sample below changes the __ForeColor__, __BackColor__ and ![WinForms RadVirtualGrid Formatting System Cells](images/virtualgrid-cells-formatting-system-cells001.png) -{{source=..\SamplesCS\VirtualGrid\Cells\VirtualGridFormattingCells.cs region=SystemCellsFormatting}} -{{source=..\SamplesVB\VirtualGrid\Cells\VirtualGridFormattingCells.vb region=SystemCellsFormatting}} + + -````C# - -private void radVirtualGrid_CellFormatting(object sender, VirtualGridCellElementEventArgs e) -{ - if (e.CellElement.RowIndex == -1) //format header row - { - if (e.CellElement.ColumnIndex == 3) - { - e.CellElement.DrawFill = true; - e.CellElement.BackColor = Color.Yellow; - e.CellElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid; - e.CellElement.ForeColor = Color.Red; - } - else - { - e.CellElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local); - } - } - else if (e.CellElement.RowIndex == -2)//format new row - { - if (e.CellElement.ColumnIndex == 1) - { - e.CellElement.DrawFill = true; - e.CellElement.BackColor = Color.Blue; - e.CellElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid; - e.CellElement.ForeColor = Color.Aqua; - } - else - { - e.CellElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local); - } - } - else if (e.CellElement.RowIndex == -3)//format filter row - { - if (e.CellElement.ColumnIndex == 5) - { - e.CellElement.DrawFill = true; - e.CellElement.BackColor = Color.Black; - e.CellElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid; - e.CellElement.ForeColor = Color.White; - } - else - { - e.CellElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local); - e.CellElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local); - } - } -} -```` -````VB.NET -Private Sub radVirtualGrid_CellFormatting(sender As Object, e As VirtualGridCellElementEventArgs) - If e.CellElement.RowIndex = -1 Then - 'format header row - If e.CellElement.ColumnIndex = 3 Then - e.CellElement.DrawFill = True - e.CellElement.BackColor = Color.Yellow - e.CellElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid - e.CellElement.ForeColor = Color.Red - Else - e.CellElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local) - End If - ElseIf e.CellElement.RowIndex = -2 Then - 'format new row - If e.CellElement.ColumnIndex = 1 Then - e.CellElement.DrawFill = True - e.CellElement.BackColor = Color.Blue - e.CellElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid - e.CellElement.ForeColor = Color.Aqua - Else - e.CellElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local) - End If - ElseIf e.CellElement.RowIndex = -3 Then - 'format filter row - If e.CellElement.ColumnIndex = 5 Then - e.CellElement.DrawFill = True - e.CellElement.BackColor = Color.Black - e.CellElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid - e.CellElement.ForeColor = Color.White - Else - e.CellElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local) - e.CellElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local) - End If - End If -End Sub - -```` - -{{endregion}} >caution Due to the UI virtualization in __RadVirtualGrid__, cell elements are created only for currently visible cells and are being reused during operations like scrolling, filtering, sorting and so on. In order to prevent applying the formatting to other columns' cell elements (because of the cell reuse) all customization should be reset for the rest of the cell elements. diff --git a/controls/virtualgrid/visual-elements/cells/tooltips.md b/controls/virtualgrid/visual-elements/cells/tooltips.md index 34bd4fef4..ee8d36645 100644 --- a/controls/virtualgrid/visual-elements/cells/tooltips.md +++ b/controls/virtualgrid/visual-elements/cells/tooltips.md @@ -18,33 +18,10 @@ There are two ways to assign tooltips to cells in __RadVirtualGrid__, namely set The code snippet below demonstrates how you can use the __ToolTipTextNeeded__ event handler to set __ToolTipText__ for the given __VirtualGridCellElement__. ![WinForms RadVirtualGrid Setting tooltips in the ToolTipTextNeeded event](images/virtualgrid-cells-tooltips002.png) -{{source=..\SamplesCS\VirtualGrid\Cells\VirtualGridFormattingCells.cs region=ToolTipTextNeeded}} -{{source=..\SamplesVB\VirtualGrid\Cells\VirtualGridFormattingCells.vb region=ToolTipTextNeeded}} - - -````C# - -private void radVirtualGrid1_ToolTipTextNeeded(object sender, ToolTipTextNeededEventArgs e) -{ - VirtualGridCellElement virtualCell = sender as VirtualGridCellElement; - if (virtualCell != null) - { - e.ToolTipText = "Tooltip: " + virtualCell.Value + ""; - } -} - -```` -````VB.NET -Private Sub radVirtualGrid1_ToolTipTextNeeded(sender As Object, e As ToolTipTextNeededEventArgs) - Dim virtualCell As VirtualGridCellElement = TryCast(sender, VirtualGridCellElement) - If virtualCell IsNot Nothing Then - e.ToolTipText = "Tooltip: " + virtualCell.Value + "" - End If -End Sub - -```` - -{{endregion}} + + + + # Setting tooltips in the CellFormatting event handler @@ -52,31 +29,10 @@ The code snippet below demonstrates how you can assign a tooltip to a cell in __ ![WinForms RadVirtualGrid Setting tooltips in the CellFormatting event handler](images/virtualgrid-cells-tooltips001.png) -{{source=..\SamplesCS\VirtualGrid\Cells\VirtualGridFormattingCells.cs region=CellsTooltips}} -{{source=..\SamplesVB\VirtualGrid\Cells\VirtualGridFormattingCells.vb region=CellsTooltips}} - - -````C# - -private void radVirtualGrid1Tooltips_CellFormatting(object sender, VirtualGridCellElementEventArgs e) -{ - if (e.CellElement.RowIndex >= 0) - { - e.CellElement.ToolTipText = e.CellElement.Value + ""; - } -} - -```` -````VB.NET -Private Sub radVirtualGrid1Tooltips_CellFormatting(sender As Object, e As VirtualGridCellElementEventArgs) - If e.CellElement.RowIndex >= 0 Then - e.CellElement.ToolTipText = e.CellElement.Value + "" - End If -End Sub + + -```` -{{endregion}} >note The __ToolTipTextNeeded__ event has higher priority and overrides the tooltips set in the __CellFormatting__ event handler. diff --git a/controls/virtualgrid/visual-elements/columns/pining-columns.md b/controls/virtualgrid/visual-elements/columns/pining-columns.md index 2848ae645..42bc8ba09 100644 --- a/controls/virtualgrid/visual-elements/columns/pining-columns.md +++ b/controls/virtualgrid/visual-elements/columns/pining-columns.md @@ -13,19 +13,9 @@ position: 0 __RadVirtualGrid__ columns can be pinned so that the rows appear anchored to the left or right of the grid. To pin a column you should use the __SetColumnPinPosition__ method where you just need to pass the column index and the desired pin position. -{{source=..\SamplesCS\VirtualGrid\pinned-cells-rows.cs region=PinColumn}} -{{source=..\SamplesVB\VirtualGrid\pinned-cells-rows.vb region=PinColumn}} -````C# - -radVirtualGrid1.VirtualGridElement.SetColumnPinPosition(2, PinnedColumnPosition.Right); + + -```` -````VB.NET -radVirtualGrid1.VirtualGridElement.SetColumnPinPosition(2, PinnedColumnPosition.Right) - -```` - -{{endregion}} The result is that the column is pined to the right. @@ -34,19 +24,8 @@ The result is that the column is pined to the right. To unpin a row you just need to set its pin position to *none*. -{{source=..\SamplesCS\VirtualGrid\pinned-cells-rows.cs region=UnpinColumn}} -{{source=..\SamplesVB\VirtualGrid\pinned-cells-rows.vb region=UnpinColumn}} -````C# - -radVirtualGrid1.VirtualGridElement.SetColumnPinPosition(2, PinnedColumnPosition.None); - -```` -````VB.NET -radVirtualGrid1.VirtualGridElement.SetColumnPinPosition(2, PinnedColumnPosition.None) - -```` - -{{endregion}} + + diff --git a/controls/virtualgrid/visual-elements/columns/resizing-columns-programmatically.md b/controls/virtualgrid/visual-elements/columns/resizing-columns-programmatically.md index d42550a6b..a30e04942 100644 --- a/controls/virtualgrid/visual-elements/columns/resizing-columns-programmatically.md +++ b/controls/virtualgrid/visual-elements/columns/resizing-columns-programmatically.md @@ -18,20 +18,10 @@ The columns inside the __RadVirtualGrid__ are resizable by default. The user is To restrict the resizing of all columns by the user set the __AllowColumnResize__ property to *false*. -{{source=..\SamplesCS\VirtualGrid\Columns\VirtualGridColumnsResizingProgrammatically.cs region=AllowColumnResize}} -{{source=..\SamplesVB\VirtualGrid\Columns\VirtualGridColumnsResizingProgrammatically.vb region=AllowColumnResize}} -````C# -this.radVirtualGrid1.AllowColumnResize = false; + + -```` -````VB.NET -Me.RadVirtualGrid1.AllowColumnResize = False -```` - - - -{{endregion}} ## Programmatically Resizing Column @@ -40,22 +30,11 @@ The width of columns can be set individually, per column. Note that the visible >caption Fig.1 Resize a Column ![WinForms RadVirtualGrid Resize a Column](images/virtualgrid-columns-resizing-columns001.png) -{{source=..\SamplesCS\VirtualGrid\Columns\VirtualGridColumnsResizingProgrammatically.cs region=ResizeSingleColumn}} -{{source=..\SamplesVB\VirtualGrid\Columns\VirtualGridColumnsResizingProgrammatically.vb region=ResizeSingleColumn}} -````C# - -this.radVirtualGrid1.TableElement.ColumnsViewState.SetItemSize(0, 200); - -```` -````VB.NET -Me.RadVirtualGrid1.TableElement.ColumnsViewState.SetItemSize(0, 200) - -```` + + -{{endregion}} - ## Column Auto-Sizing Columns can be auto-sized to a best fit value. The available API exposes methods for best-fitting all columns or just a single one: @@ -64,36 +43,19 @@ Columns can be auto-sized to a best fit value. The available API exposes methods ![WinForms RadVirtualGrid Best fit all columns](images/virtualgrid-columns-resizing-columns002.png) -{{source=..\SamplesCS\VirtualGrid\Columns\VirtualGridColumnsResizingProgrammatically.cs region=BestFitAllColumns}} -{{source=..\SamplesVB\VirtualGrid\Columns\VirtualGridColumnsResizingProgrammatically.vb region=BestFitAllColumns}} -````C# - -this.radVirtualGrid1.BestFitColumns(); - -```` -````VB.NET -Me.RadVirtualGrid1.BestFitColumns() + + -```` -{{endregion}} >caption Figure 3: Best fit one column. ![WinForms RadVirtualGrid Best fit one column](images/virtualgrid-columns-resizing-columns003.png) -{{source=..\SamplesCS\VirtualGrid\Columns\VirtualGridColumnsResizingProgrammatically.cs region=BestFitColumn}} -{{source=..\SamplesVB\VirtualGrid\Columns\VirtualGridColumnsResizingProgrammatically.vb region=BestFitColumn}} -````C# - -this.radVirtualGrid1.VirtualGridElement.BestFitColumn(1); + + -```` -````VB.NET -Me.RadVirtualGrid1.VirtualGridElement.BestFitColumn(1) -```` -{{endregion}} Columns can be auto-sized to fit the available space in __RadVirtualGrid__. It is necessary to set the __AutoSizeColumnsMode__ property to *VirtualGridAutoSizeColumnsMode.Fill*: @@ -101,18 +63,10 @@ Columns can be auto-sized to fit the available space in __RadVirtualGrid__. It i ![WinForms RadVirtualGrid AutoSizeColumnsMode Fill](images/virtualgrid-columns-resizing-columns004.gif) -{{source=..\SamplesCS\VirtualGrid\Columns\VirtualGridColumnsResizingProgrammatically.cs region=AutoSizeColumnsMode}} -{{source=..\SamplesVB\VirtualGrid\Columns\VirtualGridColumnsResizingProgrammatically.vb region=AutoSizeColumnsMode}} -````C# - -this.radVirtualGrid1.AutoSizeColumnsMode = VirtualGridAutoSizeColumnsMode.Fill; + + -```` -````VB.NET -Me.RadVirtualGrid1.AutoSizeColumnsMode = VirtualGridAutoSizeColumnsMode.Fill -```` -{{endregion}} ## Events @@ -136,37 +90,10 @@ The API exposes two events for notifications when a change in the height of a ro * __ViewInfo:__ Reference to the __VirtualGridViewInfo__ object. -{{source=..\SamplesCS\VirtualGrid\Columns\VirtualGridColumnsResizingProgrammatically.cs region=ResizingEvents}} -{{source=..\SamplesVB\VirtualGrid\Columns\VirtualGridColumnsResizingProgrammatically.vb region=ResizingEvents}} -````C# - -private void radVirtualGrid1_ColumnWidthChanging(object sender, VirtualGridColumnWidthChangingEventArgs e) -{ - if (e.ColumnIndex == 0) - { - e.Cancel = true; - } -} - -private void radVirtualGrid1_ColumnWidthChanged(object sender, VirtualGridColumnEventArgs e) -{ -} - -```` -````VB.NET -Private Sub radVirtualGrid1_ColumnWidthChanging(sender As Object, e As VirtualGridColumnWidthChangingEventArgs) - If e.ColumnIndex = 0 Then - e.Cancel = True - End If -End Sub -Private Sub radVirtualGrid1_ColumnWidthChanged(sender As Object, e As VirtualGridColumnEventArgs) -End Sub - -```` - - - -{{endregion}} + + + + # See Also * [Pinned Columns]({%slug winforms/virtualgrid/columns/pinned-columns%}) diff --git a/controls/virtualgrid/visual-elements/rows/alternating-row-colors.md b/controls/virtualgrid/visual-elements/rows/alternating-row-colors.md index 0f83a92dd..154ca1a73 100644 --- a/controls/virtualgrid/visual-elements/rows/alternating-row-colors.md +++ b/controls/virtualgrid/visual-elements/rows/alternating-row-colors.md @@ -15,21 +15,10 @@ __RadVirtualGrid__ supports an alternating row color. It can be enabled by simpl >caption Fig.1 Alternating Row color ![WinForms RadVirtualGrid Alternating Row color](images/virtualgrid-rows-alternating-row-color001.png) -{{source=..\SamplesCS\VirtualGrid\Rows\VirtualGridRowsAlternatingRownColor.cs region=Settings}} -{{source=..\SamplesVB\VirtualGrid\Rows\VirtualGridRowsAlternatingRownColor.vb region=Settings}} + + -````C# -this.radVirtualGrid1.EnableAlternatingRowColor = true; -this.radVirtualGrid1.TableElement.AlternatingRowColor = Color.LightBlue; -```` -````VB.NET -Me.RadVirtualGrid1.EnableAlternatingRowColor = True -Me.RadVirtualGrid1.TableElement.AlternatingRowColor = Color.LightBlue - -```` - -{{endregion}} # See Also * [Formatting Data Rows]({%slug winforms/virtualgrid/rows/formatting-data-rows%}) diff --git a/controls/virtualgrid/visual-elements/rows/formatting-data-rows.md b/controls/virtualgrid/visual-elements/rows/formatting-data-rows.md index 4e7b668a9..3528c1bb3 100644 --- a/controls/virtualgrid/visual-elements/rows/formatting-data-rows.md +++ b/controls/virtualgrid/visual-elements/rows/formatting-data-rows.md @@ -14,50 +14,10 @@ Use the __RowFormatting__ event to apply custom formatting to RadVirtualGrid's d ![WinForms RadVirtualGrid Formatting Data Rows](images/virtualgrid-cells-formatting-data-rows001.png) -{{source=..\SamplesCS\VirtualGrid\Rows\VirtualGridFormattingRows.cs region=FormattingRows}} -{{source=..\SamplesVB\VirtualGrid\Rows\VirtualGridFormattingRows.vb region=FormattingRows}} + + -````C# - -private void radVirtualGrid1_RowFormatting(object sender, VirtualGridRowElementEventArgs e) -{ - VirtualGridCellElement contactTitleCell = radVirtualGrid1.VirtualGridElement.GetCellElement(e.RowElement.RowIndex, 3, radVirtualGrid1.MasterViewInfo); - if (contactTitleCell != null && contactTitleCell.Value != null && contactTitleCell.Value.ToString() == "Owner") - { - e.RowElement.DrawFill = true; - e.RowElement.BackColor = Color.Yellow; - e.RowElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid; - e.RowElement.ForeColor = Color.Red; - } - else - { - e.RowElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local); - e.RowElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local); - e.RowElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local); - e.RowElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local); - } -} -```` -````VB.NET -Private Sub radVirtualGrid1_RowFormatting(sender As Object, e As VirtualGridRowElementEventArgs) - Dim contactTitleCell As VirtualGridCellElement = RadVirtualGrid1.VirtualGridElement.GetCellElement(e.RowElement.RowIndex, 3, RadVirtualGrid1.MasterViewInfo) - If contactTitleCell IsNot Nothing AndAlso contactTitleCell.Value IsNot Nothing AndAlso contactTitleCell.Value.ToString() = "Owner" Then - e.RowElement.DrawFill = True - e.RowElement.BackColor = Color.Yellow - e.RowElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid - e.RowElement.ForeColor = Color.Red - Else - e.RowElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local) - e.RowElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local) - e.RowElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local) - e.RowElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local) - End If -End Sub - -```` - -{{endregion}} >caution Due to the UI virtualization in __RadVirtualGrid__, row elements are created only for currently visible rows and are being reused during operations like scrolling, filtering, sorting and so on. In order to prevent applying the formatting to other columns' row elements (because of the row reuse) all customization should be reset for the rest of the row elements. diff --git a/controls/virtualgrid/visual-elements/rows/formatting-system-rows.md b/controls/virtualgrid/visual-elements/rows/formatting-system-rows.md index e2a2291d4..9c95c966b 100644 --- a/controls/virtualgrid/visual-elements/rows/formatting-system-rows.md +++ b/controls/virtualgrid/visual-elements/rows/formatting-system-rows.md @@ -23,75 +23,10 @@ The __RowFormatting__ event is used to add formatting to grid systems rows: head ![WinForms RadVirtualGrid Formatting System Rows](images/virtualgrid-rows-formatting-system-rows001.png) -{{source=..\SamplesCS\VirtualGrid\Rows\VirtualGridFormattingRows.cs region=SystemRowsFormatting}} -{{source=..\SamplesVB\VirtualGrid\Rows\VirtualGridFormattingRows.vb region=SystemRowsFormatting}} - -````C# - -private void radVirtualGrid_RowFormatting(object sender, VirtualGridRowElementEventArgs e) -{ - if (e.RowElement.RowIndex == -1) //format header row - { - e.RowElement.DrawFill = true; - e.RowElement.BackColor = Color.Yellow; - e.RowElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid; - e.RowElement.ForeColor = Color.Red; - } - else if (e.RowElement.RowIndex == -2)//format new row - { - e.RowElement.DrawFill = true; - e.RowElement.BackColor = Color.Blue; - e.RowElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid; - e.RowElement.ForeColor = Color.Aqua; - } - else if (e.RowElement.RowIndex == -3)//format filter row - { - e.RowElement.DrawFill = true; - e.RowElement.BackColor = Color.Green ; - e.RowElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid; - e.RowElement.ForeColor = Color.Black ; - } - else - { - e.RowElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local); - e.RowElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local); - e.RowElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local); - e.RowElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local); - } -} - -```` -````VB.NET -Private Sub radVirtualGrid_RowFormatting(sender As Object, e As VirtualGridRowElementEventArgs) - If e.RowElement.RowIndex = -1 Then - 'format header row - e.RowElement.DrawFill = True - e.RowElement.BackColor = Color.Yellow - e.RowElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid - e.RowElement.ForeColor = Color.Red - ElseIf e.RowElement.RowIndex = -2 Then - 'format new row - e.RowElement.DrawFill = True - e.RowElement.BackColor = Color.Blue - e.RowElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid - e.RowElement.ForeColor = Color.Aqua - ElseIf e.RowElement.RowIndex = -3 Then - 'format filter row - e.RowElement.DrawFill = True - e.RowElement.BackColor = Color.Green - e.RowElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid - e.RowElement.ForeColor = Color.Black - Else - e.RowElement.ResetValue(LightVisualElement.DrawFillProperty, ValueResetFlags.Local) - e.RowElement.ResetValue(LightVisualElement.BackColorProperty, ValueResetFlags.Local) - e.RowElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local) - e.RowElement.ResetValue(LightVisualElement.ForeColorProperty, ValueResetFlags.Local) - End If -End Sub - -```` - -{{endregion}} + + + + >caution Due to the UI virtualization in __RadVirtualGrid__, row elements are created only for currently visible rows and are being reused during operations like scrolling, filtering, sorting and so on. In order to prevent applying the formatting to other columns' row elements (because of the row reuse) all customization should be reset for the rest of the row elements. diff --git a/controls/virtualgrid/visual-elements/rows/pinned-rows.md b/controls/virtualgrid/visual-elements/rows/pinned-rows.md index a7f811619..5a949e0ec 100644 --- a/controls/virtualgrid/visual-elements/rows/pinned-rows.md +++ b/controls/virtualgrid/visual-elements/rows/pinned-rows.md @@ -13,19 +13,9 @@ position: 3 __RadVirtualGrid__ rows can be pinned so that the rows appear anchored to the top or bottom of the grid. To pin a row you should use the __SetRowPinPosition__ method where you just need to pass the row index and the desired pin position. -{{source=..\SamplesCS\VirtualGrid\pinned-cells-rows.cs region=PinRow}} -{{source=..\SamplesVB\VirtualGrid\pinned-cells-rows.vb region=PinRow}} -````C# - -radVirtualGrid1.VirtualGridElement.SetRowPinPosition(2, PinnedRowPosition.Top); + + -```` -````VB.NET -radVirtualGrid1.VirtualGridElement.SetRowPinPosition(2, PinnedRowPosition.Top) - -```` - -{{endregion}} The result is that the row is pined bellow the filter row. @@ -34,21 +24,10 @@ The result is that the row is pined bellow the filter row. To unpin a row you just need to set its pin position to *none*. -{{source=..\SamplesCS\VirtualGrid\pinned-cells-rows.cs region=UnpinRow}} -{{source=..\SamplesVB\VirtualGrid\pinned-cells-rows.vb region=UnpinRow}} -````C# - -radVirtualGrid1.VirtualGridElement.SetRowPinPosition(2, PinnedRowPosition.None); - -```` -````VB.NET -radVirtualGrid1.VirtualGridElement.SetRowPinPosition(2, PinnedRowPosition.None) + + -```` -{{endregion}} - - # See Also * [Alternating Row Color]({%slug winforms/virtualgrid/rows/alternating-row-colors%}) diff --git a/controls/virtualgrid/visual-elements/rows/resizing-rows-programmatically.md b/controls/virtualgrid/visual-elements/rows/resizing-rows-programmatically.md index 53d909984..fe502c524 100644 --- a/controls/virtualgrid/visual-elements/rows/resizing-rows-programmatically.md +++ b/controls/virtualgrid/visual-elements/rows/resizing-rows-programmatically.md @@ -12,20 +12,10 @@ position: 3 __RadVirtualGrid__ exposes an API allowing resizing of its rows. In order to utilize it we need to set the __AllowRowResize__ property to *true*. -{{source=..\SamplesCS\VirtualGrid\Rows\VirtualGridResizingRows.cs region=AllowRowResize}} -{{source=..\SamplesVB\VirtualGrid\Rows\VirtualGridResizingRows.vb region=AllowRowResize}} -````C# -this.radVirtualGrid1.AllowRowResize = true; + + -```` -````VB.NET -Me.RadVirtualGrid1.AllowRowResize = True -```` - - - -{{endregion}} ## Resizing System Rows @@ -35,25 +25,11 @@ The __VirtualGridViewInfo__ object exposes properties for directly accessing its ![WinForms RadVirtualGrid Resizing System Rows](images/virtualgrid-rows-resizing-rows002.png) -{{source=..\SamplesCS\VirtualGrid\Rows\VirtualGridResizingRows.cs region=ResizingSystemRows}} -{{source=..\SamplesVB\VirtualGrid\Rows\VirtualGridResizingRows.vb region=ResizingSystemRows}} -````C# -this.radVirtualGrid1.MasterViewInfo.HeaderRowHeight = 30; -this.radVirtualGrid1.MasterViewInfo.NewRowHeight = 40; -this.radVirtualGrid1.MasterViewInfo.FilterRowHeight = 50; - -```` -````VB.NET -Me.RadVirtualGrid1.MasterViewInfo.HeaderRowHeight = 30 -Me.RadVirtualGrid1.MasterViewInfo.NewRowHeight = 40 -Me.RadVirtualGrid1.MasterViewInfo.FilterRowHeight = 50 + + -```` - -{{endregion}} - ## Resizing Data Rows The data rows can also be programmatically resized. __RadVirtualGrid.VirtualGridViewInfo__ provides a property for defining a uniform height to all rows and also methods for setting or retrieving the height of a single row. @@ -62,42 +38,20 @@ The data rows can also be programmatically resized. __RadVirtualGrid.VirtualGrid ![WinForms RadVirtualGrid Resizing All Data Rows](images/virtualgrid-rows-resizing-rows003.png) -{{source=..\SamplesCS\VirtualGrid\Rows\VirtualGridResizingRows.cs region=ResizingDataRows}} -{{source=..\SamplesVB\VirtualGrid\Rows\VirtualGridResizingRows.vb region=ResizingDataRows}} -````C# -this.radVirtualGrid1.MasterViewInfo.RowHeight = 60; - -```` -````VB.NET -Me.RadVirtualGrid1.MasterViewInfo.RowHeight = 60 + + -```` - -{{endregion}} - >caption Figure 3 Resizing A Single Data Row. ![WinForms RadVirtualGrid Resizing A Single Data Row](images/virtualgrid-rows-resizing-rows004.png) -{{source=..\SamplesCS\VirtualGrid\Rows\VirtualGridResizingRows.cs region=SetRowHeight}} -{{source=..\SamplesVB\VirtualGrid\Rows\VirtualGridResizingRows.vb region=SetRowHeight}} -````C# -this.radVirtualGrid1.MasterViewInfo.SetRowHeight(0, 40); -int rowHeight = this.radVirtualGrid1.MasterViewInfo.GetRowHeight(0); - -```` -````VB.NET -Me.RadVirtualGrid1.MasterViewInfo.SetRowHeight(0, 40) -Dim rowHeight As Integer = Me.RadVirtualGrid1.MasterViewInfo.GetRowHeight(0) - -```` + + -{{endregion}} - ## Events The API exposes two events for notifications when a change in the height of a row is about to happen or has already happened. @@ -120,35 +74,10 @@ The API exposes two events for notifications when a change in the height of a ro * __ViewInfo__: Reference to the __VirtualGridViewInfo__ object. -{{source=..\SamplesCS\VirtualGrid\Rows\VirtualGridResizingRows.cs region=ResizingEvents}} -{{source=..\SamplesVB\VirtualGrid\Rows\VirtualGridResizingRows.vb region=ResizingEvents}} -````C# -private void radVirtualGrid1_RowHeightChanging(object sender, VirtualGridRowHeightChangingEventArgs e) -{ - if (e.RowIndex == 0) - { - e.Cancel = true; - } -} -private void radVirtualGrid1_RowHeightChanged(object sender, VirtualGridRowEventArgs e) -{ -} - -```` -````VB.NET -Private Sub radVirtualGrid1_RowHeightChanging(sender As Object, e As VirtualGridRowHeightChangingEventArgs) - If e.RowIndex = 0 Then - e.Cancel = True - End If -End Sub -Private Sub radVirtualGrid1_RowHeightChanged(sender As Object, e As VirtualGridRowEventArgs) -End Sub - -```` - - - -{{endregion}} + + + + # See Also * [Alternating Row Color]({%slug winforms/virtualgrid/rows/alternating-row-colors%}) diff --git a/controls/virtualgrid/working-with-data/handle-add-delete-update-of-rows.md b/controls/virtualgrid/working-with-data/handle-add-delete-update-of-rows.md index 9ff8e07b3..7ac5b43d8 100644 --- a/controls/virtualgrid/working-with-data/handle-add-delete-update-of-rows.md +++ b/controls/virtualgrid/working-with-data/handle-add-delete-update-of-rows.md @@ -1,217 +1,44 @@ ---- -title: Handle Add, Delete and Update of Rows -page_title: Handle Add, Delete and Update of Rows - WinForms VirtualGrid Control -description: Learn how you can handle Add, Delete and Update operations in WinForms VirtualGrid. -slug: winforms/virtualgrid/working-with-data/handle-add-delete-update-of-rows -tags: virtualgrid, data, add, delete, update -published: True -position: 1 ---- - -# Handle Add, Delete and Update of Rows - -When the user adds new rows, updates or deletes the existing ones, the external data source should be updated as well. Follow the steps below in order to keep the data synced: - -1\. Handle the __CellValuePushed__ event in order to detect when a cell value is changed. - -#### Push value to the data source - -{{source=..\SamplesCS\VirtualGrid\VirtualGridPopulatingWithData.cs region=PushValue}} -{{source=..\SamplesVB\VirtualGrid\VirtualGridPopulatingWithData.vb region=PushValue}} -````C# - -private void radVirtualGrid1_CellValuePushed(object sender, VirtualGridCellValuePushedEventArgs e) -{ - this.UpdateCellValue(data[e.RowIndex].CustomerId, columnNames[e.ColumnIndex], Convert.ToString(e.Value)); -} - -private void UpdateCellValue(string id, string columnName, string value) -{ - using (System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand(@"UPDATE Customers SET " + columnName + " = ? WHERE CustomerID = ?")) - { - command.Parameters.Add(new System.Data.OleDb.OleDbParameter("@columnValue", value)); - command.Parameters.Add(new System.Data.OleDb.OleDbParameter("@customerId", id)); - command.Connection = new System.Data.OleDb.OleDbConnection(connectionString); - command.Connection.Open(); - command.ExecuteNonQuery(); - command.Connection.Close(); - } - SelectData(); -} - -```` -````VB.NET -Private Sub radVirtualGrid1_CellValuePushed(sender As Object, e As VirtualGridCellValuePushedEventArgs) - Me.UpdateCellValue(data(e.RowIndex).CustomerId, columnNames(e.ColumnIndex), Convert.ToString(e.Value)) -End Sub -Private Sub UpdateCellValue(id As String, columnName As String, value As String) - Using command As New System.Data.OleDb.OleDbCommand((Convert.ToString("UPDATE Customers SET ") & columnName) + " = ? WHERE CustomerID = ?") - command.Parameters.Add(New System.Data.OleDb.OleDbParameter("@columnValue", value)) - command.Parameters.Add(New System.Data.OleDb.OleDbParameter("@customerId", id)) - command.Connection = New System.Data.OleDb.OleDbConnection(connectionString) - command.Connection.Open() - command.ExecuteNonQuery() - command.Connection.Close() - End Using - SelectData() -End Sub - -```` - - - -{{endregion}} - -2\. When the user adds a new row in the grid, it is necessary to subscribe to the __UserAddedRow__ event in order to update the data source: - -#### Add new row - -{{source=..\SamplesCS\VirtualGrid\VirtualGridPopulatingWithData.cs region=AddRow}} -{{source=..\SamplesVB\VirtualGrid\VirtualGridPopulatingWithData.vb region=AddRow}} - -````C# - -private void radVirtualGrid1_UserAddedRow(object sender, VirtualGridNewRowEventArgs e) -{ - List newValues = new List(); - for (int i = 0; i < columnNames.Length; i++) - { - newValues.Add(e.NewValues[i]); - } - this.AddDataRow(newValues); -} - -private void AddDataRow(List newValues) -{ - using (OleDbCommand command = new OleDbCommand(@"INSERT INTO Customers (CustomerID, CompanyName," + - " ContactName, ContactTitle, Address, PostalCode) values (?, ?, ?, ?, ?, ?)")) - { - command.Parameters.Add(new OleDbParameter("@param1", GenerateID())); - command.Parameters.Add(new OleDbParameter("@param2", newValues[0])); - command.Parameters.Add(new OleDbParameter("@param3", newValues[1])); - command.Parameters.Add(new OleDbParameter("@param4", newValues[2])); - command.Parameters.Add(new OleDbParameter("@param5", newValues[3])); - command.Parameters.Add(new OleDbParameter("@param6", newValues[4])); - command.Connection = new OleDbConnection(connectionString); - command.Connection.Open(); - command.ExecuteNonQuery(); - command.Connection.Close(); - } - int currentColumn = this.radVirtualGrid1.VirtualGridElement.CurrentCell.ColumnIndex; - SelectData(); - this.radVirtualGrid1.VirtualGridElement.InputBehavior.SelectCell(data.Count - 1, currentColumn, false, - false, this.radVirtualGrid1.VirtualGridElement.MasterViewInfo); -} - -private string GenerateID() -{ - StringBuilder sb = new StringBuilder(); - Random rand = new Random(); - for (int i = 0; i < 5; i++) - { - sb.Append((char)('A' + rand.Next(26))); - } - return sb.ToString(); -} - -```` -````VB.NET -Private Sub radVirtualGrid1_UserAddedRow(sender As Object, e As VirtualGridNewRowEventArgs) - Dim newValues As New List(Of Object)() - For i As Integer = 0 To columnNames.Length - 1 - newValues.Add(e.NewValues(i)) - Next - Me.AddDataRow(newValues) -End Sub -Private Sub AddDataRow(newValues As List(Of Object)) - Using command As New OleDbCommand("INSERT INTO Customers (CustomerID, CompanyName," + _ - " ContactName, ContactTitle, Address, PostalCode) values (?, ?, ?, ?, ?, ?)") - command.Parameters.Add(New OleDbParameter("@param1", GenerateID())) - command.Parameters.Add(New OleDbParameter("@param2", newValues(0))) - command.Parameters.Add(New OleDbParameter("@param3", newValues(1))) - command.Parameters.Add(New OleDbParameter("@param4", newValues(2))) - command.Parameters.Add(New OleDbParameter("@param5", newValues(3))) - command.Parameters.Add(New OleDbParameter("@param6", newValues(4))) - command.Connection = New OleDbConnection(connectionString) - command.Connection.Open() - command.ExecuteNonQuery() - command.Connection.Close() - End Using - Dim currentColumn As Integer = Me.radVirtualGrid1.VirtualGridElement.CurrentCell.ColumnIndex - SelectData() - Me.radVirtualGrid1.VirtualGridElement.InputBehavior.SelectCell(data.Count - 1, currentColumn, _ - False, False, Me.radVirtualGrid1.VirtualGridElement.MasterViewInfo) -End Sub -Private Function GenerateID() As String - Dim sb As New StringBuilder() - Dim rand As New Random() - For i As Integer = 0 To 4 - sb.Append(CChar(ChrW(Asc("A") + rand.[Next](26)))) - Next - Return sb.ToString() -End Function - -```` - -{{endregion}} - -3\. When the user deletes an existing row, you should handle the __UserDeletingRow__ event to update the data source as well: - -#### Delete row - -{{source=..\SamplesCS\VirtualGrid\VirtualGridPopulatingWithData.cs region=DeleteRow}} -{{source=..\SamplesVB\VirtualGrid\VirtualGridPopulatingWithData.vb region=DeleteRow}} - -````C# - -private void radVirtualGrid1_UserDeletedRow(object sender, VirtualGridRowsEventArgs e) -{ - string query = ""; - foreach (var item in e.RowIndices) - { - query += "'" + data[item].CustomerId + "',"; - } - DeleteDataRow(query.TrimEnd(',')); -} -private void DeleteDataRow(string query) -{ - using (OleDbCommand command = new OleDbCommand("DELETE FROM Customers where CustomerID In (" + query + ")")) - { - command.Connection = new OleDbConnection(connectionString); - command.Connection.Open(); - command.ExecuteNonQuery(); - command.Connection.Close(); - } - SelectData(); -} - -```` -````VB.NET -Private Sub radVirtualGrid1_UserDeletedRow(sender As Object, e As VirtualGridRowsEventArgs) - Dim query As String = "" - For Each item As Integer In e.RowIndices - query += "'" + data(item).CustomerId + "'," - Next - DeleteDataRow(query.TrimEnd(","c)) -End Sub - -Private Sub DeleteDataRow(query As String) - Using command As New OleDbCommand((Convert.ToString("DELETE FROM Customers where CustomerID In (") & query) + ")") - command.Connection = New OleDbConnection(connectionString) - command.Connection.Open() - command.ExecuteNonQuery() - command.Connection.Close() - End Using - SelectData() -End Sub - -```` - -{{endregion}} - - - - -# See Also -* [Populating with Data]({%slug winforms/virtualgrid/working-with-data/populating-with-data%}) - +--- +title: Handle Add, Delete and Update of Rows +page_title: Handle Add, Delete and Update of Rows - WinForms VirtualGrid Control +description: Learn how you can handle Add, Delete and Update operations in WinForms VirtualGrid. +slug: winforms/virtualgrid/working-with-data/handle-add-delete-update-of-rows +tags: virtualgrid, data, add, delete, update +published: True +position: 1 +--- + +# Handle Add, Delete and Update of Rows + +When the user adds new rows, updates or deletes the existing ones, the external data source should be updated as well. Follow the steps below in order to keep the data synced: + +1\. Handle the __CellValuePushed__ event in order to detect when a cell value is changed. + +#### Push value to the data source + + + + + + +2\. When the user adds a new row in the grid, it is necessary to subscribe to the __UserAddedRow__ event in order to update the data source: + +#### Add new row + + + + + + +3\. When the user deletes an existing row, you should handle the __UserDeletingRow__ event to update the data source as well: + +#### Delete row + + + + + + +# See Also +* [Populating with Data]({%slug winforms/virtualgrid/working-with-data/populating-with-data%}) + diff --git a/controls/virtualgrid/working-with-data/virtualgrid-populating-with-data.md b/controls/virtualgrid/working-with-data/virtualgrid-populating-with-data.md index 20a22e6a6..4690a5079 100644 --- a/controls/virtualgrid/working-with-data/virtualgrid-populating-with-data.md +++ b/controls/virtualgrid/working-with-data/virtualgrid-populating-with-data.md @@ -29,263 +29,17 @@ The code snippet below demonstrates how to select data from the Northwind.Custom #### Populate with data -{{source=..\SamplesCS\VirtualGrid\VirtualGridPopulatingWithData.cs region=FillData}} -{{source=..\SamplesVB\VirtualGrid\VirtualGridPopulatingWithData.vb region=FillData}} + + -````C# - -private string[] columnNames = new string[] { "CompanyName", "ContactName", "ContactTitle", "Address", "PostalCode" }; -string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + - @"..\..\DataSources\Nwind.mdb;Persist Security Info=True"; -List data = new List(); - -private void VirtualGridPopulatingWithData_Load(object sender, EventArgs e) -{ - this.radVirtualGrid1.CellValueNeeded += radVirtualGrid1_CellValueNeeded; - this.radVirtualGrid1.ColumnCount = columnNames.Length; - SelectData(); -} - -private void radVirtualGrid1_CellValueNeeded(object sender, VirtualGridCellValueNeededEventArgs e) -{ - if (e.ColumnIndex < 0) - return; - if (e.RowIndex == RadVirtualGrid.HeaderRowIndex) - { - e.Value = columnNames[e.ColumnIndex]; - } - - if (e.RowIndex < 0) - { - e.FieldName = columnNames[e.ColumnIndex]; - } - - if (e.RowIndex >= 0 && e.RowIndex < data.Count) - { - e.Value = data[e.RowIndex][e.ColumnIndex]; - } -} - -private void SelectData() -{ - string selectCommand = "SELECT CustomerID, CompanyName, ContactName, ContactTitle, Address, PostalCode FROM Customers"; - using (System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand(selectCommand)) - { - command.Connection = new System.Data.OleDb.OleDbConnection(connectionString); - command.Connection.Open(); - IDataReader reader = command.ExecuteReader(); - data.Clear(); - - while (reader.Read()) - { - Customer customer = new Customer( - Convert.ToString(reader[0]), - Convert.ToString(reader[1]), - Convert.ToString(reader[2]), - Convert.ToString(reader[3]), - Convert.ToString(reader[4]), - Convert.ToString(reader[5])); - data.Add(customer); - } - - command.Connection.Close(); - } - - this.radVirtualGrid1.RowCount = data.Count; -} -```` -````VB.NET -Private columnNames As String() = New String() {"CompanyName", "ContactName", "ContactTitle", "Address", "PostalCode"} -Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + _ -"..\..\DataSources\Nwind.mdb;Persist Security Info=True" -Private data As New List(Of Customer)() -Private Sub VirtualGridPopulatingWithData_Load(sender As Object, e As EventArgs) Handles Me.Load - AddHandler Me.radVirtualGrid1.CellValueNeeded, AddressOf radVirtualGrid1_CellValueNeeded - Me.radVirtualGrid1.ColumnCount = columnNames.Length - SelectData() -End Sub -Private Sub radVirtualGrid1_CellValueNeeded(sender As Object, e As VirtualGridCellValueNeededEventArgs) - If e.ColumnIndex < 0 Then - Return - End If - If e.RowIndex = RadVirtualGrid.HeaderRowIndex Then - e.Value = columnNames(e.ColumnIndex) - End If - If e.RowIndex < 0 Then - e.FieldName = columnNames(e.ColumnIndex) - End If - If e.RowIndex >= 0 AndAlso e.RowIndex < data.Count Then - e.Value = data(e.RowIndex)(e.ColumnIndex) - End If -End Sub -Private Sub SelectData() - Dim selectCommand As String = "SELECT CustomerID, CompanyName, ContactName, ContactTitle, Address, PostalCode FROM Customers" - Using command As New System.Data.OleDb.OleDbCommand(selectCommand) - command.Connection = New System.Data.OleDb.OleDbConnection(connectionString) - command.Connection.Open() - Dim reader As IDataReader = command.ExecuteReader() - data.Clear() - While reader.Read() - Dim customer As New Customer(Convert.ToString(reader(0)), Convert.ToString(reader(1)), Convert.ToString(reader(2)), _ - Convert.ToString(reader(3)), Convert.ToString(reader(4)), Convert.ToString(reader(5))) - data.Add(customer) - End While - command.Connection.Close() - End Using - Me.radVirtualGrid1.RowCount = data.Count -End Sub - -```` - -{{endregion}} #### Customer class -{{source=..\SamplesCS\VirtualGrid\VirtualGridPopulatingWithData.cs region=CustomerClass}} -{{source=..\SamplesVB\VirtualGrid\VirtualGridPopulatingWithData.vb region=CustomerClass}} -````C# - -public class Customer -{ - public string CustomerId { get; set; } - - public string CompanyName { get; set; } - - public string ContactName { get; set; } - - public string ContactTitle { get; set; } - - public string Address { get; set; } - - public string PostalCode { get; set; } - - public Customer(string customerId, string companyName, string contactName, - string contactTitle, string address, string postalCode) - { - this.CustomerId = customerId; - this.CompanyName = companyName; - this.ContactName = contactName; - this.ContactTitle = contactTitle; - this.Address = address; - this.PostalCode = postalCode; - } - - public string this[int i] - { - get - { - switch (i) - { - case 0: - return CompanyName; - case 1: - return ContactName; - case 2: - return ContactTitle; - case 3: - return Address; - case 4: - return PostalCode; - default: - return String.Empty; - } - } - } -} - -```` -````VB.NET - -Public Class Customer - Public Property CustomerId() As String - Get - Return m_CustomerId - End Get - Set(value As String) - m_CustomerId = value - End Set - End Property - Private m_CustomerId As String - Public Property CompanyName() As String - Get - Return m_CompanyName - End Get - Set(value As String) - m_CompanyName = value - End Set - End Property - Private m_CompanyName As String - Public Property ContactName() As String - Get - Return m_ContactName - End Get - Set(value As String) - m_ContactName = value - End Set - End Property - Private m_ContactName As String - Public Property ContactTitle() As String - Get - Return m_ContactTitle - End Get - Set(value As String) - m_ContactTitle = value - End Set - End Property - Private m_ContactTitle As String - Public Property Address() As String - Get - Return m_Address - End Get - Set(value As String) - m_Address = value - End Set - End Property - Private m_Address As String - Public Property PostalCode() As String - Get - Return m_PostalCode - End Get - Set(value As String) - m_PostalCode = value - End Set - End Property - Private m_PostalCode As String - Public Sub New(customerId As String, companyName As String, contactName As String, _ - contactTitle As String, address As String, postalCode As String) - Me.CustomerId = customerId - Me.CompanyName = companyName - Me.ContactName = contactName - Me.ContactTitle = contactTitle - Me.Address = address - Me.PostalCode = postalCode - End Sub - Default Public ReadOnly Property Item(i As Integer) As String - Get - Select Case i - Case 0 - Return CompanyName - Case 1 - Return ContactName - Case 2 - Return ContactTitle - Case 3 - Return Address - Case 4 - Return PostalCode - Case Else - Return [String].Empty - End Select - End Get - End Property -End Class + + -```` - -{{endregion}} - # See Also * [Handle Add, Delete and Update of Rows]({%slug winforms/virtualgrid/working-with-data/handle-add-delete-update-of-rows%}) diff --git a/controls/webcam/connect-to-camera-device.md b/controls/webcam/connect-to-camera-device.md index 23000f2c0..549b226bb 100644 --- a/controls/webcam/connect-to-camera-device.md +++ b/controls/webcam/connect-to-camera-device.md @@ -23,29 +23,8 @@ To connect to a web cam manually, execute the following steps: >note The manual initialization of RadWebCam should be executed after the control gets loaded. For example, you can use the form's Load event. -{{source=..\SamplesCS\WebCam\WebCamGettingStarted.cs region=SelectDevice}} -{{source=..\SamplesVB\WebCam\WebCamGettingStarted.vb region=SelectDevice}} - -````C# - - ReadOnlyCollection videoDevices = RadWebCam.GetVideoCaptureDevices(); - ReadOnlyCollection videoFormats = RadWebCam.GetVideoFormats(videoDevices[1], true); - ReadOnlyCollection audioDevices = RadWebCam.GetAudioCaptureDevices(); - radWebCam1.Initialize(videoDevices[1], videoFormats[9], audioDevices[1]); - radWebCam1.Start(); - -```` -````VB.NET - - Dim videoDevices As ReadOnlyCollection(Of MediaFoundationDeviceInfo) = RadWebCam.GetVideoCaptureDevices() - Dim videoFormats As ReadOnlyCollection(Of MediaFoundationVideoFormatInfo) = RadWebCam.GetVideoFormats(videoDevices(1), True) - Dim audioDevices As ReadOnlyCollection(Of MediaFoundationDeviceInfo) = RadWebCam.GetAudioCaptureDevices() - radWebCam1.Initialize(videoDevices(1), videoFormats(9), audioDevices(1)) - radWebCam1.Start() - -```` - -{{endregion}} + + diff --git a/controls/webcam/events.md b/controls/webcam/events.md index dcf429524..8868eedb6 100644 --- a/controls/webcam/events.md +++ b/controls/webcam/events.md @@ -20,27 +20,10 @@ The purpose of the event is to notify you that a snapshot has been taken and you The event arguments are of type **SnapshotTakenEventArgs** which exposes a **Snapshot** property (of type **Image**). -{{source=..\SamplesCS\WebCam\WebCamGettingStarted.cs region=Snapshot}} -{{source=..\SamplesVB\WebCam\WebCamGettingStarted.vb region=Snapshot}} + + -````C# - private void RadWebCam1_SnapshotTaken(object sender, SnapshotTakenEventArgs e) - { - Image snapshot = e.Snapshot; - // here you save the source to a file, in memory, or to show it in the UI - } - -```` -````VB.NET - - Private Sub RadWebCam1_SnapshotTaken(ByVal sender As Object, ByVal e As SnapshotTakenEventArgs) - Dim snapshot As System.Drawing.Image = e.Snapshot - End Sub - -```` - -{{endregion}} ## CameraError @@ -50,31 +33,10 @@ The event can be used to notify you about the corresponding error, or to replace The event arguments are of type **CameraErrorEventArgs** and they expose an **Error** property that contains information about the error. The **Error** property is of type **ErrorInfo** which gives you access to the message and state of the error via the **Message** and **ErrorState** properties. -{{source=..\SamplesCS\WebCam\WebCamGettingStarted.cs region=Errors}} -{{source=..\SamplesVB\WebCam\WebCamGettingStarted.vb region=Errors}} - -````C# - - private void RadWebCam1_CameraError(object sender, CameraErrorEventArgs e) - { - if (e.Error.ErrorState == CameraErrorState.NoCamera) - { - e.Error.Message = "Cannot detect a camera device."; - } - } - -```` -````VB.NET - - Private Sub RadWebCam1_CameraError(ByVal sender As Object, ByVal e As CameraErrorEventArgs) - If e.[Error].ErrorState = CameraErrorState.NoCamera Then - e.[Error].Message = "Cannot detect a camera device." - End If - End Sub + + -```` -{{endregion}} >caption Customized error message diff --git a/controls/webcam/features/errors.md b/controls/webcam/features/errors.md index b442e1eb1..200e9be88 100644 --- a/controls/webcam/features/errors.md +++ b/controls/webcam/features/errors.md @@ -36,31 +36,10 @@ There are few expected errors that could appear using the control: To replace the error message use the **CameraError** event of **RadWebCam**. The **CameraErrorEventArgs** give access to an **ErrorInfo** object, which contains information about the error state and message. Use the event to replace the default message with a custom one. -{{source=..\SamplesCS\WebCam\WebCamGettingStarted.cs region=Errors}} -{{source=..\SamplesVB\WebCam\WebCamGettingStarted.vb region=Errors}} + + -````C# - private void RadWebCam1_CameraError(object sender, CameraErrorEventArgs e) - { - if (e.Error.ErrorState == CameraErrorState.NoCamera) - { - e.Error.Message = "Cannot detect a camera device."; - } - } - -```` -````VB.NET - - Private Sub RadWebCam1_CameraError(ByVal sender As Object, ByVal e As CameraErrorEventArgs) - If e.[Error].ErrorState = CameraErrorState.NoCamera Then - e.[Error].Message = "Cannot detect a camera device." - End If - End Sub - -```` - -{{endregion}} ![WinForms RadWebCam Replace Error Message](images/webcam-errors003.png) diff --git a/controls/webcam/features/media-information.md b/controls/webcam/features/media-information.md index 7c20d0add..b1c164623 100644 --- a/controls/webcam/features/media-information.md +++ b/controls/webcam/features/media-information.md @@ -26,43 +26,18 @@ To get the available video capture devices (cameras), use the RadWebCam.**GetVid #### Getting the available cameras -{{source=..\SamplesCS\WebCam\WebCamFeatures.cs region=GetDevices}} -{{source=..\SamplesVB\WebCam\WebCamFeatures.vb region=GetDevices}} + + -````C# - ReadOnlyCollection videoDevices = RadWebCam.GetVideoCaptureDevices(); - -```` -````VB.NET - - Dim videoDevices As ReadOnlyCollection(Of MediaFoundationDeviceInfo) = RadWebCam.GetVideoCaptureDevices() - -```` - -{{endregion}} ## Get Video Formats To get the available video file formats for the connected device, you can use the RadWebCam.**GetVideoFormats** static method. -{{source=..\SamplesCS\WebCam\WebCamFeatures.cs region=VideoFormats}} -{{source=..\SamplesVB\WebCam\WebCamFeatures.vb region=VideoFormats}} - -````C# - - ReadOnlyCollection myVideoDevices = RadWebCam.GetVideoCaptureDevices(); - ReadOnlyCollection videoFormats = RadWebCam.GetVideoFormats(videoDevices[0]); - -```` -````VB.NET - - Dim myVideoDevices As ReadOnlyCollection(Of MediaFoundationDeviceInfo) = RadWebCam.GetVideoCaptureDevices() - Dim videoFormats As ReadOnlyCollection(Of MediaFoundationVideoFormatInfo) = RadWebCam.GetVideoFormats(videoDevices(0)) - -```` + + -{{endregion}} ## See Also diff --git a/controls/webcam/features/recording-video.md b/controls/webcam/features/recording-video.md index cdb8d43e5..6d9714fde 100644 --- a/controls/webcam/features/recording-video.md +++ b/controls/webcam/features/recording-video.md @@ -16,41 +16,17 @@ To start recording a video you can press the "Start recording" button or call th To enable video recording set the **RecordingFilePath** property of the control. This is the path to the video where the recording will be stored. -{{source=..\SamplesCS\WebCam\WebCamGettingStarted.cs region=Video}} -{{source=..\SamplesVB\WebCam\WebCamGettingStarted.vb region=Video}} + + -````C# - radWebCam1.RecordingFilePath = path + @"\Video1.mp4"; - radWebCam1.StartRecording(); - -```` -````VB.NET - - radWebCam1.RecordingFilePath = path + "\Video1.mp4" - radWebCam1.StartRecording() - -```` - -{{endregion}} To stop recording, press the "Stop" button or call the **StopRecording** method of **RadWebCam**. This will stop the recording and close the file stream. -{{source=..\SamplesCS\WebCam\WebCamGettingStarted.cs region=EndRecording}} -{{source=..\SamplesVB\WebCam\WebCamGettingStarted.vb region=EndRecording}} - -````C# - - radWebCam1.StopRecording(); + + -```` -````VB.NET - radWebCam1.StopRecording() - -```` - -{{endregion}} You can indicate that the camera control is recording via its **IsRecording** property. @@ -62,21 +38,10 @@ The control allows you to replace the default elapsed date-time format. To do th ![WinForms RadWebcam Elapsed Time](images/webcam-recording-video002.png) -{{source=..\SamplesCS\WebCam\WebCamGettingStarted.cs region=EllapsedTimeFormat}} -{{source=..\SamplesVB\WebCam\WebCamGettingStarted.vb region=EllapsedTimeFormat}} - -````C# - - radWebCam1.VideoRecordingElapsedTimeFormat = "ss"; - -```` -````VB.NET - - radWebCam1.VideoRecordingElapsedTimeFormat = "ss" + + -```` -{{endregion}} ## See Also * [Commands]({%slug webcam-commands%}) diff --git a/controls/webcam/features/snapshots.md b/controls/webcam/features/snapshots.md index cde68bc8a..d282fe43c 100644 --- a/controls/webcam/features/snapshots.md +++ b/controls/webcam/features/snapshots.md @@ -16,69 +16,19 @@ position: 1 #### Taking a snapshot in code -{{source=..\SamplesCS\WebCam\WebCamFeatures.cs region=TakeSnapshots}} -{{source=..\SamplesVB\WebCam\WebCamFeatures.vb region=TakeSnapshots}} + + -````C# - - public WebCamFeatures() - { - InitializeComponent(); - - this.radWebCam1.SnapshotTaken += radWebCam1_SnapshotTaken; - } - - private void radWebCam1_SnapshotTaken(object sender, Telerik.WinControls.UI.SnapshotTakenEventArgs e) - { - Image snapshot = e.Snapshot; - // here you save the image to a file, in memory, or to show it in the UI - } - - private void OnTakeSnapshot(object sender, EventArgs e) - { - this.radWebCam1.TakeSnapshot(); - } - -```` -````VB.NET - - Public Sub New() - InitializeComponent() - AddHandler Me.RadWebCam1.SnapshotTaken, AddressOf radWebCam1_SnapshotTaken - End Sub - - Private Sub radWebCam1_SnapshotTaken(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.SnapshotTakenEventArgs) - Dim snapshot As Image = e.Snapshot - End Sub - - Private Sub OnTakeSnapshot(ByVal sender As Object, ByVal e As EventArgs) - Me.RadWebCam1.TakeSnapshot() - End Sub - -```` - -{{endregion}} ## Preview Snapshots By default, when you take a snapshot a preview of the image will be shown. To disable this, set the **PreviewSnapshots** property to *false*. -{{source=..\SamplesCS\WebCam\WebCamFeatures.cs region=Preview}} -{{source=..\SamplesVB\WebCam\WebCamFeatures.vb region=Preview}} - -````C# - - this.radWebCam1.PreviewSnapshots = false; - -```` -````VB.NET - - Me.RadWebCam1.PreviewSnapshots = False + + -```` -{{endregion}} You can indicate if the snapshot preview is displayed via the **IsPreviewingSnapshot** property of **RadWebCam**. diff --git a/controls/webcam/getting-started.md b/controls/webcam/getting-started.md index 0d593e89d..24e63fcbb 100644 --- a/controls/webcam/getting-started.md +++ b/controls/webcam/getting-started.md @@ -69,29 +69,10 @@ According to a comment in [this discussion](https://social.msdn.microsoft.com/Fo #### Adding a RadWebCam at runtime -{{source=..\SamplesCS\WebCam\WebCamGettingStarted.cs region=CreatingWebCam}} -{{source=..\SamplesVB\WebCam\WebCamGettingStarted.vb region=CreatingWebCam}} + + -````C# - RadWebCam radWebCam1 = new RadWebCam(); - string path = @"..\..\Test images and videos\"; - radWebCam1.AutoStart = true; - radWebCam1.RecordingFilePath = path + @"\Video1.mp4"; - this.Controls.Add(radWebCam1); - -```` -````VB.NET - - Dim radWebCam1 As RadWebCam = New RadWebCam() - Dim path As String = "..\..\Test images and videos\" - radWebCam1.AutoStart = True - radWebCam1.RecordingFilePath = path & "\Video1.mp4" - Me.Controls.Add(radWebCam1) - -```` - -{{endregion}} From this point on, you can start using the control without any additional set up. @@ -99,41 +80,18 @@ From this point on, you can start using the control without any additional set u By default, the camera control will start automatically if a camera device is connected. You can change this by setting the **AutoStart** property of **RadWebCam** to *false*. -{{source=..\SamplesCS\WebCam\WebCamGettingStarted.cs region=WebCameraAutoStart}} -{{source=..\SamplesVB\WebCam\WebCamGettingStarted.vb region=WebCameraAutoStart}} - -````C# - - radWebCam1.AutoStart = false; - -```` -````VB.NET + + - radWebCam1.AutoStart = False -```` - -{{endregion}} ## Connect to the Webcam Manually To connect to the web cam manually you can call the **Start** method once the control is initialized. -{{source=..\SamplesCS\WebCam\WebCamGettingStarted.cs region=Start}} -{{source=..\SamplesVB\WebCam\WebCamGettingStarted.vb region=Start}} - -````C# - - radWebCam1.Start(); - -```` -````VB.NET - - radWebCam1.Start() - -```` + + -{{endregion}} >note Read more about the capture devices in the [Media Information]({%slug webcam-media-information%}) article. @@ -142,21 +100,10 @@ To connect to the web cam manually you can call the **Start** method once the co To stop the stream between the camera device and the **RadWebCam** control, call the **Stop** method. -{{source=..\SamplesCS\WebCam\WebCamGettingStarted.cs region=Stop}} -{{source=..\SamplesVB\WebCam\WebCamGettingStarted.vb region=Stop}} + + -````C# - radWebCam1.Stop(); - -```` -````VB.NET - - radWebCam1.Stop() - -```` - -{{endregion}} ## Recording Video @@ -166,47 +113,19 @@ To start recording, press the "Start recording" button or call the **StartRecord >note Read more about this in the [Recording Video]({%slug webcam-recording-video%}) article. -{{source=..\SamplesCS\WebCam\WebCamGettingStarted.cs region=RecordingPath}} -{{source=..\SamplesVB\WebCam\WebCamGettingStarted.vb region=RecordingPath}} - -````C# - - radWebCam1.RecordingFilePath = path + @"\Video1.mp4"; + + -```` -````VB.NET - radWebCam1.RecordingFilePath = path + "\Video1.mp4" - -```` - -{{endregion}} ## Taking Snapshot A snapshot of the currently displayed video feed can be taken using the **TakeSnapshot** method of the control, or by pressing the "Take snapshot button". This will fire the **SnapshotTaken** event where you get access to the current snapshot as an Image object. -{{source=..\SamplesCS\WebCam\WebCamGettingStarted.cs region=Snapshot}} -{{source=..\SamplesVB\WebCam\WebCamGettingStarted.vb region=Snapshot}} - -````C# - - private void RadWebCam1_SnapshotTaken(object sender, SnapshotTakenEventArgs e) - { - Image snapshot = e.Snapshot; - // here you save the source to a file, in memory, or to show it in the UI - } - -```` -````VB.NET - - Private Sub RadWebCam1_SnapshotTaken(ByVal sender As Object, ByVal e As SnapshotTakenEventArgs) - Dim snapshot As System.Drawing.Image = e.Snapshot - End Sub + + -```` -{{endregion}} ## See Also * [Structure]({%slug webcam-structure%}) diff --git a/controls/webcam/how-to/mute-recording-audio.md b/controls/webcam/how-to/mute-recording-audio.md index c130ea3fc..8e7fa6bd6 100644 --- a/controls/webcam/how-to/mute-recording-audio.md +++ b/controls/webcam/how-to/mute-recording-audio.md @@ -16,28 +16,10 @@ This article shows how to stop the audio recording in two steps when a video is 2. In the event handler, get the camera device and video format, and call the **Initialize** method of the control. To disable the audio, set the last parameter ("*audioDevice*") of the **Initialize** method to *null*. Then start the camera. -{{source=..\SamplesCS\WebCam\WebCamFeatures.cs region=MuteCamera}} -{{source=..\SamplesVB\WebCam\WebCamFeatures.vb region=MuteCamera}} + + -````C# - ReadOnlyCollection videoDevices = RadWebCam.GetVideoCaptureDevices(); - ReadOnlyCollection videoFormats = RadWebCam.GetVideoFormats(videoDevices[0]); - this.radWebCam1.Initialize(videoDevices[0], videoFormats[0], null); - this.radWebCam1.Start(); - -```` -````VB.NET - - Dim videoDevices As ReadOnlyCollection(Of MediaFoundationDeviceInfo) = RadWebCam.GetVideoCaptureDevices() - Dim videoFormats As ReadOnlyCollection(Of MediaFoundationVideoFormatInfo) = RadWebCam.GetVideoFormats(videoDevices(0)) - Me.RadWebCam1.Initialize(videoDevices(0), videoFormats(0), Nothing) - Me.RadWebCam1.Start() - -```` - -{{endregion}} - ## See Also * [Commands]({%slug webcam-commands%}) diff --git a/controls/webcam/how-to/save-snapshot-to-file.md b/controls/webcam/how-to/save-snapshot-to-file.md index df6d0c064..4894dead6 100644 --- a/controls/webcam/how-to/save-snapshot-to-file.md +++ b/controls/webcam/how-to/save-snapshot-to-file.md @@ -18,40 +18,10 @@ Add a **RadWebCam** to the form and subscribe to its **SnapshotTaken** event. In #### Opening a file dialog in the SnapshotTaken event handler and saving it to a file -{{source=..\SamplesCS\WebCam\WebCamFeatures.cs region=SaveSnapshot}} -{{source=..\SamplesVB\WebCam\WebCamFeatures.vb region=SaveSnapshot}} + + -````C# - private void radWebCam_SnapshotTaken(object sender, SnapshotTakenEventArgs e) - { - SaveFileDialog dialog = new SaveFileDialog(); - dialog.Filter = "Images|.png;.bmp;*.jpg"; - dialog.DefaultExt = ".png"; - dialog.FilterIndex = 0; - if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) - { - e.Snapshot.Save(dialog.FileName); - } - } - -```` -````VB.NET - - Private Sub RadWebCam_SnapshotTaken(ByVal sender As Object, ByVal e As SnapshotTakenEventArgs) - Dim dialog As SaveFileDialog = New SaveFileDialog() - dialog.Filter = "Images|.png;.bmp;*.jpg" - dialog.DefaultExt = ".png" - dialog.FilterIndex = 0 - - If dialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then - e.Snapshot.Save(dialog.FileName) - End If - End Sub - -```` - -{{endregion}} ## Taking Snapshot diff --git a/controls/wizard/localization.md b/controls/wizard/localization.md index ece8d2c2f..85a3d9c5b 100644 --- a/controls/wizard/localization.md +++ b/controls/wizard/localization.md @@ -23,69 +23,19 @@ Below is a sample implementation of an English localization provider: #### Localizing RadWizard Strings -{{source=..\SamplesCS\Wizard\WizardLocalization.cs region=CustomLocalizationProvider}} -{{source=..\SamplesVB\Wizard\WizardLocalization.vb region=CustomLocalizationProvider}} - -````C# -class MyWizardLocalizationProvider : RadWizardLocalizationProvider -{ - public override string GetLocalizedString(string id) - { - switch (id) - { - case RadWizardStringId.BackButtonText: return "< Back"; - case RadWizardStringId.NextButtonText: return "Next >"; - case RadWizardStringId.CancelButtonText: return "Cancel"; - case RadWizardStringId.FinishButtonText: return "Finish"; - case RadWizardStringId.HelpButtonText: return "Help"; - default: return string.Empty; - } - } -} - -```` -````VB.NET -Class MyWizardLocalizationProvider - Inherits RadWizardLocalizationProvider - Public Overrides Function GetLocalizedString(id As String) As String - Select Case id - Case RadWizardStringId.BackButtonText - Return "< Back" - Case RadWizardStringId.NextButtonText - Return "Next >" - Case RadWizardStringId.CancelButtonText - Return "Cancel" - Case RadWizardStringId.FinishButtonText - Return "Finish" - Case RadWizardStringId.HelpButtonText - Return "Help" - Case Else - Return String.Empty - End Select - End Function -End Class - -```` - -{{endregion}} + + -To apply the custom localization provider, instantiate and assign it to the current localization provider: -#### Assigning the Current Localization Provider -{{source=..\SamplesCS\Wizard\WizardLocalization.cs region=settingTheProvider}} -{{source=..\SamplesVB\Wizard\WizardLocalization.vb region=settingTheProvider}} +To apply the custom localization provider, instantiate and assign it to the current localization provider: -````C# -RadWizardLocalizationProvider.CurrentProvider = new MyWizardLocalizationProvider(); +#### Assigning the Current Localization Provider -```` -````VB.NET -RadWizardLocalizationProvider.CurrentProvider = New MyWizardLocalizationProvider() + + -```` -{{endregion}} The code provided above illustrates the approach to be used to localize __RadWizard__ and it is not intended as a full translation. diff --git a/controls/wizard/modes.md b/controls/wizard/modes.md index e6e6717fd..6f2c3d44f 100644 --- a/controls/wizard/modes.md +++ b/controls/wizard/modes.md @@ -15,19 +15,10 @@ __RadWizard__ supports both *Wizard 97* and *Wizard Aero* specifications. You ca #### Setting modes -{{source=..\SamplesCS\Wizard\Modes.cs region=settingMode}} -{{source=..\SamplesVB\Wizard\Modes.vb region=settingMode}} + + -````C# -this.radWizard1.Mode = WizardMode.Wizard97; -```` -````VB.NET -Me.RadWizard1.Mode = WizardMode.Wizard97 - -```` - -{{endregion}} >caption Figire 1: WizardMode.Wizard97 @@ -37,21 +28,10 @@ The aero style of WizardMode.*Aero* can be enabled (for Windows Vista and later #### Enabling aero style -{{source=..\SamplesCS\Wizard\Modes.cs region=EnableAeroStyle}} -{{source=..\SamplesVB\Wizard\Modes.vb region=EnableAeroStyle}} - -````C# -this.radWizard1.Mode = WizardMode.Aero; -this.radWizard1.EnableAeroStyle = true; + + -```` -````VB.NET -Me.RadWizard1.Mode = WizardMode.Aero -Me.RadWizard1.EnableAeroStyle = True -```` - -{{endregion}} >caption Figure 2: WizardMode.Aero with enabled aero @@ -59,21 +39,10 @@ Me.RadWizard1.EnableAeroStyle = True #### Disable __Aero Style__ -{{source=..\SamplesCS\Wizard\Modes.cs region=disableAeroStyle}} -{{source=..\SamplesVB\Wizard\Modes.vb region=disableAeroStyle}} - -````C# -this.radWizard1.Mode = WizardMode.Aero; -this.radWizard1.EnableAeroStyle = false; - -```` -````VB.NET -Me.RadWizard1.Mode = WizardMode.Aero -Me.RadWizard1.EnableAeroStyle = False + + -```` -{{endregion}} >caption Figure 3: WizardMode.Aero with disabled aero diff --git a/controls/wizard/properties-methods-events.md b/controls/wizard/properties-methods-events.md index c2c02af5b..3f5925047 100644 --- a/controls/wizard/properties-methods-events.md +++ b/controls/wizard/properties-methods-events.md @@ -72,46 +72,18 @@ Below is an example of using the __Next__ event of __RadWizard__ to choose the p #### Subscribe to the Next event -{{source=..\SamplesCS\Wizard\Events.cs region=subscribeToTheEvent}} -{{source=..\SamplesVB\Wizard\EventsForm.vb region=subscribeToTheEvent}} + + -````C# -this.radWizard1.Next += new WizardCancelEventHandler(radWizard1_Next); -```` -````VB.NET -AddHandler radWizard1.Next, AddressOf radWizard1_Next - -```` -{{endregion}} #### Handle the Next event -{{source=..\SamplesCS\Wizard\Events.cs region=nextEvent}} -{{source=..\SamplesVB\Wizard\EventsForm.vb region=nextEvent}} - -````C# -private void radWizard1_Next(object sender, WizardCancelEventArgs e) -{ - if (this.radWizard1.SelectedPage == this.radWizard1.Pages[1]) - { - e.Cancel = true; - this.radWizard1.SelectedPage = this.radWizard1.Pages[0]; - } -} - -```` -````VB.NET -Private Sub RadWizard1_Next(ByVal sender As Object, ByVal e As WizardCancelEventArgs) - If (Me.RadWizard1.SelectedPage Is Me.RadWizard1.Pages(1)) Then - e.Cancel = True - Me.RadWizard1.SelectedPage = Me.RadWizard1.Pages(0) - End If -End Sub - -```` -{{endregion}} + + + + # See Also diff --git a/controls/wizard/right-to-left-support.md b/controls/wizard/right-to-left-support.md index 0b0546c23..0a8a4987a 100644 --- a/controls/wizard/right-to-left-support.md +++ b/controls/wizard/right-to-left-support.md @@ -19,23 +19,10 @@ You can enable the right-to-left functionality, by setting the __RightToLeft__ p #### Setting Right-to-Left mode -{{source=..\SamplesCS\Wizard\WizardStructure.cs region=RTL}} -{{source=..\SamplesVB\Wizard\WizardStructure.vb region=RTL}} + + -````C# -this.radWizard1.RightToLeft = RightToLeft.Yes; -this.radLabel1.RightToLeft = RightToLeft.Yes; -this.radLabel1.Text = "Welcome page of RadWizard in RightToLeft mode."; -```` -````VB.NET -RadWizard1.RightToLeft = System.Windows.Forms.RightToLeft.Yes -RadLabel1.RightToLeft = System.Windows.Forms.RightToLeft.Yes -RadLabel1.Text = "Welcome page of RadWizard in RightToLeft mode." - -```` - -{{endregion}} # See Also