Showing posts with label Windows Control. Show all posts
Showing posts with label Windows Control. Show all posts

Saturday, May 9, 2009

Set Screen Brightness/Contrast in C#

Stumble del.icio.us Reddit MyWeb! Facebook Google bookmark

I loaded Microsoft Windows Vista Business operating System on my old Toshiba Tecra A4 laptop and then realized that my Fn key is no longer working. The software and drivers that came with my laptop were not compatible with Vista. Alas, the one thing that I missed the most was setting up the brightness using Fn+F6 key. Usually when Windows starts, my LCD screen is just so bright that I have to adjust the brightness every time I start my laptop. Now, that leisure was gone. So I thought why not give it a try in C#. Found an API on MSDN and used it here in C# to make it work for me. It's not that great a program but a stupid slider to just reduce the Gamma component to give you a feeling that brightness is reduced. Actually the contrast is reduced. See the full code here. You can just copy and paste the full code in a Form class in a new Windows project and hit F5. If one of you is interested in just the executable, let me know via your comment here so I can send you the exe if you so desire.







1 // No copyrights (c). Use it as you wish!!

2

3 using System;

4 using System.Runtime.InteropServices;

5 using System.Windows.Forms;

6

7 namespace Yours.Truly

8 {

9 // *************************************************************************

10 /// <summary>

11 /// A form class to demnstrate the brightness adjustment for computer

12 /// monitors.

13 /// </summary>

14 /// <remarks>

15 /// <para>

16 /// It uses the Interop <see cref="SetDeviceGammaRamp"/> call to set the

17 /// Gamma component to adjust the screen contrast.

18 /// </para>

19 /// <para>

20 /// The <see cref="SetDeviceGammaRamp"/> function sets the gamma ramp on

21 /// direct color display boards having drivers that support downloadable

22 /// gamma ramps in hardware.

23 /// </para>

24 /// <para>

25 /// Direct color display modes do not use color lookup tables and are

26 /// usually 16, 24, or 32 bit. Not all direct color video boards support

27 /// loadable gamma ramps. SetDeviceGammaRamp succeeds only for devices with

28 /// drivers that support downloadable gamma ramps in hardware.

29 /// </para>

30 /// </remarks>

31 public class SetBrightness : Form

32 {

33 // *********************************************************************

34 /// <summary>

35 /// A structure of gamma corrections.

36 /// </summary>

37 [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]

38 private struct RAMP

39 {

40 [ MarshalAs(UnmanagedType.ByValArray, SizeConst=256)]

41 public UInt16[] Red;

42 [ MarshalAs(UnmanagedType.ByValArray, SizeConst=256)]

43 public UInt16[] Green;

44 [ MarshalAs(UnmanagedType.ByValArray, SizeConst=256)]

45 public UInt16[] Blue;

46 }

47

48 [DllImport("gdi32.dll")]

49 private static extern bool SetDeviceGammaRamp(IntPtr hDC, ref RAMP lpRamp);

50

51 [DllImport("user32.dll")]

52 static extern IntPtr GetDC(IntPtr hWnd);

53

54 /// <summary> Required designer variable.</summary>

55 private System.ComponentModel.IContainer components = null;

56 private TrackBar m_trackBar;

57

58 private static RAMP s_ramp = new RAMP();

59

60 // *********************************************************************

61 /// <summary>

62 /// Initializes a new instance of <see cref="SetBrightness"/> class.

63 /// </summary>

64 public SetBrightness ()

65 {

66 InitializeComponent();

67 }

68

69 // *********************************************************************

70 /// <summary>

71 /// Clean up any resources being used.

72 /// </summary>

73 /// <param name="disposing">true if managed resources should be

74 /// disposed; otherwise, false.</param>

75 protected override void Dispose (bool disposing)

76 {

77 if (disposing && (components != null))

78 {

79 components.Dispose();

80 }

81 base.Dispose(disposing);

82 }

83

84 // *********************************************************************

85 /// <summary>

86 /// Handles the <see cref="TrackBar.ValueChanged"/> event for the TrackBar

87 /// control. The value of the track bar control sets the Gamma value for

88 /// the device.

89 /// </summary>

90 /// <param name="sender">The object that initiated the event.</param>

91 /// <param name="e">An <see cref="EventArgs"/> object containing event

92 /// data</param>

93 private void HandleValueChanged (object sender, EventArgs e)

94 {

95 SetGamma(m_trackBar.Value);

96 }

97

98 // *********************************************************************

99 /// <summary>

100 /// Main entry point for the application.

101 /// </summary>

102 /// <param name="args">An array of optional arguments.</param>

103 static void Main (string[] args)

104 {

105 SetBrightness mainForm = new SetBrightness();

106 Application.Run(mainForm);

107 }

108

109 // *********************************************************************

110 /// <summary>

111 /// Sets the Gamma corection at the specified <paramref name="gamma"/>

112 /// value.

113 /// </summary>

114 /// <param name="gamma">New Gamma value to be set.</param>

115 private static void SetGamma(int gamma)

116 {

117 s_ramp.Red = new ushort[256];

118 s_ramp.Green = new ushort[256];

119 s_ramp.Blue = new ushort[256];

120

121 for( int i=1; i<256; i++ )

122 {

123 // gamma is a value between 3 and 44

124 s_ramp.Red[i] = s_ramp.Green[i] = s_ramp.Blue[i] =

125 (ushort)(Math.Min(65535,

126 Math.Max(0, Math.Pow((i+1) / 256.0, gamma*0.1) * 65535 + 0.5)));

127 }

128 // Now set the value.

129 SetDeviceGammaRamp(GetDC(IntPtr.Zero), ref s_ramp);

130 }

131

132 #region Windows Form Designer generated code

133

134 /// <summary>

135 /// Required method for Designer support - do not modify

136 /// the contents of this method with the code editor.

137 /// </summary>

138 private void InitializeComponent ()

139 {

140 this.m_trackBar = new System.Windows.Forms.TrackBar();

141 ((System.ComponentModel.ISupportInitialize)(this.m_trackBar)).BeginInit();

142 this.SuspendLayout();

143 //

144 // m_trackBar

145 //

146 this.m_trackBar.Dock = System.Windows.Forms.DockStyle.Fill;

147 this.m_trackBar.Location = new System.Drawing.Point(0,0);

148 this.m_trackBar.Maximum = 44;

149 this.m_trackBar.Minimum = 3;

150 this.m_trackBar.Name = "m_trackBar";

151 this.m_trackBar.RightToLeft = System.Windows.Forms.RightToLeft.Yes;

152 this.m_trackBar.RightToLeftLayout = true;

153 this.m_trackBar.Size = new System.Drawing.Size(277,42);

154 this.m_trackBar.TabIndex = 0;

155 this.m_trackBar.Value = 18;

156 this.m_trackBar.ValueChanged += new System.EventHandler(this.HandleValueChanged);

157 //

158 // SetBrightness

159 //

160 this.AutoScaleDimensions = new System.Drawing.SizeF(6F,13F);

161 this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;

162 this.ClientSize = new System.Drawing.Size(277,42);

163 this.Controls.Add(this.m_trackBar);

164 this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;

165 this.MaximizeBox = false;

166 this.MinimizeBox = false;

167 this.Name = "SetBrightness";

168 this.Opacity = 0.8;

169 this.ShowIcon = false;

170 this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;

171 this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;

172 this.Text = "SetBrightness";

173 this.TopMost = true;

174 ((System.ComponentModel.ISupportInitialize)(this.m_trackBar)).EndInit();

175 this.ResumeLayout(false);

176 this.PerformLayout();

177

178 }

179

180 #endregion

181

182 } // end class SetBrightness

183 } // end namespace Yours.Truly


Continue >>

Friday, March 13, 2009

C# MDI control with backcolor

Stumble del.icio.us Reddit MyWeb! Facebook Google bookmark

When designing an MDI form one comes across a limitation of having to accept the default gray background of the mdi control. Here is a way out :). MDI control is just like another windows control which has a default backcolor defined. One can change the backcolor if we handle the events properly. I have tried to demonstrate one such way in the OnLoad method of the form.

The code here is just a a small part of a form class with its IsMdiContainer property set to true.

You will need to add the following using directives so as to be able to run the code after placing it in your form class file.


using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;



And here goes the main code:



/// The brush used to paint the background.
private LinearGradientBrush m_bgndBrush;

// *********************************************************************
/// <summary>
/// Raises the System.Windows.Forms.Form.Load event
/// </summary>
/// <param name="e">An <see cref="System.EventArgs"/> that contains the
/// event data.</param>
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);

// Now set the background color for the mdi client
foreach (Control control in this.Controls)
{
if (control is MdiClient)
{
control.Paint += new PaintEventHandler(
this.PaintMdiClientBackground);
control.SizeChanged += new EventHandler(
this.ReSizeMdiClientBackground);
ControlEventHandler eh =
new ControlEventHandler(HandleMdiChildAddRemove);
control.ControlAdded += eh;
control.ControlRemoved += eh;
break;
}
}

} // end OnLoad


// *********************************************************************
/// <summary>
/// Paints the background of MdiClient.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">A <see cref="System.Windows.Forms.PaintEventArgs"/>
/// object that contains the event data.</param>
private void PaintMdiClientBackground(object sender, PaintEventArgs e)
{
// Check to see if the window is just being restored from
// minimised state.
if (this.Height <= 0 || this.Width <= 0) return; // Do not call the base.OnPaintBackground because it will just keep
// repainting the whole area since the backcolor is supposed to be
// transparent.
//base.OnPaintBackground(e);
m_bgndBrush = this.GetDisplayBgndBrush( m_bgndBrush, this.ClientRectangle);
e.Graphics.FillRectangle(m_bgndBrush, this.ClientRectangle); return; }
// end PaintMdiClientBackground

// *********************************************************************
/// <summary>
/// Paints the background of MdiClient.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">A <see cref="System.Windows.Forms.PaintEventArgs"/>
/// object that contains the event data.</param>
private void ReSizeMdiClientBackground(object sender, EventArgs e)
{
((MdiClient) sender).Invalidate();
}


// *********************************************************************
/// <summary>
/// Handles the <see cref="Control.ControlAdded"/> and
/// <see cref="Control.ControlRemoved"/>
/// events to enable or disable the windows mdilist menu item.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">An <see cref="EventArgs"/> object that contains
/// the event data.</param>
private void HandleMdiChildAddRemove(object sender, ControlEventArgs e)
{
// One could just show a Mdi window menu for example
//m_windowsMenu.Visible = this.MdiChildren.Length > 0;
}

//**********************************************************************
/// <summary>
/// Gets a brush used to paint the background area in the viewer's
/// middle (display) area.
/// </summary>
/// <remarks>
/// <para>This method optimizes creation of the brush by checking if
/// the brush's rectangle still matches <paramref name="rect"/>. If so,
/// the existing brush is returned. If they do not match or
/// <paramref name="brush"/> is <see langword="null"/>, a new brush
/// will be created and returned.</para>
/// </remarks>
/// <param name="brush">An existing brush previously returned by
/// this method or <see langword="null"/>.</param>
/// <param name="rect">The rectangular region that defines the starting
/// and ending points of the gradient.</param>
/// <returns>A <see cref="System.Drawing.Brush"/>.</returns>
/// <seealso cref="GetDisplayBgndBrush(Rectangle)"/>
/// <seealso cref="System.Drawing.Drawing2D.LinearGradientBrush"/>
private LinearGradientBrush GetDisplayBgndBrush
(
LinearGradientBrush brush,
Rectangle rect
)
{
if ((brush == null) ||
(brush.Rectangle.Width != (float) rect.Width) ||
(brush.Rectangle.Height != (float) rect.Height))
{
brush = this.GetDisplayBgndBrush(rect);
}
return (brush);
} // end GetDisplayBgndBrush (LinearGradientBrush, Rectangle)

//**********************************************************************
/// <summary>
/// Gets a brush used to paint the background area in the viewer's
/// middle (display) area.
/// </summary>
/// <remarks>
/// <para>This is a gradient brush whose primary use is to draw the
/// display area of the viewer window.</para>
/// </remarks>
/// <param name="rect">The rectangular region that defines the starting
/// and ending points of the gradient.</param>
/// <returns>A <see cref="System.Drawing.Brush"/>.</returns>
/// <seealso cref="GetDisplayBgndBrush(LinearGradientBrush,Rectangle)"/>
/// <seealso cref="System.Drawing.Drawing2D.LinearGradientBrush"/>
private GetDisplayBgndBrush(Rectangle rect)
{
LinearGradientBrush brush = new LinearGradientBrush(rect,
Color.FromArgb(33, 62, 153), // dark skyblue
Color.FromArgb(0, 172, 238), // light skyblue
90.0f, true);
brush.SetBlendTriangularShape(0.5f);
return (brush);
}


Now enjoy your colored mdicontrol. :)

Continue >>

Sortable Unbound DataGridView in C#

Stumble del.icio.us Reddit MyWeb! Facebook Google bookmark

I wrote a custom datagridview from some of my existing code. I had worked on some of my earlier projects and then every now and then I realised that the .Net datagridview has a lot of features but still it might be a good idea to have some more built in support. I truly believe that guys at Microsoft developed the current DataGridView perfectly the way they wanted covering most of the things. Still, if someone wants to customize the control, OOPs comes to rescue. So here it goes. This code implements generic sorting feature for bound (not required :) ) and unbound datagridview.


// Copyright © your's truly All rights reserved.

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms;

namespace Yours.Truly
{
//**************************************************************************
/// <summary>
/// Subclass of the <see cref="System.Windows.Forms.DataGridView"/> class.
/// </summary>
/// <remarks>
/// This class enhances the standard DataGridView control class by adding a
/// sort feature for unbound columns too :)
/// <para>$Id$</para>
/// <author>Yours truly</author>
/// </remarks>
public class CgDataGridView : DataGridView
{
private DataGridViewColumn m_sortedColumn;

//**********************************************************************
/// <summary>
/// Initializes a new instance of the <see cref="CgDataGridView"/>
/// class.
/// </summary>
/// <remarks>
/// The <see cref="System.Windows.Forms.DataGridView.ColumnHeadersDefaultCellStyle"/>
/// will be modified to have its
/// alignment set to <c>DataGridViewContentAlignment.MiddleCenter</c>.
/// </remarks>
public CgDataGridView()
{
// Set our unique default properties.
AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

// Alter the default column header cell style.
DataGridViewCellStyle hdrStyle = this.ColumnHeadersDefaultCellStyle;
hdrStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
}

//**********************************************************************
/// <summary>
/// Occurs when the state of a cell changes in relation to a change in
/// its contents.
/// </summary>
/// <remarks>
/// <para>If the current cell is dirty, this will commit the change. We
/// need to do this so other code can see the change immediately.
/// Normally, changes are only committed when focus leaves the cell.</para>
/// </remarks>
/// <param name="e">An <see cref="System.EventArgs"/> that contains
/// the event data.</param>
protected override void OnCurrentCellDirtyStateChanged(EventArgs e)
{
base.OnCurrentCellDirtyStateChanged(e);
if (this.IsDisposed || null == this) return;

// This method assumes that any editable cells are of a type that
// should be committed immediately. If other writable cell types
// (e.g., DataGridViewTextBoxColumn) are added to the DataGridView,
// code should be added below to handle that.
if (this.IsCurrentCellDirty)
{
this.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}

// *********************************************************************
/// <summary>
/// Changes the selection state of the row with the specified index.
/// </summary>
/// <param name="rowIndex">The index of the row.</param>
/// <param name="selected">true to select the row; false to cancel the
/// selection of the row.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="rowIndex"/> is less than 0 or greater than the
/// number of rows in the control.</exception>
public void SetSelectedRow(int rowIndex, bool selected)
{
base.SetSelectedRowCore(rowIndex, selected);
}

// *********************************************************************
/// <summary>
/// Gets a string array of values contained in this
/// <see cref="DataGridView"/>.
/// </summary>
/// <returns>A string representation of data contained in the grid.</returns>
public List<string[]> ToArray()
{
List<string[]> rowValues = new List<string[]>();
if (this.Columns.Count > 0)
{
foreach (DataGridViewRow row in this.Rows)
{
string[] cellValues = new string[this.Columns.Count];
for (int cellCount = 0; cellCount < this.Columns.Count; cellCount++)
{
if (row.Cells[cellCount].Value != null)
{
cellValues[cellCount] = row.Cells[cellCount].Value.ToString();
}
}
rowValues.Add(cellValues);
}
}
return rowValues;
}

#region Metadata overrides

//**********************************************************************
/// <summary>
/// Gets or sets a value indicating how column widths are determined.
/// </summary>
/// <remarks>
/// This simply provides new metadata for the
/// <see cref="System.Windows.Forms.DataGridView.AutoSizeColumnsMode"/>
/// property.
/// </remarks>
/// <value>One of the <c>DataGridViewAutoSizeColumnsMode</c> values.
/// The default is <c>DataGridViewAutoSizeColumnsMode.Fill</c>.</value>
/// <seealso cref="System.Windows.Forms.DataGridViewColumn.AutoSizeMode"/>
/// <seealso cref="System.Windows.Forms.DataGridView.AutoResizeColumn(int,DataGridViewAutoSizeColumnMode)"/>
/// <seealso cref="System.Windows.Forms.DataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode)"/>
[DefaultValue(DataGridViewAutoSizeColumnsMode.Fill)]
public new DataGridViewAutoSizeColumnsMode AutoSizeColumnsMode
{
get { return base.AutoSizeColumnsMode; }
set { base.AutoSizeColumnsMode = value; }
}

#endregion Metadata overrides

#region Sorting and IComparer implementation

// *********************************************************************
/// <summary>
/// Gets the column by which the System.Windows.Forms.DataGridView
/// contents are currently sorted.
/// </summary>
/// <value>The <see cref="DataGridViewColumn"/> by which the
/// <see cref="DataGridView"/> contents are currently sorted.</value>
public DataGridViewColumn CurrentSortedColumn
{
get
{
if (this.SortedColumn != null)
{
// Datagridview supports sorting.
return this.SortedColumn;
}
else
{
// Our own sorting?
return m_sortedColumn;
}
}
private set { this.m_sortedColumn = value; }
}

// *********************************************************************
/// <summary>
/// Gets a value indicating whether the items in the
/// <see cref="DataGridView"/> control are sorted in ascending or
/// descending order, or are not sorted.
/// </summary>
/// <value>One of the <see cref="SortOrder"/> values.</value>
public SortOrder CurrentSortOrder
{
get
{
if (CurrentSortedColumn != null)
{
return CurrentSortedColumn.HeaderCell.SortGlyphDirection;
}
else
{
return SortOrder.None;
}
}
}

// *********************************************************************
/// <summary>
/// Sorts the contents of the <see cref="DataGridView"/> control
/// in ascending or descending order based on the contents of the
/// specified column.
/// </summary>
/// <typeparam name="T">The type of the underlying data in the
/// <see cref="DataGridView"/>.</typeparam>
/// <param name="dataGridViewColumn">The column by which to sort the
/// contents of the <see cref="DataGridView"/>.</param>
/// <param name="sortableArray"> The array of underlying data.</param>
public void DoSort<T>(DataGridViewColumn dataGridViewColumn,
ref T[] sortableArray)
{
List<T> list = new List<T>(sortableArray);
this.DoSort<T>(dataGridViewColumn, ref list);
sortableArray = list.ToArray();
}

// *********************************************************************
/// <summary>
/// Sorts the contents of the <see cref="DataGridView"/> control
/// in ascending or descending order based on the contents of the
/// specified column.
/// </summary>
/// <typeparam name="T">The type of the underlying data in the
/// <see cref="DataGridView"/>.</typeparam>
/// <param name="dataGridViewColumn">The column by which to sort the
/// contents of the <see cref="DataGridView"/>.</param>
/// <param name="sortableList"> The list of underlying data.</param>
public void DoSort<T>(DataGridViewColumn dataGridViewColumn,
ref List<T> sortableList)
{
DataGridViewColumn oldColumn = this.CurrentSortedColumn;
ListSortDirection direction;

// If oldColumn is null, then the DataGridView is not currently sorted.
if (oldColumn != null)
{
// Sort the same column again, reversing the SortOrder.
if (oldColumn == dataGridViewColumn &&
this.CurrentSortOrder == SortOrder.Ascending)
{
direction = ListSortDirection.Descending;
}
else
{
// Sort a new column and remove the old SortGlyph.
direction = ListSortDirection.Ascending;
oldColumn.HeaderCell.SortGlyphDirection = SortOrder.None;
}
}
else
{
direction = ListSortDirection.Ascending;
}

CgSortHelper<T> sh =
new CgSortHelper<T>(ref sortableList);

sh.Sort(dataGridViewColumn.DataPropertyName, direction);
sortableList = sh.SortableList;
// Check if the datagridview has a datasource. If yes, bind the data
if (this.DataSource != null && sh.IsSortedCore) this.DataSource = sortableList;

dataGridViewColumn.HeaderCell.SortGlyphDirection =
direction == ListSortDirection.Ascending ?
SortOrder.Ascending : SortOrder.Descending;
CurrentSortedColumn = dataGridViewColumn;

} // end DoSort

// *********************************************************************
/// <summary>
/// Sorts the array of <see cref="DataGridViewRow"/> objects by it's
/// RowIndex in the specified <paramref name="sortOrder"/>.
/// </summary>
/// <param name="array">An array of DataGridViewRow.</param>
/// <param name="sortOrder"><see cref="SortOrder"/>.</param>
public void SortSelectedRowsByIndex(DataGridViewRow[] array,
SortOrder sortOrder)
{
Array.Sort(array, new CgSortComparer(sortOrder));
}

// *************************************************************************
/// <summary>
/// A class to implement sorting for the underlying data.
/// </summary>
private class CgSortComparer : IComparer
{
private SortOrder m_sortOrder;

// *********************************************************************
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="sortOrder"> Sort order for comparison.</param>
public CgSortComparer(SortOrder sortOrder)
{
this.m_sortOrder = sortOrder;
}

// *****************************************************************
/// <summary>
/// Compares object <paramref name="x"/> to object
/// <paramref name="y"/> and returns an indication of their relative
/// values.
/// </summary>
/// <param name="x"> First object.</param>
/// <param name="y"> Second object to compare with first object.</param>
/// <returns>A signed number indicating the relative values of
/// <paramref name="x"/> and <paramref name="y"/>.
/// < 0 : The value of <paramref name="x"/> is less than
/// <paramref name="y"/>.
/// = 0 : The value of <paramref name="x"/> is equal to the value of
/// <paramref name="y"/>.
/// > 0: The value of <paramref name="x"/> is greater than
/// <paramref name="y"/> or y is null.
/// </returns>
/// <exception cref="ArgumentException"> <paramref name="x"/> and
/// <paramref name="y"/> are not the same type.</exception>
public int Compare(object x, object y)
{
switch (this.m_sortOrder)
{
case SortOrder.Descending:
return ((DataGridViewRow) y).Index.CompareTo(
((DataGridViewRow) x).Index);
case SortOrder.Ascending:
default:
return ((DataGridViewRow) x).Index.CompareTo(
((DataGridViewRow) y).Index);
}
}
} // end class CgSortComparer

#endregion Sorting and IComparer implementation

} // end class CgDataGridView

} // end namespace Yours.Truly



Here is the sorthelper class.


// Copyright © Yours.Truly 2009. All rights reserved.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;

namespace Yours.Truly
{
//**************************************************************************
/// <summary>
/// A class to help sorting different kinds of object data.
/// </summary>
/// <remarks>
/// This class makes use of the CgPropertyComparer class to compare values
/// based on the type descriptor.
/// <para>$Id$</para>
/// <author>Your's truly</author>
/// </remarks>
public class CgSortHelper<T>
{
private bool m_isSorted;
private ListSortDirection m_direction = ListSortDirection.Ascending;
private List<T> m_sortableList;
[NonSerialized()]
private PropertyDescriptor m_sort = null;

//**********************************************************************
/// <summary>
/// Initializes a new instance of the CgSortHelper.
/// class.
/// </summary>
/// <param name="sortableList"> The list of underlying data.</param>
public CgSortHelper(ref List<T> sortableList)
{
m_sortableList = sortableList;
}

//**********************************************************************
/// <summary>
/// Initializes a new instance of the CgSortHelper.
/// class.
/// </summary>
/// <param name="sortableArray"> The array of underlying data.</param>
public CgSortHelper(ref T[] sortableArray)
{
m_sortableList = new List<T>(sortableArray);
}

#region Public Sorting API

// *********************************************************************
/// <summary>
/// Sorts the contents of the underlying data in ascending or descending
/// order.
/// </summary>
public void Sort()
{
ApplySortCore(m_sort, m_direction);
}

// *********************************************************************
/// <summary>
/// Sorts the contents of the underlying data in ascending or descending
/// order based on the contents of the specified <paramref name="property"/>.
/// </summary>
/// <param name="property"> The property based on which the sorting
/// needs to be performed.</param>
public void Sort(string property)
{
/* Get the PD */
m_sort = FindPropertyDescriptor(property);

/* Sort */
ApplySortCore(m_sort, m_direction);
}

// *********************************************************************
/// <summary>
/// Sorts the contents of the underlying data in ascending or descending
/// order based on the contents of the specified <paramref name="property"/>
/// and <paramref name="direction"/>.
/// </summary>
/// <param name="property"> The property based on which the sorting
/// needs to be performed.</param>
/// <param name="direction"> One of the <see cref="ListSortDirection"/>.
/// </param>
public void Sort(string property, ListSortDirection direction)
{
/* Get the sort property */
m_sort = FindPropertyDescriptor(property);
m_direction = direction;

/* Sort */
ApplySortCore(m_sort, m_direction);
}

#endregion

#region Sorting properties

// *********************************************************************
/// <summary>
/// Gets a value indicating whether the list supports sorting.
/// </summary>
/// <value>Always returns true.</value>
public bool SupportsSortingCore
{
get { return true; }
}

// *********************************************************************
/// <summary>
/// The underlying data to be sorted.
/// </summary>
/// <value> The list of objects of type T.</value>
public List<T> SortableList
{
get { return this.m_sortableList; }
}

// *********************************************************************
/// <summary>
/// Sorts the contents of the underlying data in ascending or descending
/// order based on the contents of the specified <paramref name="property"/>
/// and <paramref name="direction"/>.
/// </summary>
/// <param name="property"> The property based on which the sorting
/// needs to be performed.</param>
/// <param name="direction"> One of the <see cref="ListSortDirection"/>.
/// </param>
public void ApplySortCore(PropertyDescriptor property,
ListSortDirection direction)
{
List<T> items = this.SortableList as List<T>;

if ((null != items) && (null != property))
{
CgPropertyComparer<T> pc =
new CgPropertyComparer<T>(property, direction);
items.Sort(pc);

/* Set sorted */
m_isSorted = true;
}
else
{
/* Set sorted */
m_isSorted = false;
}
}

// *********************************************************************
/// <summary>
/// Gets a value indicating whether the list is sorted.
/// </summary>
/// <value>true if sorted; false otherwise.</value>
public bool IsSortedCore
{
get { return m_isSorted; }
}

// *********************************************************************
/// <summary>
/// Sets the <see cref="IsSortedCore"/> value to false without removing
/// sorting.
/// </summary>
public void RemoveSortCore()
{
m_isSorted = false;
}

#endregion

#region Private Sorting API

// *********************************************************************
/// <summary>
/// Gets the <see cref="PropertyDescriptor"/> with the given
/// <paramref name="property"/>.
/// </summary>
/// <param name="property"> The property based on which the sorting
/// needs to be performed.</param>
/// <returns><see cref="PropertyDescriptor"/>.</returns>
private PropertyDescriptor FindPropertyDescriptor(string property)
{
PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(typeof(T));
PropertyDescriptor prop = null;

if (null != pdc)
{
prop = pdc.Find(property, true);
}
return prop;
}

#endregion

} // end CgSortHelper

//**************************************************************************
/// <summary>
/// A class to help sorting different kinds of object data.
/// </summary>
/// <remarks>
/// This class implements the IComparer interface and is based on
/// code implemented by Rockford Lhotka:
/// msdn.microsoft.com/library/default.asp?url=/library/en-us/dnadvnet
/// /html/vbnet01272004.asp" href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnadvnet/html/vbnet01272004.asp">
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnadvnet/html/vbnet01272004.asp
/// <para>$Id$</para>
/// <author>your's truly</author>
/// </remarks>
internal class CgPropertyComparer<T> : IComparer<T>
{
private ListSortDirection m_direction = ListSortDirection.Ascending;
private PropertyDescriptor m_property;

//**********************************************************************
/// <summary>
/// Initializes a new instance of the CgPropertyComparer.
/// class.
/// </summary>
/// <param name="property"> The property based on which the sorting
/// needs to be performed.</param>
/// <param name="direction"> One of the <see cref="ListSortDirection"/>.
/// </param>
public CgPropertyComparer(PropertyDescriptor property,
ListSortDirection direction)
{
m_property = property;
m_direction = direction;
}

// *****************************************************************
/// <summary>
/// Compares object <paramref name="x"/> to object
/// <paramref name="y"/> and returns an indication of their relative
/// values.
/// </summary>
/// <param name="x"> First object.</param>
/// <param name="y"> Second object to compare with first object.</param>
/// <returns>A signed number indicating the relative values of
/// <paramref name="x"/> and <paramref name="y"/>.
/// < 0 : The value of <paramref name="x"/> is less than
/// <paramref name="y"/>.
/// = 0 : The value of <paramref name="x"/> is equal to the value of
/// <paramref name="y"/>.
/// > 0: The value of <paramref name="x"/> is greater than
/// <paramref name="y"/> or y is null.
/// </returns>
/// <exception cref="ArgumentException"> <paramref name="x"/> and
/// <paramref name="y"/> are not the same type.</exception>
public int Compare(T x, T y)
{
/* Get property values */
object xValue = GetPropertyValue(x, m_property.Name);
object yValue = GetPropertyValue(y, m_property.Name);

/* Determine sort order */
if (m_direction == ListSortDirection.Ascending)
{
return CompareAscending(xValue, yValue);
}
else
{
return CompareDescending(xValue, yValue);
}
}

// *********************************************************************
/// <summary>
/// Determines whether the specified x object of type T is equal to the
/// other object y of type T.
/// </summary>
/// <param name="x"> First object.</param>
/// <param name="y"> Second object to compare with first object.</param>
/// <returns> true if the x is equal to y, otherwise false.</returns>
public bool Equals(T x, T y)
{
return x.Equals(y);
}

// *********************************************************************
/// <summary>
/// Serves as a hash function for a particular type. System.Object.GetHashCode()
/// is suitable for use in hashing algorithms and data structures like a hash
/// table.
/// </summary>
/// <param name="obj">The object for which hashcode is required.</param>
/// <returns>A hash code for the current object of type T.</returns>
public int GetHashCode(T obj)
{
return obj.GetHashCode();
}

// *********************************************************************
/// <summary>
/// Compares two property values of any type
/// </summary>
/// <param name="x">First object.</param>
/// <param name="y">Second object.</param>
/// <returns>A signed number indicating the relative values of
/// <paramref name="x"/> and <paramref name="y"/> in ascending order.
/// < 0 : The value of <paramref name="x"/> is less than
/// <paramref name="y"/>.
/// = 0 : The value of <paramref name="x"/> is equal to the value of
/// <paramref name="y"/>.
/// > 0: The value of <paramref name="x"/> is greater than
/// <paramref name="y"/> or y is null.
/// </returns>
/// <exception cref="ArgumentException"> <paramref name="x"/> and
/// <paramref name="y"/> are not the same type.</exception>
private int CompareAscending(object x, object y)
{
int result;

/* If values implement IComparer */
if (x is IComparable)
{
result = ((IComparable) x).CompareTo(y);
}
/* If values don't implement IComparer but are equivalent */
else if (x.Equals(y))
{
result = 0;
}
/* Values don't implement IComparer and are not equivalent, so compare as string values */
else result = x.ToString().CompareTo(y.ToString());

/* Return result */
return result;
}

// *********************************************************************
/// <summary>
/// Compares two property values of any type
/// </summary>
/// <param name="x">First object.</param>
/// <param name="y">Second object.</param>
/// <returns>A signed number indicating the relative values of
/// <paramref name="x"/> and <paramref name="y"/> in descending order.
/// < 0 : The value of <paramref name="x"/> is less than
/// <paramref name="y"/>.
/// = 0 : The value of <paramref name="x"/> is equal to the value of
/// <paramref name="y"/>.
/// > 0: The value of <paramref name="x"/> is greater than
/// <paramref name="y"/> or y is null.
/// </returns>
/// <exception cref="ArgumentException"> <paramref name="x"/> and
/// <paramref name="y"/> are not the same type.</exception>
private int CompareDescending(object x, object y)
{
/* Return result adjusted for ascending or descending sort order ie
multiplied by 1 for ascending or -1 for descending */
return CompareAscending(x, y) * -1;
}

// *********************************************************************
/// <summary>
/// Gets the property value for the specified property and type.
/// </summary>
/// <param name="value">The type of object.</param>
/// <param name="property">The property for which the value is required.
/// </param>
/// <returns>An object containing the property value.</returns>
private object GetPropertyValue(T value, string property)
{
/* Get property */
PropertyInfo propertyInfo = value.GetType().GetProperty(property);

/* Return value */
return propertyInfo.GetValue(value, null);
}

} // end class CgPropertyComparer

} // end namespace Yours.Truly



Hope this helps someone.

Continue >>