0
votes

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);
    }
}
Index -1 means there is no columns in the DGV. What this means is when the application starts and event is occurring before the DGV is constructed. The error is easily fixed by putting a IF statement in the Click event and return if the number of rows in the DGV is less than zero.jdweng