DataGridView + DataGridViewButtonColumn

16/07/2007 - 21:10 por Javier | Informe spam
Hola Comunidad.

Tengo un DataGridView, al cual le he agregado a la columna un boton
"DataGridViewButtonColumn", mi duda pasa por lo siguiente se puede agregar a
dicho botón una imagen ...

Desde ya muchas Gracias.
Saludos
Yop.

Preguntas similare

Leer las respuestas

#1 Luis Miguel Blanco
17/07/2007 - 19:48 | Informe spam
Hola Javier

La clase DataGridViewButtonColumn como ya habrás comprobado en la ayuda, no
dispone de ninguna propiedad que permita asignar una imagen al botón, como
ocurre por ejemplo con los botones estándar, así que debemos recurrir al
algunos truquillos para conseguir este efecto cuando utilizamos botones en
las celdas del grid.

La solución más inmediata consiste en reemplazar el método CellPainting del
control grid, y comprobar cuándo se va a pintar el contenido de nuestra celda
de tipo botón, en ese momento, creamos un nuevo objeto de tipo imagen y
dibujamos esta encima de la superficie del botón. Algo parecido al siguiente
bloque de código:

//
private void dataGridView1_CellPainting(object sender,
DataGridViewCellPaintingEventArgs e)
{
if (e.ColumnIndex == 2 & e.RowIndex >= 0)
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All);
DataGridViewButtonCell celda =
(DataGridViewButtonCell)this.dataGridView1.Rows[e.RowIndex].Cells["MiColBoton"];

Icon ico = new Icon(Environment.CurrentDirectory + "\\atomico.ico");
e.Graphics.DrawIcon(ico, e.CellBounds.Left + 3, e.CellBounds.Top + 3);

this.dataGridView1.Rows[e.RowIndex].Height = ico.Height + 10;
this.dataGridView1.Columns[e.ColumnIndex].Width = ico.Width + 10;

e.Handled = true;
}
}
//

La otra forma de abordar este problema es algo más elaborada. Consiste en
crear una clase derivada de DataGridViewColumn y otra derivada de
DataGridViewCell. La primera serviría para establecer las propiedades de la
imagen que posteriormente se visualizaría en los botones de cada celda.

Por otro lado, la clase hija de DataGridViewCell contendría toda la lógica
de interacción con el ratón y teclado sobre el botón, así como la operación
de pintado del botón y su imagen. Para conseguir el comportamiento del botón
emplearemos la clase estática ButtonRenderer, mientras que para establecer
los diferentes estados que puede tomar el botón usaremos la enumeración
PushButtonState. En el siguiente bloque de código tienes un ejemplo de ambas
clases.

//
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Windows.Forms.VisualStyles;

namespace CeldaBotonDGV
{
class ColBoton : DataGridViewColumn
{
string sImagen;
Bitmap bmpImagen;

public ColBoton()
: base(new CelBoton())
{
}

public string Imagen
{
get { return sImagen; }
set
{
sImagen = value;
bmpImagen = new Bitmap(value);
this.Width = bmpImagen.Size.Width;
}
}

internal Bitmap ImagenBitmap
{
get { return bmpImagen; }
}
}

//*************************
class CelBoton : DataGridViewCell
{
private PushButtonState xEstadoBoton;

public CelBoton()
{
xEstadoBoton = PushButtonState.Normal;
}

public override Type FormattedValueType
{
get
{
return typeof(object);
}
}

protected override void OnKeyDown(KeyEventArgs e, int rowIndex)
{
base.OnKeyDown(e, rowIndex);

if (e.KeyCode == Keys.Space)
{
xEstadoBoton = PushButtonState.Pressed;
this.DataGridView.InvalidateCell(this.ColumnIndex, rowIndex);
e.Handled = true;
}

if (e.KeyCode == Keys.PageDown | e.KeyCode == Keys.PageUp)
{
this.DataGridView.InvalidateColumn(this.ColumnIndex);
e.Handled = true;
}
}

protected override void OnKeyUp(KeyEventArgs e, int rowIndex)
{
base.OnKeyUp(e, rowIndex);

if (e.KeyCode == Keys.Space)
{
xEstadoBoton = PushButtonState.Normal;
this.RaiseCellContentClick(new
DataGridViewCellEventArgs(this.OwningColumn.Index, rowIndex));
this.DataGridView.InvalidateCell(this.ColumnIndex, rowIndex);
e.Handled = true;
}
}

protected override void OnEnter(int rowIndex, bool throughMouseClick)
{
base.OnEnter(rowIndex, throughMouseClick);

if (throughMouseClick)
{
xEstadoBoton = PushButtonState.Pressed;
}
else
{
xEstadoBoton = PushButtonState.Normal;
}
}

protected override void OnMouseEnter(int rowIndex)
{
base.OnMouseEnter(rowIndex);
xEstadoBoton = PushButtonState.Hot;
this.DataGridView.InvalidateCell(this.ColumnIndex, rowIndex);
}

protected override void OnMouseLeave(int rowIndex)
{
base.OnMouseLeave(rowIndex);
xEstadoBoton = PushButtonState.Normal;
this.DataGridView.InvalidateCell(this.ColumnIndex, rowIndex);
}


protected override void OnMouseDown(DataGridViewCellMouseEventArgs e)
{
base.OnMouseDown(e);

if (e.Button == MouseButtons.Left)
{
xEstadoBoton = PushButtonState.Pressed;
this.DataGridView.InvalidateCell(this.ColumnIndex, RowIndex);
}
}

protected override void OnMouseUp(DataGridViewCellMouseEventArgs e)
{
base.OnMouseUp(e);

if (e.Button == MouseButtons.Left)
{
xEstadoBoton = PushButtonState.Normal;
this.RaiseCellContentClick(new
DataGridViewCellEventArgs(this.ColumnIndex, this.RowIndex));
}
}

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);

if ((cellState & DataGridViewElementStates.Selected) ==
DataGridViewElementStates.Selected)
{
if ((paintParts &
DataGridViewPaintParts.SelectionBackground) ==
DataGridViewPaintParts.SelectionBackground)
{
SolidBrush cellBackground = new
SolidBrush(cellStyle.SelectionBackColor);
graphics.FillRectangle(cellBackground, cellBounds);
cellBackground.Dispose();
}

}
else
{
if ((paintParts & DataGridViewPaintParts.Background) ==
DataGridViewPaintParts.Background)
{
SolidBrush cellBackground = new
SolidBrush(cellStyle.BackColor);
graphics.FillRectangle(cellBackground, cellBounds);
cellBackground.Dispose();
}
}


if ((paintParts & DataGridViewPaintParts.Border) ==
DataGridViewPaintParts.Border)
{
base.PaintBorder(graphics, clipBounds, cellBounds,
cellStyle, advancedBorderStyle);
}

Rectangle RectBoton = new Rectangle(cellBounds.X, cellBounds.Y,
cellBounds.Width - 1, cellBounds.Height - 1);

Rectangle RectImagen = new Rectangle(RectBoton.X + 3,
RectBoton.Y + 3,
RectBoton.Width - 7, RectBoton.Height - 7);


ButtonRenderer.DrawButton(graphics, RectBoton,
((ColBoton)this.OwningColumn).ImagenBitmap,
RectImagen, false, xEstadoBoton);
}
}
}
//

Para que puedas probar estas clases en un formulario que contenga un
DataGridView. Después de haber creado y asignado un dataset al grid, puedes
crear una columna basada en el código que acabamos de escribir, y añadirla al
grid de forma similar a la siguiente:

//
ColBoton colBot = new ColBoton();
colBot.Name = "MiColBoton";
colBot.HeaderText = "MiCol";
colBot.Imagen = Environment.CurrentDirectory + "\\botonir.jpg";
this.dataGridView1.Columns.Add(colBot);
//

Y esto sería todo, espero que alguna de estas propuestas te sirva para
conseguir lo que necesitas.

Un saludo
Luis Miguel Blanco
http://www.dotnetmania.com


"Javier" wrote:

Hola Comunidad.

Tengo un DataGridView, al cual le he agregado a la columna un boton
"DataGridViewButtonColumn", mi duda pasa por lo siguiente se puede agregar a
dicho botón una imagen ...

Desde ya muchas Gracias.
Saludos
Yop.
Respuesta Responder a este mensaje
#2 Javier
17/07/2007 - 23:00 | Informe spam
Gracias Luis, por tu ayuda.

Saludos
Yop.
email Siga el debate Respuesta Responder a este mensaje
Ads by Google
Help Hacer una preguntaRespuesta Tengo una respuesta
Search Busqueda sugerida