thelonelyghost
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);
}
}
}
}
6 replies