Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
private void addbutton_Click(object sender, EventArgs e)
        {
            int StuID = Convert.ToInt32(this.SIDtextBox.Text);
            DataTable dt = cslStudent.GetStudents(StuID);
            this.SelectedStudentGridView.DataSource = dt;
            BindingSource bs = new BindingSource();
            bs.DataSource = dt;
            
            
            int iRowCnt = this.SelectedContainersdataGridView.Rows.Count;
           
            string StudName = this. SelectedStudentGridView.Rows[iRowCnt].Cells[0].Value.ToString();  
            string Address = this. SelectedStudentGridView.Rows[iRowCnt].Cells[1].Value.ToString();    
            string Phone = this. SelectedStudentGridView.Rows[iRowCnt].Cells[2].Value.ToString();     
            

            PHTS.DataServices.cslStudent.NewStudent(StuID, StudName, Address, Phone);

            MessageBox.Show("Student Added Sucessfully");  
            
        }


I am having trouble in saving data to the database. I am getting "Index was out of range. Must be non-negative and less than the size of the collection."

Thanks
Posted
Comments
Dr.Walt Fair, PE 19-Aug-11 16:17pm    
Where is it giving you the error? It looks to me like you are trying to access a Row before you've added one to the Rows collection.
rbjanaki 19-Aug-11 16:27pm    
I am getting the error at this. SelectedStudentGridView.Rows[iRowCnt].Cells[0].Value.ToString();

1 solution

Before you can access a Row of Cells, you need to create it. Here's one way to do it, using your own variable names, of course
C#
int n = grid.Rows.Add();
DataGridViewRow r = grid.Rows[n];
r.Cells[0].Value = ... ;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900