Need help with a telephone directory Windows Forms application

I am getting an exception when I try to click on a row to change the selected row in a DataGridView. The code is attached below: using System.Windows.Forms; namespace Lab_Prgm_8 { public partial class Form1 : Form { public class Entry { public string Name { get; set; } public string Contact { get; set; } } List<Entry> entries = new List<Entry>(); private void ClearTextBoxes() { textBoxName.Text = ""; textBoxContact.Text = ""; } public Form1() { InitializeComponent(); dataGridView1.DataSource = entries; } private void buttonAdd_Click(object sender, EventArgs e) { Entry newEntry = new Entry { Name = textBoxName.Text, Contact = textBoxContact.Text }; entries.Add(newEntry); dataGridView1.DataSource = null; // Refresh the data dataGridView1.DataSource = entries; ClearTextBoxes(); } private void buttonDelete_Click(object sender, EventArgs e) { if (dataGridView1.SelectedRows.Count > 0) { int selectedIndex = dataGridView1.SelectedRows[0].Index; entries.RemoveAt(selectedIndex); dataGridView1.DataSource = null; dataGridView1.DataSource = entries; ClearTextBoxes(); } else { MessageBox.Show("No entry selected for deletion!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } }
3 Replies
kermit
kermit11mo ago
Can you also write the exception you are getting?
thelonelyghost
thelonelyghostOP11mo ago
IndexOutOfRangeException sorry for the late reply
kermit
kermit11mo ago
Sorry for late response. I think the error is occurring by selecting the last row. Please check the below solution. Check if the "SelectionMode" property is set to FullRowSelect? The SelectionMode property must be set to FullRowSelect or RowHeaderSelect for the SelectedRows property to be populated with selected rows. When the last row is selected the SelectedRows.Count somehow returns 0
Want results from more Discord servers?
Add your server