In this blog post we will show you how to use the VIBlend DataGridView for WinForms in a WPF application.
The following code example creates a WinForms DataGrid control with Office2010Black theme in a WPF application. This example uses a WindowsFormsHost element to place the DataGrid control within the main window’s root element. The WindowsFormsHost element could be found in the WindowsFormsIntegration.dll.
[xaml]
<Window x:Class="HostWinFormsControlInWPF.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:viblend="clr-namespace:VIBlend.WinForms.DataGridView;assembly=VIBlendGrid" Title="Window1" Height="300" Width="300"> <Grid> <WindowsFormsHost> <viblend:vDataGridView x:Name="VIBlendDataGrid" VIBlendTheme="OFFICE2010BLACK"/> </WindowsFormsHost> </Grid> </Window>
In order to bind the data grid, you need to do the following: Click on the Data menu item in your Visual Studio, then select the “Add new DataSource” item. Browse to the Nwind.mdb which ships with the WinForms controls installation, choose the Employees table and click finish. In the code behind, after the InitializeComponent call or in the Load event handler , bind the data grid to the Employees table.
NwindDataSet dataSet = new NwindDataSet(); EmployeesTableAdapter adapter = new EmployeesTableAdapter(); adapter.Fill(dataSet.Employees); this.VIBlendDataGrid.DataSource = dataSet.Employees.DefaultView; this.VIBlendDataGrid.DataBind();
Here is the result:
Be the first to rate this post
Tags: viblend winforms controls, winforms datagrid, datagridview for winforms, wpf controls, wpf grid
DataGrid | GridView | olap grid | pivot grid | pivot, olap | winforms grid | WPF DataGrid
We are proud to announce the second major release of VIBlend Controls for Silverlight.
With the new release, VIBlend has officially included in the suite four new controls – OutlookPane, NavigationPane, DateTimePicker and ScrollablePanel. Not only we introduced new controls, but we also improved the quality and functionality of the existing ones and added over 10 new examples to show how our controls work.
The Menu and Context Menu controls from the toolset are now provided free of charge to all registered users.
See our Silverlight Controls Live Demo and Download a free trial today.
Tags: viblend silverlight controls, datagrid, treeview, outlookpane, navigationpane, menu, editors
DataGrid | GridView | Industry news | olap grid | pivot grid | pivot, olap | Silverlight | TreeView
VIBlend DataGridView for WinForms allows you to set the grid cells' source to Virtual mode. There are two steps to setup Virtual mode:
1. Set the cells' data source to Virtual. You can do that for a specific cell as well as for all cells under a row or a column:
vDataGridView1.CellsArea.SetCellDataSource(column, GridCellDataSource.Virtual);
2. Implement a GridCellValueNeeded event handler. Whenever the data grid renders a cell it will raise the GridCellValueNeeded event:
vDataGridView1.GridCellValueNeeded += new vDataGridView.GridCellValueNeededEventHandler(DataGridView1_GridCellValueNeeded);
void DataGridView1_GridCellValueNeeded(object sender, GridCellValueNeededEventArgs args)
{ args.Value = "Some text";
}
Here's a complete example which creates a list of 50,000 rows and sets up the grid in virtual mode:
using System; using System.Collections.Generic; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using VIBlend.WinForms.Controls; using VIBlend.WinForms.DataGridView; using VIBlend.Utilities; namespace VirtualModeDemo { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public class EmployeeSales { public EmployeeSales(string Name, DateTime Date, int ProductId, int Quantity) { this.Name = Name; this.Date = Date; this.ProductId = ProductId; this.Quantity = Quantity; } #region Private Members private string _name; private DateTime _date; private int _productid; private int _quantity; #endregion #region Properties public string Name { get { return _name; } set { _name = value; } } public DateTime Date { get { return _date; } set { _date = value; } } public string ProductName { get { return productNames[_productid, 0]; } } public double SalesAmount { get { return (double)_quantity * UnitPrice; } } public double UnitPrice { get { double unitPrice = double.Parse(productNames[_productid, 1]); return unitPrice; } } public int Quantity { get { return _quantity; } set { _quantity = value; } } public int ProductId { get { return _productid; } set { _productid = value; } } #endregion } // Implement the cell value needed event handler void DataGridView1_GridCellValueNeeded(object sender, GridCellValueNeededEventArgs args) { int rowIndex = int.Parse(args.RowItem.Caption) - 1; if (args.ColumnItem.Caption == "Employee Name") args.CellValue = lst[rowIndex].Name; else if (args.ColumnItem.Caption == "Transaction Date") args.CellValue = lst[rowIndex].Date; else if (args.ColumnItem.Caption == "Product Name") args.CellValue = lst[rowIndex].ProductName; else if (args.ColumnItem.Caption == "Quantity") args.CellValue = lst[rowIndex].Quantity; else if (args.ColumnItem.Caption == "Unit Price") args.CellValue = lst[rowIndex].UnitPrice; else if (args.ColumnItem.Caption == "Transaction Amount") args.CellValue = lst[rowIndex].SalesAmount; } #region Data string[] firstNames = new string[] { "Andrew", "Nancy", "Shelley", "Regina", "Yoshi", "Antoni", "Mayumi", "Ian", "Peter", "Lars", "Petra", "Martin", "Sven", "Elio", "Beate", "Cheryl", "Michael", "Guylène" }; string[] lastNames = new string[] { "Fuller", "Davolio", "Burke", "Murphy", "Nagase", "Saavedra", "Ohno", "Devling", "Wilson", "Peterson", "Winkler", "Bein", "Petersen", "Rossi", "Vileid", "Saylor", "Björn", "Nodier" }; static string[,] productNames = new string[,] { {"Black Tea", "1.95"}, {"Green Tea", "1.95"}, {"Caffe Espresso", "1.45"}, {"Doubleshot Espresso", "1.75"}, {"Caffe Latte", "2.25"}, {"White Chocolate Mocha", "2.35"}, {"Cramel Latte", "2.35"}, {"Caffe Americano", "1.65"}, {"Cappuccino", "2.10"}, {"Espresso Truffle", "2.45"}, {"Espresso con Panna", "1.81"}, {"Peppermint Mocha Twist", "1.99"} }; #endregion List<EmployeeSales> lst = new List<EmployeeSales>(); private void Form1_Load(object sender, EventArgs e) { vDataGridView1.RowsHierarchy.AllowResize = true; vDataGridView1.RowsHierarchy.AllowDragDrop = false; vDataGridView1.ColumnsHierarchy.AllowResize = true; vDataGridView1.ColumnsHierarchy.AllowDragDrop = false; vDataGridView1.SelectionMode = vDataGridView.SELECTION_MODE.FULL_ROW_SELECT; vDataGridView1.MultipleSelectionEnabled = true; vDataGridView1.GridCellValueNeeded += new vDataGridView.GridCellValueNeededEventHandler(DataGridView1_GridCellValueNeeded); const int rowsToLoad = 50000; // Generate test data Random rand = new Random(); for (int i = 0; i < rowsToLoad; i++) { int productId = rand.Next(0, productNames.Length / 2 - 1); int quantity = rand.Next(1, 5); lst.Add(new EmployeeSales( string.Format("{0} {1}", firstNames[rand.Next(0, firstNames.Length - 1)], lastNames[rand.Next(0, lastNames.Length - 1)]), DateTime.Now.AddDays(-rand.Next(10, 100)), productId, quantity) ); } BindGridVirtualMode(); } private void BindGridVirtualMode() { Cursor.Current = Cursors.WaitCursor; vDataGridView1.RowsHierarchy.Items.Clear(); vDataGridView1.RowsHierarchy.SummaryItems.Clear(); vDataGridView1.ColumnsHierarchy.Items.Clear(); vDataGridView1.ColumnsHierarchy.SummaryItems.Clear(); vDataGridView1.CellsArea.CellFormatting.ClearFormatProviders(); vDataGridView1.CellsArea.CellFormatting.ClearFormatSettings(); vDataGridView1.CellsArea.CellFormatting.SetFormatter("defaultNumberFormatter", null, "{0:#,###.####}"); #region Prepare the grid columns vDataGridView1.ColumnsHierarchy.Fixed = true; vDataGridView1.ColumnsHierarchy.Items.Add("Employee Name"); vDataGridView1.ColumnsHierarchy.Items.Add("Transaction Date"); vDataGridView1.ColumnsHierarchy.Items.Add("Product Name"); vDataGridView1.ColumnsHierarchy.Items.Add("Quantity"); vDataGridView1.ColumnsHierarchy.Items.Add("Unit Price"); vDataGridView1.ColumnsHierarchy.Items.Add("Transaction Amount"); // Set the cells data source to Virtual for all columns foreach (HierarchyItem column in vDataGridView1.ColumnsHierarchy.Items) vDataGridView1.CellsArea.SetCellDataSource(column, GridCellDataSource.Virtual); vDataGridView1.CellsArea.CellFormatting.ClearFormatProviders(); vDataGridView1.CellsArea.CellFormatting.ClearFormatSettings(); vDataGridView1.CellsArea.CellFormatting.SetFormatter("dateFormatter", new System.Globalization.DateTimeFormatInfo(), "{0:dd-MMM-yyyy}"); vDataGridView1.CellsArea.CellFormatting.SetFormatter("dollarFormatter", null, "${0:#.##}"); vDataGridView1.CellsArea.CellFormatting.SetCellFormatting(vDataGridView1.ColumnsHierarchy.Items[1], "dateFormatter"); vDataGridView1.CellsArea.CellFormatting.SetCellFormatting(vDataGridView1.ColumnsHierarchy.Items[4], "dollarFormatter"); vDataGridView1.CellsArea.CellFormatting.SetCellFormatting(vDataGridView1.ColumnsHierarchy.Items[5], "dollarFormatter"); vDataGridView1.ColumnsHierarchy.AutoResize(); #endregion #region Prepare the grid rows for (int i = 0; i < lst.Count; i++) vDataGridView1.RowsHierarchy.Items.Add((i + 1).ToString()); vDataGridView1.RowsHierarchy.SetColumnWidth(0, 30); vDataGridView1.RowsHierarchy.Fixed = true; #endregion vDataGridView1.Refresh(); Cursor.Current = Cursors.Default; } } }
Tags: data, grid, virtual, binding
GridView | winforms grid
We're frequently asked about the easiest way to bind the WinForms data grid control to a data source. When you install VIBlend WinForms Controls the setup installs a folder with several fully functional demo projects in VB.NET and C#. You can learn a lot by browsing through this code base.
In any case here's a very simple data binding example where we create a List of objects and use it as a data source:
C# Example:
using System; using System.Collections.Generic; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using VIBlend.WinForms.Controls; using VIBlend.WinForms.DataGridView; using VIBlend.Utilities; namespace DataBindingDemo { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { List<Employee> list = new List<Employee>(); for (int i = 0; i < 100; i++) list.Add(new Employee("Name " + i, "Title " + i, "Phone " + i, "CellPhone " + i, "Address " + i)); dataGrid.VIBlendTheme = VIBlend.Utilities.VIBLEND_THEME.OFFICEBLACK; dataGrid.BoundFields.Add(new BoundField("Employee Name", "Name")); dataGrid.BoundFields.Add(new BoundField("Employee Title", "Title")); dataGrid.BoundFields.Add(new BoundField("Employee Phone", "Phone")); dataGrid.BoundFields.Add(new BoundField("Employee Cell Phone", "CellPhone")); dataGrid.BoundFields.Add(new BoundField("Employee Address", "Address")); dataGrid.DataSource = list; dataGrid.DataBind(); dataGrid.RowsHierarchy.AutoResize(); dataGrid.ColumnsHierarchy.AutoResize(); dataGrid.Refresh(); } } class Employee { public Employee(string Name, string Title, string Phone, string CellPhone, string Address) { this.Name = Name; this.Title = Title; this.Phone = Phone; this.CellPhone = CellPhone; this.Address = Address; } #region Private Members private string _name; private string _title; private string _phone; private string _cellphone; private string _address; #endregion #region Properties public string Name { get { return _name; } set { _name = value; } } public string Title { get { return _title; } set { _title = value; } } public string Phone { get { return _phone; } set { _phone = value; } } public string CellPhone { get { return _cellphone; } set { _cellphone = value; } } public string Address { get { return _address; } set { _address = value; } } #endregion } }
VB.NET Example:
Imports System Imports System.Collections.Generic Imports System.Collections Imports System.ComponentModel Imports System.Data Imports System.Drawing Imports System.Text Imports System.Windows.Forms Imports VIBlend.WinForms.Controls Imports VIBlend.WinForms.DataGridView Imports VIBlend.Utilities Namespace DataBindingDemo Partial Public Class Form1 Inherits Form Public Sub New() InitializeComponent() End Sub Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Dim list As New List(Of Employee)() For i As Integer = 0 To 99 list.Add(New Employee("Name " & i, "Title " & i, "Phone " & i, "CellPhone " & i, "Address " & i)) Next i dataGrid.VIBlendTheme = VIBlend.Utilities.VIBLEND_THEME.OFFICEBLACK dataGrid.BoundFields.Add(New BoundField("Employee Name", "Name")) dataGrid.BoundFields.Add(New BoundField("Employee Title", "Title")) dataGrid.BoundFields.Add(New BoundField("Employee Phone", "Phone")) dataGrid.BoundFields.Add(New BoundField("Employee Cell Phone", "CellPhone")) dataGrid.BoundFields.Add(New BoundField("Employee Address", "Address")) dataGrid.DataSource = list dataGrid.DataBind() dataGrid.RowsHierarchy.AutoResize() dataGrid.ColumnsHierarchy.AutoResize() dataGrid.Refresh() End Sub End Class Friend Class Employee Public Sub New(ByVal Name As String, ByVal Title As String, ByVal Phone As String, ByVal CellPhone As String, ByVal Address As String) Me.Name = Name Me.Title = Title Me.Phone = Phone Me.CellPhone = CellPhone Me.Address = Address End Sub #Region "Private Members" Private _name As String Private _title As String Private _phone As String Private _cellphone As String Private _address As String #End Region #Region "Properties" Public Property Name() As String Get Return _name End Get Set(ByVal value As String) _name = value End Set End Property Public Property Title() As String Get Return _title End Get Set(ByVal value As String) _title = value End Set End Property Public Property Phone() As String Get Return _phone End Get Set(ByVal value As String) _phone = value End Set End Property Public Property CellPhone() As String Get Return _cellphone End Get Set(ByVal value As String) _cellphone = value End Set End Property Public Property Address() As String Get Return _address End Get Set(ByVal value As String) _address = value End Set End Property #End Region End Class End Namespace
Tags: datagrid, databinding, grid databinding
Formatting the value of a grid cell is one of the most common tasks when working with data grids. Most spreadsheet applications like Excel, provide a built-in list with the most common cell formats. These include format expressions for numbers, currencies, dates, hours, and more. In addition, the user can easily create a custom cell format expression. VIBlend DataGrid for WinForms, allows you to format the content a grid cell through a simple expression which follows the .NET string formatting rules. The value of a grid cell can be any object type, and it is up to you to specify how this value will be converted to text. Unless you associate the cell, or its column, with a format expression, the grid will try to get the text representation of the cell’s value by calling the ToString() method.
The code below formats all cells in the second column of the data grid as dollar values with two digits behind the decimal point:
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Create a pseudo-random number generator Random rand = new Random(); // Add two columns HierarchyItem column1 = vDataGridView1.ColumnsHierarchy.Items.Add("Unformatted Column"); HierarchyItem column2 = vDataGridView1.ColumnsHierarchy.Items.Add("Formatted Column"); // Add 10 rows for (int iRow = 0; iRow < 10; iRow++) { HierarchyItem row = vDataGridView1.RowsHierarchy.Items.Add(string.Format("Row {0}", iRow + 1)); // Generate a random number double value = rand.NextDouble() * 100.0f; // Set cell value at (currentRow;column1) and (currentRow;column2) to the random number vDataGridView1.CellsArea.SetCellValue(row, column1, value); vDataGridView1.CellsArea.SetCellValue(row, column2, value); // set the cell alignment to MiddleRight vDataGridView1.CellsArea.SetCellTextAlignment(row, column1, ContentAlignment.MiddleRight); vDataGridView1.CellsArea.SetCellTextAlignment(row, column2, ContentAlignment.MiddleRight); } // Create a named format expression vDataGridView1.CellsArea.CellFormatting.SetFormatter("format1", null, "${0:##.00}"); // Assign the format expression to all cells under the second grid column vDataGridView1.CellsArea.CellFormatting.SetCellFormatting(column2, "format1"); // Refresh the grid's content vDataGridView1.Refresh(); } }
In addition, VIBlend DataGridView allows you to use custom format providers to achive maximum flexibility.
Tags: datagrid, winforms, formatting, cell, grid cell
VIBlend SuperGridView ships with build-in data export providers for Microsoft Excel, XML, HTML and CSV.
The export functionality is accessible through the GridExport class inside VIBlend.SuperGridView.DataExport namespace.
Here's a a small example which demonstrates how easy it is to export the data grid's content:
VIBlend.SuperGrid.DataExport.GridExport gridExport = new VIBlend.SuperGrid.DataExport.GridExport();
gridExport.ExportToHTML(superGrid1, fileName); // export to HTML
gridExport.ExportToExcelXML(superGrid1, fileName); // export to MS Excel
gridExport.ExportToXML(superGrid1, fileName); // export to XML
gridExport.ExportToCSV(superGrid1, fileName); // export to CSV
Currently rated 5.0 by 1 people
Tags: grid, export
GridView
With the release of version 1.3, there's no doubt that SuperGridView has the most robust and flexible conditional formatting capabilities when compared to other .NET grid controls on the market. It also looks cool as you can see from the screenshot below.
Here's the simple question: How hard is it implement this?
Well, SuperGridView makes it very very easy. Let's go through the process.
In order, to apply conditional formatting with color scales we must define a group of cells and associate with a specific color scale. This normally takes three easy steps.
Step 1. Enable Conditional Formatting and Create the Conditional Formatting group
SuperGridView has a class which wraps this entire functionality. The class is defined within the DataFieldArea of the grid and it's name is ConditionalFormattingGroup. You can use it in the following way:
grid.DataFieldArea.ConditionalFormattingEnabled = true;
DataFieldArea.ConditionalFormattingGroup cfGroup = new DataFieldArea.ConditionalFormattingGroup();
cfGroup.SetConditionalFormattingColorScale(GridCellCFColorScale.GREEN_TO_RED);
The SetConditionalFormattingColorScale method allows you to select one of the built-in color scales. If you prefer to create your own you can use the SetCustomConditionalFormattingColorScale method which simply takes an array of one hundered colors which define the scale.
Step 2. Add the group to the grid's DataFieldArea and assign in a name
This is just a single line of code which basically says: "Hey, SuperGridView, this is my ConditionalFormattingGroup and for you this is its name"
grid.DataFieldArea.ConditionalFormattingGroups.Add("mygroup", cfGroup);
Step 3. Assign grid cells to the conditional formatting group
SuperGridView allows you to add individual cells to a group, as well as entire rows and columns. This is done by calling the methods SetCellConditionalFormattingGroup or SetItemConditionalFormattingGroup for individual cells and for columns/rows respectively.
grid.DataFieldArea.SetCellConditionalFormattingGroup(gridCell, "mygroup");
The following code will create a new conditional formatting group and fill it with a the selected cells:
private void buttonConditionalFormatSelectedCells_Click(object sender, EventArgs e) { grid.DataFieldArea.ConditionalFormattingGroups.Clear(); DataFieldArea.ConditionalFormattingGroup cfGroup = new DataFieldArea.ConditionalFormattingGroup(); cfGroup.SetConditionalFormattingColorScale(GridCellCFColorScale.GREEN_TO_RED);
Currently rated 4.0 by 5 people
Tags: grid conditional formatting
GridView | VIBlend SuperControls for WinForms
Pivot tables are one of the most powerful features of modern Spreadsheet applications like Microsoft Excel. They provide an easy way to group, aggregate and analyze data.
In database tables data is represented as records which consist of one or more columns. It is extremely easy to visualize such data via almost any data grid component on the market. However, the value which one can get from a list of records is somewhat limited especially when the number of rows is large. Pivot tables normally consist of Row, Column and Data (or Value) fields. They allow the user to select which columns from the original record set will form each of these three types of fields.
SuperGridView allows developer to bind to a database table, select which table columns will be used in the data binding, as well as which table columns will form the pivot table rows, columns and data (value) fields.
Let's start with a simple scenarios where we have a binding to a databse table. Below is an example of a data bound SuperGridView control which displays the records from the Invoices table of the Northwind database. The sample code uses a data adapter to fill a Dataset, creates a BoundField object for every table column and adds it to the BoundFields collection of SuperGridView. Finally, it sets the DataSource property of SuperGridView and performs the actual data binding.
NwindDataSet_InovicesTableAdapters.InvoicesTableAdapter adapter = new NwindDataSet_InovicesTableAdapters.InvoicesTableAdapter(); adapter.Fill(nwindDataSet_Inovices.Invoices); DataTable tbl = this.nwindDataSet_Inovices.Invoices;
NwindDataSet_InovicesTableAdapters.InvoicesTableAdapter adapter = new NwindDataSet_InovicesTableAdapters.InvoicesTableAdapter();
adapter.Fill(nwindDataSet_Inovices.Invoices);
DataTable tbl = this.nwindDataSet_Inovices.Invoices;
foreach (DataColumn col in tbl.Columns) { BoundField boundField = new BoundField(col.Caption, col.ColumnName); superGrid1.BoundFields.Add(boundField); }
foreach (DataColumn col in tbl.Columns) {
BoundField boundField = new BoundField(col.Caption, col.ColumnName); superGrid1.BoundFields.Add(boundField);
BoundField boundField = new BoundField(col.Caption, col.ColumnName);
superGrid1.BoundFields.Add(boundField);
superGrid1.DataSource = tbl.DefaultView; superGrid1.DataBind();
superGrid1.Refresh();
In this scenario SuperGridView will display all columns and all records from the Invoices table:
Now let’s use the same code and modify it to build a pivot table. In this example, we will create a pivot table which represents a Sales report. On Rows we will display the Cities grouped by Country, on Columns we will display the Shipping Company Name, and finally we’re interested to see the number of sales, the total dollar amount of the sales and the average sale amount as data fields. If it sounds complicated, the good news is that SuperGridView allows you to do that with just a few extra lines of code:
grid.BoundPivotRows.Add(new BoundField("Country", "Country"));
grid.BoundPivotRows.Add(new BoundField("City", "City")); grid.BoundPivotColumns.Add(new BoundField("Carrier", "Shippers_CompanyName"));
grid.BoundPivotValues.Add(new BoundValueField("Count of Sales", "ExtendedPrice", PivotFieldFunction.Count));
grid.BoundPivotValues.Add(new BoundValueField("Amount of Sales", "ExtendedPrice", PivotFieldFunction.Sum));
grid.BoundPivotValues.Add(new BoundValueField("Avg. Sale Amount", "ExtendedPrice", PivotFieldFunction.Average));
grid.PivotValuesOnRows = false;
foreach (DataColumn col in tbl.Columns) { BoundField boundField = new BoundField(col.Caption, col.ColumnName);
grid.BoundFields.Add(boundField); }
grid.DataSource = tbl.DefaultView; grid.DataMember = ""; grid.DataBind();
grid.RowsHierarchy.ExpandAllItems(); grid.ColumnsHierarchy.ExpandAllItems(); grid.ColumnsHierarchy.AutoResize(); grid.RowsHierarchy.AutoResize(); grid.Refresh();
And here is the result:
As you can see SuperGridView automatically builds hierarchies on rows and on columns and performs proper data aggregation to calculate the value of each cell. You can slightly modify this sample code and create almost any Pivot table.
We hope you will enjoy this cool feature of SuperGridView and most importantly its power, flexibility and simplicity.
Currently rated 4.0 by 6 people
Tags: pivot table, grid, data grid, winforms, hierarchial grid
None
VIBlend Blog is powered by BlogEngine.NET