'Windows Forms DataGridView returns not the selected value
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;
}
Solution 1:[1]
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 = falsein 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));
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Karen Payne |
