VIBlend
Home Products Downloads Purchase Support Forum About Blog

Format DataGridView Cells

by viblend 7. June 2012 17:32
In this post, we will demonstrate you how to format the Cells in the VIBlend DataGridView for WinForms.

To achieve this, follow these steps:  

1.Create a new instance of the vDataGridView via drag and drop from the toolbox or create it programmatically.  
2.Bind the DataGrid to the Northwind Invoices table( Nwind.mdb is included in the download of the VIBlend Controls for WinForms package).  
 
C#

NwindDataSetTableAdapters.InvoicesTableAdapter adapter = new DataBindingAndEditors.NwindDataSetTableAdapters.InvoicesTableAdapter();
adapter.Fill(nwindDataSet1.Invoices);

DataTable tbl = this.nwindDataSet1.Invoices;

vDataGridView1.BoundFields.Clear();
vDataGridView1.BoundPivotColumns.Clear();
vDataGridView1.BoundPivotRows.Clear();
vDataGridView1.BoundPivotValues.Clear();
vDataGridView1.DataSource = null;

for (int i = 0; i < tbl.Columns.Count; i++)
{
    DataColumn col = tbl.Columns[i];
    BoundField boundField = new BoundField(col.Caption, col.ColumnName);
    vDataGridView1.BoundFields.Add(boundField);
}

vDataGridView1.DataSource = tbl;

vDataGridView1.ColumnsHierarchy.AutoResize();
vDataGridView1.RowsHierarchy.AutoResize();
vDataGridView1.Refresh();

VB .NET

Dim adapter As NwindDataSetTableAdapters.InvoicesTableAdapter = New DataBindingAndEditors.NwindDataSetTableAdapters.InvoicesTableAdapter()
adapter.Fill(nwindDataSet1.Invoices)

Dim tbl As DataTable = Me.nwindDataSet1.Invoices

vDataGridView1.BoundFields.Clear()
vDataGridView1.BoundPivotColumns.Clear()
vDataGridView1.BoundPivotRows.Clear()
vDataGridView1.BoundPivotValues.Clear()
vDataGridView1.DataSource = Nothing

Dim i As Integer = 0

Do While i < tbl.Columns.Count
    Dim col As DataColumn = tbl.Columns(i)
    Dim boundField As BoundField = New BoundField(col.Caption, col.ColumnName)
    vDataGridView1.BoundFields.Add(boundField)
    i += 1
Loop

vDataGridView1.DataSource = tbl

vDataGridView1.ColumnsHierarchy.AutoResize()
vDataGridView1.RowsHierarchy.AutoResize()
vDataGridView1.Refresh()

3. Set a custom format string to an entire grid column. 
 
C#

int columnIndex = this.nwindDataSet1.Invoices.Columns.IndexOf(this.nwindDataSet1.Invoices.RequiredDateColumn);
vDataGridView1.ColumnsHierarchy.Items[columnIndex].CellsFormatString = "{0:yyyy/MMMM/dd}";

VB .NET 

Dim columnIndex As Integer = Me.nwindDataSet1.Invoices.Columns.IndexOf(Me.nwindDataSet1.Invoices.RequiredDateColumn)
vDataGridView1.ColumnsHierarchy.Items(columnIndex).CellsFormatString = "{0:yyyy/MMMM/dd}"

 

WinForms DataGridView Search Functionality

by viblend 7. May 2012 00:50

In the latest version of VIBlend Controls for WinForms, we added a new utility control called vDataGridViewSeachHeader.
This small control adds a Search Functionality to the DataGridView and allows the users to easily find a record in a large data set. The post will show you how to associate this control to an instance of the vDataGridView control.

- Drag and drop a new instance of the vDataGridViewSearchHeader.
- Drag and drop a new instance of the vDataGridView.
- Set the DataGridView property of the vDataGridViewSearchHeader to point to your vDataGridView instance.

Here are the DataGridView and its Search Header at design-time.



In the code behind, bind the Grid to a DataTable. In the post, we will use a sample data.

C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VIBlend.WinForms.DataGridView;

namespace WindowsFormsApplication6
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            DataTable table = new DataTable();
            for (int i = 0; i < 100; i++)
            {
                table.Columns.Add("Column " + i);
            }

            for (int i = 0; i < 100; i++)
            {
                string[] values = new string[100];
                for (int j = 0; j < 100; j++)
                {
                    values[j] = "Cell " + i + "." + j;
                }
                table.Rows.Add(values);
            }
            this.vDataGridView1.DataSource = table;
            this.vDataGridView1.ColumnsHierarchy.AutoResize();

        }
    }
}

 
VB .NET

Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Linq
Imports System.Text
Imports System.Windows.Forms
Imports VIBlend.WinForms.DataGridView

Namespace WindowsFormsApplication6
    Partial Public Class Form1
        Inherits Form
        Public Sub New()
            InitializeComponent()

            Dim table As New DataTable()
            For i As Integer = 0 To 99
                table.Columns.Add("Column " & i)
            Next i

            For i As Integer = 0 To 99
                Dim values(99) As String
                For j As Integer = 0 To 99
                    values(j) = "Cell " & i + AscW("." )+ j
                Next j
                table.Rows.Add(values)
            Next i
            Me.vDataGridView1.DataSource = table
            Me.vDataGridView1.ColumnsHierarchy.AutoResize()

        End Sub
    End Class
End Namespace

Here's the result:


Creating Rows and Columns Hierarchies in Unbound Mode

by viblend 3. April 2012 16:46

In this post, we will show you how to create rows and column hierarchies in unbound mode and fill the DataGrid cells with data. In order the add Columns in unbound mode, you should use the DataGrid.ColumnsHierarchy.Items.Add method. To add rows in unbound mode, use the DataGrid.RowsHierarchy.Items.Add method. The 'Add' method returns a HierarchyItem object. This allows you to add sub-items to the HierarchyItem because it has Items.Add method, too.

The code below creates a 2-level Rows Hierarchy and can be used with the VIBlend DataGrid control for Silverlight, WPF and Windows Forms. 

C#

this.DataGrid.RowsHierarchy.CompactStyleRenderingEnabled = false;
for (int i = 0; i < 10; i++)
{
    HierarchyItem row = this.DataGrid.RowsHierarchy.Items.Add("Row" + i);
    HierarchyItem column = this.DataGrid.ColumnsHierarchy.Items.Add("Column" + i);

    for (int j = 0; j < 3; j++)
    {
        HierarchyItem subRow = row.Items.Add("Row" + i + "." + j);
    }
}
  
VB .NET

Me.DataGrid.RowsHierarchy.CompactStyleRenderingEnabled = False
For i As Integer = 0 To 9
    Dim row As HierarchyItem = Me.DataGrid.RowsHierarchy.Items.Add("Row" & i)
    Dim column As HierarchyItem = Me.DataGrid.ColumnsHierarchy.Items.Add("Column" & i)

    For j As Integer = 0 To 2
        Dim subRow As HierarchyItem = row.Items.Add("Row" & i + AscW("." )+ j)
    Next j
Next i

To Fill the DataGrid with data in unbound mode, you should use the DataGrid.CellsArea.SetCellValue method. The method accepts three parameteres - row, column and the cell value.

C#

for (int i = 0; i < 10; i++)
{
    HierarchyItem row = this.DataGrid.RowsHierarchy.Items[i];
    for (int j = 0; j < 10; j++)
    {
        HierarchyItem column = this.DataGrid.ColumnsHierarchy.Items[j];
        this.DataGrid.CellsArea.SetCellValue(row, column, "Cell" + i + "." + j);
        for (int p = 0; p < 3; p++)
        {
            this.DataGrid.CellsArea.SetCellValue(row.Items[p], column, "Cell" + p + "." + j);             
        }
    }
}
       
this.DataGrid.RowsHierarchy.ExpandAllItems();
this.DataGrid.ColumnsHierarchy.ExpandAllItems();
this.DataGrid.RowsHierarchy.AutoResize(AutoResizeMode.FIT_ALL);
this.DataGrid.ColumnsHierarchy.AutoResize(AutoResizeMode.FIT_ALL);
  
VB .NET

For i As Integer = 0 To 9
    Dim row As HierarchyItem = Me.DataGrid.RowsHierarchy.Items(i)
    For j As Integer = 0 To 9
        Dim column As HierarchyItem = Me.DataGrid.ColumnsHierarchy.Items(j)
        Me.DataGrid.CellsArea.SetCellValue(row, column, "Cell" & i + AscW("." )+ j)
        For p As Integer = 0 To 2
            Me.DataGrid.CellsArea.SetCellValue(row.Items(p), column, "Cell" & p + AscW("." )+ j)
        Next p
    Next j
Next i

Me.DataGrid.RowsHierarchy.ExpandAllItems()
Me.DataGrid.ColumnsHierarchy.ExpandAllItems()
Me.DataGrid.RowsHierarchy.AutoResize(AutoResizeMode.FIT_ALL)
Me.DataGrid.ColumnsHierarchy.AutoResize(AutoResizeMode.FIT_ALL)

Bind the VIBlend DataGridView for WinForms to SQL Database

by viblend 16. March 2012 00:01

This blog post will show you how to bind the WinForms DataGridView to the Customer table of the AdventureWorksLT Database.

To achieve this, follow these steps:  

1. Create a new instance of the vDataGridView via drag and drop from the toolbox or create it programmatically.  

2. Create a new AdventureWorksLTDataSet. In order to create it, do the following: Select Data->Add New DataSource->DataBase->DataSet. Add a connection to the AdventureWorksLT Database and Click the 'Next' button. Then expand the 'Tables' tree node, select Customer and click the 'Finish' button.

Note: The AdventureWorksLT Database is installed with the installation of the SQL Server. However, you can also download and install it from http://sqlserversamples.codeplex.com  

 

3. Create a new instance of the AdventureWorksLTDataSet data set. Then create a new CustomerTableAdapter and fill the Customer table with data. Finally, bind the VIBlend DataGrid for WinForms to the Customer table. 

C#

AdventureWorksLTDataSet dataSet = new AdventureWorksLTDataSet();
AdventureWorksLTDataSetTableAdapters.CustomerTableAdapter adapter = new AdventureWorksLTDataSetTableAdapters.CustomerTableAdapter();
adapter.Fill(dataSet.Customer);
this.vDataGridView1.VIBlendTheme = VIBlend.Utilities.VIBLEND_THEME.OFFICE2010BLUE;
this.vDataGridView1.DataSource = dataSet.Customer;
this.vDataGridView1.ColumnsHierarchy.AutoResize();

VB .NET

Dim dataSet As New AdventureWorksLTDataSet()
Dim adapter As New AdventureWorksLTDataSetTableAdapters.CustomerTableAdapter()
adapter.Fill(dataSet.Customer)
Me.vDataGridView1.VIBlendTheme = VIBlend.Utilities.VIBLEND_THEME.OFFICE2010BLUE
Me.vDataGridView1.DataSource = dataSet.Customer
Me.vDataGridView1.ColumnsHierarchy.AutoResize()

 

What's coming with VIBlend WinForms Controls 9.0

by viblend 3. March 2012 21:20
In the next version of VIBlend, we will enhance the vDataGridView control by adding a new Search capabilities to it. Users will be able to choose a search criteria and easily find a Row in the Grid. This new feature can be turned on by drag and drop of a vDataGridViewSearchHeader control and setting its DataGridView property to point to your vDataGridView instance.
 
  

Display a DataGridView in a Popup

by Admin 13. January 2012 22:48

In this post we will show you how to display the WinForms GridView in a Popup control. We will also use the new Metro Blue theme.

1. The first step is to drag and drop a new instance of the VIBlend DataGridView and the ControlBox control.
The ControlBox control is a control similar to the WinForms ComboBox, but it can display any content in its Popup.

2. The next step is to initialize the Grid. We will add 5 rows and 5 columns and will populate it in unbound mode. The first column will display images in the grid cells. The rest columns will be traditional text columns.

- Create the Grid Rows and Columns:

C#

for (int i = 0; i < 5; i++)
{
    Grid1.RowsHierarchy.Items.Add(i.ToString());
    Grid1.ColumnsHierarchy.Items.Add("Column " + i);
}

VB .NET

For i As Integer = 0 To 4
    Grid1.RowsHierarchy.Items.Add(i.ToString())
    Grid1.ColumnsHierarchy.Items.Add("Column " & i)
Next i

Fill the first grid column with images. In order to display an image in a grid cell, you need to do two things - set the cell's display settings to DisplaySettings.ImageOnly and call the SetCellImage method passing the cell's row, column and image index parameters.

C#

Grid1.ImageList = imageList1;
HierarchyItem columnImage = Grid1.ColumnsHierarchy.Items[0];

for (int i = 0; i < Grid1.RowsHierarchy.Items.Count; i++)
{
    HierarchyItem rowItem = Grid1.RowsHierarchy.Items[i];
    Grid1.CellsArea.SetCellDisplaySettings(rowItem, columnImage, DisplaySettings.ImageOnly);
    Grid1.CellsArea.SetCellImage(rowItem, columnImage, i);
}

VB .NET
 
Grid1.ImageList = imageList1
Dim columnImage As HierarchyItem = Grid1.ColumnsHierarchy.Items(0)

For i As Integer = 0 To Grid1.RowsHierarchy.Items.Count - 1
    Dim rowItem As HierarchyItem = Grid1.RowsHierarchy.Items(i)
    Grid1.CellsArea.SetCellDisplaySettings(rowItem, columnImage, DisplaySettings.ImageOnly)
    Grid1.CellsArea.SetCellImage(rowItem, columnImage, i)
Next i

Fill the rest of the columns by using the SetCellValue method.

C#

Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items[0], Grid1.ColumnsHierarchy.Items[1], "Porsche Boxster");
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items[1], Grid1.ColumnsHierarchy.Items[1], "Acura TL");
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items[2], Grid1.ColumnsHierarchy.Items[1], "Audi A4");
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items[3], Grid1.ColumnsHierarchy.Items[1], "BMW 645Ci");
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items[4], Grid1.ColumnsHierarchy.Items[1], "BMW 760Li");

Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items[0], Grid1.ColumnsHierarchy.Items[2], true);
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items[1], Grid1.ColumnsHierarchy.Items[2], true);
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items[2], Grid1.ColumnsHierarchy.Items[2], true);
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items[3], Grid1.ColumnsHierarchy.Items[2], true);
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items[4], Grid1.ColumnsHierarchy.Items[2], true);

Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items[0], Grid1.ColumnsHierarchy.Items[3], "4 years");
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items[1], Grid1.ColumnsHierarchy.Items[3], "4 years");
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items[2], Grid1.ColumnsHierarchy.Items[3], "4 years");
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items[3], Grid1.ColumnsHierarchy.Items[3], "4 years");
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items[4], Grid1.ColumnsHierarchy.Items[3], "4 years");

Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items[0], Grid1.ColumnsHierarchy.Items[4], "www.porsche.com");
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items[1], Grid1.ColumnsHierarchy.Items[4], "www.acura.com");
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items[2], Grid1.ColumnsHierarchy.Items[4], "www.audi.com");
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items[3], Grid1.ColumnsHierarchy.Items[4], "www.bmw.com");
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items[4], Grid1.ColumnsHierarchy.Items[4], "www.bmw.com");

VB .NET

Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items(0), Grid1.ColumnsHierarchy.Items(1), "Porsche Boxster")
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items(1), Grid1.ColumnsHierarchy.Items(1), "Acura TL")
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items(2), Grid1.ColumnsHierarchy.Items(1), "Audi A4")
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items(3), Grid1.ColumnsHierarchy.Items(1), "BMW 645Ci")
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items(4), Grid1.ColumnsHierarchy.Items(1), "BMW 760Li")

Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items(0), Grid1.ColumnsHierarchy.Items(2), True)
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items(1), Grid1.ColumnsHierarchy.Items(2), True)
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items(2), Grid1.ColumnsHierarchy.Items(2), True)
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items(3), Grid1.ColumnsHierarchy.Items(2), True)
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items(4), Grid1.ColumnsHierarchy.Items(2), True)

Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items(0), Grid1.ColumnsHierarchy.Items(3), "4 years")
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items(1), Grid1.ColumnsHierarchy.Items(3), "4 years")
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items(2), Grid1.ColumnsHierarchy.Items(3), "4 years")
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items(3), Grid1.ColumnsHierarchy.Items(3), "4 years")
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items(4), Grid1.ColumnsHierarchy.Items(3), "4 years")

Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items(0), Grid1.ColumnsHierarchy.Items(4), "www.porsche.com")
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items(1), Grid1.ColumnsHierarchy.Items(4), "www.acura.com")
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items(2), Grid1.ColumnsHierarchy.Items(4), "www.audi.com")
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items(3), Grid1.ColumnsHierarchy.Items(4), "www.bmw.com")
Grid1.CellsArea.SetCellValue(Grid1.RowsHierarchy.Items(4), Grid1.ColumnsHierarchy.Items(4), "www.bmw.com")

3. In order to display the Grid in the ControlBox's Popup,  you need to set the ControlBox's ContentControl property to point to the Grid instance.

C#

this.vControlBox.ContentControl = this.Grid1;

VB .NET

Me.vControlBox.ContentControl = Me.Grid1

 

WinForms Grid with Merged Cells

by viblend 4. January 2012 01:06
In this post, we will show you how to use the cells merge functionality of VIBlend DataGridView for WinForms.

The first step is to add the DataGridView to your Form. You can do this by drag and drop from the Visual Studio toolbox or you can create it in the code behind.

C#

private vDataGridView grid = new vDataGridView();

public Form1()
{
    InitializeComponent();
    grid.Dock = DockStyle.Fill;
    grid.VIBlendTheme = VIBLEND_THEME.NERO;
    this.Controls.Add(grid);
    this.LoadData();
    this.MergeCells();
    this.SetCellsValues();
}

VB .NET

Private grid As New vDataGridView()

Public Sub New()
    InitializeComponent()
    grid.Dock = DockStyle.Fill
    grid.VIBlendTheme = VIBLEND_THEME.NERO
    Me.Controls.Add(grid)
    Me.LoadData()
    Me.MergeCells()
    Me.SetCellsValues()
End Sub

Now, we need to implement the LoadData, MergeCells and SetCellValues methods. The LoadData method will add rows and columns to the DataGridView.

C#

private void LoadData()
{
    // add columns.
    for (int i = 1; i <= 8; i++)
    {
        grid.ColumnsHierarchy.Items.Add("Column " + i);
    }
    // add rows.
    for (int i = 1; i <= 25; i++)
    {
        grid.RowsHierarchy.Items.Add("Row " + i);
    }

    grid.RowsHierarchy.AutoResize();
    grid.ColumnsHierarchy.AutoResize();
    grid.Refresh();
}

VB .NET

Private Sub LoadData()
    ' add columns.
    For i As Integer = 1 To 8
        grid.ColumnsHierarchy.Items.Add("Column " & i)
    Next i
    ' add rows.
    For i As Integer = 1 To 25
        grid.RowsHierarchy.Items.Add("Row " & i)
    Next i

    grid.RowsHierarchy.AutoResize()
    grid.ColumnsHierarchy.AutoResize()
    grid.Refresh()
End Sub

To add rows and columns we use the Add method of the DataGridView's Rows and Columns hierarchies.

The SetCellValues method will simply insert values in the Grid cells. This will be achieved by using the SetCellValue method which accepts three parameters - row, column and cell value.

C#

private void SetCellsValues()
{
    HierarchyItem rowItem1 = grid.RowsHierarchy.Items[0];
    HierarchyItem columnItem1 = grid.ColumnsHierarchy.Items[0];

    grid.CellsArea.SetCellValue(rowItem1, columnItem1, "Monthly Housing and Transportation Expenses");
    grid.CellsArea.SetCellValue(grid.RowsHierarchy.Items[1], columnItem1, "Primary residence");
    grid.CellsArea.SetCellValue(grid.RowsHierarchy.Items[1], this.grid.ColumnsHierarchy.Items[3], "Transportation Expenses");
    // fill data

    grid.CellsArea.SetCellValue(this.grid.RowsHierarchy.Items[2], columnItem1, "Mortgage Payment");
    grid.CellsArea.SetCellValue(this.grid.RowsHierarchy.Items[3], columnItem1, "Property Tax");
    grid.CellsArea.SetCellValue(this.grid.RowsHierarchy.Items[4], columnItem1, "Insurance");
    grid.CellsArea.SetCellValue(this.grid.RowsHierarchy.Items[5], columnItem1, "Electricity");
    grid.CellsArea.SetCellValue(this.grid.RowsHierarchy.Items[6], columnItem1, "Water");
    grid.CellsArea.SetCellValue(this.grid.RowsHierarchy.Items[7], columnItem1, "Cabel TV Service");
    grid.CellsArea.SetCellValue(this.grid.RowsHierarchy.Items[8], columnItem1, "High Speed Internet");

    // fill second column data.
    HierarchyItem columnItem2 = this.grid.ColumnsHierarchy.Items[1];
    grid.CellsArea.SetCellValue(this.grid.RowsHierarchy.Items[2], columnItem2, "$1,459,76");
    grid.CellsArea.SetCellValue(this.grid.RowsHierarchy.Items[3], columnItem2, "$212.54");
    grid.CellsArea.SetCellValue(this.grid.RowsHierarchy.Items[4], columnItem2, "$49.21");
    grid.CellsArea.SetCellValue(this.grid.RowsHierarchy.Items[5], columnItem2, "$73.44");
    grid.CellsArea.SetCellValue(this.grid.RowsHierarchy.Items[6], columnItem2, "$41.48");
    grid.CellsArea.SetCellValue(this.grid.RowsHierarchy.Items[7], columnItem2, "$22.14");
    grid.CellsArea.SetCellValue(this.grid.RowsHierarchy.Items[8], columnItem2, "$24.99");

    // fill third column data.

    HierarchyItem columnItem3 = this.grid.ColumnsHierarchy.Items[3];
    grid.CellsArea.SetCellValue(this.grid.RowsHierarchy.Items[2], columnItem3, "Vehicle 1 Payment");
    grid.CellsArea.SetCellValue(this.grid.RowsHierarchy.Items[3], columnItem3, "Vehicle 1 Insurance");
    grid.CellsArea.SetCellValue(this.grid.RowsHierarchy.Items[4], columnItem3, "Vehicle 1 Gas");
    grid.CellsArea.SetCellValue(this.grid.RowsHierarchy.Items[5], columnItem3, "Vehicle 1 Maintenance");
    grid.CellsArea.SetCellValue(this.grid.RowsHierarchy.Items[6], columnItem3, "Vehicle 2 Lease");
    grid.CellsArea.SetCellValue(this.grid.RowsHierarchy.Items[7], columnItem3, "Vehicle 2 Insurance");
    grid.CellsArea.SetCellValue(this.grid.RowsHierarchy.Items[8], columnItem3, "Vehicle 2 Gas");
    grid.CellsArea.SetCellValue(this.grid.RowsHierarchy.Items[9], columnItem3, "Vehicle 2 Maintenance");

    // fiil fourth column data.
    HierarchyItem columnItem4 = this.grid.ColumnsHierarchy.Items[4];
    grid.CellsArea.SetCellValue(this.grid.RowsHierarchy.Items[2], columnItem4, "$351,34");
    grid.CellsArea.SetCellValue(this.grid.RowsHierarchy.Items[3], columnItem4, "$55.12");
    grid.CellsArea.SetCellValue(this.grid.RowsHierarchy.Items[4], columnItem4, "$129.21");
    grid.CellsArea.SetCellValue(this.grid.RowsHierarchy.Items[5], columnItem4, "$55.17");
    grid.CellsArea.SetCellValue(this.grid.RowsHierarchy.Items[6], columnItem4, "$311.12");
    grid.CellsArea.SetCellValue(this.grid.RowsHierarchy.Items[7], columnItem4, "$109.35");
    grid.CellsArea.SetCellValue(this.grid.RowsHierarchy.Items[8], columnItem4, "$114.99");
    grid.CellsArea.SetCellValue(this.grid.RowsHierarchy.Items[9], columnItem4, "$35.19");
}

VB .NET

Private Sub SetCellsValues()
    Dim rowItem1 As HierarchyItem = grid.RowsHierarchy.Items(0)
    Dim columnItem1 As HierarchyItem = grid.ColumnsHierarchy.Items(0)

    grid.CellsArea.SetCellValue(rowItem1, columnItem1, "Monthly Housing and Transportation Expenses")
    grid.CellsArea.SetCellValue(grid.RowsHierarchy.Items(1), columnItem1, "Primary residence")
    grid.CellsArea.SetCellValue(grid.RowsHierarchy.Items(1), Me.grid.ColumnsHierarchy.Items(3), "Transportation Expenses")
    ' fill data

    grid.CellsArea.SetCellValue(Me.grid.RowsHierarchy.Items(2), columnItem1, "Mortgage Payment")
    grid.CellsArea.SetCellValue(Me.grid.RowsHierarchy.Items(3), columnItem1, "Property Tax")
    grid.CellsArea.SetCellValue(Me.grid.RowsHierarchy.Items(4), columnItem1, "Insurance")
    grid.CellsArea.SetCellValue(Me.grid.RowsHierarchy.Items(5), columnItem1, "Electricity")
    grid.CellsArea.SetCellValue(Me.grid.RowsHierarchy.Items(6), columnItem1, "Water")
    grid.CellsArea.SetCellValue(Me.grid.RowsHierarchy.Items(7), columnItem1, "Cabel TV Service")
    grid.CellsArea.SetCellValue(Me.grid.RowsHierarchy.Items(8), columnItem1, "High Speed Internet")

    ' fill second column data.
    Dim columnItem2 As HierarchyItem = Me.grid.ColumnsHierarchy.Items(1)
    grid.CellsArea.SetCellValue(Me.grid.RowsHierarchy.Items(2), columnItem2, "$1,459,76")
    grid.CellsArea.SetCellValue(Me.grid.RowsHierarchy.Items(3), columnItem2, "$212.54")
    grid.CellsArea.SetCellValue(Me.grid.RowsHierarchy.Items(4), columnItem2, "$49.21")
    grid.CellsArea.SetCellValue(Me.grid.RowsHierarchy.Items(5), columnItem2, "$73.44")
    grid.CellsArea.SetCellValue(Me.grid.RowsHierarchy.Items(6), columnItem2, "$41.48")
    grid.CellsArea.SetCellValue(Me.grid.RowsHierarchy.Items(7), columnItem2, "$22.14")
    grid.CellsArea.SetCellValue(Me.grid.RowsHierarchy.Items(8), columnItem2, "$24.99")

    ' fill third column data.

    Dim columnItem3 As HierarchyItem = Me.grid.ColumnsHierarchy.Items(3)
    grid.CellsArea.SetCellValue(Me.grid.RowsHierarchy.Items(2), columnItem3, "Vehicle 1 Payment")
    grid.CellsArea.SetCellValue(Me.grid.RowsHierarchy.Items(3), columnItem3, "Vehicle 1 Insurance")
    grid.CellsArea.SetCellValue(Me.grid.RowsHierarchy.Items(4), columnItem3, "Vehicle 1 Gas")
    grid.CellsArea.SetCellValue(Me.grid.RowsHierarchy.Items(5), columnItem3, "Vehicle 1 Maintenance")
    grid.CellsArea.SetCellValue(Me.grid.RowsHierarchy.Items(6), columnItem3, "Vehicle 2 Lease")
    grid.CellsArea.SetCellValue(Me.grid.RowsHierarchy.Items(7), columnItem3, "Vehicle 2 Insurance")
    grid.CellsArea.SetCellValue(Me.grid.RowsHierarchy.Items(8), columnItem3, "Vehicle 2 Gas")
    grid.CellsArea.SetCellValue(Me.grid.RowsHierarchy.Items(9), columnItem3, "Vehicle 2 Maintenance")

    ' fiil fourth column data.
    Dim columnItem4 As HierarchyItem = Me.grid.ColumnsHierarchy.Items(4)
    grid.CellsArea.SetCellValue(Me.grid.RowsHierarchy.Items(2), columnItem4, "$351,34")
    grid.CellsArea.SetCellValue(Me.grid.RowsHierarchy.Items(3), columnItem4, "$55.12")
    grid.CellsArea.SetCellValue(Me.grid.RowsHierarchy.Items(4), columnItem4, "$129.21")
    grid.CellsArea.SetCellValue(Me.grid.RowsHierarchy.Items(5), columnItem4, "$55.17")
    grid.CellsArea.SetCellValue(Me.grid.RowsHierarchy.Items(6), columnItem4, "$311.12")
    grid.CellsArea.SetCellValue(Me.grid.RowsHierarchy.Items(7), columnItem4, "$109.35")
    grid.CellsArea.SetCellValue(Me.grid.RowsHierarchy.Items(8), columnItem4, "$114.99")
    grid.CellsArea.SetCellValue(Me.grid.RowsHierarchy.Items(9), columnItem4, "$35.19")
    columnItem3.Width = 150
    columnItem1.Width = 150
    grid.Refresh()
End Sub

The MergeCells method will lllustrate how to merge grid cells by using the SetCellSpan method. When you use the SetCellSpan method, you need to pass four parameters to it - row, column, rows span and columns span. In the method we will merge cells in the first and second rows and we will also set custom visual style to the merged cells.

C#

private void MergeCells()
{
    HierarchyItem rowItem1 = grid.RowsHierarchy.Items[0];
    HierarchyItem columnItem1 = grid.ColumnsHierarchy.Items[0];

    // create a custom cell style.
    GridCellStyle style = new GridCellStyle();
    style.FillStyle = new FillStyleSolid(Color.FromArgb(255, 0, 175, 240));
    style.Font = new Font(this.Font.FontFamily, 11.0f, FontStyle.Bold);
    style.TextColor = Color.White;

    GridCellStyle orangestyle = new GridCellStyle();
    orangestyle.FillStyle = new FillStyleSolid(Color.FromArgb(255, 254, 122, 1));
    orangestyle.Font = new Font(this.Font.FontFamily, 10.0f, FontStyle.Bold);
    orangestyle.TextColor = Color.White;

    grid.CellsArea.SetCellTextAlignment(rowItem1, columnItem1, ContentAlignment.MiddleCenter);
    // set the cell span to 1 row and 5 columns.
    grid.CellsArea.SetCellSpan(rowItem1, columnItem1, 1, 5);
    // set the merged cell value and style.
    grid.CellsArea.SetCellDrawStyle(rowItem1, columnItem1, style);
    // set the cell span to 1 row and 2 columns.
    grid.CellsArea.SetCellSpan(grid.RowsHierarchy.Items[1], columnItem1, 1, 3);
    grid.CellsArea.SetCellDrawStyle(grid.RowsHierarchy.Items[1], columnItem1, orangestyle);
    // set the merged cell value.
    // set the cell span to 1 row and 2 columns.
    grid.CellsArea.SetCellSpan(grid.RowsHierarchy.Items[1], this.grid.ColumnsHierarchy.Items[3], 1, 2);
    // set the merged cell value.
    grid.CellsArea.SetCellDrawStyle(grid.RowsHierarchy.Items[1], this.grid.ColumnsHierarchy.Items[3], orangestyle);
}

VB .NET

Private Sub MergeCells()
    Dim rowItem1 As HierarchyItem = grid.RowsHierarchy.Items(0)
    Dim columnItem1 As HierarchyItem = grid.ColumnsHierarchy.Items(0)

    ' create a custom cell style.
    Dim style As New GridCellStyle()
    style.FillStyle = New FillStyleSolid(Color.FromArgb(255, 0, 175, 240))
    style.Font = New Font(Me.Font.FontFamily, 11.0f, FontStyle.Bold)
    style.TextColor = Color.White

    Dim orangestyle As New GridCellStyle()
    orangestyle.FillStyle = New FillStyleSolid(Color.FromArgb(255, 254, 122, 1))
    orangestyle.Font = New Font(Me.Font.FontFamily, 10.0f, FontStyle.Bold)
    orangestyle.TextColor = Color.White

    grid.CellsArea.SetCellTextAlignment(rowItem1, columnItem1, ContentAlignment.MiddleCenter)
    ' set the cell span to 1 row and 5 columns.
    grid.CellsArea.SetCellSpan(rowItem1, columnItem1, 1, 5)
    ' set the merged cell value and style.
    grid.CellsArea.SetCellDrawStyle(rowItem1, columnItem1, style)
    ' set the cell span to 1 row and 2 columns.
    grid.CellsArea.SetCellSpan(grid.RowsHierarchy.Items(1), columnItem1, 1, 3)
    grid.CellsArea.SetCellDrawStyle(grid.RowsHierarchy.Items(1), columnItem1, orangestyle)
    ' set the merged cell value.
    ' set the cell span to 1 row and 2 columns.
    grid.CellsArea.SetCellSpan(grid.RowsHierarchy.Items(1), Me.grid.ColumnsHierarchy.Items(3), 1, 2)
    ' set the merged cell value.
    grid.CellsArea.SetCellDrawStyle(grid.RowsHierarchy.Items(1), Me.grid.ColumnsHierarchy.Items(3), orangestyle)
End Sub

Sort WinForms DataGridView Rows and Columns by Label

by Admin 15. October 2011 21:16

VIBlend WinForms DataGridView has a built-in feature which allows you to set a custom Sort comparer. In this post, we will show you how to sort the DataGridView rows or columns by label.
At first, we will create a Comparer which compares HierarchyItem objects by the HierarchyItem.Caption property.

C#

private class ItemLabelComparer : IComparer<HierarchyItem>
{
    public int Compare(HierarchyItem item1, HierarchyItem item2)
    {
        return string.Compare(item1.Caption, item2.Caption);
    }
}

VB .NET

Private Class ItemLabelComparer
    Implements IComparer(Of HierarchyItem)
    Public Function Compare(ByVal item1 As HierarchyItem, ByVal item2 As HierarchyItem) As Integer
        Return String.Compare(item1.Caption, item2.Caption)
    End Function
End Class

Create an instance of the ItemLabelComparer object and pass it to the RowsHierarchy.SortBy method. If you want to sort the ColumnsHierarchy, call the ColumnsHierarchy.SortBy method.

C#

ItemLabelComparer Comparer = new ItemLabelComparer();
 this.vDataGridView1.RowsHierarchy.SortBy(this.vDataGridView1.ColumnsHierarchy.Items[0], sorting, Comparer);
this.Refresh();

VB .NET

Dim Comparer As New ItemLabelComparer()
 Me.vDataGridView1.RowsHierarchy.SortBy(Me.vDataGridView1.ColumnsHierarchy.Items(0), sorting, Comparer)
Me.Refresh()

Silverlight DataGrid – Custom Sorting using SortDescription

by viblend 8. April 2011 19:15

This post will show you how to override the built-in sorting functionality and sort the DataGrid data using the SortDescription class. The data content is sorted when a user clicks a column header.

1. The following example defines a DataGrid with six columns that bind to the Name, Date, Product, Quantity, UnitPrice and SalesAmount properties of the EmployeeSaleRecord class.

     <viblendDataGrid:DataGrid AutoGenerateColumns="True" Height="200" VerticalAlignment="Center" Name="dataGrid" Width="350">
            <viblendDataGrid:DataGrid.BoundFields>               
                <viblendDataGrid:BoundField Text="Name" DataField="Name" Width="160"  CellStyle="{StaticResource textCentered}"/>
                <viblendDataGrid:BoundField Text="Date" DataField="Date" Width="140" />
                <viblendDataGrid:BoundField Text="Product" DataField="Product" Width="140"  CellStyle="{StaticResource textCentered}"/>
                <viblendDataGrid:BoundField Text="Quantity" DataField="Quantity" Width="90"  CellStyle="{StaticResource textCentered}"/>
                <viblendDataGrid:BoundField Text="Unit Price" DataField="UnitPrice" Width="74"/>
                <viblendDataGrid:BoundField Text="Sales Amount" DataField="SalesAmount" Width="88"/>
            </viblendDataGrid:DataGrid.BoundFields>
        </viblendDataGrid:DataGrid>


2. Create column header templates with up and down arrow elements that will be displayed when the grid data is sorted.

    <UserControl.Resources>
        <Style x:Name="textCentered" TargetType="viblendDataGrid:GridCellElement">
            <Setter Property="HorizontalContentAlignment" Value="Center" />
            <Setter Property="VerticalContentAlignment" Value="Center" />
        </Style>

        <DataTemplate x:Key="SortAscendingTemplate">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"></ColumnDefinition>
                    <ColumnDefinition Width="Auto"></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <TextBlock Text="{Binding}"></TextBlock>
                <Path Grid.Column="1" x:Name="sortAscElement" Height="5" Width="9" Stretch="Fill" Stroke="#FFFFFFFF" Data="M4.5,5 L0,0 L9,0 z" RenderTransformOrigin="0.0,0.0">
                    <Path.Fill>
                        <LinearGradientBrush EndPoint="-0.237,0.525" StartPoint="0.679,0.525">
                            <GradientStop Color="#55FFFFFF"/>
                            <GradientStop Color="#55FFFFFF" Offset="0.991"/>
                        </LinearGradientBrush>
                    </Path.Fill>
                </Path>
            </Grid>
        </DataTemplate>
        <DataTemplate x:Key="SortDescendingTemplate">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"></ColumnDefinition>
                    <ColumnDefinition Width="Auto"></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <TextBlock Text="{Binding}"></TextBlock>
                <Path Grid.Column="1" x:Name="sortDescElement" Height="5" Width="9" Stretch="Fill" Stroke="#FFFFFFFF" Data="M4.5,0 L9,5 L0,5 z" RenderTransformOrigin="0.0,0.0" >
                    <Path.Fill>
                        <LinearGradientBrush EndPoint="-0.237,0.525" StartPoint="0.679,0.525">
                            <GradientStop Color="#55FFFFFF"/>
                            <GradientStop Color="#55FFFFFF" Offset="0.991"/>
                        </LinearGradientBrush>
                    </Path.Fill>
                </Path>
            </Grid>
        </DataTemplate>
    </UserControl.Resources>


3. Create  CollectionViewSource, HierarchyItem and bool? fields in the code behind.
4. Bind the DataGrid to a List of EmployeeSaleRecord objects. Set the selection mode to row selection and hide the row headers.

    C#

    // Bind DataGrid
    dataGrid.ItemsSource = listSaleRecord;
    dataGrid.SelectionMode = DataGrid.SELECTION_MODE.FULL_ROW_SELECT;
    dataGrid.RowsHierarchy.Visible = false; 

     VB .NET
    ' Bind DataGrid
    dataGrid.ItemsSource = listSaleRecord
    dataGrid.SelectionMode = DataGrid.SELECTION_MODE.FULL_ROW_SELECT
    dataGrid.RowsHierarchy.Visible = False

5. To sort the data according to the contents of a column, the example defines an event handler to handle the HierarchyItemMouseClick event that occurs when you press the column header.  In the event handler, toggle the sorting order and set the DataTemplate property of the HierarchyItem object depending on the sort order. Call the Sort method and  set the DataGrid.ItemsSource property to point to the view. Doing this, the DataGrid will be refreshed and sorted.
      

       C#
       // Subscribe to HierarchyItemMouseClick event.
      dataGrid.HierarchyItemMouseClick += new DataGrid.HierarchyItemMouseButtonEventHandler(dataGrid_HierarchyItemMouseClick);

      void dataGrid_HierarchyItemMouseClick(object sender, HierarchyItemMouseButtonEventArgs args)
        {
            if (clickedItem != null && !args.HierarchyItem.BoundField.DataField.Equals(clickedItem.BoundField.DataField))
            {
                clickedItem.BoundField.DataTemplate = null;
                ascending = null;
            }

            clickedItem = args.HierarchyItem;
            clickedItem.BoundField.DataContext = clickedItem.BoundField.DataField;

            // Load the column's DataTemplate
            if (ascending == null)
            {
                ascending = true;
                clickedItem.BoundField.DataTemplate = this.Resources["SortDescendingTemplate"] as DataTemplate;
            }
            else if (ascending.HasValue && !ascending.Value)
            {
                ascending = null;
                clickedItem.BoundField.DataTemplate = null;
            }
            else if (ascending.HasValue && ascending.Value)
            {
                ascending = false;
                clickedItem.BoundField.DataTemplate = this.Resources["SortAscendingTemplate"] as DataTemplate;
            }

            if (ascending == null)
            {
                dataGrid.ItemsSource = listSaleRecord;
            }
            else
            {
                SortDescription sortDescription = new SortDescription(args.HierarchyItem.BoundField.DataField, ascending == true ? ListSortDirection.Ascending : ListSortDirection.Descending);
                ICollectionView view = Sort(sortDescription, args.HierarchyItem.BoundField.DataField, this.listSaleRecord);
                dataGrid.ItemsSource = view;
            }
        }

      VB .NET

      ' Subscribe to HierarchyItemMouseClick event.
      Private dataGrid.HierarchyItemMouseClick += New DataGrid.HierarchyItemMouseButtonEventHandler(AddressOf dataGrid_HierarchyItemMouseClick)

      Private Sub dataGrid_HierarchyItemMouseClick(ByVal sender As Object, ByVal args As HierarchyItemMouseButtonEventArgs)
            If clickedItem IsNot Nothing AndAlso (Not args.HierarchyItem.BoundField.DataField.Equals(clickedItem.BoundField.DataField)) Then
                clickedItem.BoundField.DataTemplate = Nothing
                ascending = Nothing
            End If

            clickedItem = args.HierarchyItem
            clickedItem.BoundField.DataContext = clickedItem.BoundField.DataField

            ' Load the column's DataTemplate
            If ascending Is Nothing Then
                ascending = True
                clickedItem.BoundField.DataTemplate = TryCast(Me.Resources("SortDescendingTemplate"), DataTemplate)
            ElseIf ascending.HasValue AndAlso (Not ascending.Value) Then
                ascending = Nothing
                clickedItem.BoundField.DataTemplate = Nothing
            ElseIf ascending.HasValue AndAlso ascending.Value Then
                ascending = False
                clickedItem.BoundField.DataTemplate = TryCast(Me.Resources("SortAscendingTemplate"), DataTemplate)
            End If

            If ascending Is Nothing Then
                dataGrid.ItemsSource = listSaleRecord
            Else
                Dim sortDescription As New SortDescription(args.HierarchyItem.BoundField.DataField,If(ascending = True, ListSortDirection.Ascending, ListSortDirection.Descending))
                Dim view As ICollectionView = Sort(sortDescription, args.HierarchyItem.BoundField.DataField, Me.listSaleRecord)
                dataGrid.ItemsSource = view
            End If
      End Sub

6. Implement the Sort method. Add the SortDescription instance to the CollectionViewSource and return the view which will be used as DataGrid items source.

      C#

       public virtual ICollectionView Sort(SortDescription sortDescription, string columnName, System.Collections.IEnumerable itemsSource)
        {
            if (sortDescription == null)
                return null;

            string displayMember = columnName;

            if (String.IsNullOrEmpty(displayMember))
            {
                displayMember = "";
            }

            viewSource.SortDescriptions.Clear();
            if (itemsSource != null)
            {
                if (itemsSource as ICollectionView != null)
                {
                    viewSource.Source = (itemsSource as ICollectionView).SourceCollection;
                }
                else
                {
                    viewSource.Source = itemsSource;
                }

                viewSource.SortDescriptions.Add(sortDescription);
                return viewSource.View;
            }

            return null;
        }

     VB .NET

     Public Overridable Function Sort(ByVal sortDescription As SortDescription, ByVal columnName As String, ByVal itemsSource As System.Collections.IEnumerable) As ICollectionView
            If sortDescription Is Nothing Then
                Return Nothing
            End If

            Dim displayMember As String = columnName

            If String.IsNullOrEmpty(displayMember) Then
                displayMember = ""
            End If

            viewSource.SortDescriptions.Clear()
            If itemsSource IsNot Nothing Then
                If TryCast(itemsSource, ICollectionView) IsNot Nothing Then
                    viewSource.Source = (TryCast(itemsSource, ICollectionView)).SourceCollection
                Else
                    viewSource.Source = itemsSource
                End If

                viewSource.SortDescriptions.Add(sortDescription)
                Return viewSource.View
            End If

            Return Nothing
     End Function

 

Download demo project: DataGridCustomSortingDemo.zip

Improved filtering capabilities in the new VIBlend WPF DataGrid

by viblend 19. March 2011 22:47

The new release of VIBlend Controls for WPF is almost here and we wanted to share with you some additional details about it. One of the major changes in the new version will be the updated WPF
DataGrid
Filtering functionality. The DataGrid filtering window will be extended by providing an easier and user-friendly experience. The new filtering window will show a checked list box, allowing for single
and/or multiple selections. The previous filtering mechanism will still be available and you will be able to switch to it by clicking a single button. The Grouping Panel which is already available in our WinForms
and Silverlight grid controls is coming to the WPF DataGrid, too. This new feature allows you to drag a column header to the panel above the grid to group the data. You can also programmatically group data
by using intuitive API. Data can be grouped by single or multiple columns at the same time. It is needless to say that the API of our WPF and Silverlight Data Grid controls will still be fully compatible.

 

About the author

Some text that describes me

Tag cloud

Recent comments

Comment RSS
Copyright © 2011 VIBlend  
ALL RIGHTS RESERVED  
 
Terms of Use | Privacy Policy
WinForms Controls Purchase Online About Us
       
DataGrid Navigation Pane Technical Support Blog
ScrollBar TreeView
ListBox ProgressBar Downloads Register
ComboBox Buttons
TabControl Editors Documentation Client Login

VIBlend Blog is powered by BlogEngine.NET