index out of range in datagridview

398 Views Asked by At

I wrote a program that gets the name, family and age of student, saves them in the database and shows them in DataGridView. I can see added student after adding it in DatagridView but I can't click it. Error is index out of range (index -1 does not have value)

private void btnRegister_Click(object sender, EventArgs e)
{
    try
    {
        string name = txtName.Text;
        string family = txtFamily.Text;
        int age = int.Parse(txtAge.Text);
        foreach (var item in Database.tbl_student)
        {
            if (item.Name.Trim().ToLower().Equals(name.Trim().ToLower())
                        && item.Family.Trim().ToLower().Equals(family.Trim().ToLower()))
            {
                MessageBox.Show("this student is duplicate..");
                return;
            }
        }
        Database.tbl_student.Add(new Student() { Name = name, Family = family, Age = age });
        dataGridView1.DataSource = null;
        dataGridView1.DataSource = Database.tbl_student;
    } catch(Exception error)
    {
        MessageBox.Show(error.Message);
    }
}
0

There are 0 best solutions below