Click here to Skip to main content
15,940,246 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a bounded DataGridView. How can I add a button in one field with data? I will attach a screenshot of how I see it https://ibb.co/gjQi8H. Do you have any recommendations on this?

What I have tried:

it's WinForms and I think that I need to write a custom column type.

C#
class TextAndButtonControl : UserControl
{
   private TextBox textbox1;
   private Button button1;

   public TextAndButtonControl()
   {
       this.textbox1 = new TextBox();
       this.Controls.Add(this.textbox1);
       this.button1 = new Button();
       this.Controls.Add(this.button1);
       this.RenderControl();
       this.button1.Click += new EventHandler(button1_Click);
   }

   void button1_Click(object sender, EventArgs e)
   {
       MessageBox.Show("Hi");
   }

   public string Text
   {
       get { return this.textbox1.Text; }
       set { this.textbox1.Text = value; }
   }

   public string ButtonText
   {
       get { return this.button1.Text; }
       set { this.button1.Text = value; }
   }

   public void RenderControl()
   {
       this.textbox1.Location = new Point(0, 0);
       this.textbox1.Width = 2 * this.Width / 3;
       this.textbox1.Height = this.Height;
       this.button1.Location = new Point(2 * this.Width / 3, 0);
       this.button1.Width = this.Width / 3;
       this.button1.Height = this.Height;
    }
}


Then in main form:

C#
private void Form1_Load(object sender, EventArgs e)
{
    TextAndButtonControl bcol = new TextAndButtonControl();
    bcol.Text = "Button Column ";
    bcol.ButtonText = "Click Me";
    bcol.Name = "btnClickMe";
    bcol.RenderControl();
    dgMainGrid.Controls.Add(bcol);
}


But I'm getting: https://ibb.co/dgTaNc
Posted
Updated 1-Mar-18 1:46am
v2

1 solution

See the answer here: Add Command Button to DataGridView in C# Windows Application[^]
If you only want the button to appear in the active cell, you will have to do some custom cell painting I'm afraid, see: DataGridView.CellPainting Event (System.Windows.Forms)[^]
Another way might be doing it like in this ComboBox example: DataGridView.CellPainting Event (System.Windows.Forms)[^]
 
Share this answer
 
v3
Comments
Member 12361495 28-Feb-18 8:21am    
Not exactly, I need the field to display data (they are different) and button at once in the same field (see the picture I posted).

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900