Autor Tema: C# grilla DataGridView añadir columnas CellTemplate botón dinámico new Button  (Leído 5391 veces)

Arturking

  • Sin experiencia
  • *
  • APR2.COM
  • Mensajes: 4
    • Ver Perfil
Estimados.

No sé si alguien me podrá ayudar pero tengo un problema y es que cree un control personalizado en C# en el que tengo incrustado un botón dentro de un TextBox y este a su vez lo estoy utilizado como control base para crear un nuevo tipo de columna en un DataGridView, hasta ahí todo bien si compilo me aparece la grilla con el control que agregue, mi problema es que no se como hacerlo para heredar el evento click del botón que esta dentro de la columna, les dejo el codigo que utilice para hacer esto, quiza a alguien mas le pueda servir o me puedan ayudar, de antemano gracias por cualquier ayuda



TextBoxButton
Código: [Seleccionar]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DataGridViewPowered
{
    public class TextBoxbutton : TextBox
    {
        private readonly Button _button;

        public TextBoxbutton()
        {
            _button = new Button {
                Cursor = Cursors.Default,
                TabStop = false,
                FlatStyle = FlatStyle.Flat
            };
            this.Controls.Add(_button);
            PosicionarBoton();
        }

        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e);
            PosicionarBoton();
        }

        private void PosicionarBoton()
        {
            _button.Size = new Size(this.ClientSize.Height, this.ClientSize.Height);
            _button.Location = new Point(this.ClientSize.Width - _button.Width, 0);
            SendMessage(this.Handle, 0xd3, (IntPtr)2, (IntPtr)(_button.Width << 16));
        }
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);

        [Category("Action")]
        public event EventHandler ButtonClick
        {
            add { _button.Click += value; }
            remove { _button.Click -= value; }
        }

        private Image _buttonImage;

        [Category("Appearance"), Description("Imagen del botón")]
        public Image ButtonImage
        {
            get
            {
                return _buttonImage;
            }
            set
            {
                _buttonImage = value;
                if (_buttonImage == null)
                    _button.BackgroundImage = Properties.Resources.Elipsis;
                else
                    _button.BackgroundImage = _buttonImage;
            }
        }
    }
}

TextButonCell
Código: [Seleccionar]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.ComponentModel;

namespace DataGridViewPowered
{
    public class TextButtonCell : DataGridViewTextBoxCell
    {       
        public TextButtonCell() : base()
        {
        }

        public override void InitializeEditingControl(int rowIndex, object
        initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
        {
            base.InitializeEditingControl(rowIndex, initialFormattedValue,
            dataGridViewCellStyle);
            TextButtonEditingControl ctl =
            DataGridView.EditingControl as TextButtonEditingControl;

            // Use the default row value when Value property is null.
            if (this.Value == null)
            {
                ctl.Text = "";
            }
            else
            {
                ctl.Text = this.Value.ToString();
            }
        }

        public override Type EditType
        {
            get
            {
                // Return the type of the editing control that CalendarCell uses.
                return typeof(TextButtonEditingControl);
            }
        }

        public override Type ValueType
        {
            get
            {
                // Retorna valor tipo string
                return typeof(string);
            }
        }

        public override object DefaultNewRowValue
        {
            get
            {
                // Retrona vallor vacio por defecto
                return "";
            }
        }

       


    }
}

TextButtonColumn
Código: [Seleccionar]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DataGridViewPowered
{
    public class TextButtonColumn: DataGridViewColumn
    {
        public TextButtonColumn() : base(new TextButtonCell())
        {}

        public override DataGridViewCell CellTemplate
        {
            get
            {
                return base.CellTemplate;
            }
            set
            {
                if (value != null &&
                !value.GetType().IsAssignableFrom(typeof(TextButtonCell)))
                {
                    throw new InvalidCastException("Debe utilizar una celta del tipo TextButton");
                }
                base.CellTemplate = value;
            }
        }
    }
}

TextButtonEditingControl
Código: [Seleccionar]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DataGridViewPowered
{
    class TextButtonEditingControl :TextBoxbutton, IDataGridViewEditingControl
    {
        DataGridView dataGridView;
        private bool TextChanged = false;
        int rowIndex;

        public TextButtonEditingControl()
        {

        }

        public object EditingControlFormattedValue
        {
            get
            {
                return this.Text;
            }
            set
            {
                try
                {
                    this.Text = "";
                }
                catch
                {
                    this.Text = "";
                }
            }
        }

        public object GetEditingControlFormattedValue(
        DataGridViewDataErrorContexts context)
        {
            return EditingControlFormattedValue;
        }

        public void ApplyCellStyleToEditingControl(
        DataGridViewCellStyle dataGridViewCellStyle)
        {
            this.Font = dataGridViewCellStyle.Font;
            this.ButtonImage = Properties.Resources.Elipsis;
        }

        // Implements the IDataGridViewEditingControl.EditingControlRowIndex
        // property.
        public int EditingControlRowIndex
        {
            get
            {
                return rowIndex;
            }
            set
            {
                rowIndex = value;
            }
        }

        // Implements the IDataGridViewEditingControl.EditingControlWantsInputKey
        // method.
        public bool EditingControlWantsInputKey(
            Keys key, bool dataGridViewWantsInputKey)
        {
            // Let the DateTimePicker handle the keys listed.
            switch (key & Keys.KeyCode)
            {
                case Keys.Left:
                case Keys.Up:
                case Keys.Down:
                case Keys.Right:
                case Keys.Home:
                case Keys.End:
                case Keys.PageDown:
                case Keys.PageUp:
                    return true;
                default:
                    return !dataGridViewWantsInputKey;
            }
        }

        // Implements the IDataGridViewEditingControl.PrepareEditingControlForEdit
        // method.
        public void PrepareEditingControlForEdit(bool selectAll)
        {
            // No preparation needs to be done.
        }

        // Implements the IDataGridViewEditingControl
        // .RepositionEditingControlOnValueChange property.
        public bool RepositionEditingControlOnValueChange
        {
            get
            {
                return false;
            }
        }

        // Implements the IDataGridViewEditingControl
        // .EditingControlDataGridView property.
        public DataGridView EditingControlDataGridView
        {
            get
            {
                return dataGridView;
            }
            set
            {
                dataGridView = value;
            }
        }

        // Implements the IDataGridViewEditingControl
        // .EditingControlValueChanged property.
        public bool EditingControlValueChanged
        {
            get
            {
                return TextChanged;
            }
            set
            {
                TextChanged = value;
            }
        }

        // Implements the IDataGridViewEditingControl
        // .EditingPanelCursor property.
        public Cursor EditingPanelCursor
        {
            get
            {
                return base.Cursor;
            }
        }

        protected override void OnTextChanged(EventArgs eventargs)
        {
            // Notify the DataGridView that the contents of the cell
            // have changed.
            TextChanged = true;
            this.EditingControlDataGridView.NotifyCurrentCellDirty(true);
            base.OnTextChanged(eventargs);
        }

       

    }
}
« Última modificación: 18 de Febrero 2016, 10:56 por Alex Rodríguez »

Alex Rodríguez

  • Moderador Global
  • Experto
  • *******
  • Mensajes: 2050
    • Ver Perfil
Hola, no entiendo bien a qué te refieres con "mi problema es que no se como hacerlo para heredar el evento click del botón que esta dentro de la columna" ¿Qué es lo que quieres hacer exactamente?

Una cosa extraña: inscrustar un botón dentro de un textbox es algo que se ve extraño, no entiendo muy bien por qué lo haces así en lugar de colocar el botón junto al textbox.

Saludos

Arturking

  • Sin experiencia
  • *
  • APR2.COM
  • Mensajes: 4
    • Ver Perfil
Estimado mi duda es como llamar al evento click del botón que tengo incrustado dentro del textbox cuando este se encuentra como columna de la grilla, en este caso quiero poder capturar el click del boton que esta en la columna textButton de la grilla.

no es tan raro el tener un botón incrustado en un textbox, de hecho la mayoria de los pack de controles como infrajistic y  DevExpress lo tienen, tanto para un textbox como para las grillas, en mi caso no quiero depender de librerías externas ya que no tengo las licencias y no quiero aumentarle costos a mi proyecto, y lo hago de esta forma porque es más intuitivo y ademas me permite optimizar el espacio en la UI para dejar mas para los datos que realmente le interesa ver al usuario.

 

Sobre la educación, sólo puedo decir que es el tema más importante en el que nosotros, como pueblo, debemos involucrarnos.

Abraham Lincoln (1808-1865) Presidente estadounidense.

aprenderaprogramar.com: Desde 2006 comprometidos con la didáctica y divulgación de la programación

Preguntas y respuestas

¿Cómo establecer o cambiar la imagen asociada (avatar) de usuario?
  1. Inicia sesión con tu nombre de usuario y contraseña.
  2. Pulsa en perfil --> perfil del foro
  3. Elige la imagen personalizada que quieras usar. Puedes escogerla de una galería de imágenes o subirla desde tu ordenador.
  4. En la parte final de la página pulsa el botón "cambiar perfil".