C# .NET - DataGridView Button Click event is not working

Asked By saranya jibeesh on 19-Dec-22 02:12 AM
        public Form1()
            SqlConnection con = new SqlConnection(@"Server= DESKTOP-AK4NH6J\SQLEXPRESS;Database=Interview;Trusted_connection=True");
            SqlCommand cmd = new SqlCommand("select * from Person", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            dataGridView1.DataSource = dt;
            DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
            btn.HeaderText = "Edit";
            btn.Text = "Edit";
            btn.Name = "btn";
            btn.UseColumnTextForButtonValue = true;
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
            if (e.ColumnIndex == 6)

Button click event is not working

You did not wire up the event in Form1() constructor - Robbe Morris replied to saranya jibeesh on 22-Jan-23 11:56 AM

Type this in dataGridView1 and then type the . to get the intellisense for the event and wire up the handler.

You also need to look up how to the the "using" clause on classes like SqlConnection that implement the IDisposable interface.  If a .NET class has a Dispose() method, then it likely implements the IDisposable interface.  The purpose is to force the call of Dispose regardless of whether an exception was thrown or some other exit out of the block.  Force closing connection and/or cleaning up object references is the most common thing that occurs here.  You'll see this with StreamReader, StreamWriter, and a bunch of I/O classes on top of these database classes.

using(var con = new SqlConnection("your connection string"))
  using(var cmd = new SqlCommand("select * from Person", con))
    using(var da = new SqlDataAdapter(cmd))

     your other stuff goes here