Click here to Skip to main content
15,902,787 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am developing c# windows application using data grid view, i am retrieve my stored data for grid view, but error is came. this is for my first column code,

C#
dgvfind.Columns[0].HeaderText = "SL NO";
                       dgvfind.Columns[0].Name = "SL NO";
                       dgvfind.Columns[0].DataPropertyName = "slno";


but error is came first line. Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index, Any one please guide me.

What I have tried:

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Posted
Updated 27-Jul-16 7:25am
v2

It seems that your DataGridView has no columns. Did you forgot to set the DataGridView.ColumnCount Property (System.Windows.Forms)[^]?
 
Share this answer
 
Comments
Boopalslm 27-Jul-16 12:34pm    
sir super, working fine,thanks a lot, i am spending more than 5 hrs above for this error,thanks a lot.
Boopalslm 27-Jul-16 12:47pm    
sir one more doubt, how to bind null values in text box,

this is my text box bind code

txtstaff.Text = dr[0].ToString();

values cannot dispaly. Give me some ideas. Above text box having null values and some rows having text.
Jochen Arndt 27-Jul-16 13:01pm    
This is not related to the initial question. So you should raise a new one. Then also others here will see it and might answer.

But it is not quite clear for me of what type the objects (txtStaff, dr) are. So you should add some more information when raising a new question.
First, check that dgvfind is the expected object and not null.
Then check the number of comumns, and ensure you have at least 1 column before trying to access.
 
Share this answer
 
This error occured due to two reasons,
1)Either you are trying to access the columns before the datasource is assigned to the datagrid view or
2) The data source might be null

one simple validation does the job

C#
if (dgvfind.DataSource != null && dgvfind.ColumnCount > 0)
            {
                dgvfind.Columns[0].HeaderText = "SL NO";
                dgvfind.Columns[0].Name = "SL NO";
                dgvfind.Columns[0].DataPropertyName = "slno";
            }
 
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