By default, the TextBox control will be used as a default editor control for the string column in Vue Grid. You can customize the editor control using Multiline Textbox by rendering it as a custom component in the Grid edit form. You can use the cellEditTemplate feature of Grid to render the Multiline TextBox component in the Grid edit form. The cell edit template is used to add a custom component for a particular column by invoking the create, write, read, and destroy functions. dpParams: { create: () => { elemContent = document.createElement("textarea"); return elemContent; }, read: () => { return textEditor.value; }, destroy: () => { textEditor.destroy(); }, write: (args) => { textEditor = new TextBox({ multiline: true, value: args.rowData[args.column.field], floatLabelType: "Auto" }); textEditor.appendTo(elemContent); } } Using the valueAccessor feature of Grid, you can split the value into multiple lines in the Grid column. Note:When editing a particular cell in the Grid, you can prevent the ENTER key’s functionality using the created event in the Grid. methods: { created(args) { this.$refs.grid.ej2Instances.keyConfigs.enter = ""; }, valueAccessor: function (field, data, column) { var value = data[field]; if (value !== undefined) { return value.split("\n").join("<br>"); } else { return ""; } } } Output You can find the sample here: Vue Sample Documentation https://ej2.syncfusion.com/vue/documentation/grid/edit/#cell-edit-template https://ej2.syncfusion.com/vue/documentation/textbox/multiline/
You can disable the Cell Edit Template column by disabling the custom editor component based on your conditions. This is explained in the following code example in which, the “OrderDate” column editing feature is disabled by setting the “enabled” property of the “TimePicker” component based on some conditions to determine whether it is the user or admin. Razor <ejs-grid id="Grid" dataSource="@ViewBag.data" allowPaging="true" toolbar="@( new List<object>() {"Add","Edit","Delete","Update","Cancel"})"> <e-grid-editsettings allowAdding="true" allowDeleting="true" allowEditing="true"></e-grid-editsettings> <e-grid-columns> <e-grid-column field="OrderID" headerText="Order ID" isPrimaryKey="true" textAlign="Right" width="120"></e-grid-column> <e-grid-column field="CustomerID" headerText="Customer ID" textAlign="Right" width="120"></e-grid-column> <e-grid-column field="OrderDate" allowEditing="false" headerText="Order Date" customFormat="@(new { type ="date", format="hh:mm a" })" edit="@(new {create = "onCreate", read = "onRead", write = "onWrite", destroy= "onDestroy"})" width="130"></e-grid-column> <e-grid-column field="EmployeeID" headerText="Employee ID" textAlign="Right" width="120"></e-grid-column> </e-grid-columns> </ejs-grid> JS var isUser = true; function onCreate(args) { element = document.createElement('input'); return element; } function onRead(e) { return picker.value; } function onDestroy() { picker.destroy(); } function onWrite(args) { picker = new ej.calendars.TimePicker({ // Rendering TimePicker component value: args.rowData[args.column.field], format: 'hh:mm a', enabled: !isUser; // Disables the editing when “isUser” is true }); picker.appendTo(element); } Output Demo: https://www.syncfusion.com/downloads/support/directtrac/general/ze/EJ2GridSample1339747363
By default, Grid shows the standard formats (ex: ‘yMd’) in edit state of a column. Incase of custom formats, it will show only in display. To show the custom formats in edit state, you can use the ‘edit.params’ property of Grid columns. This is demonstrated in the below sample code in which the custom format is provided to the DateTimePicker editor component, by setting the ‘format’ property through ‘edit.params’. CSHTML @{ var editParams = new { @params = new { format = "hh:mm a" } }; } <ejs-grid id="Grid" dataSource="@ViewBag.data" allowPaging="true" toolbar="@( new List<object>() {"Add","Edit","Delete","Update","Cancel"})"> <e-grid-editsettings allowAdding="true" allowDeleting="true" allowEditing="true"></e-grid-editsettings> <e-grid-columns> <e-grid-column field="OrderID" headerText="Order ID" isPrimaryKey="true" textAlign="Right" width="120"></e-grid-column> <e-grid-column field="CustomerID" headerText="Customer ID" width="175" ></e-grid-column> <e-grid-column field="OrderDate" allowEditing="false" headerText="Order Date" editType="datetimepickeredit" edit="editParams" Format="hh:mm a" width="130"></e-grid-column> <e-grid-column field="EmployeeID" headerText="Employee ID" textAlign="Right" width="120"></e-grid-column> </e-grid-columns> </ejs-grid> OutPut Demo: https://www.syncfusion.com/downloads/support/directtrac/general/ze/customFormat-1225644421
Syncfusion® Essential® DocIO is a .NET Word library used to create, read, and edit Word documents programmatically without Microsoft Word or interop dependencies. Using this library, you can edit a Word document in C# and VB.NET. Steps to edit Word document programmatically in C#: Create a new C# console application project. Install Syncfusion.DocIO.WinForms NuGet package as a reference to your .NET Framework applications from the NuGet.org. Include the following namespace in the Program.cs file. C# using Syncfusion.DocIO.DLS; VB Imports Syncfusion.DocIO.DLS Use the following code snippet to edit Word document with simple text. C# //Opens the template Word document. using (WordDocument document = new WordDocument(@"../../Template.docx")) { //Gets the text body of first section. WTextBody textBody = document.Sections[0].Body; //Gets the first paragraph. WParagraph paragraph = textBody.Paragraphs[0]; //Gets the text range and modifies its content. WTextRange textRange = paragraph.ChildEntities[0] as WTextRange; textRange.Text = "Syncfusion Word library (Essential DocIO)"; //Sets formatting for modified content. textRange.CharacterFormat.FontSize = 20; textRange.CharacterFormat.Bold = true; //Saves the Word document. document.Save("Result.docx"); } VB 'Opens the template Word document. Using document As WordDocument = New WordDocument("../../Template.docx") 'Gets the text body of first section. Dim textBody As WTextBody = document.Sections(0).Body 'Gets the first paragraph. Dim paragraph As WParagraph = textBody.Paragraphs(0) 'Gets the text range and modifies its content. Dim textRange As WTextRange = TryCast(paragraph.ChildEntities(0), WTextRange) textRange.Text = "Syncfusion Word library (Essential DocIO)" //Sets formatting for modified content. textRange.CharacterFormat.FontSize = 20 textRange.CharacterFormat.Bold = True 'Saves the Word document. document.Save("Result.docx") End Using A complete working example to edit Word document using C# can be downloaded from Edit-Word-document.zip By executing the application, you will get the output Word document as follows. Take a moment to peruse the documentation, where you can find basic Word document processing options along with features like mail merge, merge and split documents, find and replace text in the Word document, protect the Word documents, and most importantly PDF and Image conversions with code examples. Explore more about the rich set of Syncfusion® Word Framework features. An online example to edit Word document. See Also: Create Word document in Windows Forms Create Word document in WPF Create Word document in ASP.NET Core Create Word document in ASP.NET MVC Create Word document in Xamarin Create Word document in Xamarin.Android Note:Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to link to learn about generating and registering Syncfusion® license key in your application to use the components without trail message.
By default, the TextBox control will be used as a default editor control for the string column in Javascript Grid. You can customize the editor control using Multiline Textbox by rendering it as a custom component in the Grid edit form. You can use the cellEditTemplate feature of Grid to render the Multiline TextBox component in the Grid edit form. The cell edit template is used to add a custom component for a particular column by invoking the create, write, read, and destroy functions. edit: { create: function () { elemContent = document.createElement('textarea'); return elemContent; }, destroy: function () { textEditor.destroy(); }, read: function () { return textEditor.value; }, write: function (args) { textEditor = new TextBox({ multiline: true, value: args.rowData[args.column.field], floatLabelType: 'Auto' }); textEditor.appendTo(elemContent); } } Using the valueAccessor feature of Grid, you can split the value into multiple lines in the Grid column. Note:When editing a particular cell in the Grid, you can prevent the ENTER key’s functionality using the created event in the Grid. function valueAccessor(field, data, column) { var value = data[field]; if (value != undefined) { return value.split('\n').join('<br>'); } else { return ''; } } created: function (args) { this.keyConfigs.enter = ''; } Output You can find the sample here: Javascript Sample Documentation https://ej2.syncfusion.com/documentation/textbox/multiline/ https://ej2.syncfusion.com/documentation/grid/edit/#cell-edit-template
By default, the TextBox control will be used as a default editor control for the string column in Angular Grid. You can customize the editor control using Multiline Textbox by rendering it as a custom component in the Grid edit form. You can use the cellEditTemplate feature of Grid to render the Multiline TextBox component in the Grid edit form. The cell edit template is used to add a custom component for a particular column by invoking the create, write, read, and destroy functions. this.dpParams = { create: () => { this.elemContent = document.createElement('textarea'); return this.elemContent; }, read: () => { return this.textEditor.value; }, destroy: () => { this.textEditor.destroy(); }, write: (args) => { this.textEditor = new TextBox({ multiline: true, value: args.rowData[args.column.field], floatLabelType: 'Auto' }); this.textEditor.appendTo(this.elemContent); }, }; Using the valueAccessor feature of Grid, you can split the value into multiple lines in the Grid column. Note:When editing a particular cell in the Grid, you can prevent the ENTER key’s functionality using the created event in the Grid. public valueAccessor = (field: string, data1: object, column: object) => { var value = data[field]; if (value != undefined) { return value.split('\n').join('<br>'); } else { return ''; } }; created(args) { this.grid.keyConfigs.enter = ''; } Output You can find the sample here: Angular Sample Documentation https://ej2.syncfusion.com/angular/documentation/grid/edit/#cell-edit-template https://ej2.syncfusion.com/angular/documentation/textbox/multiline/
You can update the summary values when you are changing the value by overriding OnInitializeEditElement method and DoubleTextBox.ValueChanging event in GridNumericCellRenderer in WPF DataGrid (SfDataGrid). dataGrid.LiveDataUpdateMode = LiveDataUpdateMode.AllowSummaryUpdate; this.dataGrid.CellRenderers.Remove("Numeric"); this.dataGrid.CellRenderers.Add("Numeric", new CustomizedGridCellNumericRenderer(dataGrid));internal class CustomizedGridCellNumericRenderer : GridCellNumericRenderer { RowColumnIndex RowColumnIndex; SfDataGrid DataGrid { get; set; } string newvalue = null; public CustomizedGridCellNumericRenderer(SfDataGrid dataGrid) { DataGrid = dataGrid; } public override void OnInitializeEditElement(DataColumnBase dataColumn, DoubleTextBox uiElement, object dataContext) { base.OnInitializeEditElement(dataColumn, uiElement, dataContext); uiElement.ValueChanging += UiElement_ValueChanging; this.RowColumnIndex.ColumnIndex = dataColumn.ColumnIndex; this.RowColumnIndex.RowIndex = dataColumn.RowIndex; } private void UiElement_ValueChanging(object sender, Syncfusion.Windows.Shared.ValueChangingEventArgs e) { newvalue = e.NewValue.ToString(); UpdateSummaryValues(this.RowColumnIndex.RowIndex, this.RowColumnIndex.ColumnIndex); } private void UpdateSummaryValues(int rowIndex, int columnIndex) { string editEelementText = newvalue=="0" ? "0" : newvalue; columnIndex = this.DataGrid.ResolveToGridVisibleColumnIndex(columnIndex); if (columnIndex < 0) return; var mappingName = DataGrid.Columns[columnIndex].MappingName; var recordIndex = this.DataGrid.ResolveToRecordIndex(rowIndex); if (recordIndex < 0) return; if (DataGrid.View.TopLevelGroup != null) { var record = DataGrid.View.TopLevelGroup.DisplayElements[recordIndex]; if (!record.IsRecords) return; var data = (record as RecordEntry).Data; data.GetType().GetProperty(mappingName).SetValue(data, (int.Parse(editEelementText))); } else { var record1 = DataGrid.View.Records.GetItemAt(recordIndex); record1.GetType().GetProperty(mappingName).SetValue(record1, (int.Parse(editEelementText))); } } } View sample in GitHub.
ms hDrive wi exSyncfusion Essential XlsIO is a .NET Excel library to create, read and edit Excel documents. Using this library, you can edit the Excel files downloaded from OneDrive and upload them again, with the help of Microsoft Graph. Steps to download Excel file from OneDrive, Edit and upload again programmatically: Create a Windows Forms Application: Create a new Windows Forms Application in Visual Studio. Create a Windows Forms app in Visual Studio Install the Syncfusion.XlsIO.WinForms NuGet package as reference to your .NET Framework application from NuGet.org. Install NuGet package to the project Install the following additional NuGet packages that will be used later. Microsoft.Toolkit.Services Microsoft.Identity.Client Microsoft.Toolkit.Win32.UI.Controls Install NuGet packages to the project Design the App: Add the following designer variable in Form1.Designer.cs. C# private System.ComponentModel.IContainer components = null; Replace the existing code in Form1.Designer.cs with the following content, to define the layout. C# private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.button1 = new System.Windows.Forms.Button(); this.graphLoginComponent1 = new Microsoft.Toolkit.Services.WinForms.GraphLoginComponent(this.components); this.SuspendLayout(); // // button1 // this.button1.Location = new System.Drawing.Point(325, 152); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(95, 48); this.button1.TabIndex = 0; this.button1.Text = "Edit Excel"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // graphLoginComponent1 // this.graphLoginComponent1.ClientId = null; this.graphLoginComponent1.Scopes = null; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(800, 450); this.Controls.Add(this.button1); this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false); } Now include the below components too. C# private System.Windows.Forms.Button button1; private Microsoft.Toolkit.Services.WinForms.GraphLoginComponent graphLoginComponent1; Register the App in Portal: Open a browser and navigate to the Azure Active Directory admin center and login using a personal account or Work or School Account. Register the app in Azure Select New registration. On the Register an application page, set the values as follows. Set Name to WindowsForms Graph Tutorial. Set Supported account types to Accounts in any organizational directory and personal Microsoft accounts. Under Redirect URI, change the dropdown to Public client (mobile & desktop), and set the value to urn:ietf:wg:oauth:2.0:oob. Select Register. On the WindowsForms Graph Tutorial page, copy the value of the Application (client) ID and save it, you will need it in the next step. Application ID Open Form1.cs and add the following using statements at the top of the file. C# using Microsoft.Identity.Client; using Syncfusion.XlsIO; Add the following functions to the Form1.cs class. C# private async void button1_Click(object sender, EventArgs e) { PublicClientApplication clientApp = new PublicClientApplication(ConfigurationManager.AppSettings["clientId"].ToString()); Microsoft.Graph.GraphServiceClient graphClient = new Microsoft.Graph.GraphServiceClient("https://graph.microsoft.com/v1.0", new Microsoft.Graph.DelegateAuthenticationProvider(async (requestMessage) => { requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", await GetTokenAsync(clientApp)); })); try { //Initialize ExcelEngine ExcelEngine excelEngine = new ExcelEngine(); //Initialize IApplication IApplication application = excelEngine.Excel; //Enable fast record parsing application.UseFastRecordParsing = true; //Get the file from OneDrive into stream var stream = await graphClient.Me.Drive.Root.ItemWithPath("Sample.xlsx").Content.Request().GetAsync(); //Set the stream position as '0' stream.Position = 0; //Initialize new MemoryStream and copy the existing stream to this new MemeoryStream MemoryStream file = new MemoryStream(); stream.CopyTo(file); //Set the stream position as '0' file.Position = 0; //Load the stream into IWorkbook IWorkbook workbook = application.Workbooks.Open(file); //Modify the Excel document workbook.Worksheets[0].Range["A2"].Text = "Syncfusion Essential XlsIO"; //Save the modified Excel document as new MemoryStream MemoryStream outputStream = new MemoryStream(); workbook.SaveAs(outputStream); //Set the stream position as '0' outputStream.Position = 0; //Upload the modified Excel document to OneDrive again await graphClient.Me.Drive.Root.ItemWithPath("ModifiedFile2.xlsx").Content.Request().PutAsync<Microsoft.Graph.DriveItem>(outputStream); //Close the workbook workbook.Close(); //Dispose the ExcelEngine excelEngine.Dispose(); } catch (Microsoft.Graph.ServiceException ex) { Console.WriteLine(ex); } } GetTokenAsync() method can be added as below. C# async Task<string> GetTokenAsync(PublicClientApplication clientApp) { //need to pass scope of activity to get token string[] Scopes = { "User.Read Files.ReadWrite Files.ReadWrite.All" }; string token = null; AuthenticationResult authResult = await clientApp.AcquireTokenAsync(Scopes); token = authResult.AccessToken; return token; } The Excel document should be downloaded, modified and uploaded again into OneDrive. A complete working example to download an Excel document from OneDrive, Modify it and upload the modified document to OneDrive, can be downloaded from MicrosoftGraphTutorial.zip. Take a moment to peruse the documentation, where you can find basic worksheet data manipulation options along with features like Conditional Formatting, worksheet calculations through Formulas, adding Charts in worksheet or workbook, organizing and analyzing data through Tables and Pivot Tables, appending multiple records to worksheet using Template Markers, and most importantly PDF and Image conversions with code examples. Refer here to explore the rich set of Syncfusion Excel (XlsIO) library features. Note:Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer the link to learn about generating and registering Syncfusion license key in your application to use the components without trial message. ConclusionI hope you enjoyed learning about how to download, edit, and upload Excel files in OneDrive with Microsoft Graph in WinForms.You can refer to our WinForms XIsIO feature tour page to know about its other groundbreaking feature representations documentation and how to quickly get started for configuration specifications. You can also explore our WinForms XIsIO example to understand how to create and manipulate data.For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!
You can render the ColorPicker component for a particular column while editing a record using the “Cell Edit Template” feature of JavaScript Grid component. This is explained in the following sample code in which the ColorPicker component has been rendered using the “column.edit” property. The “rowDataBound” event triggers every time the row is bounded with data. Inside this event, the color value can able to be applied to the cell background. JS var grid = new ej.grids.Grid({ dataSource: data, toolbar: ['Add', 'Edit', 'Delete', 'Update', 'Cancel'], editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true }, columns: [ { field: "OrderID", isPrimaryKey: true, headerText: "Order ID", width: 90 }, { field: "CustomerID", headerText: "CustomerID", width: 90 }, { field: "EmployeeID", headerText: "Employee ID", width: 90 }, { field: "Color", headerText: "Color", edit: { create: function () { elem = document.createElement('input'); return elem; }, destroy: function () { colorPickerObj.destroy(); }, read: function () { return colorPickerObj.value; }, write: function (args) { colorPickerObj = new ej.inputs.ColorPicker({ value: args.rowData[args.column.field] }); colorPickerObj.appendTo(elem); } }, width: 90 } ], rowDataBound: rowdatabound, }); grid.appendTo('#Grid'); function rowdatabound(args) { var colIndex = grid.getColumnIndexByField("Color"); // Get the column index for Color var colorTd = args.row.querySelectorAll("td.e-rowcell")[colIndex]; // Get the cell from Grid rows var color = colorTd.innerText;//get the colour value of the cell colorTd.innerHTML = "<div style='padding:3px'>" + color + "</div>";//Append a div element inside the colour Td element colorTd.querySelector("div").style.backgroundColor = args.data.Color; // Apply the background colour to the div element inside the td } OutPut Fig 1: Applying Color in Grid cells using RowDataBound event Fig 2: Rendering ColorPicker Component while editing. Fig 3: Updating the selected color to the corresponding Cell. JavaScript Demo Angular DemoConclusionI hope you enjoyed learning on how to render ColorPicker when editing record in JavaScript Grid.You can refer to our JavaScript Grid feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our JavaScript Grid example to understand how to create and manipulate data.For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!
Syncfusion Essential XlsIO is a .NET Excel library to create, read and edit Excel documents. Using this library, you can edit the Excel files downloaded from OneDrive and upload them again, with the help of Microsoft Graph. Steps to download Excel file from OneDrive, Edit and upload again programmatically: Create a Universal Windows Platform Application: Create a new Blank Universal Windows Application in Visual Studio. Create a Blank UWP app in Visual Studio Name the project In the New Universal Windows Platform Project dialog, ensure that the Minimum version is set to Windows 10 Fall Creators Update (10.0; Build 16299) or later and select OK. Set the minimum version to fall creators update Install the Syncfusion.XlsIO.UWP NuGet package as reference to your .NET Framework application from NuGet.org. Install NuGet package to the project Install the following additional NuGet packages that will be used later. Microsoft.Toolkit.Uwp.Ui.Controls to add some UI controls for in-app notifications and loading indicators. Microsoft.Toolkit.Uwp.Ui.Controls.DataGrid to display the information returned by Microsoft Graph. Microsoft.Toolkit.Uwp.Ui.Controls.Graph to handle login and access token retrieval. Microsoft.Graph for making calls to the Microsoft Graph. Install NuGet packages to the project Design the App: Add the following property in App.xaml.cs C# public bool IsAuthenticated { get; set; } Replace the existing code in MainPage.xaml with the following content, to define the layout for main page. XML <Page x:Class="graph_tutorial.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:graph_tutorial" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls" xmlns:graphControls="using:Microsoft.Toolkit.Uwp.UI.Controls.Graph" mc:Ignorable="d" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <Grid> <NavigationView x:Name="NavView" IsSettingsVisible="False" ItemInvoked="NavView_ItemInvoked"> <NavigationView.Header> <graphControls:AadLogin x:Name="Login" HorizontalAlignment="Left" View="SmallProfilePhotoLeft" AllowSignInAsDifferentUser="False" /> </NavigationView.Header> <NavigationView.MenuItems> <NavigationViewItem Content="Home" x:Name="Home" Tag="home"> <NavigationViewItem.Icon> <FontIcon Glyph=""/> </NavigationViewItem.Icon> </NavigationViewItem> <NavigationViewItem Content="OneDrive" x:Name="OneDrive" Tag="onedrive"> <NavigationViewItem.Icon> <FontIcon Glyph=""/> </NavigationViewItem.Icon> </NavigationViewItem> </NavigationView.MenuItems> <StackPanel> <controls:InAppNotification x:Name="Notification" ShowDismissButton="true" /> <Frame x:Name="RootFrame" Margin="24, 0" /> </StackPanel> </NavigationView> </Grid> </Page> Now add another XAML page for the Home view. Right-click on the project and select Add -> New Item -> Choose Blank Page, enter HomePage.xaml in the Name field, and select Add. Add the following code inside the <Grid> element in the file. XML <StackPanel> <TextBlock FontSize="44" FontWeight="Bold" Margin="0, 12">Microsoft Graph UWP Tutorial</TextBlock> <TextBlock x:Name="HomePageMessage">Please sign in to continue.</TextBlock> </StackPanel> Add the following function in MainPage.xaml.cs to manage authentication state. C# private void SetAuthState(bool isAuthenticated) { (App.Current as App).IsAuthenticated = isAuthenticated; //Toggle controls that require auth OneDrive.IsEnabled = isAuthenticated; } Add the following code in MainPage() constructor after the this.InitializeComponent(); line. C# //Initialize auth state to false SetAuthState(false); //Navigate to HomePage.xaml RootFrame.Navigate(typeof(HomePage)); When the app first starts, it will initialize the authentication state to false and navigate to the home page. Add the following event handler to load the requested page when the user selects an item from the navigation view. C# private void NavView_ItemInvoked(NavigationView sender, NavigationViewItemInvokedEventArgs args) { var invokedItem = args.InvokedItem as string; switch (invokedItem.ToLower()) { case "onedrive": throw new NotImplementedException(); break; case "home": default: RootFrame.Navigate(typeof(HomePage)); break; } } Save all your changes, then press F5 or select Debug -> Start Debugging in Visual Studio. Sign-In option Register the App in Portal: Open a browser and navigate to the Azure Active Directory admin center and login using a personal account or Work or School Account. Register the app in Azure Select New registration. On the Register an application page, set the values as follows. Set Name to UWP Graph Tutorial. Set Supported account types to Accounts in any organizational directory and personal Microsoft accounts. Under Redirect URI, change the dropdown to Public client (mobile & desktop), and set the value to urn:ietf:wg:oauth:2.0:oob. Select Register. On the UWP Graph Tutorial page, copy the value of the Application (client) ID and save it, you will need it in the next step. Application ID Add Azure AD Authentication: Right-click the graph-tutorial project in Solution Explorer and select Add -> New Item. Choose Resources File (.resw), name the file as OAuth.resw and select Add. When the new file opens in Visual Studio, create two resources as follows. Name: AppId, Value: the app ID you generated in Application Registration Portal Name: Scopes, Value: User.Read Files.ReadWrite Files.ReadWrite.All Provide authentication Configure the AadLogin control: Open MainPage.xaml.cs and add the following using statement to the top of the file. C# using Microsoft.Toolkit.Services.MicrosoftGraph; Replace the RootFrame.Navigate(typeof(HomePage)); line with the following code. C# //Load OAuth settings var oauthSettings = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView("OAuth"); var appId = oauthSettings.GetString("AppId"); var scopes = oauthSettings.GetString("Scopes"); if (string.IsNullOrEmpty(appId) || string.IsNullOrEmpty(scopes)) { Notification.Show("Could not load OAuth Settings from resource file."); } else { //Initialize Graph MicrosoftGraphService.Instance.AuthenticationModel = MicrosoftGraphEnums.AuthenticationModel.V2; MicrosoftGraphService.Instance.Initialize(appId, MicrosoftGraphEnums.ServicesToInitialize.UserProfile, scopes.Split(' ')); //Navigate to HomePage.xaml RootFrame.Navigate(typeof(HomePage)); } This code loads the settings from OAuth.resw and initializes the global instance of the MicrosoftGraphService with those values. Now add an event handler for the SignInCompleted event on the AadLogin control. Open the MainPage.xaml file and replace the existing <graphControls:AadLogin> element with the following. XML <graphControls:AadLogin x:Name="Login" HorizontalAlignment="Left" View="SmallProfilePhotoLeft" AllowSignInAsDifferentUser="False" SignInCompleted="Login_SignInCompleted" SignOutCompleted="Login_SignOutCompleted" /> Then add the following functions in MainPage.xaml.cs. C# private void Login_SignInCompleted(object sender, Microsoft.Toolkit.Uwp.UI.Controls.Graph.SignInEventArgs e) { //Set the auth state SetAuthState(true); //Reload the home page RootFrame.Navigate(typeof(HomePage)); } private void Login_SignOutCompleted(object sender, EventArgs e) { //Set the auth state SetAuthState(false); //Reload the home page RootFrame.Navigate(typeof(HomePage)); } Finally, open HomePage.xaml.cs and add the following code after the line this.InitializeComponent(); C# if ((App.Current as App).IsAuthenticated) { HomePageMessage.Text = "Welcome! Please use the menu to the left to select a view."; } Restart the app and click the Sign In control at the top of the app. Once you've signed in, the UI should change to indicate that you've successfully signed-in. Sign-In with your account Get the Excel file from OneDrive: Right-click the graph-tutorial project in Solution Explorer and select Add -> New Item. Choose Blank Page, enter OneDrivePage.xaml in the Name field, and select Add. Open OneDrivePage.xaml and add the following line inside the existing <Grid> element. XML <TextBlock x:Name="Events" TextWrapping="Wrap"/> Open OneDrivePage.xaml.cs and add the following using statements at the top of the file. C# using Microsoft.Toolkit.Services.MicrosoftGraph; using Microsoft.Toolkit.Uwp.UI.Controls; using Syncfusion.XlsIO; using Microsoft.Graph; Add the following functions to the OneDrivePage class. C# private void ShowNotification(string message) { //Get the main page that contains the InAppNotification var mainPage = (Window.Current.Content as Frame).Content as MainPage; //Get the notification control var notification = mainPage.FindName("Notification") as InAppNotification; notification.Show(message); } protected override async void OnNavigatedTo(NavigationEventArgs e) { //Get the Graph client from the service var graphClient = MicrosoftGraphService.Instance.GraphProvider; try { //Initialize ExcelEngine ExcelEngine excelEngine = new ExcelEngine(); //Initialize IApplication IApplication application = excelEngine.Excel; //Enable fast record parsing application.UseFastRecordParsing = true; //Get the file from OneDrive into stream var stream = await graphClient.Me.Drive.Root.ItemWithPath("Sample.xlsx").Content.Request().GetAsync(); //Set the stream position as '0' stream.Position = 0; //Initialize new MemoryStream and copy the existing stream to this new MemeoryStream MemoryStream file = new MemoryStream(); stream.CopyTo(file); //Set the stream position as '0' file.Position = 0; //Load the stream into IWorkbook IWorkbook workbook = await application.Workbooks.OpenAsync(file); //Modify the Excel document workbook.Worksheets[0].Range["A1"].Text = "Syncfusion Essential XlsIO"; //Save the modified Excel document as new MemoryStream MemoryStream outputStream = new MemoryStream(); await workbook.SaveAsAsync(outputStream); //Set the stream position as '0' outputStream.Position = 0; //Upload the modified Excel document to OneDrive again await graphClient.Me.Drive.Root.ItemWithPath("ModifiedExcel.xlsx").Content.Request().PutAsync<DriveItem>(outputStream); //Close the workbook workbook.Close(); //Dispose the ExcelEngine excelEngine.Dispose(); } catch (Microsoft.Graph.ServiceException ex) { ShowNotification($"Exception getting events: {ex.Message}"); } base.OnNavigatedTo(e); } Consider with the code in OnNavigatedTo is doing The URL that will be called is /v1.0/me/events. The Select function limits the fields returned for each event to just those the view will use. The OrderBy function sorts the results by date and time they were created, with the most recent item being first. Just before running the app, to be able to navigate to this onedrive page, modify the NavView_ItemInvoked method in the MainPage.xaml.cs file to replace the throw new NotImplementedException(); line with as follows. C# case "onedrive": RootFrame.Navigate(typeof(OneDrivePage)); break; You can now run the app, sign in, and click the OneDrive navigation item in the left-hand menu. The Excel document should be downloaded, modified and uploaded again into OneDrive. A complete working example to download an Excel document from OneDrive, Modify it and upload the modified document to OneDrive, can be downloaded from MSGraphTutorial. Take a moment to peruse the documentation, where you can find basic worksheet data manipulation options along with features like Conditional Formatting, worksheet calculations through Formulas, adding Charts in worksheet or workbook, organizing and analyzing data through Tables and Pivot Tables, appending multiple records to worksheet using Template Markers, and most importantly PDF and Image conversions with code examples. Refer here to explore the rich set of Syncfusion Excel (XlsIO) library features. Note:Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer the link to learn about generating and registering Syncfusion license key in your application to use the components without trail message.
Syncfusion Excel (XlsIO) library is a .NET Excel library used to create, read, and edit Excel documents. Also, converts Excel documents to PDF files. Using this library, you can edit Excel file in C#, VB.NET. While working with Excel templates or existing Excel workbooks, it is necessary to edit Excel file and modify data in the existing Excel file. This article explains how to add or modify data in the existing workbook and edit Excel file with an example. Steps to edit Excel file programmatically: Step 1: Create a new C# console application project. Create a new C# console application Step 2: Install Syncfusion.XlsIO.WinForms NuGet package as a reference to your .NET Framework applications from the NuGet.org. Install NuGet package Step 3: Include the following namespaces in the Program.cs file. C# using Syncfusion.XlsIO; using System.IO; using System.Reflection; VB.NET Imports Syncfusion.XlsIO Imports System.IO Imports System.Reflection Step 4: Add the following code snippet to edit Excel file in C#, VB.NET. C# //Instantiate the spreadsheet creation engine using (ExcelEngine excelEngine = new ExcelEngine()) { //Initialize application IApplication application = excelEngine.Excel; //Open existing workbook with data entered Assembly assembly = typeof(Program).GetTypeInfo().Assembly; Stream fileStream = assembly.GetManifestResourceStream("EditExcelFile_CS.Sample.xlsx"); IWorkbook workbook = application.Workbooks.Open(fileStream, ExcelOpenType.Automatic); IWorksheet worksheet = workbook.Worksheets[0]; //Add text data worksheet.Range["A1"].Text = "Employee No"; worksheet.Range["B1"].Text = "Employee Name"; worksheet.Range["C1"].Text = "Birth Date"; //Add DateTime data worksheet.Range["C2"].DateTime = new DateTime(1976, 1, 10); worksheet.Range["C3"].DateTime = new DateTime(1973, 2, 10); worksheet.Range["C4"].DateTime = new DateTime(1980, 3, 10); //Apply number format for date value cells C2 to C4 worksheet.Range["C2:C4"].NumberFormat = "mmmm, yyyy"; //Auto-size the columns to fit the content worksheet.AutofitColumn(1); worksheet.AutofitColumn(2); worksheet.AutofitColumn(3); //Add numeric data worksheet.Range["A2"].Number = 68878; worksheet.Range["A3"].Number = 71550; worksheet.Range["A4"].Number = 72808; //Save the edited workbook to disk in xlsx format workbook.SaveAs("Output.xlsx"); } VB.NET 'Instantiate the spreadsheet creation engine Using excelEngine As ExcelEngine = New ExcelEngine() 'Initialize application Dim application As IApplication = excelEngine.Excel 'Open existing workbook with data entered Dim assembly As Assembly = GetType(Module1).GetTypeInfo.Assembly Dim fileStream As Stream = assembly.GetManifestResourceStream("EditExcelFile_VB.Sample.xlsx") Dim workbook As IWorkbook = application.Workbooks.Open(fileStream, ExcelOpenType.Automatic) Dim worksheet As IWorksheet = workbook.Worksheets(0) 'Add text data worksheet.Range("A1").Text = "Employee No" worksheet.Range("B1").Text = "Employee Name" worksheet.Range("C1").Text = "Birth Date" 'Add DateTime data worksheet.Range("C2").DateTime = New DateTime(1976, 1, 10) worksheet.Range("C3").DateTime = New DateTime(1973, 2, 10) worksheet.Range("C4").DateTime = New DateTime(1980, 3, 10) 'Apply number format for date value cells C2 to C4 worksheet.Range("C2:C4").NumberFormat = "mmmm, yyyy" 'Auto-size the columns to fit the content worksheet.AutofitColumn(1) worksheet.AutofitColumn(2) worksheet.AutofitColumn(3) 'Add numeric data worksheet.Range("A2").Number = 68878 worksheet.Range("A3").Number = 71550 worksheet.Range("A4").Number = 72808 'Save the edited workbook to disk in xlsx format workbook.SaveAs("Output.xlsx") End Using A complete working example to edit Excel file along with input file used to edit can be downloaded from Edit Excel File.zip. By executing the program, you will get the edited output Excel file as shown below. Output Excel document Take a moment to peruse the documentation, where you can find basic worksheet data manipulation options along with features like Conditional Formatting, worksheet calculations through Formulas, adding Charts in worksheet or workbook, organizing and analyzing data through Tables and Pivot Tables, appending multiple records to worksheet using Template Markers, and most importantly PDF and Image conversions with code examples. Refer here to explore the rich set of Syncfusion Excel (XlsIO) library features. An online sample link to generate Excel file. See Also: Read Excel from Code in C#, VB.NET Create Excel file in Azure platform Create Excel file in WPF How to convert file to CSV in C#, VB.NET? Create Excel from DataTable in C#, VB.NET Note:Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer the link to learn about generating and registering Syncfusion license key in your application to use the components without trail message.
PowerPoint presentation is a file format that allows you to create and show a series of slides containing text, shapes, charts, images and SmartArt diagrams with rich set of formatting options to make your presentation more attractive and memorable.Syncfusion Essential Presentation is a .NET PowerPoint library used to create, open, read, and edit PowerPoint presentations. Using this library, you can start creating a PowerPoint file in Xamarin. Steps to create a PowerPoint presentation file: Create a new C# Xamarin.Forms application project. Select a project template and required platforms to deploy the application. In this application the portable assemblies to be shared across multiple platforms, the .NET Standard code sharing strategy has been selected. For more details about code sharing refer here. Install Syncfusion.Xamarin.Presentation NuGet package as a reference to the .NET Standard project in your Xamarin applications from NuGet.org. Add new Forms XAML page in portable project If there is no XAML page is defined in the App class. Otherwise proceed to the next step. To add the new XAML page, right click on the project and select Add > New Item and add a Forms XAML Page from the list. Name it as MainXamlPage. In App class of portable project (App.cs), replace the existing constructor of App class with the code snippet given below which invokes the MainXamlPage.public App() { // The root page of your application MainPage = new MainXamlPage(); } In the MainXamlPage.xaml add new button as shown below.<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="GettingStarted. MainXamlPage"> <StackLayout VerticalOptions="Center"> <Button Text="Generate Document" Clicked="OnButtonClicked" HorizontalOptions="Center"/> </StackLayout> </ContentPage> Include the following namespace in the MainXamlPage.xaml.cs file.using Syncfusion.Presentation; Include the below code snippet in the click event of the button in MainXamlPage.xaml.cs, to create an PowerPoint file and save it in a stream.//Create a new PowerPoint presentation IPresentation powerpointDoc = Presentation.Create(); //Add a blank slide to the presentation ISlide slide = powerpointDoc.Slides.Add(SlideLayoutType.Blank); //Add a textbox to the slide IShape shape = slide.AddTextBox(10, 10, 500, 100); //Add a text to the textbox. shape.TextBody.AddParagraph("Hello World!!!"); //Save the PowerPoint to stream in pptx format. MemoryStream stream = new MemoryStream(); powerpointDoc.Save(stream); powerpointDoc.Close(); //Save the stream as a file in the device and invoke it for viewing Xamarin.Forms.DependencyService.Get<ISave>().SaveAndView("GettingStared.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", stream); Download the helper files from this link and add them into the mentioned project. These helper files allow you to save the stream as a physical file and open the file for viewing. Project File Name Summary Protable project ISave.cs Represent the base interface for save operation iOS Project SaveIOS.cs Save implementation for iOS device PreviewControllerDS.cs Helper class for viewing the PowerPoint file in iOS device Android project SaveAndroid.cs Save implementation for Android device UWP project SaveWindows.cs Save implementation for UWP device. Compile and execute the application. By executing the program, you will get the PowerPoint document as follows. A complete working sample can be downloaded from Create-PowerPoint-file.zip.Take a moment to peruse the documentation, where you can find other options to format the text with code examples.Refer here to explore the rich set of Syncfusion Essential Presentation features.See Also:Create a PowerPoint file in ASP.NET MVCCreate a PowerPoint file in ASP.NETCreate a PowerPoint file in Windows FormsCreate a PowerPoint file in WPFNote:Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to link to learn about generating and registering Syncfusion license key in your application to use the components without trail message. ConclusionI hope you enjoyed learning about how to create a PowerPoint presentation file in Xamarin.Forms.You can refer to our Presentation featuretour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our WinForms Presentation example to understand how to create and manipulate data.For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you! Syncfusion.Xamarin.Presentation NuGet package as a reference to the .NET Standard project in your Xamarin applications from NuGet.org.
Syncfusion Essential Presentation is a .NET PowerPoint library used to create, open, read, edit, and convert PowerPoint presentations. The library supports reading PowerPoint presentations in C# and VB.NET from a file path or a stream. This functionality is exposed through the presentation. Open static method overloads. Steps to read PowerPoint programmatically: Create a new C# console application. Install Syncfusion.Presentation.Base NuGet package to the console application project from nuget.org. For more information about adding a NuGet feed in Visual Studio and installing NuGet packages, refer to documentation Include the following namespace in the Program.cs file.using Syncfusion.Presentation; Imports Syncfusion.Presentation Read a PowerPoint file from stream The following example demonstrates how to read a PowerPoint file from a stream and save it to a physical file path. //File stream that holds the PowerPoint presentation. FileStream fileStream = new FileStream("Sample.pptx", FileMode.Open, System.IO.FileAccess.Read); //Open the presentation. IPresentation powerpointDoc = Presentation.Open(fileStream); //Save the PowerPoint presentation to a file. powerpointDoc.Save("Resaved.pptx"); //Close the presentation. powerpointDoc.Close(); //Dispose the used memory. fileStream.Dispose(); 'File stream that holds the PowerPoint presentation. Dim fileStream As New FileStream("Sample.pptx", FileMode.Open, System.IO.FileAccess.Read) 'Open the presentation. Dim powerpointDoc As IPresentation = Presentation.Open(fileStream) 'Save the PowerPoint presentation to a file. powerpointDoc.Save("Resaved.pptx") 'Close the presentation. powerpointDoc.Close() 'Dispose the used memory. fileStream.Dispose() Read the PowerPoint file from file path The following example demonstrates how to read a PowerPoint file from a file path and save it to a stream. //Open the presentation. IPresentation powerpointDoc = Presentation.Open("Sample.pptx"); //Create a stream to save the PowerPoint presentation. MemoryStream stream = new MemoryStream(); //Save the PowerPoint presentation to the stream. powerpointDoc.Save(stream); //Close the presentation. powerpointDoc.Close(); 'Open a presentation. Dim powerpointDoc As IPresentation = Presentation.Open("Sample.pptx") 'Create a stream to save the PowerPoint presentation. Dim stream As New MemoryStream() 'Save the PowerPoint presentation to the stream. powerpointDoc.Save(stream) 'Close the presentation. powerpointDoc.Close() The following example demonstrates how to read a PowerPoint presentation from a file path, iterate over all shapes in the slides and print the text in console output. //Open the presentation IPresentation powerpointDoc = Presentation.Open("Sample.pptx"); //Iterate the slides in the PowerPoint presentation file foreach (ISlide slide in powerpointDoc.Slides) { //Iterate the shapes in the slide foreach (IShape shape in slide.Shapes) { // Check whether the shape is an auto-shape. Other types can be charts, tables or SmartArt diagrams. if (shape.SlideItemType == SlideItemType.AutoShape) //Print the text to the console output System.Console.WriteLine(shape.TextBody.Text); } } //Save the PowerPoint presentation to another file. powerpointDoc.Save("Resaved.pptx"); //Close the presentation. powerpointDoc.Close(); //Wait to check the console output System.Console.Read(); 'Open the presentation Dim powerpointDoc As IPresentation = Presentation.Open("Sample.pptx") 'Iterate the slides in the PowerPoint presentation file For Each slide As ISlide In powerpointDoc.Slides 'Iterate the shapes in the slide For Each shape As IShape In slide.Shapes ' Check whether the shape is an auto-shape. Other types can be charts, tables or SmartArt diagrams. If shape.SlideItemType = SlideItemType.AutoShape Then 'Print the text to the console output System.Console.WriteLine(shape.TextBody.Text) End If Next Next 'Save the PowerPoint presentation to another file. powerpointDoc.Save("Resaved.pptx") 'Close the presentation. powerpointDoc.Close() 'Wait to check the console output System.Console.Read() You can download the working sample from Read-PowerPoint-File.Zip. Take a moment to peruse the documentation with code examples. Refer here to explore the rich set of Syncfusion Essential Presentation features. Note:Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to link to learn about generating and registering Syncfusion license key in your application to use the components without trail message. ConclusionI hope you enjoyed learning about how to read a PowerPoint file in C#, VB.NET in WinForms.You can refer to our WinForms Presentation feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our WinForms Presentation example to understand how to create and manipulate data.For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!
You can bind a selected value from the drop-down list using the ngModel and edit it inside the text box or numeric input box. The selected item text and value can be got using the change event of the drop-down list through the args.itemData. To bind this itemData text to the text box and edit the selected text, refer to the following code. App.component.html: <div style="margin: 0px auto; width:250px; padding-top: 40px;"> <label>EJ2 DropDownList</label><br /><br /> <ejs-dropdownlist id='games' #sample [dataSource]='sportsData' (change)='onChange($event)' [(value)]='value' [(text)]='text' [fields]='fields' [placeholder]='waterMark' [popupHeight]='height'></ejs-dropdownlist> <div style="margin-top:15px"> <label>Game Id:</label><br /><br /> <input id="Gvalue" type="number" [(ngModel)]="value" /> </div> <div style="margin-top:15px"> <label>Game Name:</label><br /><br /> <input id="Gtext" type="text" [(ngModel)]="text" /> </div> </div> App.component.ts: import { Component,ViewChild } from '@angular/core'; import { DropDownListComponent } from '@syncfusion/ej2-ng-dropdowns'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { @ViewChild('sample') public ddlObj: DropDownListComponent; // define the JSON of data public sportsData: Object[] = [ { Id: 1, Game: 'American Football' }, { Id: 2, Game: 'Badminton' }, { Id: 3, Game: 'Basketball' }, { Id: 4, Game: 'Cricket' }, { Id: 5, Game: 'Football' }, { Id: 6, Game: 'Golf' }, { Id: 7, Game: 'Hockey' }, { Id: 8, Game: 'Rugby' }, { Id: 9, Game: 'Snooker' }, { Id: 10, Game: 'Tennis' } ]; // maps the appropriate column to fields property public fields: Object = { text: 'Game', value: 'Id' }; // set the height of the popup element public height: string = '220px'; // set the placeholder to DropDownList input element public waterMark: string = 'Select a game'; // set the value to select an item based on mapped value at initial rendering public value: number = 3; //set text for model textbox public text:string='Basketball'; //change event of DropDownList public onChange(args: any): void { this.text=args.itemData.Game; //assign the changed text in DropDownList to textbox } } App.module.ts: import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { DropDownListModule} from '@syncfusion/ej2-ng-dropdowns'; import { AppComponent } from './app.component'; import { HelloComponent } from './hello.component'; @NgModule({ imports: [ BrowserModule, FormsModule ,DropDownListModule], declarations: [ AppComponent, HelloComponent ], bootstrap: [ AppComponent ] }) export class AppModule { } StackBlitz sample link: https://stackblitz.com/edit/angular-svhivj Output:
A report (RDL/RDLC) can be edited or modified at runtime using ReportDefinition class. The following describes the steps to edit a report at runtime and render the output. To edit existing report, it need to be de serialized to Report Definition object using XmlSerializer. C# FileStream stream = new FileStream(info.FullName, FileMode.Open, FileAccess.Read, FileShare.Read); XElement rdl = XElement.Load(XmlReader.Create(stream)); string Namespace = (from attribute in rdl.Attributes() where attribute.Name.LocalName == "xmlns" select attribute.Value).FirstOrDefault(); XmlSerializer xs = new XmlSerializer(typeof(Syncfusion.RDL.DOM.ReportDefinition), Namespace); using (StringReader reader = new StringReader(rdl.ToString())) { reportDefinition = (Syncfusion.RDL.DOM.ReportDefinition)xs.Deserialize(reader); } The serialized report definition object contains all the properties available in report file. The properties of each XML element can accessed and updated to required values. In the below code, value of a text box report item in page header is updated with new value. C# var data = reportDefinition.ReportSections[0]; //=====Edit Report item in report header =========// Syncfusion.RDL.DOM.TextBox headertext = new Syncfusion.RDL.DOM.TextBox(); headertext = (Syncfusion.RDL.DOM.TextBox)data.Page.PageHeader.ReportItems[0]; headertext.Paragraphs[0].TextRuns[0].Value = table.Columns[0].ToString(); The below code used to edit Tablix report item and its inner cell element value in report. C# Syncfusion.RDL.DOM.Tablix reportitem = new Syncfusion.RDL.DOM.Tablix(); reportitem = (Syncfusion.RDL.DOM.Tablix)data.Body.ReportItems[0]; for (int i = 0; i < table.Columns.Count; i++) { Syncfusion.RDL.DOM.TextBox txtbox = new Syncfusion.RDL.DOM.TextBox(); txtbox = (Syncfusion.RDL.DOM.TextBox)reportitem.TablixBody.TablixRows[0].TablixCells[i].CellContents.ReportItem; txtbox.Paragraphs[0].TextRuns[0].Value = table.Columns[i].ToString(); } The modified report definition can be converted as stream or saved into a local file using the XmlSerializer’s Deserialize method. C# string nameSpace = "http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition"; if (reportDefinition.RDLType == Syncfusion.RDL.DOM.RDLType.RDL2010) { nameSpace = "http://schemas.microsoft.com/sqlserver/reporting/2010/01/reportdefinition"; } System.Xml.Serialization.XmlSerializerNamespaces serialize = new System.Xml.Serialization.XmlSerializerNamespaces(); serialize.Add("rd", "http://schemas.microsoft.com/SQLServer/reporting/reportdesigner"); XmlSerializer xs2 = new XmlSerializer(typeof(Syncfusion.RDL.DOM.ReportDefinition), nameSpace); MemoryStream memoryStream = new MemoryStream(); TextWriter ws2 = new StreamWriter(memoryStream); xs2.Serialize(ws2, reportDefinition, serialize); memoryStream.Position = 0; Samples WPF JavaScript
A report (RDL/RDLC) can be edited or modified at runtime using ReportDefinition class. The following describes the steps to edit a report at runtime and render the output. To edit existing report, it need to be de serialized to Report Definition object using XmlSerializer. C# FileStream stream = new FileStream(info.FullName, FileMode.Open, FileAccess.Read, FileShare.Read); XElement rdl = XElement.Load(XmlReader.Create(stream)); string Namespace = (from attribute in rdl.Attributes() where attribute.Name.LocalName == "xmlns" select attribute.Value).FirstOrDefault(); XmlSerializer xs = new XmlSerializer(typeof(Syncfusion.RDL.DOM.ReportDefinition), Namespace); using (StringReader reader = new StringReader(rdl.ToString())) { reportDefinition = (Syncfusion.RDL.DOM.ReportDefinition)xs.Deserialize(reader); } The serialized report definition object contains all the properties available in report file. The properties of each XML element can accessed and updated to required values. In the below code, value of a text box report item in page header is updated with new value. C# var data = reportDefinition.ReportSections[0]; //=====Edit Report item in report header =========// Syncfusion.RDL.DOM.TextBox headertext = new Syncfusion.RDL.DOM.TextBox(); headertext = (Syncfusion.RDL.DOM.TextBox)data.Page.PageHeader.ReportItems[0]; headertext.Paragraphs[0].TextRuns[0].Value = table.Columns[0].ToString(); The below code used to edit Tablix report item and its inner cell element value in report. C# Syncfusion.RDL.DOM.Tablix reportitem = new Syncfusion.RDL.DOM.Tablix(); reportitem = (Syncfusion.RDL.DOM.Tablix)data.Body.ReportItems[0]; for (int i = 0; i < table.Columns.Count; i++) { Syncfusion.RDL.DOM.TextBox txtbox = new Syncfusion.RDL.DOM.TextBox(); txtbox = (Syncfusion.RDL.DOM.TextBox)reportitem.TablixBody.TablixRows[0].TablixCells[i].CellContents.ReportItem; txtbox.Paragraphs[0].TextRuns[0].Value = table.Columns[i].ToString(); } The modified report definition can be converted as stream or saved into a local file using the XmlSerializer’s Deserialize method. C# string nameSpace = "http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition"; if (reportDefinition.RDLType == Syncfusion.RDL.DOM.RDLType.RDL2010) { nameSpace = "http://schemas.microsoft.com/sqlserver/reporting/2010/01/reportdefinition"; } System.Xml.Serialization.XmlSerializerNamespaces serialize = new System.Xml.Serialization.XmlSerializerNamespaces(); serialize.Add("rd", "http://schemas.microsoft.com/SQLServer/reporting/reportdesigner"); XmlSerializer xs2 = new XmlSerializer(typeof(Syncfusion.RDL.DOM.ReportDefinition), nameSpace); MemoryStream memoryStream = new MemoryStream(); TextWriter ws2 = new StreamWriter(memoryStream); xs2.Serialize(ws2, reportDefinition, serialize); memoryStream.Position = 0; Samples WPF JavaScript
A report (RDL/RDLC) can be edited or modified at runtime using ReportDefinition class. The following describes the steps to edit a report at runtime and render the output. To edit existing report, it need to be de serialized to Report Definition object using XmlSerializer. C# FileStream stream = new FileStream(info.FullName, FileMode.Open, FileAccess.Read, FileShare.Read); XElement rdl = XElement.Load(XmlReader.Create(stream)); string Namespace = (from attribute in rdl.Attributes() where attribute.Name.LocalName == "xmlns" select attribute.Value).FirstOrDefault(); XmlSerializer xs = new XmlSerializer(typeof(Syncfusion.RDL.DOM.ReportDefinition), Namespace); using (StringReader reader = new StringReader(rdl.ToString())) { reportDefinition = (Syncfusion.RDL.DOM.ReportDefinition)xs.Deserialize(reader); } The serialized report definition object contains all the properties available in report file. The properties of each XML element can accessed and updated to required values. In the below code, value of a text box report item in page header is updated with new value. C# var data = reportDefinition.ReportSections[0]; //=====Edit Report item in report header =========// Syncfusion.RDL.DOM.TextBox headertext = new Syncfusion.RDL.DOM.TextBox(); headertext = (Syncfusion.RDL.DOM.TextBox)data.Page.PageHeader.ReportItems[0]; headertext.Paragraphs[0].TextRuns[0].Value = table.Columns[0].ToString(); The below code used to edit Tablix report item and its inner cell element value in report. C# Syncfusion.RDL.DOM.Tablix reportitem = new Syncfusion.RDL.DOM.Tablix(); reportitem = (Syncfusion.RDL.DOM.Tablix)data.Body.ReportItems[0]; for (int i = 0; i < table.Columns.Count; i++) { Syncfusion.RDL.DOM.TextBox txtbox = new Syncfusion.RDL.DOM.TextBox(); txtbox = (Syncfusion.RDL.DOM.TextBox)reportitem.TablixBody.TablixRows[0].TablixCells[i].CellContents.ReportItem; txtbox.Paragraphs[0].TextRuns[0].Value = table.Columns[i].ToString(); } The modified report definition can be converted as stream or saved into a local file using the XmlSerializer’s Deserialize method. C# string nameSpace = "http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition"; if (reportDefinition.RDLType == Syncfusion.RDL.DOM.RDLType.RDL2010) { nameSpace = "http://schemas.microsoft.com/sqlserver/reporting/2010/01/reportdefinition"; } System.Xml.Serialization.XmlSerializerNamespaces serialize = new System.Xml.Serialization.XmlSerializerNamespaces(); serialize.Add("rd", "http://schemas.microsoft.com/SQLServer/reporting/reportdesigner"); XmlSerializer xs2 = new XmlSerializer(typeof(Syncfusion.RDL.DOM.ReportDefinition), nameSpace); MemoryStream memoryStream = new MemoryStream(); TextWriter ws2 = new StreamWriter(memoryStream); xs2.Serialize(ws2, reportDefinition, serialize); memoryStream.Position = 0; Samples WPF JavaScript
A report (RDL/RDLC) can be edited or modified at runtime using ReportDefinition class. The following describes the steps to edit a report at runtime and render the output. To edit existing report, it need to be de serialized to Report Definition object using XmlSerializer. C# FileStream stream = new FileStream(info.FullName, FileMode.Open, FileAccess.Read, FileShare.Read); XElement rdl = XElement.Load(XmlReader.Create(stream)); string Namespace = (from attribute in rdl.Attributes() where attribute.Name.LocalName == "xmlns" select attribute.Value).FirstOrDefault(); XmlSerializer xs = new XmlSerializer(typeof(Syncfusion.RDL.DOM.ReportDefinition), Namespace); using (StringReader reader = new StringReader(rdl.ToString())) { reportDefinition = (Syncfusion.RDL.DOM.ReportDefinition)xs.Deserialize(reader); } The serialized report definition object contains all the properties available in report file. The properties of each XML element can accessed and updated to required values. In the below code, value of a text box report item in page header is updated with new value. C# var data = reportDefinition.ReportSections[0]; //=====Edit Report item in report header =========// Syncfusion.RDL.DOM.TextBox headertext = new Syncfusion.RDL.DOM.TextBox(); headertext = (Syncfusion.RDL.DOM.TextBox)data.Page.PageHeader.ReportItems[0]; headertext.Paragraphs[0].TextRuns[0].Value = table.Columns[0].ToString(); The below code used to edit Tablix report item and its inner cell element value in report. C# Syncfusion.RDL.DOM.Tablix reportitem = new Syncfusion.RDL.DOM.Tablix(); reportitem = (Syncfusion.RDL.DOM.Tablix)data.Body.ReportItems[0]; for (int i = 0; i < table.Columns.Count; i++) { Syncfusion.RDL.DOM.TextBox txtbox = new Syncfusion.RDL.DOM.TextBox(); txtbox = (Syncfusion.RDL.DOM.TextBox)reportitem.TablixBody.TablixRows[0].TablixCells[i].CellContents.ReportItem; txtbox.Paragraphs[0].TextRuns[0].Value = table.Columns[i].ToString(); } The modified report definition can be converted as stream or saved into a local file using the XmlSerializer’s Deserialize method. C# string nameSpace = "http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition"; if (reportDefinition.RDLType == Syncfusion.RDL.DOM.RDLType.RDL2010) { nameSpace = "http://schemas.microsoft.com/sqlserver/reporting/2010/01/reportdefinition"; } System.Xml.Serialization.XmlSerializerNamespaces serialize = new System.Xml.Serialization.XmlSerializerNamespaces(); serialize.Add("rd", "http://schemas.microsoft.com/SQLServer/reporting/reportdesigner"); XmlSerializer xs2 = new XmlSerializer(typeof(Syncfusion.RDL.DOM.ReportDefinition), nameSpace); MemoryStream memoryStream = new MemoryStream(); TextWriter ws2 = new StreamWriter(memoryStream); xs2.Serialize(ws2, reportDefinition, serialize); memoryStream.Position = 0; Samples WPF JavaScript
A report (RDL/RDLC) can be edited or modified at runtime using ReportDefinition class. The following describes the steps to edit a report at runtime and render the output. To edit existing report, it need to be de serialized to Report Definition object using XmlSerializer. C# FileStream stream = new FileStream(info.FullName, FileMode.Open, FileAccess.Read, FileShare.Read); XElement rdl = XElement.Load(XmlReader.Create(stream)); string Namespace = (from attribute in rdl.Attributes() where attribute.Name.LocalName == "xmlns" select attribute.Value).FirstOrDefault(); XmlSerializer xs = new XmlSerializer(typeof(Syncfusion.RDL.DOM.ReportDefinition), Namespace); using (StringReader reader = new StringReader(rdl.ToString())) { reportDefinition = (Syncfusion.RDL.DOM.ReportDefinition)xs.Deserialize(reader); } The serialized report definition object contains all the properties available in report file. The properties of each XML element can accessed and updated to required values. In the below code, value of a text box report item in page header is updated with new value. C# var data = reportDefinition.ReportSections[0]; //=====Edit Report item in report header =========// Syncfusion.RDL.DOM.TextBox headertext = new Syncfusion.RDL.DOM.TextBox(); headertext = (Syncfusion.RDL.DOM.TextBox)data.Page.PageHeader.ReportItems[0]; headertext.Paragraphs[0].TextRuns[0].Value = table.Columns[0].ToString(); The below code used to edit Tablix report item and its inner cell element value in report. C# Syncfusion.RDL.DOM.Tablix reportitem = new Syncfusion.RDL.DOM.Tablix(); reportitem = (Syncfusion.RDL.DOM.Tablix)data.Body.ReportItems[0]; for (int i = 0; i < table.Columns.Count; i++) { Syncfusion.RDL.DOM.TextBox txtbox = new Syncfusion.RDL.DOM.TextBox(); txtbox = (Syncfusion.RDL.DOM.TextBox)reportitem.TablixBody.TablixRows[0].TablixCells[i].CellContents.ReportItem; txtbox.Paragraphs[0].TextRuns[0].Value = table.Columns[i].ToString(); } The modified report definition can be converted as stream or saved into a local file using the XmlSerializer’s Deserialize method. C# string nameSpace = "http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition"; if (reportDefinition.RDLType == Syncfusion.RDL.DOM.RDLType.RDL2010) { nameSpace = "http://schemas.microsoft.com/sqlserver/reporting/2010/01/reportdefinition"; } System.Xml.Serialization.XmlSerializerNamespaces serialize = new System.Xml.Serialization.XmlSerializerNamespaces(); serialize.Add("rd", "http://schemas.microsoft.com/SQLServer/reporting/reportdesigner"); XmlSerializer xs2 = new XmlSerializer(typeof(Syncfusion.RDL.DOM.ReportDefinition), nameSpace); MemoryStream memoryStream = new MemoryStream(); TextWriter ws2 = new StreamWriter(memoryStream); xs2.Serialize(ws2, reportDefinition, serialize); memoryStream.Position = 0; Samples WPF JavaScript
A report (RDL/RDLC) can be edited or modified at runtime using ReportDefinition class. The following describes the steps to edit a report at runtime and render the output. To edit existing report, it need to be de serialized to Report Definition object using XmlSerializer. C# FileStream stream = new FileStream(info.FullName, FileMode.Open, FileAccess.Read, FileShare.Read); XElement rdl = XElement.Load(XmlReader.Create(stream)); string Namespace = (from attribute in rdl.Attributes() where attribute.Name.LocalName == "xmlns" select attribute.Value).FirstOrDefault(); XmlSerializer xs = new XmlSerializer(typeof(Syncfusion.RDL.DOM.ReportDefinition), Namespace); using (StringReader reader = new StringReader(rdl.ToString())) { reportDefinition = (Syncfusion.RDL.DOM.ReportDefinition)xs.Deserialize(reader); } The serialized report definition object contains all the properties available in report file. The properties of each XML element can accessed and updated to required values. In the below code, value of a text box report item in page header is updated with new value. C# var data = reportDefinition.ReportSections[0]; //=====Edit Report item in report header =========// Syncfusion.RDL.DOM.TextBox headertext = new Syncfusion.RDL.DOM.TextBox(); headertext = (Syncfusion.RDL.DOM.TextBox)data.Page.PageHeader.ReportItems[0]; headertext.Paragraphs[0].TextRuns[0].Value = table.Columns[0].ToString(); The below code used to edit Tablix report item and its inner cell element value in report. C# Syncfusion.RDL.DOM.Tablix reportitem = new Syncfusion.RDL.DOM.Tablix(); reportitem = (Syncfusion.RDL.DOM.Tablix)data.Body.ReportItems[0]; for (int i = 0; i < table.Columns.Count; i++) { Syncfusion.RDL.DOM.TextBox txtbox = new Syncfusion.RDL.DOM.TextBox(); txtbox = (Syncfusion.RDL.DOM.TextBox)reportitem.TablixBody.TablixRows[0].TablixCells[i].CellContents.ReportItem; txtbox.Paragraphs[0].TextRuns[0].Value = table.Columns[i].ToString(); } The modified report definition can be converted as stream or saved into a local file using the XmlSerializer’s Deserialize method. C# string nameSpace = "http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition"; if (reportDefinition.RDLType == Syncfusion.RDL.DOM.RDLType.RDL2010) { nameSpace = "http://schemas.microsoft.com/sqlserver/reporting/2010/01/reportdefinition"; } System.Xml.Serialization.XmlSerializerNamespaces serialize = new System.Xml.Serialization.XmlSerializerNamespaces(); serialize.Add("rd", "http://schemas.microsoft.com/SQLServer/reporting/reportdesigner"); XmlSerializer xs2 = new XmlSerializer(typeof(Syncfusion.RDL.DOM.ReportDefinition), nameSpace); MemoryStream memoryStream = new MemoryStream(); TextWriter ws2 = new StreamWriter(memoryStream); xs2.Serialize(ws2, reportDefinition, serialize); memoryStream.Position = 0; Samples WPF JavaScript
You can perform the serverside validation using actionBegin event of ejGrid. The following code example shows how to perform server side validation in Grid. Render the Grid control. JS MVC ASP.NET In actionBegin event, you have passed the edited records value to server side using AJAX post and perform the server side validation. MVC ASP.NET You can check duplicate values that are existing in the list and returned the Boolean values. And, in AJAX success if the return value is false (Doesn’t have duplicate), we have saved the records to Grid by calling the endEdit method. If the value has duplicate, we have shown the Error message to the dialog box. MVC ASP.NET The following output is displayed as a result of the above code example. Figure: ServerSide Validation in Grid
In certain cases, you may like to set the column edit type as multi select dropdown with checkboxes in ASP.NET MVC DataGrid. You can achieve this by using the EditTemplate property of the Grid columns. The EditTemplate property is used to display a custom editor (any other control) for a column. In the following code example, a Grid is rendered with the batch editing enabled. Render the grid. MVC @(Html.EJ().Grid<object>("Grid") .Datasource(((IEnumerable<object>)ViewBag.dataSource)) .AllowPaging() .ToolbarSettings(toolbar => { toolbar.ShowToolbar().ToolbarItems(items => { items.AddTool(ToolBarItems.Add); items.AddTool(ToolBarItems.Edit); items.AddTool(ToolBarItems.Delete); items.AddTool(ToolBarItems.Update); items.AddTool(ToolBarItems.Cancel); }); }) .EditSettings(edit => edit.AllowEditing().AllowAdding().AllowDeleting()) .Columns(col => { col.Field("CustomerID").HeaderText("Customer ID").IsPrimaryKey(true).TextAlign(TextAlign.Right).Add(); col.Field("CustomerName").HeaderText("Customer Name").Add(); col.Field("OrderID").HeaderText("Order ID").Add(); col.Field("OrderList").HeaderText("Order List").EditTemplate(a => { a.Create("create").Read("read").Write("write"); }).Add(); }) ) [Controller] public ActionResult Index() { List<OrderData> order = new List<OrderData>(); List<string> list = new List<string>(); list.Add("Cream"); list.Add("Milk"); list.Add("Eggs"); list.Add("Butter"); list.Add("Curd"); list.Add("yogurt"); List<string> list1 = new List<string>(); list1.Add("Cream"); list1.Add("Eggs"); list1.Add("Curd"); List<string> list2 = new List<string>(); list2.Add("Cream"); list2.Add("Milk"); list2.Add("Butter"); list2.Add("yogurt"); var ordID = 100; var cusID = 200; for (int i = 1; i < 9; i++) { order.Add(new OrderData(cusID + 1, "Sam", ordID + 2, list)); order.Add(new OrderData(cusID + 2, "Mercy", ordID + 4, list1)); order.Add(new OrderData(cusID + 3, "Jim", ordID + 1, list)); order.Add(new OrderData(cusID + 4, "Dev", ordID + 5, list2)); order.Add(new OrderData(cusID + 5, "Jessi", ordID + 7, list1)); order.Add(new OrderData(cusID + 6, "Cath", ordID + 3, list2)); ordID += 1; cusID += 6; } ViewBag.dataSource = order; var drop = list.ToList(); var dropData = new List<object>(); foreach (var li in drop) { dropData.Add(new { value = li, text = li }); } ViewData["data"] = dropData; return View(); } } In the create event of the editTemplate, the input element for the column is created. In the write event of the editTemplate, the input text box created is converted to the ejDropDownList control with multi select option enabled. The DataSource to the ejDropDownList control is obtained from the server side in the text value format and assigned to the control. In the read event of the edittemplate, the selected values are obtained and saved accordingly in the Grid. JAVASCRIPT <script type="text/javascript"> var dropData = @Html.Raw(Json.Encode(ViewData["data"])) function create(args) { return "<input>"; } function read(args) { return args.ejDropDownList("getValue").split(","); } function write(args) { var selIndex = []; if (args.rowdata != undefined) { for (i = 0; i < args.rowdata["OrderList"].length; i++) for (j = 0; j < dropData.length; j++){ if (args.rowdata["OrderList"][i] == dropData[j].value) { selIndex.push(j); break; } } } args.element.ejDropDownList({ width: "100%", dataSource: dropData, fields: { id: "text", text: "text", value: "value" }, showCheckbox: true, allowMultiSelection: true, selectedItems: args.rowdata !== undefined ? selIndex : "" }); } </script> The following screenshots displays the multi select dropdown as edit type for a column: Figure 1: Initial Rendering Figure 2: On editing a record Figure 3: On saving the edited record ConclusionI hope you enjoyed learning about how to set multiselect dropdown in ASP.NET MVC DataGrid.You can refer to our ASP.NET MVC Grid feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our ASP.NET MVC DataGrid example to understand how to create and manipulate data.For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!
You can set the validation rules to a column by using the Validation Rules property of the column in ASP.NET MVC Grid. In certain cases, to set validation to a column based on another column value that is, to set conditional validation to a column, refer to the following solution. Solution Consider a Grid with a checkbox column and based on the value of the checkbox, another column is to be enabled or disabled and accordingly the validation is also to be set for that column. Example To achieve the above requirement in Grid, refer to the following steps. Code for Template Edit form. HTML <script type="text/template" id="template"> <b>Order Details</b> <table cellspacing="10"> <tr> <td style="text-align: right;"> Order ID </td> <td style="text-align: left"> <input id="OrderID" name="OrderID" value="{{: OrderID}}" disabled="disabled" class="e-field e-ejinputtext valid e-disable" style="text-align: right; width: 116px; height: 28px" /> </td> <td style="text-align: right;"> Customer ID </td> <td style="text-align: left"> <input id="CustomerID" name="CustomerID" value="{{: CustomerID}}" class="e-field e-ejinputtext valid" style="width: 116px; height: 28px" /> </td> </tr> <tr> <td style="text-align: right;"> Freight </td> <td style="text-align: left"> <input type="text" id="Freight" name="Freight" value="{{:Freight}}" style="text-align: right;" /> </td> <td style="text-align: right;"> Ship Country </td> <td style="text-align: left"> <select id="ShipCountry" name="ShipCountry"> <option value="Argentina">Argentina</option> <option value="Austria">Austria</option> <option value="Belgium">Belgium</option> <option value="Brazil">Brazil</option> <option value="Canada">Canada</option> <option value="Denmark">Denmark</option> <option value="Finland">Finland</option> <option value="France">France</option> <option value="Germany">Germany</option> <option value="Ireland">Ireland</option> <option value="Italy">Italy</option> <option value="Mexico">Mexico</option> <option value="Norway">Norway</option> <option value="Poland">Poland</option> <option value="Portugal">Portugal</option> <option value="Spain">Spain</option> <option value="Sweden">Sweden</option> <option value="Switzerland">Switzerland</option> <option value="UK">UK</option> <option value="USA">USA</option> <option value="Venezuela">Venezuela</option> </select> </td> </tr> <tr> <td style="text-align: right;"> Ship City </td> <td style="text-align: left"> <input id="ShipCity" name="ShipCity" value="{{: ShipCity}}" class="e-field e-ejinputtext valid" style="width: 116px; height: 28px" /> </td> <td style="text-align: right;"> Verified </td> <td style="text-align: left"> <input id="Verified" name="Verified" value="{{:Verified}}" type="checkbox" /> </td> </tr> </table> </script> Render the Grid control JS <div id="Grid"></div> <script type="text/javascript"> $(function () {// Document is ready. $("#Grid").ejGrid({ // the datasource "window.gridData" is referred from jsondata.min.js dataSource: window.gridData, allowPaging: true, editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, editMode: ej.Grid.EditMode.DialogTemplate, dialogEditorTemplateID: "#template" }, toolbarSettings: { showToolbar: true, toolbarItems: [ej.Grid.ToolBarItems.Add, ej.Grid.ToolBarItems.Edit, ej.Grid.ToolBarItems.Delete, ej.Grid.ToolBarItems.Update, ej.Grid.ToolBarItems.Cancel] }, columns: [ { field: "OrderID", headerText: "Order ID", isPrimaryKey: true, width: 100 }, { field: "CustomerID", headerText: "Customer ID", width: 130 }, { field: "Freight", headerText: "Freight", width: 100, format: "{0:C}" }, { field: "ShipCity", headerText: "Ship City", width: 100, validationRules: { required: true}, visible: false }, { field: "ShipCountry", headerText: "Ship Country", width: 100, }, { field: "Verified", width: 100, visible: false }//checkbox column ], actionComplete: "complete", }); }); </script> MVC [In View] @(Html.EJ().Grid<object>("Grid") .Datasource((IEnumerable<object>)ViewBag.data) .AllowPaging() .EditSettings(edit => edit.AllowEditing().AllowAdding().AllowDeleting().EditMode(EditMode.DialogTemplate).DialogEditorTemplateID("#template")) .ToolbarSettings(toolbar => { toolbar.ShowToolbar().ToolbarItems(items => { items.AddTool(ToolBarItems.Add); items.AddTool(ToolBarItems.Edit); items.AddTool(ToolBarItems.Delete); items.AddTool(ToolBarItems.Update); items.AddTool(ToolBarItems.Cancel); }); }) .Columns(col => { col.Field("OrderID").HeaderText("OrderID").IsPrimaryKey(true).TextAlign(TextAlign.Right).Width(100).Add(); col.Field("CustomerID").HeaderText("Customer ID").Width(100).Add(); col.Field("Freight").Width(100).Format("{0:c2}").Add(); col.Field("ShipCity").HeaderText("Ship City").Width(100).ValidationRules(v => v.AddRule("required", true)).Visible(false).Add(); col.Field("ShipCountry").HeaderText("Ship Country").Width(100).Add(); col.Field("Verified").Width(100).Visible(false).Add(); }) .ClientSideEvents(eve=>eve.ActionComplete("complete")) ) [In controller] namespace EJGrid.Controllers { public class HomeController : Controller { public ActionResult Index() { var DataSource = OrderRepository.GetAllRecords(); ViewBag.data = DataSource; return View(); } } } ASP.NET [ASPX] <ej:Grid ID="OrdersGrid" runat="server" AllowPaging="True" > <ClientSideEvents ActionComplete="complete" /> <EditSettings AllowEditing="True" AllowAdding="True" AllowDeleting="True" EditMode="DialogTemplate" DialogEditorTemplateID="#template"></EditSettings> <ToolbarSettings ShowToolbar="True" ToolbarItems="add,edit,delete,update,cancel"></ToolbarSettings> <Columns> <ej:Column Field="OrderID" HeaderText="Order ID" IsPrimaryKey="True" /> <ej:Column Field="CustomerID" HeaderText="Customer ID" /> <ej:Column Field="Freight" HeaderText="Freight" Format="{0:C}" /> <ej:Column Field="ShipCity" HeaderText="Ship City" Visible=false> <ValidationRule> <ej:KeyValue Key="required" Value="true" /> </ValidationRule> </ej:Column> <ej:Column Field="ShipCountry" HeaderText="Ship Country" /> <ej:Column Field="Verified" Visible=false />//checkbox column </Columns> </ej:Grid> [CS] public partial class _Default : Page { List<Orders> order = new List<Orders>(); protected void Page_Load(object sender, EventArgs e) { this.OrdersGrid.DataSource = new NorthwindDataContext().Orders; this.OrdersGrid.DataBind(); } } In the actionComplete events of the Grid, the textbox corresponding to the ShipCity label is disabled based on the value of the checkbox. JS function complete(args) { if ((args.requestType == "beginedit" || args.requestType == "add")) { $("#Freight").ejNumericTextbox({ value: parseFloat($("#Freight").val()), width: "116px", height: "28px", decimalPlaces: 2 }); $("#Freight").css({ 'text-align': 'left' }); if (args.requestType == "add") { $("#Verified").attr("checked", true); if ($("#Verified").is(":checked") != true) {//To disable the ShipCity textbox based on checkbox value $("#ShipCity").attr("disabled", "disabled"); } } $("#ShipCountry").ejDropDownList({ width: '116px' }); if (args.requestType == "beginedit") { $("#OrderID").attr("disabled", "disabled"); $("#ShipCountry").ejDropDownList("setSelectedValue", args.row.children().eq(4).text()); $("#Verified").attr("checked", args.model.currentViewData[args.rowIndex].Verified); if (args.model.currentViewData[args.rowIndex].Verified != true) { $("#ShipCity").attr("disabled", "disabled");//To disable the ShipCity textbox based on checkbox value } } } } In the change event of the checkbox, when the checkbox state is changed, the error messages are hidden. JS $(function (c) { $(document).on("change", "#Verified", function (c) { if (c.target.checked != true) { $("#ShipCity").attr("disabled", "disabled"); $(".e-error").css("display", "none");//to hide the error message when the checkbox state is changed } else $("#ShipCity").removeAttr("disabled"); }); }); ConclusionI hope you enjoyed learning about how to set validation for a column based on another column value in ASP.NET MVC Grid.You can refer to our ASP.NET MVC Grid feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our ASP.NET MVC Grid example to understand how to create and manipulate data.For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!
Normally, the AutomationPeer support of WPF Components holds some memory and it needs to be released manually. This can be done by using the following steps. Create a class derived from WindowAutomationPeer and override it's GetChildrenCore method and returns “null” value that clears the AutomationPeer item from memory as follows. C# public class FakeWindowsPeer : WindowAutomationPeer { public FakeWindowsPeer(Window window) : base(window) { } protected override List<AutomationPeer> GetChildrenCore() { return null; } } Now override the OnCreateAutomationPeer of the window and it returns the class as follows. C# public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } protected override AutomationPeer OnCreateAutomationPeer() { return new FakeWindowsPeer(this); } } Note:This will disable automation peers.ConclusionI hope you enjoyed learning about how release the memory held by AutomationPeer in WPF Components.You can refer to our WPF feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!
Setting the IsEditable property The default value of the IsEditable property is True. You can edit the particular TreeViewItemAdv by double-clicking the item. You can restrict the Edit mode of TreeViewItemAdv by setting the IsEditable property as False. XAML C#