Home » Visual Studio

DataGridView.DataSource throwing Index was out of range exception

Hello all,

I'm having a problem with DataGirdView. 

I am using a BindingSource object to bind that DataTable object to the DataGridView and I get the following exception thrown on the line I set the DataGirdView.DataSource = BindingSource object:-

Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index"} System.Exception {System.ArgumentOutOfRangeException}

Heres the code:-

Code Snippet

source = newBindingSource();

source.DataSource = dset.Tables[0];

resultsGrid.DataSource = source;

I am at a loss as to why this is happening as the the DataSet contains 1 table and the Table contains 1 row.

After it throws the exception the app binds the table to DataGridView as expected 

Does anyone know why this would be happening ??



10 Answers Found


Answer 1

Maybe you can use Binding object  instead BindingSource and then write:

Binding binding = new Binding("you must have some parameters in constructor");



Answer 2

Hi Dragoslav,

The thing is that BindingSource actually works. The only issue is that it thorws this exceptions before it binds the data.

I am trying to figure out why this is throwing this exception  for seemingly no reason.

Also I am unsure of how to use a Binding object. I've tried the following but its not working. Do you know what params I should be passing ??

Code Snippet

Binding source  = newBinding("resultsGrid.Rows", dset.Tables[0], "resultsGrid");



Answer 3

I think I know what is happening. It is not problem  in BindingSource.
Did you put in datagridview  to autogenerate columns ?
Did you create columns in designer to match columns that comes from dset.Tables[0]



Answer 4

Yes AutoGenerateColumns is set  to true, and I did not create columns in Form Designer


Answer 5

So did you experiment with these settings ?
Maybe you must disable autogeneratecolumns when you use BindingSource ?
Or try to disable autogenerate and create columns in desiger to match those that
come from dataset  (datatable) in code.
Set breakpoint and look structure of datatable  (click on litle magnifier icon in debug mode
when you point with mouse on datatable)


Answer 6


You can insert break point to debug. To find out which statement throw exception.

Maybe nothing to do with the BindingSource and dataGridView.

Hope helpful.


Answer 7

I just ended up removing MessageBox.Show(ex.Message) from the catch block. Like I said it works fine it just thorws this exception for some reason or another.

Not very professional I know but sure...... it works


Answer 8

Well that was the 1st thing I done. The exception  is thorwn at the line  when I assign the binding source  to the DataGridView.DataSource property.

Answer 9

Have you figured out why it threw this exception? I got exactly the same problem.



Answer 10

I had a similar issue where I was getting the following error whenever I tried changing the datasource  on a DataGridView:


Index was out of range. Must be non-negative  and less than the size  of the collection.
Parameter name: index

 at System.Collections.ArrayList.get_Item(Int32 index)
 at System.Windows.Forms.DataGridViewColumnCollection.get_Item(Int32 index)
 at System.Windows.Forms.DataGridView.PositionEditingControl(Boolean setLocation, Boolean setSize, Boolean setFocus)
 at System.Windows.Forms.DataGridView.PerformLayoutPrivate(Boolean useRowShortcut, Boolean computeVisibleRows, Boolean invalidInAdjustFillingColumns, Boolean repositionEditingControl)
 at System.Windows.Forms.DataGridView.ResetUIState(Boolean useRowShortcut, Boolean computeVisibleRows)
 at System.Windows.Forms.DataGridViewRowCollection.OnCollectionChanged_PreNotification(CollectionChangeAction cca, Int32 rowIndex, Int32 rowCount, DataGridViewRow& dataGridViewRow, Boolean changeIsInsertion)
 at System.Windows.Forms.DataGridViewRowCollection.OnCollectionChanged(CollectionChangeEventArgs e, Int32 rowIndex, Int32 rowCount, Boolean changeIsDeletion, Boolean changeIsInsertion, Boolean recreateNewRow, Point newCurrentCell)
 at System.Windows.Forms.DataGridViewRowCollection.ClearInternal(Boolean recreateNewRow)
 at System.Windows.Forms.DataGridView.RefreshColumnsAndRows()
 at System.Windows.Forms.DataGridView.OnDataSourceChanged(EventArgs e)
 at System.Windows.Forms.DataGridView.set_DataSource(Object value)
 at OQADataImport.frmMain.<bsSelectedItem_DataSourceChanged>b__1c(Object o) in D:\SVN_Support\Code\OQM Projects\OQADataImport\OQADataImport\frmMain.cs:line 611

The solution we found was to make sure that the DataGridView was not in Edit mode when you are changing the datasource. The new code  we use to update the datasource is:


dgvResults.DataSource = <New DataView>;


With this code the above error went away!



I am trying to use SlSvcUtil to create an assembly that I can use in a Silverlight application to share contracts between two different services. SlSvcUtil throws an exception that I can't seem to work around. Here is what I do:

I have an ordinary .Net assembly that I use as a data contract for the two services. From this assembly I generate xsd files with SvcUtil. I use the following command:

svcutil /dconly "C:\MyProject\bin\debug\MyAssembly.dll"

I then try to create a cs file with SlSvcUtil with the following command:

slsvcutil /noLogo /ct:System.Collections.ObjectModel.ObservableCollection`1 /r:"c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\Silverlight\v4.0\system.dll" /language:CS *.xsd /out:Emric.CommonData.Apply.CreditApplication.cs

This is when I get the following error:

Error: An error occurred in the tool.
Error: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

Does anyone know what causes this problem and how I could work around it? And am I going about the issue in the right way?

I made a Main Application Window, and from the menu I call a child window. On that child window i put a DataGridView. It worked fine. But then i wanted to change the width of some columns. I used the command:
DataGridView1.Columns[1].Width = 100;
When I inserted the line, the program stopped working when I opened the child window. I got an error message like: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index.
So I searched the net to find a solution, but after hours of wasted time I have found only one half-solution: one guy said, that he solved his (similar) problem with placing his DataGridView on the main window instead of a child window. Then I tried to change the parameter to this:
DataGridView1.Parent = this;
and the code started to work fine (except of course i didn't want the DataGridView to be on my main window).
So if I use my table on the main window, or if i don't want to change anything with my columns, the code works fine.
If needed, I can attach the whole code, but I really need a help here.
I use an Access Database, tried with empty table or with data, everything is the same
Thanks in advance


When I try to get ShapeRange from the Range of the first sentence of a docx file started by an InlineShape, I receive a COleException with error message of "The server threw an exception".

The interesting point is that if the file be saved as doc and be used with the program, the problem disappears. Another interesting point is that if I put just one sentence before the InlineShape at the begining of the file, in this case also, the problem disappears. 

what could the cause of the exception be?



I get this error message after I perform sort on any of the datagrid column and change the row selection. The datagrid is bound to an EntitySet<T> collection and each row of the grid is obviously bound to an object of type T.

Any help would be greatly appreciated.



Hi All,

I am inserting a new content control on word document at given range using following Word API.

rg.ContentControls.Add(WdContentCOntrolType.WdCOntentControlRichText, ref m_Missing)

where rg - specifed range and m_Missing - System.Reflection.Missing.Value

it is working fine but sometimes the above line code throws "command failed exception". Since this a COM exception and is happening spoaradically, i am not able to figure out the issue.

Can anybody tell me in what scenarios ContentControls.Add throws the exception and how to avoid that?? I need to use RichTextContentControl only.


Srinivas Akella



Hi All,

I am inserting a new content control on word document at given range using following Word API.

rg.ContentControls.Add(WdContentCOntrolType.WdCOntentControlRichText, ref m_Missing)

where rg - specifed range and m_Missing - System.Reflection.Missing.Value

it is working fine but sometimes the above line code throws "command failed exception". Since this a COM exception and is happening spoaradically, i am not able to figure out the issue.

Can anybody tell me in what scenarios ContentControls.Add throws the exception and how to avoid that?? I need to use RichTextContentControl only.


Srinivas Akella




I have just recently migrated my WM application from WM 6.1 to WM 6.5. The application all works OK apart from when I try to open up the serial port to connect to some Bluetooth hardware.

The hardware is paired to the WM device and I can connect to the device if I go to the Bluetooth settings and select connect. Thus proving I have the correct port number in my application (COM2).

However, when I try to connect to the hardware using the application, firstly I see a prompt from WM6.5 to select a connection Bluetooth shortcut. This is most annoying so is there a way of disabling this so that the application just connects to the specified COM port as it did when running on WM6.1. Secondly when I select the correct shortcut the application then throws an Argument Out of Range Exception with a message:

An error message is available for this exception but cannot be displayed because these messages are optional and are not currently installed on this device. Please install ‘NETCFv35.Messages.EN.wm.cab’ for Windows Mobile 5.0 and above or  ‘NETCFv35.Messages.EN.cab’ for other platforms. Restart the application to see the message.

I have installed the 'NETCFv35.Messages.EN.wm.cab’ but this has not made any difference to providing a more useful error message.

All the parameters for Port initialization seem to be correct or at least what I would expect.

Any help would be most appreciated.

The hardware what the application is running on is a HTC mobile which is the same as what it previously ran on albeit a faster processor, more memory etc.

Many Thanks.






I am getting an argument out of rance exception error when trying to set the DGV column names.  I set the Datasource of the DGV in another function then  immediately call this code to set up column name information for the DGV



void SetUpGrid()



//dgvJobData.AutoGenerateColumns = false;

dgvJobData.AllowUserToAddRows =


dgvJobData.AllowUserToDeleteRows =


dgvJobData.AllowUserToResizeColumns =


dgvJobData.AllowUserToOrderColumns =


dgvJobData.Columns[0].AutoSizeMode =


dgvJobData.Columns[0].HeaderText =

"Job ID";


dgvJobData.Columns[1].AutoSizeMode =


dgvJobData.Columns[1].HeaderText =


dgvJobData.Columns[2].AutoSizeMode =


dgvJobData.Columns[2].HeaderText =


dgvJobData.Columns[3].AutoSizeMode =


dgvJobData.Columns[3].HeaderText =

"Job Fixed";

dgvJobData.Columns[4].AutoSizeMode =


dgvJobData.Columns[4].HeaderText =

"Job Start";

dgvJobData.Columns[5].AutoSizeMode =


dgvJobData.Columns[5].HeaderText =

"Job Close";

dgvJobData.Columns[6].AutoSizeMode =


dgvJobData.Columns[6].HeaderText =

"Latest End Time";

dgvJobData.Columns[7].Visible =

false; // Hide the status column

dgvJobData.Columns[8].Visible =

false; // Hide the alert status column


When the code hits the first Column[0] line it throws the exception with the following message:-

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

Any help would greatly be appreciated





I am building a single-dimensional array and when I try to iterate through the array and print out the values using a while loop using the .Length function I get an index out of range exception. Sure I could tell the while loop to stop when i reaches a fixed value... but I would like to learn how to use the .Length function properly.


Here is the code I have:


int[] singleArray2 = { 12, 32, 16, 23, }; // new array holding predefined values

      int i = 0;
      while (i < singleArray1.Length)


I appreciate the help


Hi everyone


I am new to SSIS and this is what i am getting when trying to process .csv file in to database. Can any one let me know why this is happening. This is not happening all the times.


Error: The script threw an exception: Exception of type 'System.OutOfMemoryException' was thrown

I am trying to make an Http request to an http web service from within an operation in a WCF service. The WCF service is hosted on IIS6 and I am using the DefaultyNetworkCredentials for as the credentials for both the proxy and request objects.
    A proxy is used to access internet resources however the web service I am trying to send data to resides within our intranet. Even so I have provided the name and the port for the proxy on the request object.
    The data I am trying to send is XML and I have set the Content-Type of the request to 'text/xml' .
  When I attempt to call the GetResponse method of the request Object I have created in the code and exception is thrown but the message portion of the exception is empty so I do not know what exactly is going wrong.
   I can POST the same XML data to the web service successfully using fiddler so I know it works but not getting anywhere trying to do the same via .Net code within the WCF service operation.
     A quick response will be much appreciated.
I have DataTable as a DataSource of DataGridView. I am using DataGridView for viewing data, sorting, adding, removing etc. DataGridView contains only few columns. All data can be viewed or manipulated by textboxes. I am not using databinding between DataGridView active row and textboxes. When some row in DataGridView is selected, data of this row can be manipulated by textboxes (again, I am not using databinding)

Scenario for adding new rows:
User clicks on button
New dataRow is added with default values into DataTable.
Selection in DataGridView is changed to newly added row
User can change row data by textboxes

I have working solution:

DataTable dataTable = (DataTable)_dataGridView1.DataSource;
DataRow row = dataTable.NewRow();
row[_columnId] = _idOfNewlyAddedRow;

  for( int i=0; i<_dataGridView1.Rows.Count; i++)
       if((( DataRowView)_dataGridView1.Rows[ i].DataBoundItem).Row == row)
           _dataGridViewCodes.Rows[ i].Selected = true;

I am able find out index of row in DataGridView based on DataRow in DataTable.
But as you can see it can be very slow in case of a lot of entries.

Is there any other possibility how to convert DataRow to appropriate index in DataGridView? Or only some kind of mapping function DataRow -> DataGridViewRow + DataGridView.Rows.IndexOf(...) is possible?

Thanks a lot


Binding the datagridview to an output of a LINQ to xml works for me but I am running into 2 issues:

The column order is in column name's alphabetic order, not the order from the Linq output.

Column is not sortable.



I have a datatable that adds three columns automatically to a datagridview. Then I want to add a button column that is not from a datasource. The button column has an index of 3 which my program relies on. After a few refreshes of the grid the button column ends up being in the front at index 0. What is the standard operating procedure for adding columns after setting the datasource so the columns maintain the right order? I don't want to have to loop over every column every time I want to get a cell. Here is the code to set the datasource and then add a column.

m_VariableDataGrid->DataSource = nullptr;
m_VariableDataGrid->DataSource = m_VarTable->DefaultView;

How can I make sure m_pInfoColumn stays at index 3 assuming the datatable has three columns?




I have a datagridview which is bound to a datatable. I have a text box used for context filtering the datatable. The textchnaged event uses the datatable.select method to query the table on the fly providing a quick method for filtering the list.

The problem is, when the user removes there is a large delay in repopulating the grid. I realise it will take a bit longer to repopulate the grid with 2000+ records but when the repopulation takes substantially more time than the initial load of the data i figure there must be a better way of doing this. The code i have is shown below.


 if (sCriteria == "")
    dgvDocs.DataSource = dsDocs.Tables[0];
     DataRow[] drTemp = dsDocs.Tables[0].Select("DOCID LIKE '*" + sCriteria + "*'");
     foreach (DataRow dr in drTemp)
     dgvDocs.DataSource = dtDocs;


Thanks for your help




Here is my problem. I am using a DataGridView and have a master table which contains values which different tables related to the master data, i.e. StatusID =1 in master table = TrailerStatus (1, 2, 3, 4 and their descriptions) are in a related table.  I am able to retrieve the values from Table B 1 = Empty, 2 = Rejected, 3 = Onsite, etc.  However, I don't know how to relate the master table StatusID = 1 to default my dropdown list from the relational table 1, 2, 3, 4.

I have been fighting with this for quite some time and just have not found a solid example of how to do this.  I actually have two dropdownlists which will need to be correctly wired in order for my application to work.

This will also be an editable dataGridView but I will tackle that challenge once I get this first hair plucked from my butt.

Any help would be greatly appreciated.  I am able to insert code from the aspx source but not sure that would help at this point.

There is some code-behind which doesn't work at all pertaining to a ;;     gvSCACDetail_RowDataBound   ;;
but I dont' think I can even get the code to compoile when this is not commented out.

Here are some of the details:

<td style="width: 700px; height: 20px">
<asp:GridView ID="gvSCACDetail" runat="server" AutoGenerateColumns="False" AutoGenerateEditButton="True" DataKeyNames="trailerid,locationid,scacid,statusid,capacityid" AutoGenerateDeleteButton="True" DataSourceID="SCACDetailView" Visible="False" Width="698px">
 <PagerStyle CssClass="centerh" HorizontalAlign="Center" />
 <HeaderStyle CssClass="centerh" Height="15px" Font-Bold="True" />
 <RowStyle CssClass="centerd" Height="15px" />
  <asp:BoundField DataField="TrailerID" Visible="False" HeaderText="TrailerID" SortExpression="TrailerID" />
  <asp:BoundField DataField="DivisionID" Visible="False" HeaderText="DivisionID" SortExpression="DivisionID" />
  <asp:BoundField DataField="Trailer" HeaderText="Trailer" SortExpression="Trailer" />
  <asp:TemplateField HeaderText="locationid">
    <asp:DropDownList ID="ddlLocation" runat="server" DataSourceID="location" DataTextField="Location" DataValueField="ID"></asp:DropDownList>
  <asp:TemplateField HeaderText="Trailer Status">
    <asp:DropDownList ID="ddlStatus" runat="server" DataSourceID="trailerStatus" DataTextField="ID" DataValueField="Status"></asp:DropDownList>
  <asp:BoundField DataField="CapacityID" Visible ="False" HeaderText="CapacityID" SortExpression="CapacityID" />
  <asp:BoundField DataField="MaxWeightCapacity" HeaderText="MaxWt" SortExpression="MaxWt" />
  <asp:BoundField DataField="Contents" HeaderText="Contents" SortExpression="Contents" />
  <asp:BoundField DataField="Customer" HeaderText="Customer" SortExpression="Customer" />
  <asp:BoundField DataField="Notes" HeaderText="Notes" SortExpression="Notes" />
<asp:SqlDataSource ID="SCACDetailView" runat="server" ConnectionString="<%$ ConnectionStrings:ppenetConnectionString3 %>"
 SelectCommand="trPl_GetTrailerStatusBySCACDivision_sp" SelectCommandType="StoredProcedure"
 UpdateCommand="exec [dbo].[trpl_UpdateTrailer_sp] ID = @ID,
 DivisionID = @DivisionID,
 LocationID = @LocationID,
 Trailer = @Trailer,
 StatusID = @StatusID,
 CapacityID = @CapacityID,
 MaxWeightCapacity = @MaxWeightCapacity,
 Contents = @Contents,
 Customer = @Customer,
 BillOfLading = @BillOfLading,
 Notes = @Notes"
 DeleteCommand="exec [dbo].[trpl_DeleteTrailer_sp] ID = @ID">
  <asp:QueryStringParameter Name="SCACID" QueryStringField="SCACID" Type="Int32" />
  <asp:ControlParameter ControlID="DivisionID" Name="DivisionID" PropertyName="SelectedValue"
  Type="Int32" />
<asp:SqlDataSource ID="location" runat="server" ConnectionString="<%$ ConnectionStrings:ppenetConnectionString3 %>"
 SelectCommand="TrPl_LocationSelectAll" SelectCommandType="StoredProcedure">
  <asp:Parameter Name="ID" />
  <asp:Parameter Name="ID" />
  <asp:Parameter Name="DivisionID" />
  <asp:Parameter Name="LocationID" />
  <asp:Parameter Name="SCACID" />
  <asp:Parameter Name="Trailer" />
  <asp:Parameter Name="StatusID" />
  <asp:Parameter Name="CapacityID" />
  <asp:Parameter Name="MaxWeightCapacity" />
  <asp:Parameter Name="Contents" />
  <asp:Parameter Name="Customer" />
  <asp:Parameter Name="BillOfLading" />
  <asp:Parameter Name="Notes" />
<asp:SqlDataSource ID="trailerStatus" runat="server" ConnectionString="<%$ ConnectionStrings:ppenetConnectionString3 %>"
 SelectCommand="TrPl_StatusSelectAll" SelectCommandType="StoredProcedure">



Any help would certainly be appreciated.

Thanks in advance.



Hi I would like to build a datasource my self for my datagridview :-)

here is what I was thinking

// data tables.
DataTable dtSport = new DataTable();
DataTable dtLevel = new DataTable();
DataTable dtSportsMan = new DataTable();

// build sport
dtSport.Columns.Add("SportID", System.Type.GetType("System.Int32");
dtSport.Columns.Add("SportDesc", System.Type.GetType("System.String");

// build ProOrNot
dtLevel.Columns.Add("LevelID", System.Type.GetType("System.Int32");
dtLevel.Columns.Add("LevelDesc", System.Type.GetType("System.String");

// build SportsMan
dtSportsMan.Columns.Add("SportsManID", System.Type.GetType("System.Int32");
dtSportsMan.Columns.Add("sm_fullname", System.Type.GetType("System.String");
dtSportsMan.Columns.Add("sm_SportID", System.Type.GetType("System.Int32");
dtSportsMan.Columns.Add("sm_LevelID", System.Type.GetType("System.Int32");

/* this a un-related db structure it's very very very simplefied from the original one but it's the main point of what im trying to get to work, I'd like to know if it's possible to use this manually filled datatable build the relations between the tables and add them to a dataset this way a datagridview could be bounded to the data source and automaticly know it should be a combo box for the external keys *//* thanks in advance!! */



I have a form where there is DataGridView with Custom Columns like DataGridViewTextBoxColumns, DataGridViewComboBoxColumn. I set grdEmployeeDetails.AutoGenerateColumns=true; grdEmployeeDetails.AllowUserToAddRows = true; in From_Load event, created structure for filling n Retrieving the data(i.e, I'm using array of classes, instead of DataSet/DataTable). here i'm doing retrieval, insert/ update, delete operations.

DataGridView.datasource is assigned by the objects of array class. In this case only the backend records are filling  to DataGridView,  but when my control is in last row of the DataGridView to edit/ insert its not adding the one  more row below the control.

        I tried with the grdEmployeeDetails.Rows.Add(dr);

but giving error  "Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound".

I want one more row when my control is in last row, DataGridview should keep on adding the rows bydefault. I googled lot but didnt get any proper response.

Pleae anybody help me out i have been trying this for 3 days...

i have a datagridview that is bind to a bindingsource, the bindingsource.datasource is set a typeof() when the form initialize and then i change the datasource to my datatable at the form load event. at design time, i set the id columns and couple of other columns visibility to false, but when i run the program, the id columns visiblity changed to true when i change the bindingsource.datasource to my datatable, but the other columns didnt change.  this is very strange because only the id columns visibility changes. for now i just set the visibility to false again after changing the datasource property. but why is this happening?


this is my first post on this forum, but i still hope, it's the right way to post here (:

So, my problem is, that I can't refresh the DataSource from my DataGridView.

I got a DataGridView with an DataSet, which inherits a DataTable.

I now fill a DTO from a second WinForm, handing the DTO to my Method in my MainForm - which then tries to put the data into the DataGridView.

publicvoid GetValuesFromAddClientAndSetToTable(DTOClientInfo dto)
      DataRow newDataRow = dataSet.Tables[0].NewRow(); // Table[0] of ds is the data I want to display
      newDataRow["Titel"] = dto.Titel;
      newDataRow["Anrede"] = dto.Anrede;
      newDataRow["Firmenname"] = dto.Firmenname;
      newDataRow["Vorname"] = dto.Vorname;
      newDataRow["Nachname"] = dto.Nachname;
      newDataRow["Zusatz"] = dto.Zusatz;
      newDataRow["Strasse"] = dto.Strasse;
      newDataRow["Nr."] = dto.Hausnummer;
      newDataRow["Ort"] = dto.Ort;
      newDataRow["PLZ"] = dto.PLZ;
      newDataRow["E-Mail"] = dto.Email;
      newDataRow["Bemerkungen"] = dto.Bemerkungen;


      dataGridView1.DataSource = dataSet.Tables[0].DefaultView;

The point now is, that the DataGridView isn't showing the new Row, which has just been added by my method written above.

Can anyone out there might help me? :)



<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure