Как отобразить иконку в DataGridViewRowHeaderCell?
От: Аноним  
Дата: 28.08.07 12:08
Оценка:
Всем доброго времени суток.
Подскажите пожалуйста как решить проблему.
Мне необходимо в зависимости от значения некоторого свойства элемента в DataSource отображать определенную иконку в каждой строке в DataGridView.
Создал свой класс наследующий DataGridViewRowHeaderCell
public class DGVRowHeaderCell_T001 : DataGridViewRowHeaderCell
{
#region Fields
Dictionary<object, Icon> iconDictionary;
PropertyInfo iconBindedProperty;
#endregion
#region Properties
public Dictionary<object, Icon> IconDictionary
{
get { return this.iconDictionary; }
set { this.iconDictionary = value; }
}
public PropertyInfo IconBindedProperty
{
get { return this.iconBindedProperty; }
set { this.iconBindedProperty = value; }
}
#endregion
#region Constructors
#endregion
#region Methods
private Icon GetIconForDraw(int index)
{
try
{
object item = ((DataTable)this.DataGridView.DataSource).Rows[index];
return this.iconDictionary[this.iconBindedProperty.GetValue(item, new object[] { "Color" })];
}
catch { return null; }
}
#endregion
protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
{
base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
Icon ico = this.GetIconForDraw(rowIndex);
try
{
Rectangle rctg = new Rectangle(this.ContentBounds.Location, ico.Size);
graphics.DrawIcon(ico, rctg);
}
catch { }

}
}
В приложении инициализирую DataGridView.RowTemplate.HeaderCell как объект типа DGVRowHeaderCell_T001
Также при обработке события RowAdded инициализирую this.dataGridView1.Rows[this.dataGridView1.NewRowIndex].HeaderCell как объект типа DGVRowHeaderCell_T001
Однако иконки не отображаются.
Посмотрел после инициализации DataSource так там все Rows имеют HeaderCell стандартного типа а не того который я определил.
Знает кто нибудь в чем здесь проблема?
Зараннее благодарен за совет.
С уважением
spongebob



Данное сообщение получено с сайта www.gotdotnet.ru
Re: Как отобразить иконку в DataGridViewRowHeaderCell?
От: Vaspo  
Дата: 22.05.08 09:06
Оценка:
Попробовал, всё работает, RowAdded не использую вообще

Единственное, что надо соблюдать порядок:

dataGridView1.RowTemplate.HeaderCell = new DGVRowHeaderCell_T001();
dataGridView1.DataSource = table;

а не наоборот.

Куски кода:

        private void Form1_Load(object sender, EventArgs e)
        {
            DataTable table = new DataTable();
            DataColumn column0 = new DataColumn("icon", typeof(Icon));
            DataColumn column1 = new DataColumn("description", typeof(string));
            table.Columns.Add(column0);
            table.Columns.Add(column1);
            DataRow row = table.NewRow();
            row[0] = this.Icon;
            row[1] = "desc1";
            table.Rows.Add(row);
            row = table.NewRow();
            row[0] = Icon;
            row[1] = "desc2";
            table.Rows.Add(row);
            dataGridView1.RowTemplate.HeaderCell = new DGVRowHeaderCell_T001();
            dataGridView1.DataSource = table;
        }



    public class DGVRowHeaderCell_T001 : DataGridViewRowHeaderCell
    {
        #region Methods

        private Icon GetIconForDraw(int index)
        {
            try
            {
                DataRow item = ((DataTable) DataGridView.DataSource).Rows[index];
                return (Icon) item[0];
            }
            catch
            {
                return null;
            }
        }

        #endregion

        protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
        {
            base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
            Icon ico = GetIconForDraw(rowIndex);
            if (ico != null)
            {
                graphics.DrawIcon(ico, cellBounds);
            }
        }
    }
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.