using System; using System.IO; using System.Collections.Generic; using System.Text; using System.Drawing; using System.Windows.Forms; using System.ComponentModel; using System.Reflection; namespace ExerciseProgram { /// <summary> /// Create a Custom DataGridViewImageColumn /// </summary> public class StringImageColumn : DataGridViewImageColumn { public StringImageColumn() { this.CellTemplate = new CustomImageCell(); this.ValueType = typeof(string); // value of this column is a string, but it shows images in the cells after formatting } } /// <summary> /// Create a Custom DataGridViewImageCell /// </summary> public class CustomImageCell : DataGridViewImageCell { // mapping between filename and image static System.Collections.Generic.Dictionary<string, Image> dotImages = new Dictionary<string, Image>(); // load up custom dot images static public System.Collections.Generic.Dictionary<string, Image> Images { get { return dotImages; } } public CustomImageCell() { this.ValueType = typeof(int); } protected override object GetFormattedValue( object value, int rowIndex, ref DataGridViewCellStyle cellStyle, TypeConverter valueTypeConverter, TypeConverter formattedValueTypeConverter, DataGridViewDataErrorContexts context) { if (value.GetType() != typeof(string)) return null; // get the image from the string and return it LoadImage(value); // return the mapped image return dotImages[(string)value]; } public static void LoadImage(object value) { // load the image from the images directory if it does not exist if (dotImages.ContainsKey((string)value) == false) { string path = Path.GetDirectoryName(Application.ExecutablePath) + "\\images\\" + (string)value; // read the image file Image theImage = Image.FromFile(path); // assign the image mapping dotImages[(string)value] = theImage; } } public override object DefaultNewRowValue { get { return 0; } } } } |