Home > OS >  Windows Forms DataGridView returns not the selected value
Windows Forms DataGridView returns not the selected value

Time:05-24

currently I am making first steps with Windows Forms and I have noticed a DataGridView issue what I can't explain by myself. I set the selection mode to whole row and if I click on the row it returns me sometimes not the selected values and shows me still the same values of the preselected row. Is this known, could anyone explain why this happens? Thanks.

Here is my code of the CellContentClick method:f

 private void dgvData_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        int rowIndex = e.RowIndex;
        if (rowIndex == -1) return;

        string firstName = dgvData.Rows[rowIndex].Cells[0].Value.ToString() ?? "No first name";
        string lastName = dgvData.Rows[rowIndex].Cells[1].Value.ToString() ?? "No last name";
        string email = dgvData.Rows[rowIndex].Cells[2].Value.ToString() ?? "No email";

        string d = $"Firstname: {firstName}, Lastname: {lastName}, Email: {email}";

        txtboxPersonData.Text = d;
    }

enter image description here

CodePudding user response:

private void dgvData_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (dgvData.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
    {
       MessageBox.Show(dgvData.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
    }
}

CodePudding user response:

I would suggest using a BindingSource, set it's DataSource to a list then assign the BindingSource to the DataGridView.

The list type represents your data, change to match your incoming data.

public class Contact
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Phone { get; set; }
    public string Email { get; set; }
    public DateTime BirthDate { get; set; }
}

For displaying information in a label on your form add the following readonly property to the class above.

public string DisplayInformation =>
    $"Name: {(FirstName ?? "no first" )} {(LastName ?? "no last")} "  
    $"Mail: {(Email ?? "no mail")}";

In your form data binding DisplayInformation to a label.

Notes

  • if you need sorting see the following.
  • If all properties need not be shown, set up columns in the DataGridView to those which need to be displayed followed by dataGridView1.AutoGenerateColumns = false in form load.

Form code

public partial class ExampleForm : Form
{
    private readonly BindingSource _bindingSource = new();
    public ExampleForm()
    {
        InitializeComponent();
  
        _bindingSource.DataSource = GetYourDataMethod();
        dataGridView1.DataSource = _bindingSource;
 
        DisplayLabel.DataBindings.Add(
            "Text", 
            _bindingSource, 
            nameof(Contact.DisplayInformation));
    }
}
  • Related