ADD BUTTON IN DATAGRIDVIEW USING C#

lois waisbrooker

Total Post:70

Points:494
Posted by  lois waisbrooker
C# 
C#
 1873  View(s)
Ratings:
Rate this:
Hi Deelopers,

How can I add button in a DataGridView at runtime using C#

Thanks in advance.
  1. Sumit Kesarwani

    Post:378

    Points:2694
    Re: Add Button in DataGridView using C#

    Hi Lois,


    You can this code:

    using System;
    using System.Data;
    using System.Windows.Forms;
    using System.Data.SqlClient;
     
    namespace WindowsApplication1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
     
            private void button1_Click(object sender, EventArgs e)
            {
                dataGridView1.ColumnCount = 3;
                dataGridView1.Columns[0].Name = "Product ID";
                dataGridView1.Columns[1].Name = "Product Name";
                dataGridView1.Columns[2].Name = "Product Price";
                string[] row = new string[] { "1", "Product 1", "1000" };
                dataGridView1.Rows.Add(row);
                row = new string[] { "2", "Product 2", "2000" };
                dataGridView1.Rows.Add(row);
                row = new string[] { "3", "Product 3", "3000" };
                dataGridView1.Rows.Add(row);
                row = new string[] { "4", "Product 4", "4000" };
                dataGridView1.Rows.Add(row);
                DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
                dataGridView1.Columns.Add(btn);
                btn.HeaderText = "Click Data";
                btn.Text = "Click Here";
                btn.Name = "btn";
                btn.UseColumnTextForButtonValue = true;
            }
     
            private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
            {
                if (e.ColumnIndex == 3)
                {
                    MessageBox.Show((e.RowIndex + 1) + "  Row  " + (e.ColumnIndex + 1) + "  Column button clicked ");
                }
            }
        }
    }

      Modified On Mar-30-2018 04:12:39 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!