Search code examples
c#winformsdatagridview

When click a row in a datagrid view , how data are autofill to relevant input fields in same form in C#?


I am doing a project on c#. I have created forms. In my userform, there are 3 input fields for user details as username, phone number and password . when i click the add button it added details to the database and show in the grid view named "usersgv". the users details are viewed in the usersgv as one user detail(username , phone number and password) is stored in one row.

I want is when i click a row, the details in that selected row such as username , phone number and password should automatically filled to the relevant input fields. I used this code part for it.

    unameTb.Text = usersgv.SelectedRows[0].Cells[0].Value.ToString();
    uphoneTb.Text = usersgv.SelectedRows[0].Cells[1].Value.ToString();
    upassTb.Text = usersgv.SelectedRows[0].Cells[2].Value.ToString();   

when i run the program, when i click a row the details are not fill in to the relevant input fields. How can I solve this problem?


Solution

  • I tried to test your problem and it works fine wit CurrentRow as suggested in the comments. Here my code in the CellClick event:

        private void usersgv_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if(usersgv.CurrentRow.Cells[0].Value != null)
            {
                unameTb.Text = usersgv.CurrentRow.Cells[0].Value.ToString();
                uphoneTb.Text = usersgv.CurrentRow.Cells[1].Value.ToString();
                upassTb.Text = usersgv.CurrentRow.Cells[2].Value.ToString();
            }
        }
    

    Heres how it should look:

    DataGridView with selected row

    Let me know if it works also on your machine.