C# how to code a button

Michelle Kamp 41 Reputation points
2022-05-04T14:40:45.693+00:00

Hi I am new to C#, I have a datagridview that populates student data. I also have a button beside each student row. This button would go to a new form with the student details of that selected student in the first form.

Here is an example of what that would look like. How do I code the button to go to a student details form for that selected student that the button was pressed for?
198827-image.png

Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 60,161 Reputation points
    2022-05-04T15:00:10.907+00:00

    Making an assumption here that you're building a Windows Forms app. If you are building something else then the steps change a little.

    That depends on how you have your data represented in the app. I'm going to assume here that your DGV is bound to a set of Student business objects. So each row in the DGV has a corresponding Student object that the data comes from. The button would have been added as a DataGridViewButtonColumn. When the user clicks the button it will trigger the CellClick event on the DGV. Unfortunately this is triggered on any cell click so you have to make sure it is right column first.

    If the button is clicked then you can get the object associated with the row and, if you get a valid student, then show your form. Something like this perhaps.

       private void dataGridView1_CellClick ( object sender, DataGridViewCellEventArgs e )  
       {  
           var grid = sender as DataGridView;  
         
           //Ensure this is the button column and not the header  
           if (e.ColumnIndex != StudentDetailsColumnIndex && e.RowIndex > 0)  
               return;  
         
           //Get the data  
           var student = grid[e.RowIndex, e.ColumnIndex].Value as Student;  
           if (student != null)  
           {  
               var childForm = new StudentDetailsForm();  
               childForm.Student = student;  
               childForm.ShowDialog();  
           };  
       }  
         
       private const int StudentDetailsColumnIndex = 0;  
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.